From marshall44 at home.com Sun Apr 15 04:22:03 2007 From: marshall44 at home.com (marshall) Date: Sun, 15 Apr 2007 04:22:03 -0400 Subject: embeddding Tkinter in C app Message-ID: <4621E0AB.C85A139F@home.com> Trying to embed python/Tkinter app with C backend. All I get is attribute errors when running the embedded python app from C. Either the error is basename from th Tkinter module or new instance of Tkinter in module. Here is the python module from Tkinter import * from ARLclasses import GuiMixin from MLNcommon import Display from mlnclient import MLNDisplay from Dialog import Dialog from ScrolledText import ScrolledText from normalDate import ND from commands import * from socket import * from ftplib import FTP import os import sys,random import regex import string import struct import select import time, glob import Pmw class DOMI(GuiMixin,MLNDisplay,Display): def __init__(self, master=None): #Frame.__init__(self, master) #self.pack(self) #self.Init_Display(0000,3,3) self.Init_GUI = "Display" print self.Init_GUI def Init_Display(self,tod,num_ci,num_mlns): from Tkinter import * from ARLclasses import GuiMixin from MLNcommon import Display from mlnclient import MLNDisplay self.ClientGui() print "Starting GUI" def start_sim(self): for self.trk_x,self.trk_y,self.trk_z,self.hdg in [(23,340,400,2),(45,400,5000,3),(30,450,20000,3),(78,500,10000,3),(88,476,600,2),(564,34,30000,7),(453,56,14532,5),(400,76,23489,1),(356,89,15439,2)]: self.target_icon(self.ppi_display,self.trk_x,self.trk_y,self.trk_x,self.trk_y,4) self.link_sim() print "simulated tracks from sim" def ownship_loc(self,tod,x,y,Xdot,Ydot): self.timeofday = tod self.osX = x self.osY = y print self.timeofday self.os_loc(self.ppi_display,self.osX,self.osY,Xdot,Ydot) def ppi_plot_track(self,trk_id,Xpos,Ypos,Xdot,Ydot): self.trkx = Xpos self.trky = Ypos plot = self.target_icon(self.ppi_display,self.trkx,self.trky,Xdot,Ydot,trk_id) class TEST: def __init__(self, display=None): self.function = "Odell" self.printer() def printer(self): print 'Odells ass' if __name__ == '__main__': DOMI().mainloop() Odell -------------- next part -------------- A non-text attachment was scrubbed... Name: marshall44.vcf Type: text/x-vcard Size: 220 bytes Desc: Card for marshall URL: From fumanchu at amor.org Sat Apr 14 00:58:46 2007 From: fumanchu at amor.org (fumanchu) Date: 13 Apr 2007 21:58:46 -0700 Subject: File DB instead of real database? In-Reply-To: <1176524076.446204.70730@w1g2000hsg.googlegroups.com> References: <1176524076.446204.70730@w1g2000hsg.googlegroups.com> Message-ID: <1176526726.455987.305280@o5g2000hsb.googlegroups.com> On Apr 13, 9:14 pm, "Jia Lu" wrote: > I do not want to use a real DB like MySQL ... > But I need something to save about more than > 1000 articles. Is there any good ways? The latest version of Dejavu includes a filesystem backend. See "Folders" at http://projects.amor.org/docs/dejavu/1.5.0RC1/storage.html#other Robert Brewer System Architect Amor Ministries fumanchu at amor.org From gandalf at designaproduct.biz Wed Apr 11 15:57:46 2007 From: gandalf at designaproduct.biz (Laszlo Nagy) Date: Wed, 11 Apr 2007 21:57:46 +0200 Subject: ValueError: too many values to unpack In-Reply-To: <1176319688.666986.183980@o5g2000hsb.googlegroups.com> References: <1176311618.617765.120560@p77g2000hsh.googlegroups.com> <1176319688.666986.183980@o5g2000hsb.googlegroups.com> Message-ID: <461D3DBA.7020101@designaproduct.biz> > Hmm, well I have counted the fields in the CSV and verified there are > only 11. Here is the offending code: > > .... Try this instead: lineno = 0 for values in csvreader: try: lineno += 1 boxid, mac, activated, hw_ver, sw_ver, heartbeat, name, address,phone, country, city = values except: print "Problem at line #",lineno print repr(values) break Or even: lineno = 0 for values in csvreader: lineno += 1 if len(values) != 11: print "Problem at line #",lineno print repr(values) Best, Laszlo From saint.infidel at gmail.com Mon Apr 23 15:26:52 2007 From: saint.infidel at gmail.com (infidel) Date: 23 Apr 2007 12:26:52 -0700 Subject: Generate report containing pdf or ps figures? In-Reply-To: <132pnp6r4qg0lc2@corp.supernews.com> References: <132pnp6r4qg0lc2@corp.supernews.com> Message-ID: <1177356412.269325.85990@d57g2000hsg.googlegroups.com> On Apr 23, 9:30 am, Grant Edwards wrote: > I need to be able to generate a PDF report which consists > mostly of vector images (which I can generate as encapsulated > Postscript, PDF, or SVG). What I need is a way to combine > these figures into a single PDF document. Right now the > reports consist entire of these figures, so I just write the > figures out to temp files and then use os.system() to run > ghostscript with appropriate options to combine them into a > single PDF file. > > I'd like to be able to add some text and/or place the figures > in a manner other than one per page in the output document. > > I've looked at ReportLab's documentation, but although it > appears to be able to use bitmap images (e.g jpeg) it doesn't > appear to be able to use vector images (EPS/PDF/SVG). > > Is there a PDF generation library that can place EPS or > PDF figures on a page? I've had great success using Apache's FOP utility (http:// xmlgraphics.apache.org/fop) to generate PDFs out of XSL-FO, which can contain SVG graphics (at least the 0.20.5 version can, the newer rewrite version doesn't yet). FOP is a java library but has a suitable command line interface. From rschroev_nospam_ml at fastmail.fm Mon Apr 2 10:43:38 2007 From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven) Date: Mon, 02 Apr 2007 14:43:38 GMT Subject: Problem with global variables In-Reply-To: <57ciafF2cf6qdU1@mid.individual.net> References: <1311u48bqkehk24@corp.supernews.com> <57ciafF2cf6qdU1@mid.individual.net> Message-ID: Bjoern Schliessmann schreef: > Laurent Pointal wrote: > >> And so the solution to add "global foo" before using it. > > Didn't you read his final question? > > | All of a sudden, tiny() can see the global variable "foo". Very > | confusing! Why is it that tiny() sometimes can, and sometimes > | can't, see the global variable "foo"? > > I have no explanation for this, but I'm interested in one, too. Within functions Python can read from global variables, even without a 'global' statement. Complications only arise when you try to write to it: in that case Python assumes it is a local variable instead of a global. It surprised me a bit when I first found out about this: I would have thought that Python would threat it as a local throughout the function until the function assigns something to it. That's not what happens: if the function assigns to it, *all* mentions of the variable are considered local. -- If I have been able to see further, it was only because I stood on the shoulders of giants. -- Isaac Newton Roel Schroeven From aisaac at american.edu Thu Apr 19 13:00:29 2007 From: aisaac at american.edu (Alan Isaac) Date: Thu, 19 Apr 2007 17:00:29 GMT Subject: comparison with None References: <_JAVh.1700$jR5.897@trnddc08> Message-ID: "Steven D'Aprano" wrote in message news:pan.2007.04.19.07.04.43.363933 at REMOVE.THIS.cybersource.com.au... > You shouldn't expect comparisons between types to > sort the same from one version of Python to another, although they may, > and in the future (Python 3) it is likely to become an error to compare > incomparable objects. Indeed, that was the basis of my original question. I wondered why no exception was raised. Thanks, Alan Isaac PS Note that the change you mention will conflict with currently documented behavior: "objects of different types always compare unequal". So this seems like a large change. From fuzzyman at gmail.com Sun Apr 8 16:22:03 2007 From: fuzzyman at gmail.com (Fuzzyman) Date: 8 Apr 2007 13:22:03 -0700 Subject: What happened to http://www.pythonware.com/daily and http://mechanicalcat.net/pyblagg.html? In-Reply-To: <1175957075.056246.15120@l77g2000hsb.googlegroups.com> References: <1175957075.056246.15120@l77g2000hsb.googlegroups.com> Message-ID: <1176063723.883976.145570@d57g2000hsg.googlegroups.com> On Apr 7, 3:44 pm, "asker" wrote: > These sites are not updated since almost one month. > Does anybody knows why? I assume the pythonware folk are busy. I notice that Fredrik Lundh hasn't blogged for some time either. Fuzzyman http://www.voidspace.org.uk/ironpython/index.shtml From Roka100 at gmail.com Sat Apr 14 00:14:36 2007 From: Roka100 at gmail.com (Jia Lu) Date: 13 Apr 2007 21:14:36 -0700 Subject: File DB instead of real database? Message-ID: <1176524076.446204.70730@w1g2000hsg.googlegroups.com> Hello all I donot want to use a real DB like MySQL ... But I need something to save about more than 1000 articles. Is there any good ways? Thanx Jia Lu From danpaquin at yahoo.com Mon Apr 30 16:42:41 2007 From: danpaquin at yahoo.com (Dan Thomas-Paquin) Date: Mon, 30 Apr 2007 13:42:41 -0700 (PDT) Subject: zipfile: grabbing whole directories Message-ID: <334582.90971.qm@web50808.mail.re2.yahoo.com> Hi, The built in zipfile.write doesn't seem to like taking a directory instead of a filename. for example: for each in listofdir: archive.write(each) blows up when one of the items listed in listofdir is a subdirectory. File "/usr/local/lib/python2.4/zipfile.py", line 405, in write fp = open(filename, "rb") is there a mode or a '-r' style param I am missing? Thanks in advance, Dan -------------- next part -------------- An HTML attachment was scrubbed... URL: From aleax at mac.com Wed Apr 18 22:45:50 2007 From: aleax at mac.com (Alex Martelli) Date: Wed, 18 Apr 2007 19:45:50 -0700 Subject: What makes an iterator an iterator? References: <1hwr9pv.13v4ci6106qn0aN%aleax@mac.com> <1176936067.315082.17970@y80g2000hsf.googlegroups.com> Message-ID: <1hws6rd.u0a6hd78fhhpN%aleax@mac.com> 7stud wrote: ... > Can you explain some of the details of why this code fails: ... > def next(self): > for word in "Norwegian Blue's have beautiful > plumage!".split(): > yield word Sure, easily: a loop like "for x in y:" binds an unnamed temporary variable (say _t) to iter(y) and then repeatedly calls _t.next() [or to be pedantic type(_t).next(t)] until that raises StopIteration. Calling a generator, such as this next method, returns an iterator object; calling it repeatedly returns many such iterator objects, and never raises StopIteration, thus obviously producing an unending loop. Alex From see_signature at nospam.nowire.org Tue Apr 10 03:38:13 2007 From: see_signature at nospam.nowire.org (=?ISO-8859-1?Q?Thomas_Kr=FCger?=) Date: Tue, 10 Apr 2007 09:38:13 +0200 Subject: Queue get timeout parameter question In-Reply-To: <1176178232.836311.19390@p77g2000hsh.googlegroups.com> References: <1176178232.836311.19390@p77g2000hsh.googlegroups.com> Message-ID: Godzilla schrieb: > I have been using the queue module for a multithreaded environment and > things seem to work well... until we had a requirement for the > application to be able to time sync to the server. With the time sync, > it actually disorientated the timeout in the queue's get() method... > e.g. > > get(item, 2.0) > > After the time sync, say 15 seconds backward, the thread is sitting on > that get() method for a total of 17 seconds. We can only sync the > device once per day and the time can drift up to 15 seconds per day!! > I had tried to get around this problem by having a sleep(2) (sleep is > not local system time dependant) just before the get(), but that will > slow down the application too much. > > Anyone knows a solution to this problem or an alternative method? I was fixing a serious time drift problem on Linux lately. If your server runs on Linux I can give you some hints: - set the system clock - delete /etc/adjtime and resync system time and hardware time "hwclock --systohc" - on some distributions you may have to reboot - give it some time to see if it is still drifting - if only the system clocks drifts (see output of "hwclock; date") you may have a timer related kernel problem. This may help: * deactivate ACPI via kernel boot parameter * change timer frequency * try different setting for all timer related stuff like CONFIG_HPET_TIMER or CONFIG_X86_PM_TIMER Thomas -- sinature: http://nospam.nowire.org/signature_usenet.png From carsten at uniqsys.com Tue Apr 17 15:48:24 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Tue, 17 Apr 2007 15:48:24 -0400 Subject: Traceback when trying to run script from cron? In-Reply-To: <1176838405.545383.10400@o5g2000hsb.googlegroups.com> References: <1176602160.043372.225190@q75g2000hsh.googlegroups.com> <1176838405.545383.10400@o5g2000hsb.googlegroups.com> Message-ID: <1176839304.12611.2.camel@dot.uniqsys.com> On Tue, 2007-04-17 at 12:33 -0700, erikcw wrote: > You're right. Something is not right with my sys.path. > > cron: > '/home/lybp/public_html/winneralert', '/usr/lib/python2.2', '/usr/lib/ > python2.2/plat-linux2', '/usr/lib/python2.2/lib-tk', '/usr/lib/ > python2.2/lib-dynload', '/usr/lib/python2.2/site-packages'] > Traceback (most recent call last): > File "/home/lybp/public_html/winneralert/wa.py", line 18, in ? > import MySQLdb > ImportError: No module named MySQLdb > > > SHELL: > # python wa.py > ['/home/lybp/public_html/winneralert', '/usr/local/lib/python2.4/site- > packages/setuptools-0.6c5-py2.4.egg', '/usr/local/lib/python2.4/site- > packages/MySQL_python-1.2.2-py2.4-linux-i686.egg', '/usr/local/lib/ > python24.zip', '/usr/local/lib/python2.4', '/usr/local/lib/python2.4/ > plat-linux2', '/usr/local/lib/python2.4/lib-tk', '/usr/local/lib/ > python2.4/lib-dynload', '/usr/local/lib/python2.4/site-packages'] > +OK Hello there. > > Why isn't cron able to import the MySJL module? How do I make this > work? (newbie) You have two Python versions installed on your system. Cron picks the system-installed Python 2.2 in /usr, whereas your shell picks the installation of Python 2.4 in /usr/local. Obviously, your Python 2.2 installation doesn't know MySQL, your Python 2.4 installation does. Your cron script needs to set the PATH environment variable correctly to include /usr/local/bin before /usr/bin so that it'll launch the correct Python version. HTH, Carsten From rw at smsnet.pl Mon Apr 16 08:28:36 2007 From: rw at smsnet.pl (Rob Wolfe) Date: 16 Apr 2007 05:28:36 -0700 Subject: Boost Problem! Boost.Build not found In-Reply-To: <1176722688.351441.303410@w1g2000hsg.googlegroups.com> References: <1176719740.525832.132610@e65g2000hsc.googlegroups.com> <1176720813.976821.237610@w1g2000hsg.googlegroups.com> <1176722688.351441.303410@w1g2000hsg.googlegroups.com> Message-ID: <1176726516.333233.4890@y80g2000hsf.googlegroups.com> Soren wrote: > > Try to create boost-build.jam file like this: > > > > # boost-build.jam > > boost-build C:\boost\boost_1_33_1\tools\build\v1 ; > > > Hi Rob, Thanks for the answer! > > It did solve the error.. but produced a new one: > > C:\boost\boost_1_33_1\libs\python\example\tutorial>bjam -sTOOLS=vc-8_0 > Unable to load Boost.Build: could not find build system. > --------------------------------------------------------- > C:\boost\boost_1_33_1\libs\python\example\boost-build.jam attempted to > load the > build system by invoking > > 'boost-build C:/boost/boost_1_33_1/tools/build/v1 ;' > > but we were unable to find "bootstrap.jam" in the specified directory > or in BOOST_BUILD_PATH (searching C:\boost\boost_1_33_1, C:/boost/ > boost_1_33_1/t > ools/build/v1). There is something wrong with your boost installation. Do you have subdirectory tools/build/v1 in your installation? > > What is bootstrap.jam? .. Haven't seen that one in the short > tutorial... It is essential for boost build system that the file bootstrap.jam could be found. -- HTH, Rob From aleax at mac.com Sun Apr 29 23:27:12 2007 From: aleax at mac.com (Alex Martelli) Date: Sun, 29 Apr 2007 20:27:12 -0700 Subject: While we're talking about annoyances References: <1177837565.317999.244420@c35g2000hsg.googlegroups.com> <1177857049.938363.166170@p77g2000hsh.googlegroups.com> <1hxchgp.7sw7efb72rh2N%aleax@mac.com> Message-ID: <1hxcm3o.19dhbys1wllx20N%aleax@mac.com> Michael Hoffman wrote: > Alex Martelli wrote: > > Arnaud Delobelle wrote: > > ... > >>>>> decorated.sort() > > ... > >>> def index(sequence): > >>> return sorted(range(len(sequence)), key=sequence.__getitem__) > > ... > >> But really these two versions of rank are slower than the original one > >> (as sorting a list is O(nlogn) whereas filling a table with > >> precomputed values is O(n) ). > > > > Wrong, because the original one also had a sort step, of course, so it > > was also, inevitably, O(N log N) -- I've quoted the .sort step above. > > Well, counting the index() function that is called in both cases, the > original rank() had one sort, but my version has two sorts. That doesn't affet the big-O behavior -- O(N log N) holds whether you have one sort, or three, or twentyseven. Alex From Roka100 at gmail.com Fri Apr 13 10:27:48 2007 From: Roka100 at gmail.com (Jia Lu) Date: 13 Apr 2007 07:27:48 -0700 Subject: Problem with algorithm In-Reply-To: <1176473989.420067.190970@l77g2000hsb.googlegroups.com> References: <1176434160.047703.214600@q75g2000hsh.googlegroups.com> <1176434937.258002.162220@p77g2000hsh.googlegroups.com> <1176448576.047996.12930@d57g2000hsg.googlegroups.com> <1176473989.420067.190970@l77g2000hsb.googlegroups.com> Message-ID: <1176474468.803037.170160@p77g2000hsh.googlegroups.com> > If you just expand the length to five million* or so, one of those > strings will contain all the works of Shakespeare. Oops, you have this formula in math? Actually I want to scan a range of network for some certain files. From user at example.net Fri Apr 6 20:43:00 2007 From: user at example.net (cyb) Date: Fri, 06 Apr 2007 20:43:00 -0400 Subject: Cant access http://cheeseshop.python.org/ or wiki Message-ID: For some reason I can ping these two sites fine, but when I try to go to them I cannot get to them. Normal python.org homepage works just fine. This is preventing me from getting setuptools and using pyOpenGL =( I'm using COmcast in savannah, GA From dca860MAPS at yahooMAPS.co.uk Mon Apr 30 04:16:16 2007 From: dca860MAPS at yahooMAPS.co.uk (DCA) Date: Mon, 30 Apr 2007 08:16:16 GMT Subject: Free Windows Vista Download In-Reply-To: References: <1177866404.344342.175400@h2g2000hsg.googlegroups.com> Message-ID: Spin Dryer wrote: > On Sun, 29 Apr 2007 20:23:22 -0400, ["Alvin Bruney [MVP]" without an email address>] said :- > > >> That's a misleading post, you should indicate that this is an evaluation >> copy. >> > > > You did it again Sonny, making yourself look a total fool. > > Will you stop top posting replies to spam and _leaving the spamed site > attached_. > > Fool - probably not Oversight - probably yes From see at signature.invalid Fri Apr 20 00:00:24 2007 From: see at signature.invalid (Nigel Rowe) Date: Fri, 20 Apr 2007 04:00:24 GMT Subject: Do other Python GUI toolkits require this? References: <462697A6.6010007@codebykevin.com> Message-ID: On Thu, 19 Apr 2007 19:11, Antoon Pardon wrote in comp.lang.python: > On 2007-04-19, Michael Bentley wrote: >> The learning curve is rather steep IMO, but worth it. > > Just a throw in remark, that you may ignore if you wish, but a steep > learning curve means that the subject is easily familiarized and that > the learning period is short. > > You seem to use it as if it is the opposite. > Who says the axes are labeled "familiarity" and "learning period"? I just assume they are labeled (y-axis) "Effort" and (x-axis) "Knowledge" (or "skill" or ....). Which means that something with a 'steep learning curve' requires a lot of effort to achieve a small amount of knowledge (or skill or ...). -- Nigel Rowe A pox upon the spammers that make me write my address like.. rho (snail) swiftdsl (stop) com (stop) au From nagle at animats.com Thu Apr 26 02:56:17 2007 From: nagle at animats.com (John Nagle) Date: Wed, 25 Apr 2007 23:56:17 -0700 Subject: If Dict Contains a particular key In-Reply-To: <1177565430.992904.149450@n35g2000prd.googlegroups.com> References: <000001c78695$ed321540$c7963fc0$@rawlins@thinkbluemedia.co.uk> <1177436682.3441.15.camel@dot.uniqsys.com> <1177565430.992904.149450@n35g2000prd.googlegroups.com> Message-ID: mensanator at aol.com wrote: > On Apr 24, 1:41 pm, Steven Bethard wrote: > >>Steven Howe wrote: >> >>>Carsten Haese wrote: >>> >>>>On Tue, 2007-04-24 at 18:28 +0100, Robert Rawlins - Think Blue wrote: >> >>>>>Hello Guys, >> >>>>>I'm Looking to build a quick if/else statement that checks a >>>>>dictionary for a key like follows. It would be useful if there was some direct way to get the value associated with a key, and None if there's not one. The basic options are if dict.has_key(key} : value = dict[key] else : value = None or try: value = dict[key] except: value = None one of which requires two lookups, and the other of which takes you through the exception machinery. This can be a bottleneck in some text processing applications. But it's not a big deal. John Nagle From manuelospina at yahoo.es Sun Apr 1 04:26:48 2007 From: manuelospina at yahoo.es (Manuel Ospina) Date: Sun, 1 Apr 2007 08:26:48 +0000 (GMT) Subject: tag replacement in toxml() Message-ID: <812945.62887.qm@web23213.mail.ird.yahoo.com> Hi all, I am new on the list and I already have a question :-(. I have something like this: import xml.dom.minidom from xml.dom.minidom import getDOMImplementation impl = getDOMImplementation() myDoc = impl.createDocument(None, "example", None) myRoot = myDoc.documentElement myNode1 = myDoc.createElement("node") myNode2 = myDoc.createElement("nodeTwo") myText = myDoc.createTextNode("Here is the problem") myNode2.appendChild(myText) myNode1.appendChild(myNode2) myRoot.appendChild(myNode1) print myDoc.toxml() The result is: '\nHere is the <b>problem</>' My question is how I can avoid that toxml() replaces the tags? Regards, Manuel ______________________________________________ LLama Gratis a cualquier PC del Mundo. Llamadas a fijos y m?viles desde 1 c?ntimo por minuto. http://es.voice.yahoo.com From python at hope.cz Wed Apr 25 01:09:49 2007 From: python at hope.cz (Johny) Date: 24 Apr 2007 22:09:49 -0700 Subject: PIL and font colours. Message-ID: <1177477789.652447.18260@r3g2000prh.googlegroups.com> I use PIL to write some text to a picture.The text must be seen wery clearly. I write the text to different pictures but to the same position. As pictures maybe different, colour, in the position where I write the text, is also different. Is there a way how to set the font colour so that it will be seen very clearly in the picture? For example, if the picture is bright ( for example yellow), the font colour should be dark( e.g. black) and vice versa. Can anyone help? Thanks L. From steve at holdenweb.com Thu Apr 12 09:30:29 2007 From: steve at holdenweb.com (Steve Holden) Date: Thu, 12 Apr 2007 09:30:29 -0400 Subject: Capturing the entry point of a script In-Reply-To: <1176379765.744534.148780@o5g2000hsb.googlegroups.com> References: <1176379765.744534.148780@o5g2000hsb.googlegroups.com> Message-ID: SamG wrote: > If a function does not have main function defined and there is only a > > if __name__="__main__": > > how do i make a call to that using > > profile.runcall( ...) > > in my profiling script. Is there a way to find the entry point of a > script and indentify it with module method. > There is no way to do that without modifying your module (by the way, I think you should have said "If a *module* does not ..."). The easiest way to do this is to replace the line if __name == "__main__: with def main(): and then at the end of the module put if __name__ == "__main__": main() The second step is not required unless you still want the module to run as a standalone script. Now you can call profile.runcall(module.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 cam.ac.uk at mh391.invalid Thu Apr 26 10:00:34 2007 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Thu, 26 Apr 2007 15:00:34 +0100 Subject: Tutorial creates confusion about slices In-Reply-To: References: <1177535739.431386.77300@s33g2000prh.googlegroups.com> Message-ID: Neil Cerutti wrote: >> On Apr 23, 1:38 pm, Antoon Pardon wrote: >>> The following is part of the explanation on slices in the >>> tutorial: >>> >>> The best way to remember how slices work is >> ... >>> +---+---+---+---+---+ >>> | H | e | l | p | A | >>> +---+---+---+---+---+ >>> 0 1 2 3 4 5 >>> -5 -4 -3 -2 -1 > > I object only to the word "best". I don't like the above model > because it divorces the indexes that appear in subscripts from > those that appear in slices. I 't find it complicated to think: > a[2:4] is the contiguous slice of elements starting at the gap > between element 1 and 2, and ending at the gap between element 3 > and 4. I've always found thinking of [2:4] as a half-open range > much easier. > > I suppose the above model could avoid this notational problem if > you say that a[k] means the one element slice a[k:k+1] > (technically true for strings, but false for lists), rather than > ever thinking of item indexes as pointing directly at an item. > > So I vote that the word "best" be removed. I agree. It would be better to say that, "One way to help you understand how slices work is to think of..." -- Michael Hoffman From chris.cavalaria at free.fr Thu Apr 12 04:29:33 2007 From: chris.cavalaria at free.fr (Christophe) Date: Thu, 12 Apr 2007 10:29:33 +0200 Subject: pop() clarification In-Reply-To: <1176338113.035908.52880@b75g2000hsg.googlegroups.com> References: <1176318615.056436.47430@y5g2000hsa.googlegroups.com> <1176338113.035908.52880@b75g2000hsg.googlegroups.com> Message-ID: <461dee0b$0$4360$426a34cc@news.free.fr> Carl Banks a ?crit : > On Apr 11, 3:10 pm, "7stud" wrote: >> On Apr 11, 10:44 am, "Scott" wrote: >> >> >> >>> As said before I'm new to programming, and I need in depth explaination to >>> understand everything the way I want to know it, call it a personality quirk >>> ;p. >>> With pop() you remove the last element of a list and return its value: >>> Now I know list is a bad name, but for the sake of arguement lets assume its >>> not a built in sequence> >>>>>> list = ['this', 'is', 'an', 'example'] >>>>>> list.pop() >>> 'example' >>>>>> list >>> ['this', 'is', 'an'] >>> I understand all that. What I don't understand is why all the documentation >>> I see says, "When removing a specific element from a list using pop() it >>> must be in this format: list.pop([i]). >>> At first I took that to mean that list.pop(i) would return some type of >>> error, but it doesn't. >> It's understandable that the definition of pop() is confusing in that >> way. It looks like the argument should be a list. As others have >> said, that is not what the brackets mean when the documents show the >> formal definition of a function. > > I wonder if the documentation could take advantage of Python 3000 > annotation syntax. So > > pop([x]) > > would be replaced in the docs by > > pop(x: OPTIONAL) > > Just a thought, probably not a good one. The brackets are so > pervasive that it's probably better to just let newbies be confused > for a little bit. I'd rather go for the overloading syntax. ie: pop(i) pop() Remove the item at the given position in the list, and return it. If no index is specified, a.pop() removes and returns the last item in the list. From nogradi at gmail.com Sun Apr 29 08:14:48 2007 From: nogradi at gmail.com (Daniel Nogradi) Date: Sun, 29 Apr 2007 14:14:48 +0200 Subject: Could zipfile module process the zip data in memory? In-Reply-To: <1177847479.803195.12820@c35g2000hsg.googlegroups.com> References: <1177845313.798239.71580@o5g2000hsb.googlegroups.com> <1177847479.803195.12820@c35g2000hsg.googlegroups.com> Message-ID: <5f56302b0704290514wbd251cfo25944177056f0aaa@mail.gmail.com> > > > I made a C/S network program, the client receive the zip file from the > > > server, and read the data into a variable. how could I process the > > > zipfile directly without saving it into file. > > > In the document of the zipfile module, I note that it mentions the > > > file-like object? what does it mean? > > > > > class ZipFile( file[, mode[, compression[, allowZip64]]]) > > > Open a ZIP file, where file can be either a path to a file (a > > > string) or a file-like object. > > > > Yes it is possible to process the content of the zipfile without > > saving every file: > > > > [untested] > > > > from zipfile import ZipFile > > from StringIO import StringIO > > > > zipp = ZipFile( this_is_the_zip_file_from_your_server, 'r' ) > > for name in zipp.namelist( ): > > content = zipp.read( name ) > > s = StringIO( ) > > s.write( content ) > > # now the file 'name' is in 's' (in memory) > > # you can process it further > > # ............ > > s.close( ) > > zipp.close( ) > > > > HTH, > > Daniel > Thanks! > Maybe my poor english makes you confusion:-). The client receive the > zip file data from the server, and keep these data as a variable, not > as a file in harddisk. such as "zipFileData", but the first argument > of the "ZipFile" is filename. I would like to let the ZipFile() open > the file from "zipFileData" directly but not file in harddisk > > zipp = ZipFile( this_is_the_zip_file_from_your_server, 'r' ) > ^ I don't have this file, all its data > is in a variable. Well, as you correctly pointed out in your original post ZipFile can receive a filename or a file-like object. If the zip archive data is in zipFileData then you might do: from StringIO import StringIO from zipfile import ZipFile data = StringIO( ) data.write( zipFileData ) data.close( ) zipp = ZipFile( data ) ......... and continue in the same way as before. Daniel From rweth at cisco.com Sun Apr 8 02:40:58 2007 From: rweth at cisco.com (rweth) Date: Sat, 07 Apr 2007 23:40:58 -0700 Subject: defining functions In-Reply-To: <1175798327.249407.129860@o5g2000hsb.googlegroups.com> References: <1175798327.249407.129860@o5g2000hsb.googlegroups.com> Message-ID: <1176014461.957569@sj-nntpcache-2.cisco.com> Andre P.S Duarte wrote: > How do I define a function, then import it, without having to save it > in lib; like "C:\python25\lib". ? > The best way I have found (in windows ) for permanently extending your search path for modules is to create the file: package.pth and put your path/s in a line by line format: c:\qa\PythonLibs c:\qa\PythonUtils The file needs to be in a location in your install under the site-packages .. in windows for my system thats: C:\Python25\Lib\site-packages\package.pth After you do that you can put your modules in the paths you define in the package.pth file and sys,path will pick up your modules automatically. From tgrav at mac.com Tue Apr 3 17:02:25 2007 From: tgrav at mac.com (Tommy Grav) Date: Tue, 3 Apr 2007 17:02:25 -0400 Subject: Parsing a setup file Message-ID: <6961AB82-76EA-496A-BE64-F775702B2048@mac.com> Hi, I have a setup file for some numerical simulation code written in C that looks like this: dt 0.1 time 0.0 nupdate 10 noutput 100 ntotal 10000 G 39.476926421373015 Sun 1.00000597682 mplanet 9.547861040430418e-4 3.409530427945 3.635870038323 .03424028779975 -2.0471057839802485 2.0178211484578044 -9.730193916219667e-4 mplanet 2.8558373315055975e-4 6.612079829705 6.386934883415 -.1361443021015 -1.5268292602445992 1.4623064051166743 6.108354829704997e-3 mplanet 4.372731645458918e-5 11.16769742623 16.04343604329 .3617849409933 -1.1927379555398092 .7563317049955387 -7.950313544811802e-3 particle 5.0 0.2 10.5 0.0 0.0 10.0 particle 6.0 0.1 5.5 0.0 180.0 -10.0 there can be any number of mplanet and particle enteries in the the file. As I am working on porting this code to python I am trying to figure out an efficient way of parsing such data into the program. I have the freedom to play around with the setup file(s) which is nice. I have played around with cfgparse, which I like, and made a file like this [DEFAULT] dt = 0.1 time = 0.0 and so on, but that does not give me a good way of parsing in the list of mplanets and particles. I can write my own little parser to handle a file that contains only the mplanets or particles, but I am wondering if there are any parsers out there that will handle this type of data? Or is there a way to organize my setup file that would simplify the input that I am missing? Cheers Tommy From apardon at forel.vub.ac.be Tue Apr 17 10:32:01 2007 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 17 Apr 2007 14:32:01 GMT Subject: Queue enhancement suggestion References: Message-ID: On 2007-04-17, Jean-Paul Calderone wrote: > On 17 Apr 2007 13:32:52 GMT, Antoon Pardon wrote: >>On 2007-04-17, Hendrik van Rooyen wrote: >> [snip] > >>> Not sure I understand this - it sounds vaguely incestous to me. >>> I normally use a GUI with two queues, one for input, one for >>> output, to two threads that front end two named pipes to >>> the next process - I try to avoid more than one thing reading or >>> writing to one end of a queue or a pipe, so the dataflow diagram >>> for my stuff always looks like a TinkerToy... >> >>The problem is that sometimes the gui thread has something to show >>too. With the added problem that the code wanting to show something >>doesn't know when it is executing the gui thread or an other. So >>it is very difficult to avoid the gui thread putting things on the >>queue. But since the gui thread is the single reader, it will dead >>lock if the queue happens to be full at the moment the gui thread >>want to add another item. >> > > This is pretty easily solved: > > def sendToGUI(event): > if isInGUIThread(): > gui.scheduleCall(event) > else: > guiQueue.put(event) No that is not a solution for the simple reason that now things can be shown out of order. Suppose I have a thread that shows the value of a certain variable. Now I have a button that can stop this thread and zero the variable. If I go for your solution a value may still be in the queue and my window ends up showing this last value instead of zero. -- Antoon Pardon From bdesth.quelquechose at free.quelquepart.fr Sat Apr 21 16:22:55 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sat, 21 Apr 2007 22:22:55 +0200 Subject: Do other Python GUI toolkits require this? In-Reply-To: References: Message-ID: <462a692d$0$29274$426a74cc@news.free.fr> Kevin Walzer a ?crit : > From the introduction to PyObjC, the Python-Objective-C bridge on Mac > OS X: > > "As described in Objective-C for PyObjC users the creation of > Objective-C objects is a two-stage process. To initialize objects, first > call a class method to allocate the memory (typically alloc), and then > call an initializer (typically starts with init). Some classes have > class methods which perform this behind the scenes, especially classes > that create cached, immutable, or singleton instances." > > An example: > > myObject = NSObject.alloc().init() > > I know Tkinter doesn't require any manual memory allocation of this > sort. Does wxPython, PyQt, PyGtk require anything like this when > creating objects? > PyObjC is not a GUI toolkit, it's a bridge between Python and Objective-C (a smalltalk-inspired OO superset of ansi C). And FWIW, under the hood, Python also uses this 2-stages instanciation/initialisation scheme (methods __new__ and __init__), even if it doesn't requires you to call them both explicitly. From surekap at gmail.com Sun Apr 22 22:26:46 2007 From: surekap at gmail.com (Prateek) Date: 22 Apr 2007 19:26:46 -0700 Subject: pickled object, read and write.. In-Reply-To: <1177267228.603237.113070@n59g2000hsh.googlegroups.com> References: <1177267228.603237.113070@n59g2000hsh.googlegroups.com> Message-ID: <1177295206.193467.164360@n59g2000hsh.googlegroups.com> On Apr 22, 11:40 pm, "israph... at googlemail.com" wrote: > Hi all. > > I have to put together some code that reads high scores from a saved > file, then gives the user the opportunity to add their name and score > to the high scores list, which is then saved. > > Trouble is, I can't tell the program to read a file that doesn't > exist, that generates an error. > > So I must have a file created, problem HERE is everytime the program > is run, it will overwrite the current list of saved high scores. > > Advice would be much appreciated. Try the following idiom: try: try: fp = open("filename", 'r+') except IOError: fp = open("filename", 'w+') fp.write(high_score) finally: fp.close() -Prateek From john106henry at hotmail.com Mon Apr 9 19:10:51 2007 From: john106henry at hotmail.com (John Henry) Date: 9 Apr 2007 16:10:51 -0700 Subject: Debugging multithreaded program using Eclipse/Pydev In-Reply-To: References: <1175887942.192837.187600@n76g2000hsh.googlegroups.com> Message-ID: <1176160251.545264.246230@w1g2000hsg.googlegroups.com> On Apr 7, 3:23 pm, Heikki Toivonen wrote: > John Henry wrote: > >>From what I can gather, it appears the only *real* option I have is to > > debug under Eclipse/Pydev. I did a google search of this newsgroup > > and didn't turn up too many hits. Before I invest the time to learn > > Eclipse/Pydev, I like to hear from somebody that have gone this path. > > Have you been successful in using Eclipse/Pydev to debug multi- > > threaded Python applications? Is so, what was the learning curve like > > to you? > > ActiveState Komodo can also do multithreaded debugging. > > And if all else fails, you can insert: > > import pdb > pdb.set_trace() > > in your code and that way you will break on any thread. > > Currently I am using pydev myself, having gone through WingIDE and Komodo. > > -- > Heikki Toivonen I ran the alpha version of Wing. So far, it appears to do a fine job in debugging multi-threaded applications. And yes, I fixed my bug within 5 minutes. From cam.ac.uk at mh391.invalid Wed Apr 25 17:57:39 2007 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Wed, 25 Apr 2007 22:57:39 +0100 Subject: sorting question In-Reply-To: References: Message-ID: belinda thom wrote: > Hi, > > I've had a look at http://wiki.python.org/moin/HowTo/Sorting, but am not > sure if I can get the operator.itemgetter to do what I want for my > particular need. I'm also not sure why creating my own cmp for pulling > tuple parts out and passing it to a list sort doesn't just work. > > I'm sure this stuff is old hat to many on this list. Suggestions happily > accepted. > > Suppose I've got a list like: > > l = [(-.3,(4,3)),(.2,(5,1)),(.10,(3,2))] > > and I want to sort on the 2nd item in the 2nd tuple. sorted(l, key=lambda item: item[1][1]) > I've tried things like: > > cmp = lambda x,y : x[1][1] > y[1][1] > l.sort(cmp=cmp) Don't call your comparison function cmp. There's already a built-in, which is what you should be using: l.sort(cmp=lambda x, y: cmp(x[1][1], y[1][1])) cmp returns -1, 0, or 1, but your function only returned 0 or 1. But using key is better, because the key function has to be run only once per item. The comparison has to be run for every comparison--which there can be many of if you are sorting a long list. > but l isn't then changed in place. > > Using > > sorted(l,operator.itemgetter(1)) > > behaves as I'd expect, but I really want something like > operator.itemgetter(1).itemgetter(1), which (understandably) causes a > syntax error. Unless you are doing something really weird, it should cause an AttributeError, not a SyntaxError. -- Michael Hoffman From mwilson at the-wire.com Fri Apr 6 11:30:57 2007 From: mwilson at the-wire.com (Mel Wilson) Date: Fri, 06 Apr 2007 11:30:57 -0400 Subject: [optparse] Problem with getting an option value In-Reply-To: References: Message-ID: Peter Otten wrote: > Lucas Malor wrote: > >> Hello all. I'm trying to do a little script. Simply I want to make a list >> of all options with them default values. If the option is not specified in >> the command line, the script must try to read it in a config.ini file. If >> it's not present also there, it must set the default value. >> >> The problem is I maked a simple list for this: >> >> optname = [ >> [ "delete", False ], >> [ "file", "file" ], >> [ "dir", "" ], >> >> But I must check that the option was specified in command line: >> >> (options, args) = parser.parse_args() >> for opt in optname : >> if not options.opt[0] : >> # read the options from config.ini >> >> The problem is options is an instance, so options."delete", for example, >> is wrong; I should pass options.delete . How can I do? > > Use getattr(): > > for name, default_value in optname: > if getattr(options, name) == default_value: > value = ... # read value from config file > setattr(options, name, value) > > Personally, I would always read the config file, use the values found there > to set up the parser and avoid such post-proc But then, if the command-line value == the default_value the program will try to get a value from the config file. If the config file overrides the defaults, then the command line can't re-override. Stuck with this, I usually initialize with None, then after all the option sources have been done, set anything that's still None to the default. It's not tidy. If even None could be a valid value, then a new None: class LikeNothingElse: '''Not a reasonable option value for anything''' # ... various code option_a = LikeNothingElse option_b = LikeNothingElse # ... process all the option sources if option_a == LikeNothingElse: option_a = None Mel. From kw at codebykevin.com Wed Apr 18 20:30:32 2007 From: kw at codebykevin.com (Kevin Walzer) Date: Wed, 18 Apr 2007 20:30:32 -0400 Subject: Future Python Gui? In-Reply-To: <1176941169.750013.216660@e65g2000hsc.googlegroups.com> References: <1176859699.906386.326720@b75g2000hsg.googlegroups.com> <1176923448.998078.170760@e65g2000hsc.googlegroups.com> <46267C84.8040505@codebykevin.com> <1176941169.750013.216660@e65g2000hsc.googlegroups.com> Message-ID: <4626B828.8070607@codebykevin.com> Since the Tkinter wiki is still down, here is the Tile wrapper I maintain: ####### ####November 2006: Posted by Kevin Walzer, kw at codebykevin.com. Based on Tile wrapper by Martin Franklin. This version updates the wrapper to reflect changes in Tile commands, and adds support for Tile-based frames (ttk::frame). Freely reusable. import Tkinter from Tkconstants import * class Style: def default(self, style, **kw): """Sets the default value of the specified option(s) in style""" pass def map_style(self, **kw): """Sets dynamic values of the specified option(s) in style. See "STATE MAPS", below.""" pass def layout(self, style, layoutSpec): """Define the widget layout for style style. See "LAYOUTS" below for the format of layoutSpec. If layoutSpec is omitted, return the layout specification for style style. """ pass def element_create(self, name, type, *args): """Creates a new element in the current theme of type type. The only built-in element type is image (see image(n)), although themes may define other element types (see Ttk_RegisterElementFactory). """ pass def element_names(self): """Returns a list of all elements defined in the current theme. """ pass def theme_create(self, name, parent=None, basedon=None): """Creates a new theme. It is an error if themeName already exists. If -parent is specified, the new theme will inherit styles, elements, and layouts from the parent theme basedon. If -settings is present, script is evaluated in the context of the new theme as per style theme settings. """ pass def theme_settings(self, name, script): """Temporarily sets the current theme to themeName, evaluate script, then restore the previous theme. Typically script simply defines styles and elements, though arbitrary Tcl code may appear. """ pass def theme_names(self): """Returns a list of the available themes. """ return self.tk.call("style", "theme", "names") def theme_use(self, theme): """Sets the current theme to themeName, and refreshes all widgets.""" return self.tk.call("style", "theme", "use", theme) class Widget(Tkinter.Widget, Style): def __init__(self, master, widgetName=None, cnf={}, kw={}, extra=()): if not widgetName: ## why you would ever want to create a Tile Widget is behond me! widgetName="ttk::widget" Tkinter.Widget.__init__(self, master, widgetName, cnf, kw) def instate(self, spec=None, script=None): """Test the widget's state. If script is not specified, returns 1 if the widget state matches statespec and 0 otherwise. If script is specified, equivalent to if {[pathName instate stateSpec]} script. """ return self.tk.call(self._w, "instate", spec, script) def state(self, spec=None): """Modify or inquire widget state. If stateSpec is present, sets the widget state: for each flag in stateSpec, sets the corresponding flag or clears it if prefixed by an exclamation point. Returns a new state spec indicating which flags were changed: ''set changes [pathName state spec] ; pathName state $changes'' will restore pathName to the original state. If stateSpec is not specified, returns a list of the currently-enabled state flags. """ return self.tk.call(self._w, "state", spec) class Button(Widget, Tkinter.Button): def __init__(self, master=None, cnf={}, **kw): Widget.__init__(self, master, "ttk::button", cnf, kw) ###add frame support here--KWs class Frame(Widget, Tkinter.Frame): def __init__(self, master=None, cnf={}, **kw): Widget.__init__(self, master, "ttk::frame", cnf, kw) class Checkbutton(Widget, Tkinter.Checkbutton): def __init__(self, master=None, cnf={}, **kw): Widget.__init__(self, master, "ttk::checkbutton", cnf, kw) class Combobox(Widget, Tkinter.Entry): def __init__(self, master=None, cnf={}, **kw): Widget.__init__(self, master, "ttk::combobox", cnf, kw) def current(self, index=None): """If index is supplied, sets the combobox value to the element at position newIndex in the list of -values. Otherwise, returns the index of the current value in the list of -values or -1 if the current value does not appear in the list. """ return self.tk.call(self._w, "current", index) class Entry(Widget, Tkinter.Entry): def __init__(self, master=None, cnf={}, **kw): Widget.__init__(self, master, "ttk::entry", cnf, kw) def validate(self): """Force revalidation, independent of the conditions specified by the -validate option. Returns 0 if the -validatecommand returns a false value, or 1 if it returns a true value or is not specified. """ return self.tk.call(self._w, "validate") class Label(Widget, Tkinter.Label): def __init__(self, master=None, cnf={}, **kw): Widget.__init__(self, master, "ttk::label", cnf, kw) ###add LabelFrame class here--KW class LabelFrame(Widget, Tkinter.Label): def __init__(self, master=None, cnf={}, **kw): Widget.__init__(self, master, "ttk::labelframe", cnf, kw) class Menubutton(Widget, Tkinter.Menubutton): def __init__(self, master=None, cnf={}, **kw): Widget.__init__(self, master, "ttk::menubutton", cnf, kw) class Notebook(Widget): def __init__(self, master=None, cnf={}, **kw): Widget.__init__(self, master, "ttk::notebook", cnf, kw) def add(self, child, cnf=(), **kw): """Adds a new tab to the notebook. When the tab is selected, the child window will be displayed. child must be a direct child of the notebook window. See TAB OPTIONS for the list of available options. """ return self.tk.call((self._w, "add", child) + self._options(cnf, kw)) def forget(self, index): """Removes the tab specified by index, unmaps and unmanages the associated child window. """ return self.tk.call(self._w, "forget", index) def index(self, index): """Returns the numeric index of the tab specified by index, or the total number of tabs if index is the string "end". """ return self.tk.call(self._w, "index") def select(self, index): """Selects the specified tab; the associated child pane will be displayed, and the previously-selected pane (if different) is unmapped. """ return self.tk.call(self._w, "select", index) def tab(self, index, **kw): """Query or modify the options of the specific tab. If no -option is specified, returns a dictionary of the tab option values. If one -option is specified, returns the value of tha t option. Otherwise, sets the -options to the corresponding values. See TAB OPTIONS for the available options. """ return self.tk.call((self._w, "tab", index) + self._options(kw)) def tabs(self): """Returns a list of all pane windows managed by the widget.""" return self.tk.call(self._w, "tabs") class Paned(Widget): """ WIDGET OPTIONS Name Database name Database class -orient orient Orient Specifies the orientation of the window. If vertical, subpanes are stacked top-to-bottom; if horizontal, subpanes are stacked left-to-right. PANE OPTIONS The following options may be specified for each pane: Name Database name Database class -weight weight Weight An integer specifying the relative stretchability of the pane. When the paned window is resized, the extra space is added or subracted to each pane proportionally to its -weight """ def __init__(self, master=None, cnf={}, **kw): Widget.__init__(self, master, "ttk::paned", cnf, kw) def add(self, subwindow, **kw): """Adds a new pane to the window. subwindow must be a direct child of the paned window pathname. See PANE OPTIONS for the list of available options. """ return self.tk.call((self._w, "add", subwindow) + self._options(kw)) def forget(self, pane): """Removes the specified subpane from the widget. pane is either an integer index or the name of a managed subwindow. """ self.tk.call(self._w, "forget", pane) def insert(self, pos, subwindow, **kw): """Inserts a pane at the specified position. pos is either the string end, an integer index, or the name of a managed subwindow. If subwindow is already managed by the paned window, moves it to the specified position. See PANE OPTIONS for the list of available options. """ return self.tk.call((self._w, "insert", pos, subwindow) + self._options(kw)) def pane(self, pane, **kw): """Query or modify the options of the specified pane, where pane is either an integer index or the name of a managed subwindow. If no -option is specified, returns a dictionary of the pane option values. If one -option is specified, returns the value of that option. Otherwise, sets the -options to the corresponding values. """ return self.tk.call((self._w, "pane", pane) + self._options(kw)) class Progressbar(Widget): def __init__(self, master=None, cnf={}, **kw): Widget.__init__(self, master, "ttk::progressbar", cnf, kw) def step(self, amount=1.0): """Increments the -value by amount. amount defaults to 1.0 if omitted. """ return self.tk.call(self._w, "step", amount) def start(self): self.tk.call("ttk::progressbar::start", self._w) def stop(self): self.tk.call("ttk::progressbar::stop", self._w) class Radiobutton(Widget, Tkinter.Radiobutton): def __init__(self, master=None, cnf={}, **kw): Widget.__init__(self, master, "ttk::radiobutton", cnf, kw) class Scrollbar(Widget, Tkinter.Scrollbar): def __init__(self, master=None, cnf={}, **kw): Widget.__init__(self, master, "ttk::scrollbar", cnf, kw) class Separator(Widget): def __init__(self, master=None, cnf={}, **kw): Widget.__init__(self, master, "ttk::separator", cnf, kw) class Treeview(Widget, Tkinter.Listbox): def __init__(self, master=None, cnf={}, **kw): Widget.__init__(self, master, 'ttk::treeview', cnf, kw) def children(self, item, newchildren=None): """If newchildren is not specified, returns the list of children belonging to item. If newchildren is specified, replaces item's child list with newchildren. Items in the old child list not present in the new child list are detached from the tree. None of the items in newchildren may be an ancestor of item. """ return self.tk.call(self._w, "children", item, newchildren) def column(self, column, **kw): """Query or modify the options for the specified column. If no options are specified, returns a dictionary of option/value pairs. If a single option is specified, returns the value of that option. Otherwise, the options are updated with the specified values. The following options may be set on each column: -id name The column name. This is a read-only option. For example, [$pathname column #n -id] returns the data column associated with data column #n. -anchor Specifies how the text in this column should be aligned with respect to the cell. One of n, ne, e, se, s, sw, w, nw, or center. -width w The width of the column in pixels. Default is something reasonable, probably 200 or so. """ pass def delete(self, items): """Deletes each of the items and all of their descendants. The root item may not be deleted. See also: detach. """ return self.tk.call(self._w, "delete", items) def detach(self, items): """Unlinks all of the specified items from the tree. The items and all of their descendants are still present and may be reinserted at another point in the tree but will not be displayed. The root item may not be detached. See also: delete. """ return self.tk.call(self._w, "detach", items) def exists(self, item): """Returns 1 if the specified item is present in the tree, 0 otherwise. """ return self.tk.call(self._w, "exists", item) def focus(self, item=None): """If item is specified, sets the focus item to item. Otherwise, returns the current focus item, or {} if there is none. """ return self.tk.call(self._w, "focus", item) def heading(self, column, **kw): """Query or modify the heading options for the specified column. Valid options are: -text text The text to display in the column heading. -image imageName Specifies an image to display to the right of the column heading. -command script A script to evaluate when the heading label is pressed. """ pass def identify(self, x, y): """Returns a description of the widget component under the point given by x and y. The return value is a list with one of the following forms: heading #n The column heading for display column #n. separator #n The border to the right of display column #n. cell itemid #n The data value for item itemid in display column #n. item itemid element The tree label for item itemid; element is one of text, image, or indicator, or another element name depending on the style. row itemid The y position is over the item but x does not identify any element or displayed data value. nothing The coordinates are not over any identifiable object. See COLUMN IDENTIFIERS for a discussion of display columns and data columns. """ pass def index(self, item): """Returns the integer index of item within its parent's list of children. """ pass def insert(self, parent, index, id=None, **kw): """Creates a new item. parent is the item ID of the parent item, or the empty string {} to create a new top-level item. index is an integer, or the value end, specifying where in the list of parent's children to insert the new item. If index is less than or equal to zero, the new node is inserted at the beginning; if index is greater than or equal to the current number of children, it is inserted at the end. If -id is specified, it is used as the item identifier; id must not already exist in the tree. Otherwise, a new unique identifier is generated. returns the item identifier of the newly created item. See ITEM OPTIONS for the list of available options. """ pass def item(item, **kw): """Query or modify the options for the specified item. If no -option is specified, returns a dictionary of option/value pairs. If a single -option is specified, returns the value of that option. Otherwise, the item's options are updated with the specified values. See ITEM OPTIONS for the list of available options. """ pass def move(self, item, parent, index): """Moves item to position index in parent's list of children. It is illegal to move an item under one of its descendants. If index is less than or equal to zero, item is moved to the beginning; if greater than or equal to the number of children, it's moved to the end. """ pass def next(self, item): """Returns the identifier of item's next sibling, or {} if item is the last child of its parent. """ pass def parent(self, item): """Returns the ID of the parent of item, or {} if item is at the top level of the hierarchy. """ pass def prev(self, item): """Returns the identifier of item's previous sibling, or {} if item is the first child of its parent. """ pass def selection(self): """Returns the list of selected items""" pass def selection_set(self, items): """items becomes the new selection. """ pass def selection_add(self, items): """Add items to the selection """ pass def selection_remove(self, items): """Remove items from the selection """ pass def selection_toggle(self, items): """Toggle the selection state of each item in items. """ pass def set(self, item, column, value=None): """If value is specified, sets the value of column column in item item, otherwise returns the current value. See COLUMN IDENTIFIERS. """ pass if __name__=="__main__": def callback(): print "Hello" root = Tkinter.Tk() root.tk.call("package", "require", "tile") f = Frame(root, width=150) f.pack(fill="both", expand="yes") b = Button(root, text="Tile Button", command=callback) b.pack() #~ c = Checkbutton(root) #~ c.pack() #~ print b.theme_names() #~ cb = Combobox(root) #~ cb.pack() #~ e = Entry(root) #~ e.validate() #~ e.pack() #~ l = Label(root, text="Tile Label") #~ l.pack() #~ mb = Menubutton(root) #~ mb.pack() #~ nb = Notebook(root) #~ f1 = Label(nb, text="page1") #~ nb.add(f1, text="Page1") #~ f1.pack() #~ f2 = Label(nb, text="page2") #~ nb.add(f2, text="Page 2") #~ f2.pack() #~ nb.pack() pb = Progressbar(root, mode="indeterminate") pb.pack() pb.start() b = Button(root, text="Start", command=pb.start) b.pack() b = Button(root, text="Stop", command=pb.stop) b.pack() #~ rb = Radiobutton(root) #~ rb.pack() #~ text = Tkinter.Text(root) #~ scrol = Scrollbar(root) #~ text.pack(side="left", fill="both", expand="yes") #~ scrol.pack(side="left", fill="y") #~ text['yscrollcommand'] = scrol.set #~ scrol['command'] = text.yview #~ l = Label(root, text="Label1") #~ l.pack() #~ s = Separator(root) #~ s.pack(fill="x") #~ l = Label(root, text="Label2") #~ l.pack() #b.theme_use("default") #~ b1 = Tkinter.Button(root, text="Tk Button", command=callback) #~ b1.pack() panes = Paned(root) panes.pack(fill="both", expand="yes") label1 = Label(panes, text="pane1") label2 = Label(panes, text="Pane2") panes.add(label1) panes.add(label2) #~ tree = Treeview(root, columns=("One", "Two", "Three")) #~ tree.insert(None, "end", text="Hello") #~ tree.pack() root.mainloop() From rich at example.net Tue Apr 24 13:02:43 2007 From: rich at example.net (Rich Grise) Date: Tue, 24 Apr 2007 17:02:43 GMT Subject: *** Dr G Polya BRILLIANTLY analyses the Virgina Shooting Incident *** References: <1177266754.126153.202760@b58g2000hsg.googlegroups.com> <1177287460.376404.323520@b58g2000hsg.googlegroups.com> <1177416547.394200.314950@r3g2000prh.googlegroups.com> <1177430456.620057.190820@n15g2000prd.googlegroups.com> Message-ID: On Tue, 24 Apr 2007 09:00:56 -0700, bill.sloman wrote: > On Apr 24, 2:09 pm, Quadibloc wrote: >> The Real Andy wrote: >> > Makes me wonder about the credibility of any statement Dr Gideon Polya >> > makes. >> . >> I never thought that I would feel the urge to call someone an >> edelweiss-eating Tanzanian devil, but Dr. Polya proved that I lacked >> imagination. >> >> (Note that "Tanzanian" is pronounced Tan.zan._ee_.yan, not >> Tan._zayn_.ee.an; one wouldn't want to spoil the effect.) > > The effect is - in fact - more severely damaged by your confusion > between Tasmania - where Dr. Polya actually lives - and Tanzania which > is a country in Africa with a name similar enough to confuse semi- > literate Americans. Tasmania is a reasonably large island (about the > same size as Ireland) a couple of hundred miles south of the > Australian mainland. It is a state of Australia (not Austria, which is > where you'd need to go for edelweiss). LOL! Thanks! Rich From gherron at islandtraining.com Wed Apr 18 18:48:38 2007 From: gherron at islandtraining.com (Gary Herron) Date: Wed, 18 Apr 2007 15:48:38 -0700 Subject: comparison with None In-Reply-To: <1176935680.707717.53490@y5g2000hsa.googlegroups.com> References: <3IqdnfRnCNWPC7vbnZ2dnUVZ_jqdnZ2d@rcn.net> <1176935680.707717.53490@y5g2000hsa.googlegroups.com> Message-ID: <4626A046.2010604@islandtraining.com> brzrkr0 at gmail.com wrote: > On Apr 18, 3:19 pm, Steven Howe wrote: > >> I've read and found that 'None' comparisons is not always a good idea. >> Better to: >> from types import NoneType >> >> x = None >> if type( x ) == NoneType: >> # true >> < code > >> else: >> # false; do something else. >> < more code > >> >> Steven Howe >> > > Is that any better than this? > > if x is None: > # do something > else: > # do something else > No. using if x is None: is the recommended way. Gary Herron From steve at holdenweb.com Sat Apr 21 10:44:21 2007 From: steve at holdenweb.com (Steve Holden) Date: Sat, 21 Apr 2007 10:44:21 -0400 Subject: Unexpected exception from socket.getaddrinfo on Unicode URL In-Reply-To: References: Message-ID: John Nagle wrote: > Here's a strange little bug. "socket.getaddrinfo" blows up > if given a bad domain name containing ".." in Unicode. The > same string in ASCII produces the correct "gaierror" exception. > > Actually, this deserves a documentation mention. The "socket" module, > given a Unicode string, calls the International Domain Name parser, > "idna.py", which has a a whole error system of its own. The IDNA > documentation says that "Furthermore, the socket module transparently converts > Unicode host names to ACE, so that applications need not be concerned about > converting host names themselves when they pass them to the socket module." > However, that's not quite true; the IDNA rules say that syntax errors must > be treated as errors, so you have to be prepared for IDNA exceptions. > They are all "UnicodeError" exceptions. > > It's worth a mention in the documentation for "socket". > > John Nagle > > D:\>/python25/python.exe > Python 2.5 (r25:51908, Sep 19 2006, 09:52:17) [MSC v.1310 32 bit (Intel)] on win > 32 > Type "help", "copyright", "credits" or "license" for more information. > >>> ss = 'www.gallery84..com' > >>> uss = unicode(ss) > >>> import socket > >>> socket.getaddrinfo(ss,"http") > Traceback (most recent call last): > File "", line 1, in > socket.gaierror: (11001, 'getaddrinfo failed') > >>> socket.getaddrinfo(uss,"http") > Traceback (most recent call last): > File "", line 1, in > File "D:\python25\lib\encodings\idna.py", line 164, in encode > result.append(ToASCII(label)) > File "D:\python25\lib\encodings\idna.py", line 73, in ToASCII > raise UnicodeError("label empty or too long") > UnicodeError: label empty or too long > >>> > I took a look at the documentation but couldn't see where to add what, given that the documentation for socket already says: """All errors raise exceptions. The normal exceptions for invalid argument types and out-of-memory conditions can be raised; errors related to socket or address semantics raise the error socket.error. """. Do we really need to specifically mention Unicode errors? 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 zhonghua.m.yang at gmail.com Tue Apr 3 01:32:04 2007 From: zhonghua.m.yang at gmail.com (ZMY) Date: 2 Apr 2007 22:32:04 -0700 Subject: Numeric compiling problem under QNX 4.25 Message-ID: <1175578324.426293.21970@y80g2000hsf.googlegroups.com> Dear all, I am a real newbie for both python and QNX, but I am still trying to compile Numeric-24.2 under QNX4.25 with python 2.2. I got following error message: $ sudo python setup.py install Password: running install ... building '_numpy' extension skipping Src/_numpymodule.c (build/temp.qnx-O-PCI-2.2/_numpymodule.o up-to-date) skipping Src/arrayobject.c (build/temp.qnx-O-PCI-2.2/arrayobject.o up- to-date) skipping Src/ufuncobject.c (build/temp.qnx-O-PCI-2.2/ufuncobject.o up- to-date) ld build/temp.qnx-O-PCI-2.2/_numpymodule.o build/temp.qnx-O-PCI-2.2/ arrayobject.o build/temp.qnx-O-PCI-2.2/ufuncobject.o -o build/lib.qnx- O-PCI-2.2/_numpy.so unable to execute ld: No such file or directory error: command 'ld' failed with exit status 1 I looked at directory /build/temp.qnx-O-PCI-2.2/ and found following object files: _numpymodule.o, arrayobject.o, ufuncobject.o So it looks that ld got all files before linking them - or is it?? Thanks a lot for any suggestions, - ZMY From robert.kern at gmail.com Tue Apr 3 13:30:13 2007 From: robert.kern at gmail.com (Robert Kern) Date: Tue, 03 Apr 2007 12:30:13 -0500 Subject: numpy performance and list comprehension In-Reply-To: <1175611372.971235.191280@d57g2000hsg.googlegroups.com> References: <1175611372.971235.191280@d57g2000hsg.googlegroups.com> Message-ID: TG wrote: > Hi there. > > Reading the page on python performance ( http://scipy.org/PerformancePython > ) made me realize that I can achieve tremendous code acceleration with > numpy just by using "u[:,:]" kind of syntax the clever way. > > Here is a little problem (Oja's rule of synaptic plasticity) > > * W is a matrix containing the weights of connections between elements > i > and j > * V is an array containing the values of elements > > I want to make W evolve with this rule : > > dW[i,j] / dt = alpha * (V[i] * V[j] - W[i,j] * V[i]^2) > > (don't pay attention to the derivate and stuff) > > So, how would you write it in this nifty clever way ? irstas is correct. I'm just going to show off another feature of numpy, numpy.newaxis. import numpy as np V = np.array([1, 2, 3]) VT = V[:, np.newaxis] # VT.shape == (3, 1) W = np.array([[1,2,3], [4,5,6], [7,8,9]]) dWdt = alpha * VT*(V - W*VT) -- 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 deets at nospam.web.de Tue Apr 17 04:16:49 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 17 Apr 2007 10:16:49 +0200 Subject: Compare regular expressions In-Reply-To: <1176758691.558817.295880@p77g2000hsh.googlegroups.com> References: <58hrabF2g9sfqU1@mid.uni-berlin.de> <1176758691.558817.295880@p77g2000hsh.googlegroups.com> Message-ID: <58je3lF2hg4r3U1@mid.uni-berlin.de> Adam Atlas schrieb: > On Apr 16, 1:50 pm, "Diez B. Roggisch" wrote: >> It's not. For the simplest of expressions one might come up with a >> relation between them, but even that would be hard. General case? No chance. > > I wouldn't say there's 'no chance'. It would require external parsing, > for sure, but if anything, it may only be impossible for unusual > cases. The external parsing of regular expressions is cheap. But once you are there, how do you proceed? That's where it becomes hard. I can think of some simple strategies, but nothing that can't be easily found a counter-example for. Diez From david at boddie.org.uk Fri Apr 20 21:15:00 2007 From: david at boddie.org.uk (David Boddie) Date: Sat, 21 Apr 2007 03:15:00 +0200 Subject: Beginner: Simple Output to a Dialog PyQt4 References: Message-ID: <1e3a4$46296596$54d1d767$7184@news.chello.no> On Tuesday 17 April 2007 07:42, Glen wrote: > I've written a script in python and put together a simple QFrame with a > QTextBrowser with Designer. I've translated the C++ into python using > puic4. Just to avoid any misunderstanding: the form is actually stored as XML. You can create C++ code with uic or Python code with pyuic4. > The .py file is called outputWin.py. My Script and its > functions are in cnt.py. OK. Ideally, your window will contain a button (or some other control) that the user can click to execute the functions. > Finally, my main is in pball.py which follows > here: > import sys > from PyQt4 import Qt, QtCore > from outputWin import * > from cnt import * > if __name__ == "__main__": > app = Qt.QApplication(sys.argv) > window = Qt.QDialog() > ui = Ui_Dialog() > ui.setupUi(window) > window.show() > app.exec_() > > I want to call my functions in cnt and have an output to my QDialog. Can > somebody give me a clue as to how to proceed? I can't find good an easy > tutorial for PyQt4 and I've never used Qt before. If, for example, you included a push button (QPushButton) in the form you created with Qt Designer, and called it executeButton, you could connect its clicked() signal to a function in cnt by including the following line after setting up the user interface: window.connect(ui.executeButton, SIGNAL("clicked()"), cnt.myFunction) This assumes that your function is called myFunction(), of course. However, you wouldn't be able to get the output from this function back to the dialog just by using a signal-slot connection like this. One way to solve this would be to wrap the function using another function or instance that is able to modify the contents of the dialog. Another cleaner approach would be to subclass the user interface class (Ui_Dialog) and implement a custom slot that can both call the function and modify the dialog. For example: class Dialog(QDialog, Ui_Dialog) def __init__(self, parent = None): QDialog.__init__(self, parent) self.setupUi(self) self.connect(self.executeButton, SIGNAL("clicked()"), self.callFunction) def callFunction(self): data = cnt.myFunction() # Do something with the data. Hope this gets you started, David From jsavard at ecn.ab.ca Tue Apr 24 08:09:07 2007 From: jsavard at ecn.ab.ca (Quadibloc) Date: 24 Apr 2007 05:09:07 -0700 Subject: *** Dr G Polya BRILLIANTLY analyses the Virgina Shooting Incident *** In-Reply-To: References: <1177266754.126153.202760@b58g2000hsg.googlegroups.com> <1177287460.376404.323520@b58g2000hsg.googlegroups.com> Message-ID: <1177416547.394200.314950@r3g2000prh.googlegroups.com> The Real Andy wrote: > Makes me wonder about the credibility of any statement Dr Gideon Polya > makes. . I never thought that I would feel the urge to call someone an edelweiss-eating Tanzanian devil, but Dr. Polya proved that I lacked imagination. (Note that "Tanzanian" is pronounced Tan.zan._ee_.yan, not Tan._zayn_.ee.an; one wouldn't want to spoil the effect.) John Savard From list.repository at gmail.com Tue Apr 24 16:57:57 2007 From: list.repository at gmail.com (list.repository at gmail.com) Date: 24 Apr 2007 13:57:57 -0700 Subject: os.system('tar -c * | tar -C dst') ##Any other suggestions... Message-ID: <1177448277.150142.146130@c18g2000prb.googlegroups.com> I'm getting the following error: tar: You must specify one of the `-Acdtrux' options Try `tar --help' or `tar --usage' for more information. tar: -: Cannot write: Broken pipe tar: Error is not recoverable: exiting now Any suggestions on a different approach or fix? -List From vito.detullio at gmail.com Sun Apr 15 14:13:51 2007 From: vito.detullio at gmail.com (ZeD) Date: Sun, 15 Apr 2007 18:13:51 GMT Subject: Standardizing XML References: <1176625793.392269.24060@n59g2000hsh.googlegroups.com> <462215bc$1@griseus.its.uu.se> <1176660139.990518.239470@l77g2000hsb.googlegroups.com> Message-ID: ZeeGeek wrote: > in the code returned by Live Space, they use
instead of
so > that Blogger will complain that this tag is not valid because it > doesn't have a closing tag. Another example is that the contents of a > lot of the tag attributes like "color" and "size" are not surrounded > by quotes. Are you sure it's xml? It sounds to me like "old" HTML -- Under construction From paul at boddie.org.uk Mon Apr 2 07:27:33 2007 From: paul at boddie.org.uk (Paul Boddie) Date: 2 Apr 2007 04:27:33 -0700 Subject: Shed Skin Python-to-C++ Compiler 0.0.21, Help needed In-Reply-To: <1175511923.323321.30220@n76g2000hsh.googlegroups.com> References: <576vhbF2ca1guU1@mid.individual.net> <1175376373.241744.6220@y80g2000hsf.googlegroups.com> <1175413310.295953.230840@e65g2000hsc.googlegroups.com> <1175455529.936887.249170@e65g2000hsc.googlegroups.com> <1175496721.899984.193690@n76g2000hsh.googlegroups.com> <1175509861.292455.226280@b75g2000hsg.googlegroups.com> <1175511923.323321.30220@n76g2000hsh.googlegroups.com> Message-ID: <1175513253.595204.220110@o5g2000hsb.googlegroups.com> On 2 Apr, 13:05, bearophileH... at lycos.com wrote: > > There is some possibility that Python 3.1 will have what you ask for:http://www.python.org/dev/peps/pep-3108/ Prior to that PEP being written/published, I made this proposal: http://wiki.python.org/moin/CodingProjectIdeas/StandardLibrary/RestructuredStandardLibrary After being brought to the attention of the PEP's author, it seems to have been swept under the carpet on the Wiki, but it's a more radical proposal in a number of ways than the PEP seems to be. Paul From NikitaTheSpider at gmail.com Fri Apr 20 11:51:30 2007 From: NikitaTheSpider at gmail.com (Nikita the Spider) Date: Fri, 20 Apr 2007 11:51:30 -0400 Subject: Domain Keys in Python References: Message-ID: In article , Andrew Veitch wrote: > I am trying to implement Domain Keys > (http://domainkeys.sourceforge.net/) in Python. > > In Perl I would just use Crypt:RSA which has a sign > method with an armour option which generates exactly > what I want but I can't find a way of doing this in > Python. > > I tried this: > > from M2Crypto import RSA > key = RSA.load_key('rsa.private') > msg='Hello world' > print key.sign(msg) > > But the output isn't quite right because there isn't > an armour option - I verified this by reading the > source. > > I'm not even sure if M2Crypto is the right library to > be using or is it just that I need to use something > else for the final step? Hi Andrew, There's also pycrypto for doing RSA encryption: http://www.amk.ca/python/code/crypto I messed around with this for a little while but decided I didn't need it. ISTR figuring out that it does not implement any padding; is this perhaps the armour option you're talking about? I'm not a cryptographer and I don't even play one on TV, so the accuracy of this is probably even less reliable than an average Usenet posting... Good luck -- Philip http://NikitaTheSpider.com/ Whole-site HTML validation, link checking and more From steve at holdenweb.com Tue Apr 10 09:57:00 2007 From: steve at holdenweb.com (Steve Holden) Date: Tue, 10 Apr 2007 09:57:00 -0400 Subject: tuples, index method, Python's design In-Reply-To: <1176200361.260546.280510@n76g2000hsh.googlegroups.com> References: <1175867771.114540.61810@n76g2000hsh.googlegroups.com> <1175884427.779950.267220@y80g2000hsf.googlegroups.com> <1175953520.316208.241490@o5g2000hsb.googlegroups.com> <7xzm5igbrb.fsf@ruckus.brouhaha.com> <1176200361.260546.280510@n76g2000hsh.googlegroups.com> Message-ID: Paul Boddie wrote: > On 10 Apr, 11:48, Antoon Pardon wrote: >> On 2007-04-10, Duncan Booth wrote: >> >>> There is a cost to every new language feature: it has to be implemented, >>> documented, maintained, and above all learned by the users. Good design >>> involves, in part, not adding to these burdens except where there is a >>> benefit at least equal to the cost. >> So what is the easiest to learn: "All sequences have an index method" or >> "Such and so sequences have an index method and others don't" > > I think this observation leads to insights both at the end-user level > and at the implementer level. Tuples and lists are sequences; the > index method can be defined generically for all sequences; adding such > a method to the tuple type can be done with barely any changes to the > implementation taken from the list type. This leads to the observation > that a generic index method (defined as a function in the > implementation) could be made to work with both lists and tuples, and > that various other methods might also be defined similarly, although > things like append, extend and other mutating methods wouldn't be > appropriate for a tuple. > A generic definition of index would be tricky, though, if you wanted to include strings as sequences. In that case you aren't testing for the presence of a single element but a sub-sequence - I think this change was introduced in 2.4 to allow checks like "men" in "three good men" to succeed where formerly only single characters could be checked for. One might perversely allow extension to lists and tuples to allow [3, 4] in [1, 2, 3, 4, 5, 6] to succeed, but that's forcing the use case beyond normal limits. The point I am trying to make is that circumstances alter cases, and that we can't always rely on our intuition to determine how specific methods work, let alone whether they are available. I hear the screams of "just add the index() method to tuples and have done with it" and, to an extent, can sympathize with them. But that way lies creeping featurism and the next thing you know we'll have a ternary operator in the language - oh wait, we do now! >> Which of the above is the easiest to document? >> >> Now with implementation and maintaining. If you would start with a class >> of sequence which classes like tuple and list would inherit from, then >> there also would be a single function to be implemented and maintained. >> It would just be usable in more types. > > There isn't a "big win" in this case: the intersection of useful > methods between mutable and immutable sequence types is rather small. > Nevertheless, providing a slightly deeper abstract class hierarchy > might be appropriate, and this is being considered for Python 3000. > > [...] > >> The same happened with the ternary operator. Every use case someone >> could come up with was rejected by rewriting the code without using >> a ternary operator. AFAICS the only reason the ternary operator >> finaly got introduced was because a python developer was bitten by an >> illusive bug, introduced by one of the idioms that was often used as a >> way to simulate a ternary operator. > > The ternary operator, whilst providing new and occasionally useful > functionality, is rather "badly phrased" in my opinion: when used, > it's a bit like reading one natural language and suddenly having the > grammar of another in use for the rest of the sentence. > Indeed the syntax is deliberately "crippled" - Guido's reasoning being, I believe, that if it were too easy and natural to use then people would use it inappropriately and too frequently. 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 iltchevi at gmail.com Mon Apr 16 16:39:19 2007 From: iltchevi at gmail.com (ici) Date: 16 Apr 2007 13:39:19 -0700 Subject: moving multiple directories In-Reply-To: <4623C22B.2000304@websafe.com> References: <1176740512.975411.158380@p77g2000hsh.googlegroups.com> <4623C22B.2000304@websafe.com> Message-ID: <1176755959.487705.248110@n59g2000hsh.googlegroups.com> On Apr 16, 9:36 pm, Larry Bates wrote: > DataSmash wrote: > > Hi, > > I need to organize thousands of directories full of files. > > I want to move these directories into other subdirectories. > > For example, all the directories that start with 01, move to > > a directory named "one", all directories that start with 02, move > > to a directory name "two", and so on.... > > > I can't seem to find any easy way to do this. > > Looks like shutil.move only lets you move if the subdirectory DOES > > NOT exist, so after the first directory moves, the script blows up on > > the second move. > > I guess you could use shutil.copy or shutil.copytree but then you have > > to > > delete as well. Much longer process when you have hundreds of > > gigabytes of data. > > > Thanks for your help! > > R.D. > > Use win32.moveFile method instead. This links directly to the Windows > MoveFile method that just moves the directory entries around. > > From Win32 Documentation: > > win32api.MoveFile > MoveFile(srcName, destName) > > Renames a file, or a directory (including its children). > > Parameters > > srcName : string > > The name of the source file. > > destName : string > > The name of the destination file. > > Comments > This method can not move files across volumes. > > -Larry Instead win32api, use "native" shutil module import shutil shutil.move(src,dest) Recursively move a file or directory to another location. From nagle at animats.com Tue Apr 24 12:48:25 2007 From: nagle at animats.com (John Nagle) Date: Tue, 24 Apr 2007 16:48:25 GMT Subject: Socket exceptions aren't in the standard exception hierarchy In-Reply-To: References: Message-ID: Steve Holden wrote: > John Nagle wrote: > [socket.error bug report] > >>> >>> Where did you get this information? If true it would certainly need >>> to be logged as a bug, but under Windows on 2,4 I see >>> >>> >>> issubclass(socket.gaierror, Exception) >>> True >>> >>> >>> >>> and the same under Cygwin 2.5. I am presuming most other users will >>> see the same thing. >>> >>> regards >>> Steve >> >> >> Ah. "socket.error" is a subclass of "Exception", but not >> of "StandardError". >> >> issubclass(socket.error,StandardError) >> >> is False. >> > Right, so this *is* a bug, as long as Brett Cannon's upcoming (further) > reorganization of the standard exception hierarchy doesn't stamp on it. > It probably *was* overlooked in the reorganization of the hierarchy, and > this implies there may be other extensions that also make the same error. > > It should be logged as a bug in the tracker - the fix is probably pretty > simple, but it'll need some consideration of the forward compatibility > considerations. > > regards > Steve The bug tracker shows quite a number of problems related to socket exceptions. Searching for "socket AND exception" returns 45 results. These seem to be the most relevant ones: [ 805194 ] Inappropriate error received using socket timeout [ 1019808 ] wrong socket error returned [ 1571878 ] Improvements to socket module exceptions [ 708927 ] socket timeouts produce wrong errors in win32 None of them quite cover this new issue, but it's clear that the area needs some work. Should this new issue be added as a new bug or as an added comment to one of the above? Just figuring out what exceptions can be raised from the socket module is tough. I've seen exceptions derived from "socket.error", exceptions from IOError, and exceptions from the SSL layer, which patches the sockets module when loaded. These are non-bug exceptions; that is, the problem is out in the network, external to the program. I'm still not sure I have all the possibilities covered. Retrying on unknown exceptions isn't the answer; that leads to exception loops if there's a program bug. The most important distinction with sockets is "external network problem" vs. "local program program". I'd like to see a "NetworkException" in the exception hierarchy, with all the things that can go wrong due to conditions external to the local machine under that exception. I'd suggest the following: 1. Add "NetworkError" under "IOError" in the exception hierarchy. 2. Put the existing "socket.error" under "NetworkError". Since "socket.error" needs to be reparented anyway (it's currently a direct descendant of "Exception") this provides a good place for it. 3. Find any places where the socket module can raise IOError or OSError due to an external network condition, and make them raise something under NetworkError instead. Code that catches IOError will still work. 4. Put all errors in the various SSL modules (SSLError, etc.) which can be raised due to external network conditions under "NetworkError". 5. Move "urllib2.URLError", which is currently under IOError, to be under NetworkError. 6. Move the misc. errors from "urllib", like "ContentTooShortError", which are currently under IOError, down a level under NetworkError. Then, programs that catch NetworkError could be sure of catching all network trouble conditions, but not local code bugs. John Nagle From bbxx789_05ss at yahoo.com Sat Apr 14 15:00:34 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: 14 Apr 2007 12:00:34 -0700 Subject: Really badly structured Python Books. In-Reply-To: <1176575848.526066.254520@y80g2000hsf.googlegroups.com> References: <1176575848.526066.254520@y80g2000hsf.googlegroups.com> Message-ID: <1176577234.860922.216800@l77g2000hsb.googlegroups.com> On Apr 14, 12:37 pm, "Andre P.S Duarte" wrote: > I started reading the beginning Python book. It is intended for people > who are starting out in the Python world. But it is really > complicated, because he tries to explain, then after a bad explanation > he puts out a bad example. I really recommend NOT reading the book. > For it will make you want not to continue in Python. This is just me > letting the air out of my lungs. No need to reply this is just a > recommendation. Txs for the opportunity . There are several beginning python books. You might want to be a little more explicit about the book you are talking about. What is the title? From bearophileHUGS at lycos.com Tue Apr 10 13:15:06 2007 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 10 Apr 2007 10:15:06 -0700 Subject: tuples, index method, Python's design In-Reply-To: References: <1175953520.316208.241490@o5g2000hsb.googlegroups.com> <7xzm5igbrb.fsf@ruckus.brouhaha.com> <1176200361.260546.280510@n76g2000hsh.googlegroups.com> Message-ID: <1176225306.161212.90830@o5g2000hsb.googlegroups.com> BJ?rn Lindqvist: > > One might perversely allow extension to lists and tuples to allow > > [3, 4] in [1, 2, 3, 4, 5, 6] > > to succeed, but that's forcing the use case beyond normal limits. The > > point I am trying to make is that circumstances alter cases, and that we > > can't always rely on our intuition to determine how specific methods > > work, let alone whether they are available. > > I'd love to have that! There are at least one million use cases for > finding a sequence in a sequence and implementing it yourself is > non-trivial. Plus then both list and tuple's index methods would work > *exactly* like string's. It would be easier to document and more > useful. A big win. Sublist search (and generally adding a bit of pattern matching features to Python) looks far from being perverse, it may even become pythonic ;-) Bye, bearophile From rupole at hotmail.com Mon Apr 30 16:04:18 2007 From: rupole at hotmail.com (Roger Upole) Date: Mon, 30 Apr 2007 16:04:18 -0400 Subject: Python-URL! - weekly Python news and links (Apr 30) References: Message-ID: <1177963548_23061@sp12lax.superfeed.net> Cameron Laird wrote: > QOTW: "That is just as feasible as passing a cruise ship through a phone > line." - Carsten Haese, on transporting a COM object across a network. > Less vividly but more formally, as he notes, "A COM object represents a > connection to a service or executable that is running on one computer. > Transferring that connection to another computer is impossible." > While this is indeed a nice turn of phrase, in substance it's incorrect. You can marshal a live COM object and unmarshal it on a different machine. Roger ----== 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 gagsl-py2 at yahoo.com.ar Fri Apr 20 16:36:13 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 20 Apr 2007 17:36:13 -0300 Subject: service for file monitoring References: <1177099611.498274.323180@y5g2000hsa.googlegroups.com> Message-ID: En Fri, 20 Apr 2007 17:06:51 -0300, rohit escribi?: > i am designing a desktop search engine using python. > i am having a query , is there a package available that contains > functions for retrieving the files being edited , created,deleted in > the file system. For windows you can use the techniques described here: http://tgolden.sc.sabren.com/python/win32_how_do_i/watch_directory_for_changes.html -- Gabriel Genellina From mail at timgolden.me.uk Mon Apr 16 11:10:48 2007 From: mail at timgolden.me.uk (Tim Golden) Date: Mon, 16 Apr 2007 16:10:48 +0100 Subject: Writing Log CSV (Efficiently) In-Reply-To: <003601c78037$879b5890$96d209b0$@rawlins@thinkbluemedia.co.uk> References: <7554276584215132819@unknownmsgid> <6e42ec490704160700i20469453j6af39db62dd6b427@mail.gmail.com> <17955.33861.211843.361355@montanaro.dyndns.org> <002a01c78032$27190620$754b1260$@rawlins@thinkbluemedia.co.uk> <46238800.1000302@timgolden.me.uk> <003601c78037$879b5890$96d209b0$@rawlins@thinkbluemedia.co.uk> Message-ID: <462391F8.3000303@timgolden.me.uk> Robert Rawlins - Think Blue wrote: > Thanks for that Tim, > > I could use a little more help with this CSV stuff this afternoon and I > can't get it to write the output I want for the life of me. I'm trying to > write a method for my logging class that receives a string as an argument, > and then writes a row to the CSV with the string and a date/time stamp. > > ''' Add Application Log Entry ''' > def addApp(self, event): > writer = csv.writer(open("some.csv", "a")) > writer.writerow(event) > > Now if I do something like this; addApp('Application Started') then it > writes to the CSV file somthing like. > > A,p,p,l,i,c,a,t,i,o,n, ,S,t,a,r,t,e,d > > Which isn't much use to me :-D any ideas how I can get something like this: > > 2007-01-01,13:00:00,Application Started The writer.writerow method expects an iterable of some sort. Usually you give it a list or a tuple (perhaps of length one). You've given it a string, which it can happily iterate over. Try: for c in "Application Started": print c If you just want to print the string, pass it in as the only element of a list or tuple: writer.writerow ([event]) If you want to add a timestamp or whatever, then make a list/tuple of both. (Tries to avoid restarting The Great Tuple War (tm)): import datetime . . . now = datetime.datetime.now () writer.writerow ([event, str (now)]) TJG From bdesth.quelquechose at free.quelquepart.fr Fri Apr 13 18:52:46 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sat, 14 Apr 2007 00:52:46 +0200 Subject: help In-Reply-To: <461fea2b$0$17973$426a74cc@news.free.fr> References: <461fea2b$0$17973$426a74cc@news.free.fr> Message-ID: <4620008a$0$22999$426a74cc@news.free.fr> Bruno Desthuilliers a ?crit : > pierre-yves guido a ?crit : > >> hello (I hope my english is not so bad), > > > De ce point de vue l?, ?a peut aller... > Oh, yes, while we're at it, I forgot to mention: there's also a french Python newsgroup, fr.comp.lang.python. It's far from being as active as this one[1][2], but it's as friendly and tries very hard to be as helpful !-) [1] this can be seen positive too - at least your posts won't go unnoticed !-) [2] anyway, very few newsgroups are as active (abd friendly and helpful) as c.l.py From jeremy+complangpython at jeremysanders.net Mon Apr 9 08:33:57 2007 From: jeremy+complangpython at jeremysanders.net (Jeremy Sanders) Date: Mon, 09 Apr 2007 13:33:57 +0100 Subject: Console UI References: <1175994720.819372.232380@o5g2000hsb.googlegroups.com> Message-ID: Clement wrote: > My project is based on console Application. Is there any console UI > except urwid. If so, can i come to know. You might try pytvision, http://pytvision.sourceforge.net/ , which are python bindings for a of the old borland turbovision environment (see http://tvision.sourceforge.net/ ). I haven't used these, but I fondly remember turbovision from my Turbo Pascal/Turbo C++ days. I think it is still a good text based GUI. Jeremy -- Jeremy Sanders http://www.jeremysanders.net/ From gagsl-py2 at yahoo.com.ar Tue Apr 10 08:03:09 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 10 Apr 2007 09:03:09 -0300 Subject: setup() and C extensions References: <1176184942.119878.230850@p77g2000hsh.googlegroups.com> <1176186934.996315.142040@w1g2000hsg.googlegroups.com> Message-ID: En Tue, 10 Apr 2007 03:35:35 -0300, 7stud escribi?: > 1) When you create a C array to map python names to the C functions > that you defined: > > static PyMethodDef MyFunctions[] = > { > {"my_calc", (PyCFunction)my_func, METH_VARARGS, "my very speedy c > function"}, > {NULL, NULL, 0, NULL} > }; > > Why do you need to cast my_func to PyCFunction? Because it does not *have* to be a PyCFunction; the ml_flags field is used to indicate exactly what kind of function it is (METH_KEYWORDS indicating a PyCFunctionWithKeywords, by example). But the C struct declaration (PyMethodDef) has a fixed type. See http://docs.python.org/api/common-structs.html > 2) When returning None, why use the idiom: > > Py_INCREF(Py_None); > return Py_None; > > instead of: > > return Py_BuildValue(""); Because it's a lot faster and clear? -- Gabriel Genellina From b83503104 at yahoo.com Tue Apr 3 16:50:35 2007 From: b83503104 at yahoo.com (bahoo) Date: 3 Apr 2007 13:50:35 -0700 Subject: Need help on reading line from file into list In-Reply-To: <4612b8f2$0$28546$426a74cc@news.free.fr> References: <1175630106.220186.107900@y66g2000hsf.googlegroups.com> <4612b8f2$0$28546$426a74cc@news.free.fr> Message-ID: <1175633434.823351.69800@q75g2000hsh.googlegroups.com> On Apr 3, 5:06 pm, Bruno Desthuilliers wrote: > bahoo a ?crit : > > > Hi, > > > I have a text file containing a single line of text, such as > > 0024 > > > How should I read it into a "list"? > > You mean ['0024'], or ['0', '0', '2', '4'] ? > > > I tried this, but the "join" did not work as expected. > > What did you expect ? > > help(str.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. > > > Any > > suggestions? > > Honestly, the first would be to learn to ask questions, and the second > to pay more attention to what's written in the doc. But let's try : > > > infile = open('my_file.txt','r') > > for line in infile: > > line.join(line) > > my_list.extend( line ) > > If you have a single line of text, you don't need to iterate. > > file has a readlines() method that will return a list of all lines. It > also has a read() method that reads the whole content. Notice that none > of these methods will strip newlines characters. > > Also, str has a strip() method that - by default - strip out any > 'whitespace' characters - which includes newline characters. And > finally, passing a string as an argument to list's constructor gives you > a list of the characters in the string. > > This is all you need to know to solve your problem - or at least the two > possible definitions of it I mentionned above. > > >>> open('source.txt').readlines() > ['0024\n'] > >>> map(str.strip, open('source.txt').readlines()) > ['0024'] > >>> open('source.txt').read() > '0024\n' > >>> list(open('source.txt').read().strip()) > ['0', '0', '2', '4'] > >>> Thanks, this helped a lot. I am now using the suggested map(str.strip, open('source.txt').readlines()) However, I am a C programmer, and I have a bit difficulty understanding the syntax. I don't see where the "str" came from, so perhaps the output of "open('source.txt').readlines()" is defaulted to "str? Thanks! From duncan.booth at invalid.invalid Sat Apr 14 08:06:36 2007 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 14 Apr 2007 12:06:36 GMT Subject: Python Feature Request: Add the "using" keyword which works like "with" in Visual Basic References: <1176547372.584539.89170@q75g2000hsh.googlegroups.com> Message-ID: James Stroud wrote: > I like this one for some reason. Just the "using self" would save > hella typing in a lot of classes. I would favor a convention with > leading dots to disambiguate from other variables. This wouldn't > conflict with, say, floats, because variable names can't begin with a > number. I can't see how it is going to save you any typing over what you can already do. The suggested example: self.setFixedSize(200, 120) self.quit = QtGui.QPushButton("Quit", self) self.quit.setGeometry(62, 40, 75, 30) self.quit.setFont(QtGui.QFont("Times", 18, QtGui.QFont.Bold)) self.connect(self.quit, QtCore.SIGNAL("clicked()"), QtGui.qApp, QtCore.SLOT("quit()")) (259 characters including newlines but not leading indents). would become: using self: .setFixedSize(200,120) .quit = QtGui.QPushButton("Quit", self) using quit: .setGeometry(62, 40, 75, 30) .setFont(QtGui.QFont("Times", 18, QtGui.QFont.Bold)) .connect(self.quit, QtCore.SIGNAL("clicked()"), QtGui.qApp, QtCore.SLOT("quit()")) (251 characters including newlines but not leading indents). If you are going to reference self.quit a lot of times then it makes sense to also assign it to a local variable and then you already get even fewer characters (239): self.setFixedSize(200, 120) q = self.quit = QtGui.QPushButton("Quit", self) q.setGeometry(62, 40, 75, 30) f = QtGui.QFont q.setFont(f("Times", 18, f.Bold)) self.connect(q, QtCore.SIGNAL("clicked()"), QtGui.qApp, QtCore.SLOT("quit()")) Assigning 's=self' would save even more typing, but there are limits to how unreadable you want it. Using local variables also means you don't have any ambiguity and can use a variety of such shorthands interchangeably (e.g. q and f above). From admin at loial.co.uk Fri Apr 20 07:38:13 2007 From: admin at loial.co.uk (loial) Date: 20 Apr 2007 04:38:13 -0700 Subject: Problems with os.rename Message-ID: <1177069093.003491.194840@b75g2000hsg.googlegroups.com> I am having problems with os.rename on AIX The source file definately exists and the target file does not. However the rename always generates an OSerror exception. I can do the rename via a mv statement at the AIX command line with no problem. How can I get more info what the cause of the OSError exception is? N.B. The source file is created by a process run via subprocess e.g. from subprocess import Popen, PIPE, STDOUT p = Popen(self.command, stdout=PIPE, stderr=STDOUT, shell=True) return p.wait() Could this be the issue? From kyosohma at gmail.com Tue Apr 3 14:49:24 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: 3 Apr 2007 11:49:24 -0700 Subject: how to remove multiple occurrences of a string within a list? In-Reply-To: <1175625098.269660.184790@o5g2000hsb.googlegroups.com> References: <1175624433.206953.214290@n59g2000hsh.googlegroups.com> <1175625098.269660.184790@o5g2000hsb.googlegroups.com> Message-ID: <1175626164.428718.267670@w1g2000hsg.googlegroups.com> On Apr 3, 1:31 pm, "Matimus" wrote: > It depends on your application, but a 'set' might really be what you > want, as opposed to a list. > > >>> s = set(["0024","haha","0024"]) > >>> s > > set(["0024","haha"])>>> s.remove("0024") > >>> s > > set(["haha"]) If you want, you can also loop over the list, like so: counter = 0 your_list = ["0024","haha","0024"] for i in your_list: if i == '0024': your_list.pop(counter) counter += 1 Mike From michael at jedimindworks.com Sat Apr 14 05:50:26 2007 From: michael at jedimindworks.com (Michael Bentley) Date: Sat, 14 Apr 2007 04:50:26 -0500 Subject: Double backslash in filepaths ? In-Reply-To: <700ec$46209de2$d443bb3a$21603@news.speedlinq.nl> References: <700ec$46209de2$d443bb3a$21603@news.speedlinq.nl> Message-ID: <19C70B61-4F19-4F6E-8795-0FF46852928D@jedimindworks.com> On Apr 14, 2007, at 4:26 AM, Stef Mientki wrote: > It looks like sometimes a single backslash is replaced by a double > backslash, > but sometimes it's not ??? > See the error message below, > the first backslash is somewhere (not explicitly in my code) replaced, > but the second is not ??? > Is it in general better to use double backslash in filepaths ? > > thanks, > Stef Mientki > > >>>> Write_Signal_File_Ext (IOO, fSamp, 'D:\data_to_test >>>> \test_global.pd') > Traceback (most recent call last): > File "", line 21, in ? > File "D:\data_to_test\Signal_WorkBench.py", line 118, in > Write_Signal_File_Ext > DataFile.Write_Data (Data) > File "D:\data_to_test\Signal_WorkBench.py", line 95, in > Write_Data > self.Write_Header(Nchan) > File "D:\data_to_test\Signal_WorkBench.py", line 83, in > Write_Header > self.datafile = open(self.filename,'wb') > IOError: [Errno 2] No such file or directory: 'D:\\data_to_test > \test_global.pd' If I remember correctly, you don't really have to use backslashes at all. I think that's just a holdover from when DOS filesystems first became hierarchical -- and they had already used the sensible directory delimiter '/' as a command line switch character. So I think you can just substitute forward slashes and forget that double- backslash madness. But that's not really answering your question, is it? What you're looking for is called 'escape characters'. The single backslash combines with the 't' to become a TAB character. The double backslashes combine to become '\'. So: >>> print 'D:\\data_to_test\test_global.pd' D:\data_to_test est_global.pd hth, Michael From robert.kern at gmail.com Tue Apr 3 13:21:44 2007 From: robert.kern at gmail.com (Robert Kern) Date: Tue, 03 Apr 2007 12:21:44 -0500 Subject: Numeric compiling problem under QNX 4.25 In-Reply-To: <1175598705.298670.39960@b75g2000hsg.googlegroups.com> References: <1175578324.426293.21970@y80g2000hsf.googlegroups.com> <1175598705.298670.39960@b75g2000hsg.googlegroups.com> Message-ID: bernhard.voigt at gmail.com wrote: > Hi, > > unfortunately I don't have a solution. However, if you're not forced > to use Python2.2 and Numeric you should use Numpy (the successor for > both, Numeric and Numarray). Numpy requires Python2.3, though. He's already asked about numpy. He is stuck with 2.2. -- 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 i3dmaster at gmail.com Wed Apr 11 00:51:13 2007 From: i3dmaster at gmail.com (i3dmaster) Date: 10 Apr 2007 21:51:13 -0700 Subject: Universal Feed Parser issue In-Reply-To: References: <1176227922.910993.36910@y80g2000hsf.googlegroups.com> Message-ID: <1176267073.787216.80170@n76g2000hsh.googlegroups.com> On Apr 10, 6:45 pm, "Gabriel Genellina" wrote: > En Tue, 10 Apr 2007 14:58:42 -0300, i3dmaster > escribi?: > > > I have a sample Atom feed like this: > > > > > ... > > > > > > > > > After parsed by feedparser, the timezone element does not get the > > attribute "America/Mountain". Same thing on status element. This does > > not sound an expected result. I am wondering if it should be > > considered a bug... > > Usually it's a good idea to read the documentation... http://www.feedparser.org/docs/namespace-handling.html > > -- > Gabriel Genellina I did. Perhaps its because of not 100% atom compatible of my feed format? See if I use gnosis xml utility to parse it, it works fine though... From saif.shakeel at gmail.com Tue Apr 24 04:10:42 2007 From: saif.shakeel at gmail.com (saif.shakeel at gmail.com) Date: 24 Apr 2007 01:10:42 -0700 Subject: I/O Error Message-ID: <1177402242.614113.289570@r30g2000prh.googlegroups.com> Hi, I am using File I/O to input an xml file form user and parse it.I have used something like this: file_input = raw_input("Enter The ODX File Path:") odx_file_output = raw_input("Enter the output file path : ") log_file_output = raw_input("Enter the path for LogFile : ") saveout = sys.stdout try: f_open=open(odx_file_output, 'w') except: print "cant open file" sys.exit() sys.stdout = f_open try: input_xml = open(file_input,'r') except: print "The File Cannot Be Opened" sys.exit() if input_xml.read(5)!=' file_input = raw_input("Enter The ODX File Path:") ValueError: I/O operation on closed file any idea what should be modified. Thx From horpner at yahoo.com Thu Apr 26 14:05:45 2007 From: horpner at yahoo.com (Neil Cerutti) Date: 26 Apr 2007 20:05:45 +0200 Subject: My python annoyances so far References: <1177541453.471959.120830@c18g2000prb.googlegroups.com> <59bf34F2k27v5U1@mid.individual.net> <1177603623.774892.230390@t38g2000prd.googlegroups.com> Message-ID: On 2007-04-26, Steven Howe wrote: > flifus at gmail.com wrote: >>> Well, why do some things in the library have to be functions, >>> and other things have to be class methods? > > Perhaps because some things are more naturally function like? > For 'instance' (pardon the pun), functions shouldn't retain > data. They perform an operation, return data and quit. While > retaining data is a feature of an class/instance. Functions do retain data. Classes and instances are just a convenient notation. ;) >>> def funmaker(f, x): ... return lambda: f(x) ... >>> d = funmaker(int, 10) >>> d() 10 In addition, all functions in Python have data members, too. >>> d.label = "d" >>> d.label 'd' Python's scoping rules make certain kinds of functional idioms hard to use, though. I'm not sure how to get the following to work in Python using functions: >>> def account(s): ... b = s ... def add(a): ... b += a ... def balance(): ... return b ... return add, balance ... >>> add, balance = account(100) >>> balance() 100 >>> add(5) Traceback (most recent call last): File "", line 1, in ? File "", line 4, in add UnboundLocalError: local variable 'b' referenced before assignment Anyhow, it doesn't work, but you can see how closely it resembles a class definition. > And before someone get's all technical, I know everything in > Python is an 'object' even None, which implies class, or is it > the other way around? Classes are just objects like everything else. -- Neil Cerutti Bach's death is attributed to the end of the Baroque era. --Music Lit Essay From kyosohma at gmail.com Thu Apr 19 09:09:33 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: 19 Apr 2007 06:09:33 -0700 Subject: using tkinter to display html In-Reply-To: References: Message-ID: <1176988173.015892.273660@e65g2000hsc.googlegroups.com> On Apr 19, 6:29 am, "Stephen M. Gava" wrote: > Hi all, > > I prefer using tkinter to wxpython (so sue me :) and i need to display a > lot of html in a particular app. does anyone know if one of the existing > add on tk html widgets have been wrapped for tkinter already? > > TIA for any reply, > Stephen The following thread has various ideas in it: http://mail.python.org/pipermail/python-list/2001-October/107989.html I know wxpython has widgets specifically made to display html or even wrap Internet Explorer, ActiveX and more. Good luck! Mike From martin at v.loewis.de Sun Apr 8 23:21:08 2007 From: martin at v.loewis.de (=?UTF-8?B?Ik1hcnRpbiB2LiBMw7Z3aXMi?=) Date: Mon, 09 Apr 2007 05:21:08 +0200 Subject: Unicode problem In-Reply-To: References: <1175975209.261304.183220@p77g2000hsh.googlegroups.com> Message-ID: <4619B124.6040707@v.loewis.de> > Thanks! That's a nice little stumbling block for a newbie like me ;) Is > there a way to make utf-8 the default encoding for every string, so that > I do not have to encode each string explicitly? You can make sys.stdout encode each string with UTF-8, with sys.stdout = codecs.getwriter('utf-8')(sys.stdout) Make sure that you then that *all* strings that you print are Unicode strings. HTH, Martin From nyamatongwe+thunder at gmail.com Fri Apr 27 17:54:35 2007 From: nyamatongwe+thunder at gmail.com (Neil Hodgson) Date: Fri, 27 Apr 2007 21:54:35 GMT Subject: use urllib library to have an upload status bar In-Reply-To: <1177688613.085156.116170@o40g2000prh.googlegroups.com> References: <1177688613.085156.116170@o40g2000prh.googlegroups.com> Message-ID: shirish: > We have a bug-reporting system in ubuntu called apport. Apparently > apport uses a python library called urllib. As of now, apport does a > bouncing bar while uploading which doesn't give the user idea as to > how much is being uploaded. Here is a Python project that has implemented an upload progress bar: http://www.opensky.ca/~jdhildeb/software/kodakloader/ Neil From wangday at gmail.com Mon Apr 16 06:03:40 2007 From: wangday at gmail.com (lancered) Date: 16 Apr 2007 03:03:40 -0700 Subject: newbie question: how to read back the dictionary from a file? Message-ID: <1176717819.937015.9890@y80g2000hsf.googlegroups.com> Hi Dear all, I have some data here in the form of a dictionary, called "vdic". Then I write them to a data file "f" using the write function as f.write(str(vdic)). The keys of this dictionary are integers and values are float numbers. Something like this: { 1: 0.00951486513347, 2: 0.0388123556019, ... ...} Now, I want to read these data back in another function. Of course, I could parse the string little by little, e.g, first read a "{", then loop read a int, then read a ":", then a float etc etc... Since it is written out with standard python builtin functions, I guess there may be some more direct method than this, say a function in some modules? Could someone give me a hint? From carles at pina.cat Fri Apr 20 08:07:50 2007 From: carles at pina.cat (Carles Pina i Estany) Date: Fri, 20 Apr 2007 14:07:50 +0200 Subject: mysqldb execute timeout Message-ID: <20070420120750.GA1973@pinux.info> Hello, I need to implement timeout for execute method in Mysql queries. I am using MySQLdb. I have tried it: signal.signal(signal.SIGALRM,handler) signal.alarm(1) cursor.execute(sql) signal.alarm(0) But handler is never executed. In other example (changing cursor.execute by time.sleep(5)) it is executed. Maybe execute disables signals? In Perl it is disabled b ut there is a way to use. I found it: http://mail.python.org/pipermail/tutor/2002-July/015343.html And: http://www.timo-tasi.org/python/timeoutsocket.py I prefer to use alarm method (more clear, less instrusive, I only need it) Any way how to do? I will read now tmieoutsocket.py to learn some way, but they are not using signals or alarms. Thank you very much, -- Carles Pina i Estany GPG id: 0x8CBDAE64 http://pinux.info From http Wed Apr 11 00:23:28 2007 From: http (Paul Rubin) Date: 10 Apr 2007 21:23:28 -0700 Subject: tuples, index method, Python's design References: <1175867771.114540.61810@n76g2000hsh.googlegroups.com> <1175884427.779950.267220@y80g2000hsf.googlegroups.com> <1176210960.3430.20.camel@dot.uniqsys.com> <740c3aec0704100810g5f962e8eu614fbaedecf3608e@mail.gmail.com> Message-ID: <7xirc3czen.fsf@ruckus.brouhaha.com> Carsten Haese writes: > You have a point. Here is my revised solution: > > assert current_player in p > opponents = tuple(x for x in p if x is not current_player) Still wrong on two counts. First, assert is a no-op if optimization is turned on. Second, your version returns a different result from the original if current_player occurs in p more than once. From bearophileHUGS at lycos.com Fri Apr 6 15:15:52 2007 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 6 Apr 2007 12:15:52 -0700 Subject: Picture resolution and PIL In-Reply-To: <1175883388.743729.111850@o5g2000hsb.googlegroups.com> References: <1175883388.743729.111850@o5g2000hsb.googlegroups.com> Message-ID: <1175886952.047503.19390@w1g2000hsg.googlegroups.com> Johny: > Is it possible to find out a picture resolution by using PIL package By Gian Mario Tagliaretti: import PIL.Image a = PIL.Image.open("foo.jpg") a.info["dpi"] (72, 72) (It may raise an exception if that information isn't available) I don't know if that can be used to read the DPI tag inside a TIFF image. You can also read the pixel size of any image. Bye, bearophile From steve at holdenweb.com Wed Apr 25 09:54:06 2007 From: steve at holdenweb.com (Steve Holden) Date: Wed, 25 Apr 2007 09:54:06 -0400 Subject: Tutorial creates confusion about slices In-Reply-To: References: <1177496078.319400.324720@r30g2000prh.googlegroups.com> Message-ID: Antoon Pardon wrote: > On 2007-04-25, Ant wrote: >> On Apr 23, 1:38 pm, Antoon Pardon wrote: >>> The following is part of the explanation on slices in the >>> tutorial: >>> >>> The best way to remember how slices work is to think of the indices as >> ... >>> +---+---+---+---+---+ >>> | H | e | l | p | A | >>> +---+---+---+---+---+ >>> 0 1 2 3 4 5 >>> -5 -4 -3 -2 -1 >> For a tutorial this is sound advice. A tutorial is designed to give >> readers an easy intro to a topic, which is what this achieves. At this >> stage the target audience has no idea that extended slices even exist, >> let alone that you can use negative indices with them. > > OK. But eventually they will come into contact with negative indexes. > If they still rely on the above representation for understanding slices > that may cause confusions. It is possible that the time lost in clearing > up these later confusions will be bigger than the time gained by using > this simplification in the tutorial. > > So I'm not so sure it is sound advice in this case. > > If the consensus is that something like this should remain, I would > suggest replacing: > > "The best way to remember how slices work is" > > with: > > "A way to remember how slices work, it is not entirly correct > but may be usefull, is" > > Or something similar. > > > Wording to that effect makes it more clear that it is a crutch > that can be usefull now but that it should be discarded later. > Most people reading a tutorial are aware that they are being given the knowledge they need to put the subject matter to immediate use, and that there may well be refinements that are glossed over or covered in detail later or elsewhere. I don't believe this needs to be made explicit wherever it applies. regards Steve -- Steve Holden +1 571 484 6266 +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 bj_666 at gmx.net Tue Apr 3 05:33:16 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Tue, 03 Apr 2007 11:33:16 +0200 Subject: Parsing Problems References: <1175591597.120154.240820@q75g2000hsh.googlegroups.com> Message-ID: In <1175591597.120154.240820 at q75g2000hsh.googlegroups.com>, saif.shakeel wrote: > I have just started learning python.I need to parse an XML file > and present the contents in a particular format.The format is called > as "ini" file.I have written some code.A section of the format needs > the data to be present in format as given below: > > [Services] > supported=0x10,0x1A,0x3B,0x20,0x27,0x28,0x34,0x36,0x3E,0xA2,0xA5,0x2D, > 0x22,0xA9,0x04,0xAA,0xAE > > My code for this section parses the xml file and gives : > [Services] > Supported=['0x3e', '0x28', '0x3b', '0x22', '0x20', '0x27', '0xaa', > '0x10', '0xae', '0x34', '0x36', '0x2d', '0xa9', '0xa5', '0x4', '0xa2', > '0x1a'] > > {forget the numericals matching}.As you can see there > are single quotes around numericals ,which is not desired .I think the > problem lies in me using a list for storing and later printing out > values. It's not that you store them in the list but that you simply print the string representation of the list which does not meet your requirements. You want to join the list elements with a comma:: print 'supported=%s' % ','.join(ser) Ciao, Marc 'BlackJack' Rintsch From deets at nospam.web.de Wed Apr 25 08:58:42 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 25 Apr 2007 14:58:42 +0200 Subject: jython: user-defined modules References: <1177501051.043114.261420@r30g2000prh.googlegroups.com> Message-ID: <5991k2F2k2ak0U1@mid.uni-berlin.de> Gregor Stich wrote: > Dear all, > > I hope my question is here in the right place... > What I want to achieve is a communication between Java and Python. We > have a pretty strong framework of existing python scripts and modules. > Now I want to use jython in order to faciliate the communication > between another Java framework. > > But I`m currently stuck with jython: Trying to import the user-defined > python modules, these cannot be found. I read a lot about the jython > registry and I setup a $HOME/.jython file where I created a > python.path=... resource, however, when I start the jython command > line and type > print python.path > then this property is not found. Passing it with the -D option does > not work as well, or maybe I`m too confused to make it work anyway? First of all, you should subscribe to the jython mailing list. Second, you access the python.path inside jython via import sys print sys.path HTH, Diez From grante at visi.com Tue Apr 24 17:45:20 2007 From: grante at visi.com (Grant Edwards) Date: Tue, 24 Apr 2007 21:45:20 -0000 Subject: Generate report containing pdf or ps figures? References: <132pnp6r4qg0lc2@corp.supernews.com> <132sdmde3vg6kf3@corp.supernews.com> <132sn8eh1iphnf0@corp.supernews.com> Message-ID: <132sujgo29hgsfa@corp.supernews.com> On 2007-04-24, Cameron Laird wrote: >>I can't even find any mention of a commercial version of >>ReportLab on the web site. The FAQ says ReportLib is available >>under the BSD license. Period. >> >>There are some other "projects" listed, but they don't appear >>to be relevent. > . > . > . > Uh huh, can't afford that. :) -- Grant Edwards grante Yow! World War Three can at be averted by adherence visi.com to a strictly enforced dress code! From hugonz at gmail.com Sun Apr 22 03:51:35 2007 From: hugonz at gmail.com (hugonz at gmail.com) Date: 22 Apr 2007 00:51:35 -0700 Subject: Flat DB seeking speed In-Reply-To: <1177216068.518970.29470@o5g2000hsb.googlegroups.com> References: <1177216068.518970.29470@o5g2000hsb.googlegroups.com> Message-ID: <1177228295.013179.241380@y80g2000hsf.googlegroups.com> Jia Lu skribis: > Hello all > > I see there are lots of flat db or db-like modules in the standard > python modules. > What about the keywords seeking speed of them ? > > (I want to put about 10000 articles with 10000 IDs, and I can do > searching keywords with them) > > The db-like modules are : > dbm, gdbm, dbhash,anydbm, > pickle(cPickle), shelve, marshal > > Any advice? Thank you. > If you need near DB quality, you should give buzhug a look: it is pure python: http://buzhug.sourceforge.net/ From aleax at mac.com Sat Apr 28 17:27:52 2007 From: aleax at mac.com (Alex Martelli) Date: Sat, 28 Apr 2007 14:27:52 -0700 Subject: Portable SciPy v0.1 released References: <2418d$463275ce$d443bb3a$25239@news.speedlinq.nl> <1177714703.751242.61090@e65g2000hsc.googlegroups.com> Message-ID: <1hxaa61.1ltror06v9qgN%aleax@mac.com> Beliavsky wrote: > On Apr 27, 6:17 pm, Stef Mientki > wrote: > > Portable SciPy, is an easy installer of SciPy for M$ windows users. > > If you have an announcement for Windows users, I suggest that you not > needlessly turn them off by abbreviating Microsoft as M$ . You don't > like Windows, but many of us Windows users don't like the anti-Windows > snobs. There is nothing wrong with making money by selling software. Speaking as a Microsoft stockholder, and having recently broken out the champagne because MSFT is finally back over $30 again [1] (and hoping this time is STAYS that way, as opposed to the flash-in-the-pan at the end of January) I'm perfectly happy with seeing $ associated to Microsoft, for a change. I entirely agree about making money by selling software, and indeed that's why I'm a stockholder -- now if you could just convince Ballmer and friends that making money by selling SW is better than losing money by failing to sell online ads and music players (and just about breaking even with videogame HW, thanks be for Sony's incredible mistakes in the field that allowed Microsoft to "stay above water") then I won't be the only MSFT stockholder to want to offer you a steak dinner (warning: excess of steak dinners might raise your LDL cholesterol!-). Microsoft can still make kick-ass software, if need be by hiring the right people, and they proved it well with IronPython, IMHO. They obviously _can't_ do as well in HW and online services; if they stopped throwing good money after bad, and instead raised the dividend and renewed and increased the stock-repurchase program, that would be great for the economy of Western France (and Catalunya, for those who prefer cava, etc -- basically, all regions that export champagne!-). Alex [1] yah, I do remember MSFT flirting with $60 [considering the early'03 split] at the end of '99 -- that was just Wall Street being crazy, and the fall from THOSE heights is NOT any fault of Microsoft's management. The interminable last 5+ years below $30, OTOH... From Martin.Drautzburg at web.de Sun Apr 22 03:11:05 2007 From: Martin.Drautzburg at web.de (Martin Drautzburg) Date: Sun, 22 Apr 2007 09:11:05 +0200 Subject: favourite IDE References: <1176422188.006169.141100@q75g2000hsh.googlegroups.com> Message-ID: <45282641.c4jn7SmoKb@beaureve.gmx.net> azrael wrote: > Some time ago I posted a question about the favourite IDE. I finally > found it. WING IDE i the best I've ever seen for python. Yes WingIde is cool but it is not free. A fairly good alternative is the "pydev" plugin for eclipse. From rw at smsnet.pl Mon Apr 16 06:53:34 2007 From: rw at smsnet.pl (Rob Wolfe) Date: 16 Apr 2007 03:53:34 -0700 Subject: Boost Problem! Boost.Build not found In-Reply-To: <1176719740.525832.132610@e65g2000hsc.googlegroups.com> References: <1176719740.525832.132610@e65g2000hsc.googlegroups.com> Message-ID: <1176720813.976821.237610@w1g2000hsg.googlegroups.com> Soren wrote: > Unable to load Boost.Build: could not find "boost-build.jam" > --------------------------------------------------------------- > Attempted search from C:\boost\boost_1_33_1\libs\python\example > \tutorial up to t > he root and in these directories from BOOST_BUILD_PATH and BOOST_ROOT: > C:\boost\boost_1_ > 33_1. > Please consult the documentation at 'http://www.boost.org'. > > Can anyone please tell me what I am doing wrong?? Theres no tutorial > on how to make a boost-build.jam file.. and as I understand I don't > need one as long as I set BOOST_BUILD_PATH .. Try to create boost-build.jam file like this: # boost-build.jam boost-build C:\boost\boost_1_33_1\tools\build\v1 ; -- HTH, Rob From b.r.willems at gmail.com Sun Apr 8 19:42:50 2007 From: b.r.willems at gmail.com (Bart Willems) Date: Sun, 08 Apr 2007 19:42:50 -0400 Subject: tuples are useless??? In-Reply-To: References: Message-ID: James Stroud wrote: > ... It boils down to the fact that tuples are useless as a > result unless you know you really need them--and you never really NEED > them. Could you clarify that for me? I use tuples *a lot* and I really *NEED* them - I'm building a lot of multi-tier reports where detail-level data is pulled out of a dictionary based on a composed key. It is impossible to build those dictionaries *without* using tuples. So, I *need* those tuples, and they're far from useless to me. For the rare, rare, rare cases where I *would* need an index function on a tuple (I've never needed it): class IndexTuple(tuple): def index(n): # your code goes here would be sufficient, wouldn't it? Best regards, Bart From apardon at forel.vub.ac.be Thu Apr 26 02:58:11 2007 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 26 Apr 2007 06:58:11 GMT Subject: conditional print statement ? References: <2c923$462fb3e0$d443bb3a$18429@news.speedlinq.nl> Message-ID: On 2007-04-25, Stef Mientki wrote: > hello, > > > As part of a procedure I've a number sequences like this: > > > if Print_Info: print Datafile.readline() > else: Datafile.readline() > > > Is there a more compressed way to write such a statement, > especially I dislike the redundancy "Datafile.readline()". > > thanks, > Stef Mientki You could consider the following def Print(arg): print arg def Noop(arg): pass (Print if Print_Info else Noop) (Datafile.readline()) -- Antoon Pardon From kw at codebykevin.com Sat Apr 21 09:57:09 2007 From: kw at codebykevin.com (Kevin Walzer) Date: Sat, 21 Apr 2007 09:57:09 -0400 Subject: using tkinter to display html In-Reply-To: References: <1176988173.015892.273660@e65g2000hsc.googlegroups.com> <1177064902.230394.133830@d57g2000hsg.googlegroups.com> Message-ID: <462A1835.5090005@codebykevin.com> Stephen M. Gava wrote: > On Fri, 20 Apr 2007 03:28:22 -0700, Rob Wolfe wrote: >>>> The following thread has various ideas in it: >>>> http://mail.python.org/pipermail/python-list/2001-October/107989.html >>> thanks mike, i found that thread before i posted here, it doesn'rt >>> answer my question though. >> Why not? Did you try to use tkhtml [1]_ with python wrapper [2]_. IMHO >> it works pretty nice. > > i found the tkhtml page but it hasn't been updated since 2002 and the > mailing list doesn't even exist anymore. so unsure of the future on that. > >> .. [1] http://www.hwaci.com/sw/tkhtml/ .. [2] > > didn't find these bindings though, so thanks, i'll have a play. > > stephen. > >> http://tix.sourceforge.net/Tixapps/src/Python/TkHtml.py >> TkHTML: http://tkhtml.tcl.tk -- Kevin Walzer Code by Kevin http://www.codebykevin.com From apardon at forel.vub.ac.be Tue Apr 24 07:35:47 2007 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 24 Apr 2007 11:35:47 GMT Subject: Tutorial creates confusion about slices References: Message-ID: On 2007-04-24, Michael Bentley wrote: > > On Apr 24, 2007, at 4:47 AM, Antoon Pardon wrote: > >> On 2007-04-24, Michael Bentley wrote: >>> >>> On Apr 24, 2007, at 1:39 AM, Antoon Pardon wrote: >>> >>>> I suspect that if you give this explanation to someone and explain >>>> that there is also a step parameter, chances are he will answer >>>> correctly if you ask him, what he thinks the following will result >>>> in: >>>> >>>> >>>> "This is an example line"[12:19:2] >>>> >>>> >>>> >>>> If you ask him what the following will result in: >>>> >>>> "This is an example line"[19:12:-1] >>>> >>>> Chances are he will give the wrong answer. >>> >>> To be honest, bro -- I'd expect him to have enough intelligence to >>> experiment for a second and figure it out. This isn't rocket science >>> -- you can plainly see what's happening -- so learn it and move >>> on. >> >> I don't think that the possibility to experiment and see for oneself >> is a good reason to keep a possible confusing explanation in a >> tutorial. > > It's only potentially confusing if you already know more than has > been presented and are in fact, *experimenting* with techniques that > have yet to be presented. People don't read tutorials in a strictly linear fashion. They can continue to later subjects and then come back here to see how things tie together. So the fact that it is only confusing to those who know more than is already presented doesn't seem a very good reason to leave it in. >>> Or better yet, quietly submit a patch... >> >> Why should I? If the reactions would have been one of agreement that >> this is confusing and that the explanation should be changed, I would >> have considered submitting a patch. >> >> But most people that reacted seem to defend the current text in some >> way or another. So if most people seem to feel there is no need for >> a change why should I then submit a patch? > > ... or even continue the thread? It is always interresting to see how far people are willing to go to defend the status quo. I bet that if the tutorial was written now, given the possible confusion, nobody would defend including this section. But now that it already is in the tutorial it suddenly is worth defending. -- Antoon Pardon From dotancohen at gmail.com Sun Apr 1 15:54:35 2007 From: dotancohen at gmail.com (Dotan Cohen) Date: Sun, 1 Apr 2007 22:54:35 +0300 Subject: Extract information from HTML table In-Reply-To: <1175439364.515873.142340@p15g2000hsd.googlegroups.com> References: <1175429635.278697.92690@b75g2000hsg.googlegroups.com> <1175431924.800332.325820@n76g2000hsh.googlegroups.com> <1175439364.515873.142340@p15g2000hsd.googlegroups.com> Message-ID: <880dece00704011254x3c3269a4s7425e503da8ef876@mail.gmail.com> On 1 Apr 2007 07:56:04 -0700, Ulysse wrote: > I have seen the Beautiful Soup online help and tried to apply that to > my problem. But it seems to be a little bit hard. I will rather try to > do this with regular expressions... > If you think that Beautiful Soup is difficult than wait till you try to do this with regexes. Granted you know the exact format of the HTML you are scraping will help, if you ever need to parse HTML from an unknown source than Beautiful Soup is the only way to go. Not all HTML authors close their td and tr tags, and sometimes there are attributes to those tags. If you plan on ever reusing the code or the format of the HTML may change, then you are best off sticking with Beautiful Soup. Dotan Cohen http://lyricslist.com/ http://what-is-what.com/ From gregpinero at gmail.com Tue Apr 10 03:44:24 2007 From: gregpinero at gmail.com (gregpinero at gmail.com) Date: 10 Apr 2007 00:44:24 -0700 Subject: exec statement Syntax Error on string pulled from MySQL Message-ID: <1176191064.840339.247160@d57g2000hsg.googlegroups.com> It's the strangest thing, I'm pulling some text out of a MySQL table and trying to run exec on it, and it keeps giving me a syntax error, always at the end of the first line. Thanks in advance for any help. I'm really stuck on this one! -Greg I'm not sure what information would be most useful but here's a start: The last code I stored in the table and pulled out was simply: print 'greg' print 'greg2' To which my error log says: Traceback (most recent call last): File "/home/public/web/webapi.py", line 303, in wsgifunc result = func() File "/home/public/web/request.py", line 125, in func = lambda: handle(inp, fvars) File "/home/public/web/request.py", line 61, in handle return tocall(*([urllib.unquote(x) for x in args] + fna)) File "/home/public/EZsession.py", line 119, in proxyfunc return func(self, *args, **kw) File "/home/htdocs/code.py", line 94, in POST print utility.run(name,revision,inp) File "/home/public/utility.py", line 177, in run exec code+'\n' in context File "", line 1 print 'greg' ^ SyntaxError: invalid syntax (Note the ^ actually appears under after the ' ) To really get a picture of what is coming out of the DB I had the program print out everything about this string using this code: print code print repr(code) print type(code) for char in code: print ord(char),char To which I got: print 'greg' print 'greg2' "print 'greg'\r\nprint 'greg2'" 112 p 114 r 105 i 110 n 116 t 32 39 ' 103 g 114 r 101 e 103 g 39 ' 13 10 112 p 114 r 105 i 110 n 116 t 32 39 ' 103 g 114 r 101 e 103 g 50 2 39 ' From gagsl-py2 at yahoo.com.ar Wed Apr 11 23:32:32 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 12 Apr 2007 00:32:32 -0300 Subject: Strange Behavior with Old-Style classes and implicit __contains__ References: <1176334655.677943.70030@q75g2000hsh.googlegroups.com> Message-ID: En Wed, 11 Apr 2007 20:37:35 -0300, escribi?: > First, we create an instance of an Old-Style class without defining a > __contains__ but instead define a __getitem__ method in which we raise > KeyError. Next we repeatedly use the 'in' operator to test to see > whether something, a string, an int, etc is an attribute of this new > instance. > > Here's the strange part: The first test will return False as if the > __getitem__ was never called. The next test will raise a KeyError as > we'd expect. The test after that will again return False. This goes on > ad infinitum. > > In Code: > Python 2.5 (r25:51908, Jan 21 2007, 03:10:25) > [GCC 3.4.6 20060404 (Red Hat 3.4.6-3)] on linux2 > Type "help", "copyright", "credits" or "license" for more > information. > >>> class Foo: > ... def __getitem__(self, key): > ... raise KeyError > ... > >>> foo = Foo() > >>> "asdf" in foo > False > >>> "asdf" in foo > Traceback (most recent call last): > File "", line 1, in > File "", line 3, in __getitem__ > KeyError First I want to say that __getitem__ should raise IndexError, not KeyError, to indicate "not found" - just to make clear the observed behavior. (Using IndexError, you always get False, as expected). Python 2.4 and 2.3 never return False, always showing the KeyError exception, also as expected. >>>> foo = Foo() >>>> "asdf" in foo > False >>>> 1 in set([1,2,3]) <---- So the prior KeyError from another class >>>> is interacting and producing bad output > Traceback (most recent call last): > File "", line 1, in > File "", line 3, in __getitem__ > KeyError I have a displayhook installed, and it also were interfering with the results; it appears that the next __getitem__ call after the KeyError was raised (wherever it is called) "sees" the previous exception. You should file a bug at http://sourceforge.net/bugs/?group_id=5470 -- Gabriel Genellina From flyzone at technologist.com Fri Apr 13 05:30:11 2007 From: flyzone at technologist.com (Flyzone) Date: 13 Apr 2007 02:30:11 -0700 Subject: split and regexp on textfile In-Reply-To: <1176455681.424814.223830@q75g2000hsh.googlegroups.com> References: <1176451192.364949.8260@w1g2000hsg.googlegroups.com> <1176453634.577706.326170@y80g2000hsf.googlegroups.com> <1176454505.336514.90910@p77g2000hsh.googlegroups.com> <1176455681.424814.223830@q75g2000hsh.googlegroups.com> Message-ID: <1176456611.648400.254850@q75g2000hsh.googlegroups.com> On 13 Apr, 11:14, mik3l3... at gmail.com wrote: > change to pat.split(data) then. next what i have tried originally..but is not working, my result is here: ["Mon Feb 26 11:25:04 2007\ntext\n text\ntext\nMon Feb 26 11:25:16 2007\ntext\n text\n text\nMon Feb 26 17:06:41 2007\ntext"] all together :( From bearophileHUGS at lycos.com Sun Apr 15 05:38:31 2007 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 15 Apr 2007 02:38:31 -0700 Subject: combination function in python In-Reply-To: <1176615838.830315.160210@b75g2000hsg.googlegroups.com> References: <1176615838.830315.160210@b75g2000hsg.googlegroups.com> Message-ID: <1176629911.409257.149780@l77g2000hsb.googlegroups.com> DanielJohnson: > Please help, I couldnt find the function through help. You can't find it because it's not there: def factorial(n): """factorial(n): return the factorial of the integer n. factorial(0) = 1 factorial(n) with n<0 is -factorial(abs(n)) """ result = 1 for i in xrange(1, abs(n)+1): result *= i if n >= 0: return result else: return -result def binomial(n, k): """binomial(n, k): return the binomial coefficient (n k).""" assert n>0 and isinstance(n, (int, long)) and isinstance(k, (int, long)) if k < 0 or k > n: return 0 if k == 0 or k == n: return 1 return factorial(n) // (factorial(k) * factorial(n-k)) Bye, bearophile From gdamjan at gmail.com Mon Apr 2 12:29:06 2007 From: gdamjan at gmail.com (Damjan) Date: Mon, 02 Apr 2007 18:29:06 +0200 Subject: I18n issue with optik References: Message-ID: <46112f10$0$90271$14726298@news.sunsite.dk> > Actually rxvt, Poderosa and console have the ability to display non- > ASCII characters. I use the dejavu fonts that support non-ASCII, too. > > But the problem is even simpler: I can't even set the standard Windows > console ("cmd") to Windows 1252 in Python. Although directly executing > "chcp 1252" works. Maybe try to use http://sourceforge.net/projects/console it's claimed to be muc better than the sucky CDM (I don't have windows to try it). -- damjan From steve at holdenweb.com Tue Apr 3 12:44:53 2007 From: steve at holdenweb.com (Steve Holden) Date: Tue, 03 Apr 2007 12:44:53 -0400 Subject: Stack experiment In-Reply-To: <1175617406.269202.301490@l77g2000hsb.googlegroups.com> References: <5QuQh.152$9L1.108@read3.inet.fi> <1175617406.269202.301490@l77g2000hsb.googlegroups.com> Message-ID: kyosohma at gmail.com wrote: [...] > > Steve, > > How do you do "tokenList = split(expr)"? There is no builtin called > "split". > > Mike > Sorry, that should have been a call to the .split() method of expr, i.e.: tokenList = expr.split() 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 myheartinamerica at gmail.com Mon Apr 16 13:11:18 2007 From: myheartinamerica at gmail.com (myheartinamerica) Date: 16 Apr 2007 10:11:18 -0700 Subject: swig win32 scons Message-ID: <1176743478.092658.24540@l77g2000hsb.googlegroups.com> Hello, I spent the morning figuring out how to use SWIG on Microsoft Windows. I compiled the example from the SWIG tutorial on http://www.swig.org. The biggest stumbling block was not knowing that I needed to rename the DLL created to have a PYD extension. I also ended up writing a .def file for exporting functions from the DLL. Here is my SConstruct file for using SCons to build the library. It is not perfect, but it should be evident as to what I was doing. I hope that others will be able to find this in the future and save themselves some time.: ############################## SWIG_EXE = r'C:\Python25\swig\swig.exe' env = Environment(SWIG=SWIG_EXE, SWIGFLAGS=['-python'], CPPPATH=[r'C:\Python25\include'], LIBPATH=[r'C:\Python25\libs']) swigObject = env.SharedObject(['example.i']) copyToPYD = Copy('_example.pyd', '_example.dll') env.AddPostAction('_example.dll', copyToPYD) env.SharedLibrary('_example.dll', ['example.c', swigObject]) From Hillary.Schwartz at lsrlaw.com Wed Apr 18 17:09:03 2007 From: Hillary.Schwartz at lsrlaw.com (Schwartz, Hillary) Date: Wed, 18 Apr 2007 17:09:03 -0400 Subject: Installing Python on NT Message-ID: ___________________________________________ Hillary Schwartz Applications Specialist, IT - Development Lerner, Sampson & Rothfuss, LPA Phone: (513) 241-3100 x3138 Hillary.Schwartz at lsrlaw.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From mik3l3374 at gmail.com Fri Apr 13 04:40:34 2007 From: mik3l3374 at gmail.com (mik3l3374 at gmail.com) Date: 13 Apr 2007 01:40:34 -0700 Subject: split and regexp on textfile In-Reply-To: <1176451192.364949.8260@w1g2000hsg.googlegroups.com> References: <1176451192.364949.8260@w1g2000hsg.googlegroups.com> Message-ID: <1176453634.577706.326170@y80g2000hsf.googlegroups.com> On Apr 13, 3:59 pm, "Flyzone" wrote: > Hi, > i have a problem with the split function and regexp. > I have a file that i want to split using the date as token. > Here a sample: > ----- > Mon Apr 9 22:30:18 2007 > text > text > Mon Apr 9 22:31:10 2007 > text > text > ---- > > I'm trying to put all the lines in a one string and then to separate > it > (could be better to not delete the \n if possible...) > while 1: > line = ftoparse.readline() > if not line: break > if line[-1]=='\n': line=line[:-1] > file_str += line > matchobj=re.compile('[A-Z][a-z][a-z][ ][A-Z][a-z][a-z][ ][0-9| ][0-9] > [ ][0-9][0-9][:]') > matchobj=matchobj.split(file_str) > print matchobj > > i have tried also > matchobj=re.split(r"^[A-Z][a-z][a-z][ ][A-Z][a-z][a-z][ ][0-9| ] > [0-9][ ][0-9][0-9][:]",file_str) > and reading all with one: > file_str=ftoparse.readlines() > but the split doesn't work...where i am wronging? you trying to match the date part right? if re is what you desire, here's one example: >>> data = open("file").read() >>> pat = re.compile("[A-Z][a-z]{2} [A-Z][a-z]{2} \d{,2}\s+\d{,2}:\d{,2}:\d{,2} \d{4}",re.M|re.DOTALL) >>> print pat.findall(data) ['Mon Apr 9 22:30:18 2007', 'Mon Apr 9 22:31:10 2007'] From goodTweetieBird at hotmail.com Mon Apr 30 10:51:02 2007 From: goodTweetieBird at hotmail.com (gtb) Date: 30 Apr 2007 07:51:02 -0700 Subject: Re-running script from Tk shell Message-ID: <1177944662.957393.306620@h2g2000hsg.googlegroups.com> I am testing a simple script by running it in the Tk shell. It imports a class from another module. I edit and save the file from which I import. When I want to re-run I delete the Tk window and run the module from the Edit window (F5 - Run Module). The script that does the importing does not see the changes to the imported class, even if I delete the compiled files. For it to see the changes I must close all the edit windows and re-open an Idle edit. Perhaps I need to de-import the class, but I have not found a method in the tutorial or the reference (yet). Thanks From jstroud at mbi.ucla.edu Wed Apr 25 17:27:06 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Wed, 25 Apr 2007 14:27:06 -0700 Subject: Controlling gnuplot via subprocess.Popen In-Reply-To: <599hu0F2k8k1qU1@mid.uni-berlin.de> References: <599hu0F2k8k1qU1@mid.uni-berlin.de> Message-ID: Peter Beattie wrote: > I am trying to plot something in gnuplot 4.2 using co-ordinates a Python > 2.5 program computes. Here's what I'm doing: > > py> from subprocess import * > py> plot = Popen("c:/progs/gp/bin/wgnuplot.exe", stdin=PIPE) > py> plot.stdin.write("plot x*x") > > The first command dutifully opens gnuplot, but the second doesn't do > anything. Could someone favour me with an explanation as to the whyness? > Why re-invent the wheel? Not trying to be pedantic, but usually the google search "python %s" % thing_im_working_on will yield lucrative results that far exceed anything you can create in a reasonable amount of time. For example, "python gnuplot" first hit is: http://gnuplot-py.sourceforge.net/ And speaking from experience, it works beautifully. James From bj_666 at gmx.net Thu Apr 26 12:03:44 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Thu, 26 Apr 2007 18:03:44 +0200 Subject: Python keywords References: <1177599386.204340.65680@r35g2000prh.googlegroups.com> Message-ID: In <1177599386.204340.65680 at r35g2000prh.googlegroups.com>, gtb wrote: > Have done some searching but have not found a place where I can look > up python keywords. I was looking at a script that contained the > following line: > > assert self.getResponseCode() in (200, 304, 302) > > I can infer the usage here but previously I had thought that "in" was > only used with '"for". I looked thru 'the Python Reference Manual and > found "in" is a keyword but in skimming thru I found it only with > "for". The reference manual seems good but seems not to be setup for > searching. Or maybe I just missed something. If you look in the library reference index you'll find a link to the `Sequence Types`_ section where it is mentioned as an operator that tests if some object "contains" another. And the reference manual has an index entry called `in operator` which leads to the page Comparisons_, telling how to overwrite the behaviour in your own classes. .. _Sequence Types: http://docs.python.org/lib/typesseq.html .. _Comparisons: http://docs.python.org/ref/comparisons.html Ciao, Marc 'BlackJack' Rintsch From lorenzo at diespammerhethurmans.com Fri Apr 6 21:39:52 2007 From: lorenzo at diespammerhethurmans.com (Lorenzo Thurman) Date: Fri, 06 Apr 2007 20:39:52 -0500 Subject: Mail not setting timestamp Message-ID: I'm using the Mimewriter and mimetools modules to create html messages. They work OK, except that when the messages are received, they always have the timestamp of 12/31/1969. I've looked through both packages and can't find anything that would allow me to manually set it. Can someone help me out? TIA From list-ener at strank.info Wed Apr 18 03:46:53 2007 From: list-ener at strank.info (Stefan Rank) Date: Wed, 18 Apr 2007 09:46:53 +0200 Subject: What makes an iterator an iterator? In-Reply-To: References: Message-ID: <4625CCED.5090106@strank.info> on 18.04.2007 07:39 Steven D'Aprano said the following: > I thought that an iterator was any object that follows the iterator replace object with "instance of a class", i.e. the relevant methods are looked up in the __class__ not in the instance (I think). I had the same troubles trying to dynamically reassign a __call__ method... > protocol, that is, it has a next() method and an __iter__() method. > > But I'm having problems writing a class that acts as an iterator. I have: > > class Parrot(object): > def __iter__(self): > return self > def __init__(self): > self.next = self._next() > def _next(self): > for word in "Norwegian Blue's have beautiful plumage!".split(): > yield word Try this:: class Parrot(object): def __iter__(self): return self def __init__(self): self.__class__.next = self._next().next # see post by I V def _next(self): for word in "Norwegian Blue's have beautiful plumage!".split(): yield word This works but practically forces the class to be used as a singleton... not very helpful :) Better: * use the '__iter__ returns/is a generator' way, * or if you need the object to be the iterator, implement the next method directly on the class:: class Parrot(object): def _next(self): for word in "Norwegian Blue's have beautiful plumage!".split(): yield word def __iter__(self): self.generator = self._next() return self def next(self): return self.generator.next() cheers, stefan From kyosohma at gmail.com Tue Apr 3 09:27:28 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: 3 Apr 2007 06:27:28 -0700 Subject: XML DTD analysis, diffing ... In-Reply-To: <1175603926.371027.69390@e65g2000hsc.googlegroups.com> References: <1175603926.371027.69390@e65g2000hsc.googlegroups.com> Message-ID: <1175606848.838850.18150@w1g2000hsg.googlegroups.com> On Apr 3, 7:38 am, "olive" wrote: > Hi, > > I have a bunch of similar DTDs written by different coders. > > I would like to normalize, sort elements and attributes by name and > compare those files. > > Do you know any XML DTD parser/normalizer written in Python ? > > If not, how would you perform that task in Python language ? > > Please, > > Olive. Olive, Beautiful Soup is usually recommended for parsing XML/HTML. www.crummy.com/software/BeautifulSoup/ You could also use pyXML. See the recipe below for one way to use it: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/220472 xmlproc has a way of parsing DTDs, or so I hear. I think it's a part of pyXML. I hope this stuff gives you some ideas. Mike See also the SAX module: http://docs.python.org/lib/module-xml.sax.handler.html From robert.kern at gmail.com Wed Apr 11 17:39:39 2007 From: robert.kern at gmail.com (Robert Kern) Date: Wed, 11 Apr 2007 16:39:39 -0500 Subject: About Trolltech QT OpenSource license. In-Reply-To: <878xcyaa7l.fsf@gmail.com> References: <1176233376.712861.67160@o5g2000hsb.googlegroups.com> <1176237050.409742.8760@30g2000cwc.googlegroups.com> <1176285062.178372.15090@d57g2000hsg.googlegroups.com> <878xcyaa7l.fsf@gmail.com> Message-ID: Jorge Godoy wrote: > Robert Kern writes: > >> I don't recommend it. You are talking to their salesman, not your lawyer. You >> are being given a sales pitch, not legal advice. > > On the other hand, he's stating Trolltech's policies and agreeing / > disagreeing on your understanding of their license. He's selling you his > product and stating how you can / can't use it. Nothing the salesman has said about what one can and can't do disagrees with my understanding of the license. There's just some vagueness in the terminology used to *label* the not-open-source Qt license. The label is legally inconsequential. -- 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 bayer.justin at googlemail.com Thu Apr 12 17:29:01 2007 From: bayer.justin at googlemail.com (bayer.justin at googlemail.com) Date: 12 Apr 2007 14:29:01 -0700 Subject: SQLite problems In-Reply-To: <1176375899.401083.216620@e65g2000hsc.googlegroups.com> References: <1176371562.110295.217360@l77g2000hsb.googlegroups.com> <1176375899.401083.216620@e65g2000hsc.googlegroups.com> Message-ID: <1176413341.727715.101320@p77g2000hsh.googlegroups.com> > Why fink ?, it is very easy to make sqlite. download the source, > configure, make and install from terminal I did so and now I have the latest sqlite version. But it did not make a difference. From robert.rawlins at thinkbluemedia.co.uk Wed Apr 11 10:43:19 2007 From: robert.rawlins at thinkbluemedia.co.uk (Robert Rawlins - Think Blue) Date: Wed, 11 Apr 2007 15:43:19 +0100 Subject: Writing XML Logs Message-ID: <007301c77c47$c7f9d630$57ed8290$@rawlins@thinkbluemedia.co.uk> Hello Chaps, I'm trying to write an application that will log to an XML file, that'll be later parsed by another application. The proposed log file will look something like this, listing different event elements and then a record for each time that event occurs. What I would really like to do is have a different function for each event, so logReboot() or something like that which can be called when the application starts, and it'll create and entry with the current date and time. This must be a static file that is on the box, allot of the examples I've seen seem to work using the 'print' function which is a little sketchy as outputting to the screen isn't any use to me, this needs to be a file that can be collected by another application. Can anyone offer any advice on how best to get started with this kind of thing? I'm running python 2.4.4 but when I've tried running any examples with SAX involved they seem to say 'no module found: sax" or something to that effect, I was under the impression that sax came bundled with python 2.0 and above? Thanks guys, Rob -------------- next part -------------- An HTML attachment was scrubbed... URL: From sjdevnull at yahoo.com Wed Apr 4 18:49:26 2007 From: sjdevnull at yahoo.com (sjdevnull at yahoo.com) Date: 4 Apr 2007 15:49:26 -0700 Subject: operator overloading In-Reply-To: References: <1175679412.741899.45990@l77g2000hsb.googlegroups.com> <1175711246.488717.262560@e65g2000hsc.googlegroups.com> Message-ID: <1175726966.127531.273500@b75g2000hsg.googlegroups.com> On Apr 4, 4:55 pm, "Terry Reedy" wrote: > "Ziga Seilnacht" wrote in message > > news:1175711246.488717.262560 at e65g2000hsc.googlegroups.com... > | This looks like a bug in Python. It works for all the other > | operators: [SNIP] > | >>> i ** 3 > | 74088 > | > | You should submit a bug report to the bug tracker: > | > |http://sourceforge.net/bugs/?group_id=5470 > > Nice test. I thought maybe __pow__ might be different in not having a > reverse form, but indeed, int has an __rpow__ method. > > Before submitting, make sure that this does not work in 2.5, and then say > so in the bug report. In fact, copy the version/system info that the > interactive interpreter puts up when it starts. FWIW: Python 2.5 (r25:51908, Jan 21 2007, 03:10:25) [GCC 3.4.6 20060404 (Red Hat 3.4.6-3)] on HOSTNAME_REDACTED Type "help", "copyright", "credits" or "license" for more information. >>> class MyInt(int): ... __pow__ = int.__add__ ... >>> i=MyInt(42) >>> i**3 74088 From aleax at mac.com Tue Apr 24 23:51:59 2007 From: aleax at mac.com (Alex Martelli) Date: Tue, 24 Apr 2007 20:51:59 -0700 Subject: gotcha or bug? random state reset on irrelevant import References: <33yXh.5839$Fc1.4387@trnddc05> <462EB311.2010508@lexicon.net> Message-ID: <1hx3dv0.1888i74w45xnhN%aleax@mac.com> Alan Isaac wrote: > "John Machin" wrote in message > news:462EB311.2010508 at lexicon.net... > > It's not irrelevant; the test2 module has to be *executed* as part of > > the import. [...] seed(314) is executed. > > OK, I understand this is the right answer. > But another way to look at the question is: > is it a good design to only be able to use seed > to set a global state? (See for contrast > numpy.random, for which my appreciation > has just increased yet again.) What do you mean? Just instantiate the random.Random class and you can call .seed on it as well as anything else, and no other module will infringe on "your" module's Random instance. The "global functions" of module random exist for those who *SPECIFICALLY* want globally shared behavior, of course. Alex From bbxx789_05ss at yahoo.com Wed Apr 4 03:36:32 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: 4 Apr 2007 00:36:32 -0700 Subject: How can I time how much each thread takes? In-Reply-To: <1175662835.758899.13340@o5g2000hsb.googlegroups.com> References: <1175662835.758899.13340@o5g2000hsb.googlegroups.com> Message-ID: <1175672192.169517.144590@q75g2000hsh.googlegroups.com> On Apr 3, 11:00 pm, "silverburgh.me... at gmail.com" wrote: > Hi, > > I have the following code which spawn a number of thread and do > something (in the run method of MyThread). > how can I record how much time does EACH thread takes to complete the > 'run'? > > for j in range(threadCount): > t = MyThread(testNo) > threads.append(t) > t.start() > testNo += 1 > > for t in threads: > print "len = %d", len(threads) > t.join() > > I have read example of timeit.Timer() funcion, but I don' t know how > can i use it in a multiple thread program? > Thank you for any help. How about this: import time, threading class MyThread(threading.Thread): def __init__(self): threading.Thread.__init__(self) self.begin = 0 self.end = 0 def run(self): print "thread starting in background" self.begin = time.time() time.sleep(3) self.end = time.time() print "thread ending" mt = MyThread() mt.start() print "main still running in foreground" print "main going to wait for thread to end ....." mt.join() diff = mt.end - mt.begin print "Thread's run() time was: %.5f" % diff From zombiefreakx at gmail.com Tue Apr 24 18:13:58 2007 From: zombiefreakx at gmail.com (P-Cubed) Date: Tue, 24 Apr 2007 17:13:58 -0500 Subject: Help with trees, lists and checkboxes Message-ID: <7badbbac0704241513u2f575266vff809c61f87d4e8a@mail.gmail.com> I'm looking for some assistance extending the TreeListCtrl class to include the check box ability of the CustomTreeCtrl as well as 3-state check boxes. Main Column Column1 ----------------------------------------- ------------- [o] Child1 |-----[ ]Child1.1 |-----[ ]Child1.2 |-----[o]Child1.3 |-----[ ]Child1.3.1 Value1 |-----[ ]Child1.3.2 Value2 |-----[ ]Child1.3.3 Value3 |-----[X]Child1.3.4 Value4 [o] Child2 |-----[ ]Child2.1 |-----[ ]Child2.2 |-----[ ]Child2.3 |-----[o]Child2.4 |-----[ ]Child2.4.1 Value1 |-----[X]Child2.4.2 Value2 |-----[ ]Child2.4.3 Value3 |-----[ ]Child2.4.4 Value4 [o] Child3 |-----[ ]Child3.1 |-----[ ]Child3.2 |-----[ ]Child3.3 |-----[ ]Child3.4 |-----[ ]Child3.4.1 Value1 |-----[ ]Child3.4.2 Value2 |-----[ ]Child3.4.3 Value3 |-----[ ]Child3.4.4 Value4 Any ideas on the easiest and most effective way to do this? -------------- next part -------------- An HTML attachment was scrubbed... URL: From david.bear at asu.edu Wed Apr 4 18:05:46 2007 From: david.bear at asu.edu (David Bear) Date: Wed, 04 Apr 2007 15:05:46 -0700 Subject: string templates Message-ID: <1235142.VYMsP3if9A@teancum> I was justing wondering how safe python string templates are to use with unicode. I was just scanning pep 292 and it seems to say that they are -- or can by with inheritance... but I don't quite understand. -- David Bear -- let me buy your intellectual property, I want to own your thoughts -- From cam.ac.uk at mh391.invalid Fri Apr 27 05:12:50 2007 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Fri, 27 Apr 2007 10:12:50 +0100 Subject: webbrowser.open works in IDLE and cmd shell but not from cygwin prompt In-Reply-To: <1177646975.285805.106920@b40g2000prd.googlegroups.com> References: <1177646975.285805.106920@b40g2000prd.googlegroups.com> Message-ID: Gregory Bloom wrote: > I'm running Python 2.5 under Windows. If I fire up IDLE and enter: > >>>> import webbrowser >>>> url = 'http://www.python.org' >>>> webbrowser.open_new(url) > > it works like a champ, opening the page in Firefox. Same thing goes > from a Windows cmd shell: it works as advertised. > > But if I open a cygwin bash shell and try the same thing from a python > prompt, I get: > >>>> import webbrowser >>>> url = 'http://www.python.org' >>>> webbrowser.open_new(url) > Traceback (most recent call last): > File "", line 1, in > File "C:\Python25\lib\webbrowser.py", line 60, in open_new > return open(url, 1) > File "C:\Python25\lib\webbrowser.py", line 55, in open > if browser.open(url, new, autoraise): > File "C:\Python25\lib\webbrowser.py", line 185, in open > p = subprocess.Popen(cmdline, close_fds=True, preexec_fn=setsid) > File "C:\Python25\lib\subprocess.py", line 551, in __init__ > raise ValueError("close_fds is not supported on Windows " > ValueError: close_fds is not supported on Windows platforms > > What's up with that? It's not a Cygwin issue, really. This occurs when one of ["firefox", "firebird", "seamonkey", "mozilla", "netscape", "opera"] is in your path. Your Cygwin environment must be set so one of these is in your path when it isn't normally. You should also submit a bug. > And, more to the point, how can I use webbrowser from scripts launched under > cygwin? If you're using native Windows Python as you seem to be, try webbrowser.get("windows-default").open_new(url) If you want to use Cygwin Python instead, I submitted a patch more than 1.5 years ago to allow it, but it hasn't been reviewed: http://python.org/sf/1244861 -- Michael Hoffman From martin at v.loewis.de Fri Apr 13 18:48:49 2007 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sat, 14 Apr 2007 00:48:49 +0200 Subject: Portably generating infinity and NaN In-Reply-To: References: Message-ID: <462008d1$0$11763$9b622d9e@news.freenet.de> > (Note the absence of a demonstration on Windows.) Can't the above be > blessed as the One True Way and wormed around in floatmodule.c for those > platforms where float'ing "NaN" or "Inf" doesn't currently work? How would you do the worming-around? Regards, Martin From psdasilvaX at esotericaX.ptX Tue Apr 3 11:32:22 2007 From: psdasilvaX at esotericaX.ptX (Paulo da Silva) Date: Tue, 03 Apr 2007 16:32:22 +0100 Subject: getattr/setattr q. In-Reply-To: <1175576772.241573.256980@b75g2000hsg.googlegroups.com> References: <1175573213.682671@jubilee.claranet.pt> <1175576772.241573.256980@b75g2000hsg.googlegroups.com> Message-ID: <1175614741.30844@jubilee.claranet.pt> 7stud escreveu: > On Apr 2, 10:08 pm, Paulo da Silva wrote: >> Is it possible to use getattr/setattr for variables not inside >> classes...? > > What does the python documentation say about the definition of > setattr()? > I didn't read the full python documentation, yet! I hope to survive until then :-) In the meanwhile, I searched google for setattr python but all references I could see were about X.foo type. One more "RTFM culture" response ... Thanks. Paulo From mirandacascade at yahoo.com Mon Apr 30 10:22:23 2007 From: mirandacascade at yahoo.com (mirandacascade at yahoo.com) Date: 30 Apr 2007 07:22:23 -0700 Subject: socket module - recv() method Message-ID: <1177942942.996962.122680@n76g2000hsh.googlegroups.com> Currently using the following technique in serveral client applications to send a request message and receive a response: import socket bufferSize = 500000 connectionHandle = socket.socket(socket.AF_INET, socket.SOCK_STREAM) connectionHandle.connect(sa) connectionHandle.sendall(requestMessage) fullResponse = '' # use while loop in case the entire response not sent in one chunk while (1): response = connectionHandle.recv(bufferSize) fullResponse = fullResponse + response if fullResponse.find(endOfMessageText) != -1: break where: sa = 2-element tuple; 1st elem is string denoting ip address; 2nd elem is int denoting port requestMessage = string containing request message endOfMessageText = string that unambiguously denotes the end of response message All of the client apps on which this technique is employed are very predictable in the sense that the client apps always know in advance the value of endOfMessageText. Questions: 1) is it theoretically possible that a client app will want to send a request and receive a response where the response message does not have something that unambigusously marks its end? 2) if so, are there any best-practices techniques for constructing the code such that the client app knows that there is nothing else in the response message? Thank you. From cam.ac.uk at mh391.invalid Tue Apr 17 16:19:13 2007 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Tue, 17 Apr 2007 21:19:13 +0100 Subject: Binary file output using python In-Reply-To: References: Message-ID: Chi Yin Cheung wrote: > Hi, > Is there a way in python to output binary files? I need to python to > write out a stream of 5 million floating point numbers, separated by > some separator, but it seems that all python supports natively is string > information output, which is extremely space inefficient. I recommend using PyTables for this sort of thing. It also allows you to choose from several compression algorithms. I'm using it to store files with 22000 x (2000, 12) datasets, or 528 million Float64s. -- Michael Hoffman From fdemmer at gmail.com Thu Apr 19 03:04:03 2007 From: fdemmer at gmail.com (Florian Demmer) Date: 19 Apr 2007 00:04:03 -0700 Subject: 2.5 from source install problem with extensions In-Reply-To: References: <1176892612.378898.34580@e65g2000hsc.googlegroups.com> <1176898857.656696.221690@p77g2000hsh.googlegroups.com> Message-ID: <1176966243.538647.126460@l77g2000hsb.googlegroups.com> On Apr 18, 7:39 pm, Anton Hartl wrote: > Hi, > > On 2007-04-18, Florian Demmer wrote: > > > On Apr 18, 12:36 pm, Florian Demmer wrote: > >> Hi! > > >> I am doing a from source installation of Python 2.5 on some old Debian > >> machine. As the target directoy I want /opt/somename so i added it to > >> the configure like so: > > >> ./configure --prefix=/opt/somedir > > >> The following make works fine as far as I can see. Then the make > >> install also actually works and installs python in /opt/somedir with > >> all its subdirectoris (bin, lib, man, include). > >> The extensions (*.so) however get put in /usr/local/lib/... and there > >> also in the wrong python directoy: 2.4 > > Basically I had the same problem(s). > > >> (How) can I change the install_dir for the extensions? > >> Why does it use python2.4 anyway?! What env var or else is set here > >> that I cannot find? > > I've patched setup.py as follows: > > --- setup.py.orig Thu Aug 10 01:42:18 2006 > +++ setup.py Mon Dec 25 19:05:29 2006 > @@ -147,6 +147,14 @@ > if ext.name in sys.builtin_module_names: > self.extensions.remove(ext) > > + # so -lpython2.5 works in the build > + ext.library_dirs.append('.') > + > + # so shared libs requiring libpython2.5.so work > + py_instdir = os.environ.get("INSTDIR_PYTHON", None) > + if py_instdir: > + ext.library_dirs.append(os.path.join(py_instdir, 'lib')) > + > if platform != 'mac': > # Parse Modules/Setup and Modules/Setup.local to figure out which > # modules are turned on in the file. > > Then you have to add INSTDIR_PYTHON to your shell environment, i.e. > > INSTDIR_PYTHON=/opt/somedir ; export INSTDIR_PYTHON > > or whatever your shell requires. > > This works for me. Hope it helps, nice workaround (and it does work), thank you... at least until when i try to install Python2.6 and forget about that again ;) since i was not quite satisfied by the solution (i will have to install py25 from source on a customer's system that i dont know much about yet at a later time and that _has_ to work then), i searched for more reasons why it fails in the first place... and actually found something: ~/.pydistutils.cfg --> install_lib = /usr/local/lib/python2.4/site-packages ... uncommented it and ran make install again --> works! :D br Florian From nanjundi at gmail.com Tue Apr 10 16:46:17 2007 From: nanjundi at gmail.com (Nanjundi) Date: 10 Apr 2007 13:46:17 -0700 Subject: Problem with getting an option value In-Reply-To: References: Message-ID: <1176237977.075245.324880@8g2000cwh.googlegroups.com> On Apr 10, 10:23 am, "Lucas Malor" <80xuux... at sneakemail.com> wrote: > Peter Otten wrote: > > Lucas Malor wrote: > > >> The problem is options is an instance, so options."delete", for example, > >> is wrong; I should pass options.delete . How can I do? > > > Use getattr(): > > Thank you. Do you know also if I can do a similar operation with functions? I want to select with a string a certain get() function of ConfigParser: > > if type == "int" : > funcname = "getint" > elif type == "bool" : > funcname = "getboolean" > etc. > > How can I invoke the funcion with its name in a string? Use exec to assign to a variable. >>> def testPrint(msg): ... print 'Msg: %s' % msg ... >>> sfunc = "testPrint" >>> exec("f = %s" % sfunc) >>> f('Hello Python') Msg: Hello Python & use 'f = self.%s' % name for class methods. Hope its not a bad practice! From rrs at researchut.com Sat Apr 7 06:09:53 2007 From: rrs at researchut.com (Ritesh Raj Sarraf) Date: Sat, 07 Apr 2007 15:39:53 +0530 Subject: Debugging multithreaded program using Eclipse/Pydev References: <1175887942.192837.187600@n76g2000hsh.googlegroups.com> Message-ID: John Henry wrote: >>From what I can gather, it appears the only real option I have is to > debug under Eclipse/Pydev. ?I did a google search of this newsgroup > and didn't turn up too many hits. ?Before I invest the time to learn > Eclipse/Pydev, I like to hear from somebody that have gone this path. > Have you been successful in using Eclipse/Pydev to debug multi- > threaded Python applications? ?Is so, what was the learning curve like > to you? I use pydev extensively for all my Python related work. And I really love it. The good part about Eclipse/PyDev is that (if you are an Eclipse user) you'll have to learn only a single IDE for all your programming works in most of the languages. The interface, the shortcut keys to step, all are the same across all languages that you use in Eclipse. As for PyDev, it works very good with Eclipse. Be it code-completion or thread debugging, all is supported. For multithreaded applications, in PyDev, you'll see all the threads listed. Then you can use each thread and proceed with debugging the code. Learning Eclipse might take some time but that's worth it. HTH, 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 apardon at forel.vub.ac.be Fri Apr 20 03:42:00 2007 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 20 Apr 2007 07:42:00 GMT Subject: Do other Python GUI toolkits require this? References: <462697A6.6010007@codebykevin.com> <1obf23tjhhpi8rotsuh0kde2ejf47p5k9l@4ax.com> Message-ID: On 2007-04-19, Wayne Brehaut wrote: > On 19 Apr 2007 10:54:20 GMT, Antoon Pardon > wrote: > >>On 2007-04-19, Michael Bentley wrote: >>> >>> On Apr 19, 2007, at 4:11 AM, Antoon Pardon wrote: >>> >>>> On 2007-04-19, Michael Bentley wrote: >>>>> >>>>> PyObjC is pretty slick (and since Ronald hasn't made any commits in a >>>>> while I'm nearly certain it'll show up in the next official >>>>> distribution of the devtools). About the time you gave up on PyQt on >>>>> the Mac and switched over to Tkinter, I switched to PyObjC. The >>>>> learning curve is rather steep IMO, but worth it. >>>> >>>> Just a throw in remark, that you may ignore if you wish, but a steep >>>> learning curve means that the subject is easily familiarized and that >>>> the learning period is short. >>>> >>>> You seem to use it as if it is the opposite. >>> >>> Mathematical absurdities aside, it's the common usage -- but perhaps >>> you knew that. >> >>I don't know how you come to the conclusion that it is a mathematical >>absurdity but consider this: If you find that common usage propagates >>something that is incorrect, should we just shrug it off or should we >>attemp a correction? There is always a chance that one day you find >>yourself exposed to a learning curve while going through a document. >>If you just depend on common usage you will probably draw the wrong >>conclusion. > > The only way one could assume the "common usage" to be a mathematical > absurdity would be not to think about it or not to have much > mathematical insight or "maturity". Is a vertical cliff not steep no > matter how high it is? And is a gentle grade (say <= 10%) not > un-steep no matter how long it is? Is the slope of a curve dependent > on its length? > > So the remark that " a steep learning curve means that the subject is > easily familiarized and that the learning period is short" is > completely incorrect on two points (i.e., all points that are > relevant): first, steep always implies much to learn in a relatively > short time (what else could the slope of a curve possibly mean > "mathematicallY" or logically?); No it doesn't imply that at all. A learning curve doesn't show some goal of a person who was given just so much time to familiarize himself with some material. A learning curve shows the progres that is made in familiarizing one self while studying. A steep curve means a lot of actual learning in a short time. > second, steepness is independent of > length, so "steep" has no implication in general about how long the > learning curve will be--on the contrary, in fact, it's quite possible > that a learning curve will never have any great challenges (steep > portions) but be only a very long gradual process--as the learning of > many natural languages is. That doesn't contradict that if one language has a steeper curve to learn than a second. Familiarisation with the first language will be faster and easier than with the second. > A learning curve is conventionally the graph of a function of > "quantity to be learned" vs. time, No it doesn't. A learning curve is the graph that somehow quantifies what is actually learned vs time. -- Antoon Pardon From erikwickstrom at gmail.com Mon Apr 2 15:09:21 2007 From: erikwickstrom at gmail.com (erikcw) Date: 2 Apr 2007 12:09:21 -0700 Subject: Math with unicode strings? Message-ID: <1175540961.679578.199370@o5g2000hsb.googlegroups.com> Hi, I'm parsing xml data with xml.sax and I need to perform some arithmetic on some of the xml attributes. The problem is they are all being "extracted" as unicode strings, so whenever I try to perform math operations on the variables, I get this error: cr[0] = data['cls1']/data['ims1']; TypeError: unsupported operand type(s) for /: 'unicode' and 'unicode' What do I need to do to extract the intergers from these unicode strings (or better yet, parse them as intergers in the first place.). I'm using the SAX method attrs.get('cls1',"") to parse the xml. Can I "cast" the string into an interger? Thanks! Erik From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Tue Apr 3 09:47:53 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Tue, 03 Apr 2007 15:47:53 +0200 Subject: raw_input just continues anyway? References: <1175606844.249364.290060@o5g2000hsb.googlegroups.com> Message-ID: <57f489F2c787iU1@mid.individual.net> oliver at obeattie.com wrote: > if __name__ == "__main__": > bucket_name = raw_input('Name of the bucket you wish the files to be placed into? ') > update_s3() > > Basically, it just asks the question and continues anyway? It reads stdin until a line break. Then it continues. Exactly what behaviour do you get? Regards, Bj?rn -- BOFH excuse #328: Fiber optics caused gas main leak From jura.grozni at gmail.com Fri Apr 13 04:17:27 2007 From: jura.grozni at gmail.com (azrael) Date: 13 Apr 2007 01:17:27 -0700 Subject: Problem with algorithm In-Reply-To: <1176448576.047996.12930@d57g2000hsg.googlegroups.com> References: <1176434160.047703.214600@q75g2000hsh.googlegroups.com> <1176434937.258002.162220@p77g2000hsh.googlegroups.com> <1176448576.047996.12930@d57g2000hsg.googlegroups.com> Message-ID: <1176452247.231807.65060@e65g2000hsc.googlegroups.com> I think that this would be very silly to do. bad kung foo. The recoursion technique would be more satisfying. You sholud consider that this would take about 4 lines to write. Also be avare of the default recoursion depth in python wich is 1000. you can get and set the recoursion limit hrough importing the "sys" module and using getrecoursionlimit() and setrecoursionlimit(). On Apr 13, 9:16 am, "Jia Lu" wrote: > > for m in test: > > for n in test: > > for o in test: > > for p in test: > > print m+n+o+p > > Thanx for your anwser. > But if I consider about a combination of over 26 letter's list just > like: > "abcdefssdzxcvzxcvzcv" > "asllxcvxcbbedfgdfgdg" > ..... > > Need I write 26 for loops to do this? > > Thanx > > Jia LU From gordonlr at DELETEswbell.net Sun Apr 29 14:14:41 2007 From: gordonlr at DELETEswbell.net (Gordon) Date: Sun, 29 Apr 2007 13:14:41 -0500 Subject: Video: Professor of Physics Phd at Cal Tech says: 911 Inside Job References: <1177467203.719625.93920@u32g2000prd.googlegroups.com> Message-ID: On Thu, 26 Apr 2007 00:33:19 GMT, "Bill Habr" wrote: > > wrote in message >news:1177467203.719625.93920 at u32g2000prd.googlegroups.com... >> Cal Tech is the ELITE of ELITE in physics. >> >> If Feynman were alive, he would point his finger straight at the 911 >> criminal operators, the yank bastards themselves ....... >> >> http://www.911blogger.com/node/8101 >> >> No self-respecting scientist should keep his mouth shut. Its a >> fundamental challenge to the method of science, a detective work most >> demanding of INTELLECTUAL HONESTY. >> > >Isn't this the guy who has more conspiracy theories than Carter has pills? > >Whitewater, Vince Foster, moon landing hoax one week - we found a UFO on the moon the >next, Oklahoma City bombing, a new conspiracy every day ad nauseum? > Maybe the thread title is wrong. Should it perhaps read, "Video Professor took a physic then spewed out some really stinky stuff." From __peter__ at web.de Wed Apr 18 06:53:46 2007 From: __peter__ at web.de (Peter Otten) Date: Wed, 18 Apr 2007 12:53:46 +0200 Subject: What makes an iterator an iterator? References: Message-ID: Steven D'Aprano wrote: > class SortedDict(dict): > ????def?__iter__(self): > ????????for?key?in?sorted(self.keys()): > ????????????yield?key > > Note that using sorted(self) does not work. That's because sorted() invokes __iter__() if present. To prevent the recursion you can explicitly invoke dict.__iter__(): >>> class SortedDict(dict): ... def __iter__(self): ... return iter(sorted(super(SortedDict, self).__iter__())) ... >>> sd = SortedDict(a=1, b=2, c=3) >>> list(sd) ['a', 'b', 'c'] Note that a list of keys is still built before the first key is yielded, and, unlike dict, you can modify your SortedDict while iterating over it: >>> for k in sd: ... if k == "b": sd["x"] = 42 ... >>> sd {'a': 1, 'x': 42, 'c': 3, 'b': 2} whereas: >>> d = dict(a=1, b=2, c=3) >>> for k in d: ... if k == "b": d["x"] = 42 ... Traceback (most recent call last): File "", line 1, in RuntimeError: dictionary changed size during iteration By the way, I think it would be worthwile to change super() to allow e. g. super(SomeClass, self)[...] as an alternate spelling for super(SomeClass, self).__getitem__(...) etc. With such an enhancement SortedDict would become class SortedDict(dict): def __iter__(self): # doesn't work in current Python iter(sorted(super(SortedDict, self))) Peter From elguavas at users.sourceforge.net Sat Apr 21 00:05:30 2007 From: elguavas at users.sourceforge.net (Stephen M. Gava) Date: Sat, 21 Apr 2007 04:05:30 -0000 Subject: using tkinter to display html References: <1176988173.015892.273660@e65g2000hsc.googlegroups.com> <1177051369.897460.109980@e65g2000hsc.googlegroups.com> Message-ID: On Thu, 19 Apr 2007 23:42:49 -0700, Glenn Hutchings wrote: > On 20 Apr, 02:54, "Stephen M. Gava" > wrote: >> yeah. i feel like i'm being forced to use wxwidgets/wxpython just >> because i need pretty good html display though. > > You could always use a real web browser: > > import webbrowser > webbrowser.open_new("index.html") > > Glenn yep, thnx glen, but need the html display windo to be more a part of the app than that. stephen. From kyosohma at gmail.com Wed Apr 4 13:31:05 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: 4 Apr 2007 10:31:05 -0700 Subject: only loading a language installed on system In-Reply-To: <1175668048.344217.185780@n76g2000hsh.googlegroups.com> References: <1175668048.344217.185780@n76g2000hsh.googlegroups.com> Message-ID: <1175707865.382003.235070@l77g2000hsb.googlegroups.com> On Apr 4, 1:27 am, "ianar?" wrote: > i'm doing this: > > mylocale = wx.Locale(wx.LANGUAGE_POLISH, wx.LOCALE_LOAD_DEFAULT) > if not wx.Locale.IsOk(mylocale): > mylocale = wx.Locale(wx.LANGUAGE_DEFAULT, wx.LOCALE_LOAD_DEFAULT) > > and getting this: > Segmentation fault (core dumped) > > I'm trying to see if I can properly load a language. If the system > will not load it, then use system default. What am I doing wrong? > > TIA You would probably be better off to post this question to the wxPython users group: http://wxpython.org/maillist.php Here's some related links about Internationalization with wxPython though: http://wiki.wxpython.org/index.cgi/Internationalization http://wiki.wxpython.org/index.cgi/RecipesI18n Mike From cam.ac.uk at mh391.invalid Sun Apr 1 21:43:37 2007 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Mon, 02 Apr 2007 02:43:37 +0100 Subject: can a method access/set another's variables? In-Reply-To: <1175477764.549115.159410@n59g2000hsh.googlegroups.com> References: <1175477764.549115.159410@n59g2000hsh.googlegroups.com> Message-ID: asdf1234234 wrote: > -a.py- > import b > > class A: > def __init__(self): > pass > def my_method(self): > var = 1 > self.var = 2 > b.set_var(self) > print var > print self.var > > my_a = A() > my_a.my_method() > > -b.py- > def set_var(self): > var = 2 > self.var = 2 > > I want both var and self.var to be 2 at the end. Is there anything I > can pass to set_var() that will give it access to the variables in > my_method() like I can use self for the variables in the class A? I hope there isn't a way to do this that simply. :) Why do you want to do this, or is it idle curiosity? There is almost surely a better way to solve your underlying problem. You can *read* your caller's local variables (either pass locals() as an argument or use inspect to get the frame locals), but writing to this dictionary has undefined behavior. -- Michael Hoffman From dillonco at comcast.net Sat Apr 14 17:27:59 2007 From: dillonco at comcast.net (DillonCo) Date: Sat, 14 Apr 2007 17:27:59 -0400 Subject: That might be the case for more complex objects... In-Reply-To: References: <1176546078.934340.253810@y5g2000hsa.googlegroups.com> <7saUh.37$4S1.2@newsfe12.lga> Message-ID: <200704141727.59681.dillonco@comcast.net> On Saturday 14 April 2007, James Stroud wrote: > I think that after a += 1, a memory location with a 6 is created and now > a points to that because += has assignment buried in it. Bingo. a+=1 will (basically) translate to either "a=a.__iadd__(1)" or "a=a.__add__(1)" depending on whether __iadd__ is defined of not. >>> '__iadd__' in dir(5) False >>> '__add__' in dir(5) True So therefore "a+=1" becomes "a=a.__add__(a, 1)" That make is relatively obvious that a '6' would be created and assigned back to a. You can have some fun with this using the 'is' operator. Remember that 'is' compares objects and not values. So different objects can be equal, but aren't the same. Thus: >>> a=[1,2,3] >>> b=[1,2,3] >>> a == b True >>> a is b False To demonstrate the idea of name binding: >>> a=500 >>> b=500 >>> a == b True >>> a is b False >>> b=a >>> a is b True So typing the literal '500' creates an integer object with the value 500. By typing it twice, two different objects of identical value are created and "put in" two variables. However, by assigning one from the other, the same object (created by the literal '500') is assigned to both variables. This is why Python calls assignments "bindings"; you're realling just binding the object from the right side to the name on the left. For confusion's sake, here's what happens if you use smaller numbers: >>> a=1 >>> b=1 >>> a is b True >>> 3-2 is a True That happens because CPython (a particular and very common implementation of Python) pre-creates objects for all small integers (something like <=100). This saves memory, because all values of '1' are the same! So the literal '1' simply gets a reference to the existing object of value '1', rather than creating a new one (like the literal '500' does). The same is also true for strings with len<=1. From psdasilvaX at esotericaX.ptX Tue Apr 3 00:08:42 2007 From: psdasilvaX at esotericaX.ptX (Paulo da Silva) Date: Tue, 03 Apr 2007 05:08:42 +0100 Subject: getattr/setattr q. Message-ID: <1175573213.682671@jubilee.claranet.pt> Hi! In a class C, I may do setattr(C,'x',10). Is it possible to use getattr/setattr for variables not inside classes or something equivalent? I mean with the same result as exec("x=10"). Thanks. From yinglcs at gmail.com Thu Apr 19 17:03:55 2007 From: yinglcs at gmail.com (yinglcs at gmail.com) Date: 19 Apr 2007 14:03:55 -0700 Subject: How to upgrade python from 2.3 to 2.4 Message-ID: <1177016635.483952.27450@y5g2000hsa.googlegroups.com> Hi, Red hat 4 comes with python 2.3, and I am trying to upgrade to python 2.4. So I download and compile the source of python2.4. But as I run it I get the following error, can you please tell me how to fix it? # /root/src/Python-2.4.4/python ./nov/scripts/stressTestServlet.py ./ nov/scripts/stressTestInputFile 10 127.0.0.1 Traceback (most recent call last): File "./nov/scripts/stressTestServlet.py", line 6, in ? import time ImportError: No module named time From python at hope.cz Wed Apr 25 05:17:36 2007 From: python at hope.cz (python at hope.cz) Date: Wed, 25 Apr 2007 11:17:36 +0200 Subject: How to change font colour Message-ID: <462F38D0.16786.17E9FB1C@python.hope.cz> An HTML attachment was scrubbed... URL: From forgems at gmail.com Mon Apr 2 03:38:24 2007 From: forgems at gmail.com (forgems) Date: 2 Apr 2007 00:38:24 -0700 Subject: vim python: substitute 'spaces' indent to 'tabs'? In-Reply-To: <1175491803.283208.198020@l77g2000hsb.googlegroups.com> References: <1175491803.283208.198020@l77g2000hsb.googlegroups.com> Message-ID: <1175499504.792462.203190@b75g2000hsg.googlegroups.com> On Apr 2, 7:30 am, "Rocky Zhou" wrote: > I am accustomed to vi my pthon scripts with 'tab' indent. But when I > copy some code to my script, the indent may be 'spaces'. So I wanna a > way to substitute those 'spaces' to be 'tabs' conveniently. > > For example, I: > expand -t4 test.py >/tmp/test2.py > vi /tmp/test2.py > > Then in vim, the indents should be: > /^\( \{4\}\)*/ > but I don't know how to substitute this to that: > /^\(\t\{\4\}\)*/ > > Is there any way? > > Thanks. :set noet :retab From half.italian at gmail.com Wed Apr 18 16:34:46 2007 From: half.italian at gmail.com (half.italian at gmail.com) Date: 18 Apr 2007 13:34:46 -0700 Subject: image sequence to Quicktime movie In-Reply-To: References: Message-ID: <1176928486.052815.244700@b58g2000hsg.googlegroups.com> I haven't experimented with it myself, but you'll probably find what you need here. (Only works on original mac python distribution) [sean:~] sean% python Python 2.3.5 (#1, Aug 12 2006, 00:08:11) [GCC 4.0.1 (Apple Computer, Inc. build 5363)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> from Carbon import Qt >>> dir(Qt) ['AddSoundDescriptionExtension', 'AddTime', 'AlignWindow', 'CanQuickTimeOpenDataRef', 'CanQuickTimeOpenFile', 'ClearMoviesStickyError', 'CloseMovieFile', 'ConvertTime', 'ConvertTimeScale', 'CreateMovieFile', 'CreateShortcutMovieFile', 'DeleteMovieFile', 'DisposeMatte', 'DragAlignedWindow', 'EndFullScreen', 'EnterMovies', 'Error', 'ExitMovies', 'FlashMediaDoButtonActions', 'FlashMediaFrameLabelToMovieTime', 'FlashMediaFrameNumberToMovieTime', 'FlashMediaGetDisplayedFrameNumber', 'FlashMediaGetFlashVariable', 'FlashMediaGetRefConBounds', 'FlashMediaGetRefConID', 'FlashMediaGetSupportedSwfVersion', 'FlashMediaIDToRefCon', 'FlashMediaSetFlashVariable', 'FlashMediaSetPan', 'FlashMediaSetZoom', 'FlashMediaSetZoomRect', 'GetDataHandler', 'GetMovieImporterForDataRef', 'GetMoviesError', 'GetMoviesStickyError', 'GetSoundDescriptionExtension', 'Media', 'Media3DGetCameraAngleAspect', 'Media3DGetCameraData', 'Media3DGetCameraRange', 'Media3DGetCurrentGroup', 'Media3DRotateNamedObjectTo', 'Media3DScaleNamedObjectTo', 'Media3DSetCameraAngleAspect', 'Media3DSetCameraData', 'Media3DSetCameraRange', 'Media3DTranslateNamedObjectTo', 'MediaType', 'Movie', 'MovieController', 'MovieControllerType', 'MovieType', 'MoviesTask', 'MusicMediaGetIndexedTunePlayer', 'NewMovie', 'NewMovieFromDataFork', 'NewMovieFromDataFork64', 'NewMovieFromDataRef', 'NewMovieFromFile', 'NewMovieFromHandle', 'NewMovieFromScrap', 'NewTimeBase', 'NewUserData', 'NewUserDataFromHandle', 'OpenMovieFile', 'PasteHandleIntoMovie', 'QTDismissStandardParameterDialog', 'QTGetMIMETypeInfo', 'QTIsStandardParameterDialogEvent', 'QTNewAlias', 'QTRegisterAccessKey', 'QTStandardParameterDialogDoAction', 'QTTextToNativeText', 'QTUnregisterAccessKey', 'RemoveMovieResource', 'RemoveSoundDescriptionExtension', 'SpriteMediaCountImages', 'SpriteMediaCountSprites', 'SpriteMediaDisposeSprite', 'SpriteMediaGetActionVariable', 'SpriteMediaGetActionVariableAsString', 'SpriteMediaGetDisplayedSampleNumber', 'SpriteMediaGetImageName', 'SpriteMediaGetIndImageDescription', 'SpriteMediaGetProperty', 'SpriteMediaGetSpriteName', 'SpriteMediaGetSpriteProperty', 'SpriteMediaHitTestAllSprites', 'SpriteMediaHitTestOneSprite', 'SpriteMediaHitTestSprites', 'SpriteMediaSetActionVariable', 'SpriteMediaSetActionVariableToString', 'SpriteMediaSetProperty', 'SpriteMediaSetSpriteProperty', 'SpriteMediaSpriteIDToIndex', 'SpriteMediaSpriteIndexToID', 'SubtractTime', 'TextMediaAddHiliteSample', 'TextMediaAddTESample', 'TextMediaAddTextSample', 'TextMediaDrawRaw', 'TextMediaFindNextText', 'TextMediaGetTextProperty', 'TextMediaHiliteTextSample', 'TextMediaRawIdle', 'TextMediaRawSetup', 'TextMediaSetTextProperty', 'TextMediaSetTextSampleData', 'TimeBase', 'TimeBaseType', 'Track', 'TrackTimeToMediaTime', 'TrackType', 'UserData', 'UserDataType', 'VideoMediaGetCodecParameter', 'VideoMediaGetStallCount', 'VideoMediaGetStatistics', 'VideoMediaResetStatistics', 'VideoMediaSetCodecParameter', '__builtins__', '__doc__', '__file__', '__name__'] >>> ~Sean On Apr 18, 10:16 am, Simon Cassels wrote: > did u ever find anything out about this ? > > if so can you help me with some leads i am trying to figure an action > that can convert image files to quicktime automatically. > > cheers > simon From steve at holdenweb.com Tue Apr 10 10:57:25 2007 From: steve at holdenweb.com (Steve Holden) Date: Tue, 10 Apr 2007 10:57:25 -0400 Subject: tuples, index method, Python's design In-Reply-To: <1176214831.3430.49.camel@dot.uniqsys.com> References: <1175867771.114540.61810@n76g2000hsh.googlegroups.com> <1175884427.779950.267220@y80g2000hsf.googlegroups.com> <1175953520.316208.241490@o5g2000hsb.googlegroups.com> <7xzm5igbrb.fsf@ruckus.brouhaha.com> <1176200361.260546.280510@n76g2000hsh.googlegroups.com> <1176214831.3430.49.camel@dot.uniqsys.com> Message-ID: Carsten Haese wrote: > On Tue, 2007-04-10 at 09:57 -0400, Steve Holden wrote: >> I hear the screams of "just add the index() method to tuples and have >> done with it" and, to an extent, can sympathize with them. But that way >> lies creeping featurism and the next thing you know we'll have a ternary >> operator in the language - oh wait, we do now! > > It would indeed be much easier to just give up. However, the resistance > to tuple.index is more than a generic resistance to feature creep. As I > have demonstrated elsewhere on this thread, any use case for tuple.index > will be inherently obfuscated. Code clarity is a major design goal of > Python, and adding tuple.index would be contrary to this goal. > > I'm just a user with no influence on the development of Python itself, > but in my humble opinion, the non-existence of tuple.index is more > pythonic than its existence would be. > I quite agree. I was not advocating it as a serious course of action, more admiring its noise-reduction potential. I'm no great fan of the if ... else expression either, come to that. 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 adam at atlas.st Sun Apr 29 11:28:39 2007 From: adam at atlas.st (Adam Atlas) Date: 29 Apr 2007 08:28:39 -0700 Subject: editing scripts on a mac In-Reply-To: References: Message-ID: <1177860519.636917.114890@e65g2000hsc.googlegroups.com> On Apr 27, 12:08 pm, Steve Holden wrote: > Now, frankly, I don't think this answer is correct, since I know OS X is > a UNIX derivative, but I am loathe to involve a programming noob with vi > or something similar. So I wondered if one of the c.l.py mac users could > give brief instructions for firing up a visual text editor of some sort > and saving a file somewhere it can easily be accessed from a terminal > window (which I presume starts up in his home directory). I strongly recommend TextMate (http://www.macromates.com/). It's not free, but it rocks. There's also TextWrangler (http://www.barebones.com/products/ textwrangler/), a free (as in beer) lite version of BBEdit, the most venerable Mac text editor. I used to use BBEdit; it's quite excellent, though TextMate feels a bit more modern and OS X-like. From robert.rawlins at thinkbluemedia.co.uk Mon Apr 30 08:46:09 2007 From: robert.rawlins at thinkbluemedia.co.uk (Robert Rawlins - Think Blue) Date: Mon, 30 Apr 2007 13:46:09 +0100 Subject: Dict Copy & Compare In-Reply-To: <4635D8F4.5010308@timgolden.me.uk> References: <00da01c78b01$3e80b900$bb822b00$@rawlins@thinkbluemedia.co.uk> <4635AB95.4010309@timgolden.me.uk> <000601c78b06$b9fb0950$2df11bf0$@rawlins@thinkbluemedia.co.uk> <4635B38E.5020606@timgolden.me.uk> <000701c78b10$1e8aa9d0$5b9ffd70$@rawlins@thinkbluemedia.co.uk> <4635C473.4010109@timgolden.me.uk> <000e01c78b18$03457cb0$09d07610$@rawlins@thinkbluemedia.co.uk> <4635D8F4.5010308@timgolden.me.uk> Message-ID: <002101c78b25$87e65ae0$97b310a0$@rawlins@thinkbluemedia.co.uk> No that makes sense Tim, Thanks again for all your help on this one, it'll all prove invaluable I'm sure. I managed to crack all the big troubles last week with my reoccurring tasks, it's just a case of tidying up a few of these loose ends, then that'll be python project no.1 over and done with :-D Thanks, Rob -----Original Message----- From: python-list-bounces+robert.rawlins=thinkbluemedia.co.uk at python.org [mailto:python-list-bounces+robert.rawlins=thinkbluemedia.co.uk at python.org] On Behalf Of Tim Golden Sent: 30 April 2007 12:54 Cc: python-list at python.org Subject: Re: Dict Copy & Compare Robert Rawlins - Think Blue wrote: > On[e] quick question, how can I order a dict by > the 'values' (not keys) before looping? Is that possible? Depends on what you want to do. You can loop on the sorted values very easily: d1 = dict (a=2, b=1) for value in sorted (d1.values): print value but inferring the equivalent key is, in effect, not possible since more than one key might correspond to that value. Depending on what you're after, the following technique might be of use: import operator d = dict (a=2, b=1, c=-1, d=4) for k, v in sorted ( d.items (), key=operator.itemgetter (1) ): print k, "=>", v It may look a bit hairy, but break it down: d.items () returns a list of 2-tuples, each one corresponding to a key-value pair from the dict. In our case, that'll be: [('a', 2), ('b', 1), ('c', -1), ('d', 4)] Although I've written them out like that, the order they'll come in is undefined. sorted () will return a sorted version of whatever iterable you chuck at it. Under normal Python semantics, sorted() on the list above will return no change since I've listed things out in alphanumeric order. The extra key= parameter tells the sorted routine to call the function you provide against each of the items in the list (in our case that means against each of the 2-tuples) and using the result of that function as the sorting order. The operation.itemgetter (1) bit is a touch complicated unless you're already familiar with partial functions, but it basically returns *another* function which takes the item you give it and returns the -- in this case -- 1st item. Just believe me: it works. So, in summary: + Get a list of key-value pairs + Sort them according to the 1st item (Python-style) which in this case is the value. + Do something with the result Before the key= param was introduced into sort/sorted, people used to do the same thing with what's often called DSU (short for decorate-sort-undecorate), a technique which here would look something like this: items = d.items () sortable_items = [(i[1], i) for i in items] sortable_items.sort () sorted_items = [i[-1] for i in sortable_items] I mention this because (a) you still see it around a fair bit and (b) there are occasions where it's still useful, for example where a simple function call can't really cope. (Did I answer the question, or was I just rambling?) TJG -- http://mail.python.org/mailman/listinfo/python-list From martin at v.loewis.de Mon Apr 23 01:24:21 2007 From: martin at v.loewis.de (=?ISO-8859-15?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Mon, 23 Apr 2007 07:24:21 +0200 Subject: Python's handling of unicode surrogates In-Reply-To: References: <1177051493.468698.176740@b75g2000hsg.googlegroups.com> <4629591a$0$13629$9b622d9e@news.freenet.de> <1177122874.524447.85130@p77g2000hsh.googlegroups.com> Message-ID: <462C4305.1000809@v.loewis.de> > The Unicode standard doesn't require that you support surrogates, or > any other kind of character, so no you wouldn't be lying. There is the notion of Unicode implementation levels, and each of them does include a set of characters to support. In level 1, combining characters need not to be supported (which is sufficient for scripts that can be represented without combining characters, such as Latin and Cyrillic, using precomposed characters if necessary). In level 2, combining characters must be supported for some scripts that absolutely need them, and in level 3, all characters must be supported. It is probably an interpretation issue what "supported" means. Python clearly supports Unicode level 1 (if we leave alone the issue that it can't render all these characters out of the box, as it doesn't ship any fonts); it could be argued that it implements level 3, as it is capable of representing all Unicode characters (but, of course, so does Python 1.5.2, if you put UTF-8 into byte strings). Regards, Martin From exarkun at divmod.com Tue Apr 17 09:52:58 2007 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Tue, 17 Apr 2007 09:52:58 -0400 Subject: Using X509 (and TLSlite) authentication In-Reply-To: Message-ID: <20070417135258.19381.499637477.divmod.quotient.2436@ohm> On Tue, 17 Apr 2007 13:44:05 GMT, Chaz Ginger wrote: >I have been looking for a server application as an example of how to use >TLSLite or PyOpenSSL X509 certificates for authentication. Does any one >have a pointer or two? You might want to take a look at the code in Twisted for this. It's based on PyOpenSSL. http://twistedmatrix.com/trac/browser/trunk/twisted/internet/_sslverify.py Jean-Paul From stewart.midwinter at gmail.com Thu Apr 12 00:40:25 2007 From: stewart.midwinter at gmail.com (midtoad) Date: 11 Apr 2007 21:40:25 -0700 Subject: What happened to http://www.pythonware.com/daily and http://mechanicalcat.net/pyblagg.html? In-Reply-To: <1176352737.116063.67570@d57g2000hsg.googlegroups.com> References: <1175957075.056246.15120@l77g2000hsb.googlegroups.com> <1176063723.883976.145570@d57g2000hsg.googlegroups.com> <1176352737.116063.67570@d57g2000hsg.googlegroups.com> Message-ID: <1176352825.703737.20920@n76g2000hsh.googlegroups.com> BTW, there's an update on the Pythonware.com/daily list again today, April 11th. Yay! S From ptmcg at austin.rr.com Tue Apr 10 15:57:35 2007 From: ptmcg at austin.rr.com (Paul McGuire) Date: 10 Apr 2007 12:57:35 -0700 Subject: OT: Question about RGB color method In-Reply-To: <1176234785.473773.181840@s48g2000cws.googlegroups.com> References: <461be63b$0$31839$c3e8da3@news.astraweb.com> <1176234785.473773.181840@s48g2000cws.googlegroups.com> Message-ID: <1176235055.483443.186960@l30g2000cwa.googlegroups.com> Ah, the Wikipedia article for "Primary Colors" is much better at explaining this than the one for "RGB Color". For instance, in the Tempra-paint-compatible subtractive system, you probably recall mixing red, yellow, and blue, and getting black, or at least a dark muddy brown. Conversely, in the additive system of RGB, mixing red, green, and blue, gives you... white! You've combined all the light there is, you should get the lightest color of them all. -- Paul From steve at holdenweb.com Fri Apr 20 00:52:21 2007 From: steve at holdenweb.com (Steve Holden) Date: Fri, 20 Apr 2007 00:52:21 -0400 Subject: List of Objects In-Reply-To: References: <1177037915.042476.153190@n76g2000hsh.googlegroups.com> Message-ID: Steven D'Aprano wrote: [...] > > Forth method: create identical gazelles, then modify them: > > list_of_beasties = [Gazelle(defaults) for i in xrange(1000)] > for i, beastie in enumerate(xrange(1000)): > list_of_beasties[i] = modify(beastie) > Nope, 'sorry, that's Python a's well. Forth u'se's rever'se Poli'sh notation. regard's "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 holdenweb.com Mon Apr 16 07:44:15 2007 From: steve at holdenweb.com (Steve Holden) Date: Mon, 16 Apr 2007 07:44:15 -0400 Subject: Getting started with python In-Reply-To: References: <1176598011.463543.96990@q75g2000hsh.googlegroups.com> <1176608302.928513.274400@y5g2000hsa.googlegroups.com> <%LyUh.10121$YL5.5753@newssvr29.news.prodigy.net> Message-ID: James Stroud wrote: > Steve Holden wrote: >> You'd be worth more if you'd used elif and omitted the continue >> statements, but for a first solution it's acceptable. > > Depends on what you are after. > > py> s = """ > ... for i in xrange(1,101): > ... if not i % 15: > ... continue > ... if not i % 5: > ... continue > ... if not i % 3: > ... continue > ... else: > ... pass > ... """ > py> t = timeit.Timer(stmt=s) > py> print "%.2f usec/pass" % (1000000 * t.timeit(number=100000)/100000) > 40.49 usec/pass > py> s = """ > ... for i in xrange(1,101): > ... if not i % 15: > ... pass > ... elif not i % 5: > ... pass > ... elif not i % 3: > ... pass > ... else: > ... pass > ... """ > py> t = timeit.Timer(stmt=s) > py> print "%.2f usec/pass" % (1000000 * t.timeit(number=100000)/100000) > 40.88 usec/pass > To be strictly comparable you should have pass statements before the continue statements as well. Ignoring that, clearly it's well worth saving that extra 390 nanoseconds each time round the loop. Repeat after me "premature optimization is the root of all evil". http://en.wikipedia.org/wiki/Optimization_(computer_science) 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 grante at visi.com Tue Apr 24 00:40:11 2007 From: grante at visi.com (Grant Edwards) Date: Tue, 24 Apr 2007 04:40:11 -0000 Subject: getting scancodes References: Message-ID: <132r2hb2gltbf4d@corp.supernews.com> On 2007-04-24, andmarti at gmail.com wrote: > Anyone knows if its possible to get scan codes ??? What hardware? What OS? > I tried with getch () but with no success, just keycodes. > May be using the something in the sys.stdin module ?? > > Please, any help would be very appreciated. You're going to have to be a little more specific... -- Grant Edwards grante Yow! I'm encased in the at lining of a pure pork visi.com sausage!! From a.schmolck at gmail.com Wed Apr 4 15:47:59 2007 From: a.schmolck at gmail.com (Alexander Schmolck) Date: 04 Apr 2007 20:47:59 +0100 Subject: String manipulation References: <1175699768.427986.210310@l77g2000hsb.googlegroups.com> <1175702569.161940.113040@y66g2000hsf.googlegroups.com> Message-ID: marco.minerva at gmail.com writes: > Thank you very much, your code works perfectly! One thing I forgot: you might want to make the whitespace handling a bit more robust/general e.g. by using something along the lines of set_phrase.replace(' ', r'\w+') 'as From erikwickstrom at gmail.com Mon Apr 9 13:11:56 2007 From: erikwickstrom at gmail.com (erikcw) Date: 9 Apr 2007 10:11:56 -0700 Subject: MySQL Insert Unicode Problem Message-ID: <1176138716.534847.209890@n59g2000hsh.googlegroups.com> Hi, I'm trying to insert some data from an XML file into MySQL. However, while importing one of the files, I got this error: Traceback (most recent call last): File "wa.py", line 304, in ? main() File "wa.py", line 257, in main curHandler.walkData() File "wa.py", line 112, in walkData self.cursor.execute(*sql) #try multi-execute to speed up query. File "build/bdist.linux-i686/egg/MySQLdb/cursors.py", line 151, in execute File "build/bdist.linux-i686/egg/MySQLdb/connections.py", line 247, in literal File "build/bdist.linux-i686/egg/MySQLdb/connections.py", line 185, in unicode_literal UnicodeEncodeError: 'latin-1' codec can't encode character u'\u20ac' in position 28: ordinal not in range(256) What do I need to change to make this work? Thanks! Erik From jstroud at mbi.ucla.edu Sat Apr 14 07:41:13 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Sat, 14 Apr 2007 11:41:13 GMT Subject: Python Feature Request: Add the "using" keyword which works like "with" in Visual Basic In-Reply-To: <1176549606.542551.36480@b75g2000hsg.googlegroups.com> References: <1176547372.584539.89170@q75g2000hsh.googlegroups.com> <1176549606.542551.36480@b75g2000hsg.googlegroups.com> Message-ID: jamadagni wrote: >> I like this one for some reason. Just the "using self" would save hella >> typing in a lot of classes. I would favor a convention with leading dots >> to disambiguate from other variables. This wouldn't conflict with, say, >> floats, because variable names can't begin with a number. > > Excellent. Now we don't have to worry about the "first applicable > instance" etc. Any member that begins with a dot will have the context > governer auto-prefixed by the parser. This means that nested using > statements should be like follows: > > using self: > __using .quit: Under what circumstances would this not mean "using self.quit"? I think one must be refreshingly imaginative to infer that I was proposing that we add "." to variable names in general. The idea would be that it specifies to which names the using statement applies. James From DustanGroups at gmail.com Sat Apr 21 17:13:34 2007 From: DustanGroups at gmail.com (Dustan) Date: 21 Apr 2007 14:13:34 -0700 Subject: Easy make money! In-Reply-To: <1177188351.751842.169370@d57g2000hsg.googlegroups.com> References: <1177188351.751842.169370@d57g2000hsg.googlegroups.com> Message-ID: <1177190013.974042.231630@d57g2000hsg.googlegroups.com> On Apr 21, 3:45 pm, GPcapital wrote: > Lately I've been surfing trought some web pages and got this one > www.gpcapitalgroup.com. It looks quite interesting, it may be a great > chance to invest. >>> advertisement.delete() Traceback (most recent call last): File "", line 1, in advertisement.delete() ActionNotPossibleError: advertisements are a fact of life >>> advertisement.ignore() Traceback (most recent call last): File "", line 1, in advertisement.ignore() ActionNotPossibleError: they're all around us From haraldarminmassa at gmail.com Sun Apr 29 05:06:05 2007 From: haraldarminmassa at gmail.com (GHUM) Date: 29 Apr 2007 02:06:05 -0700 Subject: While we're talking about annoyances In-Reply-To: References: Message-ID: <1177837565.317999.244420@c35g2000hsg.googlegroups.com> Steven, > def index(sequence): > decorated = zip(sequence, xrange(len(sequence))) > decorated.sort() > return [idx for (value, idx) in decorated] would'nt that be equivalent code? def index(sequence): return [c for _,c in sorted((b,a) for a, b in enumerate(sequence))] tested, gave same results. But worsens your doc2code ratio :) Harald Armin Massa -- From gagsl-py2 at yahoo.com.ar Mon Apr 9 12:04:00 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 09 Apr 2007 13:04:00 -0300 Subject: Kill thread References: <1176110066.940676.173020@e65g2000hsc.googlegroups.com> Message-ID: En Mon, 09 Apr 2007 06:14:26 -0300, Teja escribi?: > Can any on help me out in killing a thread (i.e deleteing the reources > like, stack ,memory etc) which is started with > win32process.beginthreadex()??? As you can read on: http://msdn2.microsoft.com/en-us/library/kdzttdcb(VS.80).aspx if you use this C runtime function, you should call _endthreadex() (from the same thread you want to end!) I wonder, why don't you use the thread support already present in Python? -- Gabriel Genellina From C.delete_this.Sanders at BoM.GOv.AU Tue Apr 24 05:06:42 2007 From: C.delete_this.Sanders at BoM.GOv.AU (Charles Sanders) Date: Tue, 24 Apr 2007 19:06:42 +1000 Subject: Strange terminal behavior after quitting Tkinter application In-Reply-To: <1177389473.935407.20950@o40g2000prh.googlegroups.com> References: <1177389473.935407.20950@o40g2000prh.googlegroups.com> Message-ID: <462dc8a4$0$44860$c30e37c6@lon-reader.news.telstra.net> Chris wrote: > ... Quitting by typing 'sys.exit()' in the interpreter > also works fine. Only quitting via the GUI seems to cause the > problem. As previously stated, I know nothing about Tkinter, but it definitely looks like there is some cleanup being skipped on a GUI exit that is in fact being run on exit via ^D and sys.exit from the terminal. If I remember correctly, the low level details of how this sort of thing is usually handled on unix like systems is for the application to - Do an ioctl TCGETA system call to get the current settings, and save them somewhere. - Do an ioctl TCSETA system call to change the settings. - Arrange, via signal handlers, atexit, or other means for a cleanup routine to be called on exit. - The cleanup routine does an ioctl TCSETA call with the saved settings. (all this would typically involve C calls) I believe that in your case this last cleanup is being omitted on exit via the GUI. > For the moment, including the line 'os.system("stty sane")' > before sys.exit() is the solution I'll use. If that is satisfactory, well and good. However, there is a possibility that you may lose some settings that you would prefer to keep. The terminal settings have been trashed, and stty sane has restored a minimally workable set, but some settings may not be what you expect. If you are on a unix like system (eg Linux), and can wrap your Tkinter application in a shell script, you should be able to save/restore the settings outside of Tkinter and python, ie #! /bin/sh saved_settings=`stty -g` i # Note backquotes, save current settings python Tkinter-application.py # Or whatever stty "$saved_settings" i # Restore settings Doing the save within the Tkinter application, with (for example) os.system("stty -g > saved_settings") and os.system("stty `cat saved_settings`") may not work as the setting may have been changed by Tkinter before you get a chance to save them - I just do not know. Just in case, I did a google search. I am not familiar with TKinter, but a couple of articles out there imply that rather than calling sys.exit you should be calling a TkInter routine root.destroy. I am not sure if root is a variable for the main window (ie you call the destroy method on the main window) or if it has some special Tkinter meaning. Presumably this routine cleans things up before calling sys.exit or an equivalent. Charles From malaclypse2 at gmail.com Tue Apr 3 11:31:14 2007 From: malaclypse2 at gmail.com (Jerry Hill) Date: Tue, 3 Apr 2007 11:31:14 -0400 Subject: Problem with filter() In-Reply-To: <09042D621CD4AA479C678463F3A646D0F73D24@sottemail1.ent.ad.cognos.com> References: <09042D621CD4AA479C678463F3A646D0F73D1A@sottemail1.ent.ad.cognos.com> <09042D621CD4AA479C678463F3A646D0F73D24@sottemail1.ent.ad.cognos.com> Message-ID: <16651e80704030831y51ebcfes316c29324b2fc680@mail.gmail.com> On 4/3/07, Boudreau, Emile wrote: > Sorry folks my mistake def is_dev should be: > def is_Dev(stringy): > stringx = stringy.split('-') > if stringx[0] == '': > if stringx[1] == r'win32': > if stringx[2] == r'app': > if stringx[4] == r'dev.tar.gz': > return 1 > > But now the results of the filter is an empty list and i know it shouldn't > be. Well, you haven't told us what you expect the result to be, but as far as I can tell, an empty list is the correct answer, because you don't have any files in your list that match your rules. This line > if stringx[0] == '': is very likely your problem. That requires that your file start with a '-', so that after you split it stringx[0] will equal ''. You may need something more like this: def is_Dev(stringy): print stringy try: stringx = stringy.split('-') if stringx[1] == r'win32': if stringx[2] == r'app': if stringx[4] == r'dev.tar.gz': return 1 except IndexError, e: pass That will still give you an empty list when run on your proposed inputs though, because none of them are of the form -win32-app--dev.tar.gz If this doesn't help, please give us some sample inputs and what you expect the output to be. -- Jerry From Aurel.Thomi at ruag.com Wed Apr 4 12:40:10 2007 From: Aurel.Thomi at ruag.com (Thomi Aurel RUAG A) Date: Wed, 4 Apr 2007 18:40:10 +0200 Subject: Write to a binary file Message-ID: <1A234A2831E39542B982C57BF92174F6BCCC8B@RTHUS5503.rintra.ruag.com> Hy I'm using Python 2.4.2 on an ARM (PXA-270) platform (linux-2.6.17). My Goal is to write a list of bytes down to a file (opened in binary mode) in one cycle. The crux is that a '0x0a' (line feed) will break the cycle of one writing into several pieces. Writing to a "simple" file, this wouldn't cause any problem. Assuming - without questioning ;-) - that a device file (/dev/*) has to be written in one cycle because one write call will be interpreted as one "transaction". The write behaviour on line feed's isn't really usefull because such "transactions" would be broken up into serveral pieces and therefore for the device into several "transactions". Is there a possibility to write a list of bytes "en bloc" to a binary file? (without the interpreting of the line feed's) Opening a file i binary mode (i.e "wb") seems not to be enough. Thank you for any help Aurel From irstas at gmail.com Sun Apr 1 12:13:10 2007 From: irstas at gmail.com (irstas at gmail.com) Date: 1 Apr 2007 09:13:10 -0700 Subject: reverse engineering Excel spreadsheet In-Reply-To: <460fd6d0.0@entanet> References: <460fd6d0.0@entanet> Message-ID: <1175443990.651064.299120@y66g2000hsf.googlegroups.com> On Apr 1, 6:59 pm, Duncan Smith wrote: > Hello, > I am currently implementing (mainly in Python) 'models' that come > to me as Excel spreadsheets, with little additional information. I am > expected to use these models in a web application. Some contain many > worksheets and various macros. > > What I'd like to do is extract the data and business logic so that I can > figure out exactly what these models actually do and code it up. An > obvious (I think) idea is to generate an acyclic graph of the cell > dependencies so that I can identify which cells contain only data (no > parents) and those that depend on other cells. If I could also extract > the relationships (functions), then I could feasibly produce something > in pure Python that would mirror the functionality of the original > spreadsheet (using e.g. Matplotlib for plots and more reliable RNGs / > statistical functions). > > The final application will be running on a Linux server, but I can use a > Windows box (i.e. win32all) for processing the spreadsheets (hopefully > not manually). Any advice on the feasibility of this, and how I might > achieve it would be appreciated. > > I assume there are plenty of people who have a better knowledge of e.g. > COM than I do. I suppose an alternative would be to convert to Open > Office and use PyUNO, but I have no experience with PyUNO and am not > sure how much more reliable the statistical functions of Open Office > are. At the end of the day, the business logic will not generally be > complex, it's extracting it from the spreadsheet that's awkward. Any > advice appreciated. TIA. Cheers. > > Duncan I'm not sure I understood what kind of information you want to get out of the Excel sheet, sorry. But I hope this'll get you started (at least it has a few nice tokens that might help you in googling): import win32com.client class Excel: def __init__(self, filename): self.closed = True self.xlApp = win32com.client.dynamic.Dispatch('Excel.Application') self.xlBook = self.xlApp.Workbooks.Open(filename) self.closed = False def sheet(self, sheetName): return self.xlBook.Worksheets(sheetName) def __del__(self): if not self.closed: self.close() def close(self): self.xlBook.Close(SaveChanges=1) self.xlApp.Quit() self.closed = True excel = Excel('file.xls') sheet = excel.sheet(1) print sheet.Cells(6, 3) I used it a few years ago to read and populate spreadsheet cells. From cjames at callone.net Mon Apr 2 08:58:28 2007 From: cjames at callone.net (c james) Date: Mon, 02 Apr 2007 07:58:28 -0500 Subject: SimpleXMLRPCServer - client address In-Reply-To: <460fc4a8$1@griseus.its.uu.se> References: <460fc4a8$1@griseus.its.uu.se> Message-ID: Jan Danielsson wrote: > Hello all, > > I writing an application based on the SimpleXMLRPCServer class. I > would like to know the IP address of the client performing the RPC. Is > that possible, without having to abandon the SimpleXMLRPCServer class? > I did this a long time ago so it's not likely the best solution. class RPCServer(SimpleXMLRPCServer): def _dispatch(self, method, params): """Extend dispatch, adding client info to some parameters.""" if method in ({my list of methods I needed client address}): return SimpleXMLRPCServer._dispatch(self, method, params+(self.client_address,)) return SimpleXMLRPCServer._dispatch(self, method, params); From cam.ac.uk at mh391.invalid Fri Apr 13 20:18:16 2007 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Sat, 14 Apr 2007 01:18:16 +0100 Subject: Portably generating infinity and NaN In-Reply-To: References: <462008d1$0$11763$9b622d9e@news.freenet.de> Message-ID: Michael Hoffman wrote: > skip at pobox.com wrote: >> >> (Note the absence of a demonstration on Windows.) Can't the >> above be >> >> blessed as the One True Way and wormed around in floatmodule.c for >> >> those platforms where float'ing "NaN" or "Inf" doesn't currently >> >> work? >> >> Martin> How would you do the worming-around? >> >> I don't know. On I was just asking. On unixoid systems I sort of assume >> you could add tests to the configure script to detect what worked. If >> converting the strings works you're done. If not, maybe Robert Kern's >> numpy >> code could be run in the configure script to generate constants for >> NaN and >> Inf that could be used in floatmodule.c. Windows would probably have >> to be >> hard-coded, but except for 32-bit and 64-bit differences it should be the >> same all over, yes? > > If you're going to change CPython to do this, I think adopting PEP 754, > and using the fpconst module would be better than changing how float() > works when called on string literals. The only thing I don't like about > it is the camelcasing of the functions. > > http://www.python.org/dev/peps/pep-0754/ I notice in the tracker, kousu suggested an alternative design, where the test functions become part of the float type. So you'd have float.isnan(), float.isfinite(), etc. http://sourceforge.net/tracker/?func=detail&aid=1151323&group_id=5470&atid=305470 -- Michael Hoffman From alextabone at gmail.com Wed Apr 25 02:58:10 2007 From: alextabone at gmail.com (Alchemist) Date: 24 Apr 2007 23:58:10 -0700 Subject: trinary operator - if then else Message-ID: <1177484290.449378.93720@t38g2000prd.googlegroups.com> What is Python's version for the trinary if..then..else operator? I want a one-liner such as a?b:c for the if..then..else control structure if a then b else c Does Python 2.4 support it? From me2 at privacy.net Mon Apr 30 02:23:58 2007 From: me2 at privacy.net (Spin Dryer) Date: Mon, 30 Apr 2007 07:23:58 +0100 Subject: SEO - Search Engine Optimization - Seo Consulting References: <1177808356.681710.42980@n76g2000hsh.googlegroups.com> Message-ID: On Sun, 29 Apr 2007 20:55:11 -0400, [Juan T. Llibre] said :- >re: >!>>>Top posting >!>> Did not. I replied to the message at the bottom of the thread. >!> Congratulations, you've now made a fool of yourself in public. > >OK, cut it out. > >Top or bottom posting is a user choice. >No need to flame someone for using either. Of course there is, especially when the top posting included the spam because top posters invariably do not snip anything. You too are saying you're an MVP ? Do you own nowhere.com ? From ayaz at dev.slash.null Wed Apr 4 15:29:08 2007 From: ayaz at dev.slash.null (Ayaz Ahmed Khan) Date: Thu, 05 Apr 2007 00:29:08 +0500 Subject: how to remove multiple occurrences of a string within a list? References: <1175624433.206953.214290@n59g2000hsh.googlegroups.com> <1175625098.269660.184790@o5g2000hsb.googlegroups.com> <1175626164.428718.267670@w1g2000hsg.googlegroups.com> <1175626674.836668.293850@b75g2000hsg.googlegroups.com> Message-ID: "kyosohma" typed: > If you want to get really fancy, you could do a list comprehension > too: > > your_list = ["0024","haha","0024"] > new_list = [i for i in your_list if i != '0024'] Or, just: In [1]: l = ["0024","haha","0024"] In [2]: filter(lambda x: x != "0024", l) Out[2]: ['haha'] -- Ayaz Ahmed Khan Do what comes naturally now. Seethe and fume and throw a tantrum. From http Sat Apr 14 01:05:06 2007 From: http (Paul Rubin) Date: 13 Apr 2007 22:05:06 -0700 Subject: tuples, index method, Python's design References: <1175953520.316208.241490@o5g2000hsb.googlegroups.com> <7xzm5igbrb.fsf@ruckus.brouhaha.com> <1176200361.260546.280510@n76g2000hsh.googlegroups.com> <740c3aec0704100824m132c45fbi5c4c3ec0c0fa3a67@mail.gmail.com> <1176489534.568939.249910@q75g2000hsh.googlegroups.com> Message-ID: <7x3b33k0l9.fsf@ruckus.brouhaha.com> "Rhamphoryncus" writes: > > i = s.index(e) => s[i] = e > > Then this algorithm is no longer guaranteed to work with strings. > It never worked correctly on unicode strings anyway (which becomes the > canonical string in python 3.0). What?! Are you sure? That sounds broken to me. From irstas at gmail.com Sun Apr 1 08:52:04 2007 From: irstas at gmail.com (irstas at gmail.com) Date: 1 Apr 2007 05:52:04 -0700 Subject: Extract information from HTML table In-Reply-To: <1175429635.278697.92690@b75g2000hsg.googlegroups.com> References: <1175429635.278697.92690@b75g2000hsg.googlegroups.com> Message-ID: <1175431924.800332.325820@n76g2000hsh.googlegroups.com> On Apr 1, 3:13 pm, "Ulysse" wrote: > Hello, > > I'm trying to extract the data from HTML table. Here is the part of > the HTML source : > > .... > > Do you know the way to do it ? Beautiful Soup is an easy way to parse HTML (that may be broken). http://www.crummy.com/software/BeautifulSoup/ Here's a start of a parser for your HTML: soup = BeautifulSoup(txt) for tr in soup('tr'): dateTd, textTd = tr('td')[1:] print 'Date :', dateTd.contents[0].strip() print textTd #element still needs parsing where txt is the string in your message. From wadnerk at gmail.com Thu Apr 5 19:14:59 2007 From: wadnerk at gmail.com (Kiel W.) Date: 5 Apr 2007 16:14:59 -0700 Subject: Prevent Modification of Script? In-Reply-To: References: <1175735097.856840.177510@e65g2000hsc.googlegroups.com> <1175743177.489242.214700@w1g2000hsg.googlegroups.com> Message-ID: <1175814899.698178.282800@q75g2000hsh.googlegroups.com> On Apr 4, 10:19 pm, James Stroud wrote: > You are worrying a little too much. Lets say you are genuinely worried > about malware Thanks for the feedback. Perhaps you are correct about being too worried.. eh, to be honest you probably are. > Write your program in the language most suited for it and, when you hit > it big, hire some security experts. Very good advice..thanks for taking the time to respond. From sender at sender.send Tue Apr 10 04:36:05 2007 From: sender at sender.send (Passer By) Date: Tue, 10 Apr 2007 08:36:05 GMT Subject: NLTK, Random Sentence Generators? Message-ID: <87slb8d3uj.fsf@localhost.localdomain> Has any created or not of examples of random sentence generators using n-gram models (or other models might be interesting). I know of one example from a course at MIT, but besides that nothing. Any help would be great. From jzgoda at o2.usun.pl Wed Apr 18 15:58:24 2007 From: jzgoda at o2.usun.pl (Jarek Zgoda) Date: Wed, 18 Apr 2007 21:58:24 +0200 Subject: Future Python Gui? In-Reply-To: <1176909848.455264.174730@e65g2000hsc.googlegroups.com> References: <1176859699.906386.326720@b75g2000hsg.googlegroups.com> <1176863948.526051.186210@n76g2000hsh.googlegroups.com> <1176909848.455264.174730@e65g2000hsc.googlegroups.com> Message-ID: bcwhite at pobox.com napisa?(a): > If this were just a tool for me, it wouldn't matter. My concern is > distribution. If anybody who wants to run my software then they also > have to go through all the trouble to install these extensions, none > of which seem to have decent instructions. I'm an old-time hack and I > have trouble getting them to work. A simple user won't have a chance! I am not a hacker, just a software developer, but I'd have no problems in either installing PyGTK on Ubuntu box (sudo apt-get install python-gtk2, but it's installed by default anyway) or on Windows XP machine (double click on installer icon). "Simple user" is not an idiot either and if she can read English, she wouldn't have hard time too. The rumours on "problems installing GUI toolkits" are greatly exagerated IMO. -- Jarek Zgoda http://jpa.berlios.de/ From kw at codebykevin.com Thu Apr 5 11:34:45 2007 From: kw at codebykevin.com (Kevin Walzer) Date: Thu, 05 Apr 2007 11:34:45 -0400 Subject: Review/commit patch? Message-ID: How long does it take for a patch at the Python SF tracker to be reviewed and/or committed? I am unfamiliar with how the process works. (I originally submitted a bug report, then figured out how to patch the item in question, and subsequently submitted a patch.) -- Kevin Walzer Code by Kevin http://www.codebykevin.com From steve at holdenweb.com Fri Apr 6 07:39:35 2007 From: steve at holdenweb.com (Steve Holden) Date: Fri, 06 Apr 2007 07:39:35 -0400 Subject: No subject In-Reply-To: References: Message-ID: C.L. wrote: > James Stroud mbi.ucla.edu> writes: >> C.L. wrote: >>> I was looking for a function or method that would return the index to the >>> first matching element in a list. ... >>> ... __please don't be overly defensive__ ... >> The amount of typing wasted to defend design decisions such as this can >> boggle one's mind. Just use lists unless you have on overwhelming reason >> to do otherwise. >> >> James > > > Read the quote. I *am* using a list. > > That doesn't change the fact that this is unfriendly design. It's an ugly > inconsistent chunk of a Python's past in which built-in types didn't behave like > objects. It sticks out like a sore thumb, maybe just not very often. > OK, if you want a *reason*, the *reason* is that tuples were originally intended to be used in the same way that tuples are used in mathematics: as an ordered collection of dissimilar objects. Given that the sequence held by a tuple wasn't intended to be homogeneous it didn't originally make sense to be able to find something (which would of necessity be of a particular type) in it. Of course much has changed since then, and nowadays the world goes in for tuple-abuse. Consequently the majority don't appear to understand why tuple doesn't become simply an immutable list. But you have clearly found the preferred solution on your own, so this is basically just a history lesson. Glad you asked? Is your thumb any less sore. > Oh, and thanks for the insulting tone of your anticipated response. Have you > anything better to do with your time than wasting bytes writing empty responses > to what you already deem a waste of typing? > I'd have thought you would have saved time simply by refusing to rise to what you clearly see as bait. > *sighs* just what I expected: another idle troll defending something just for > the sake of defending it. On the other hand, thanks 7stud, for the truly helpful > response. > Get over it. This is Usenet, abuse is next door. 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 cam.ac.uk at mh391.invalid Tue Apr 17 14:41:52 2007 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Tue, 17 Apr 2007 19:41:52 +0100 Subject: The smallest and largest values of numeric types In-Reply-To: <1176825226.633555.85860@d57g2000hsg.googlegroups.com> References: <1176825226.633555.85860@d57g2000hsg.googlegroups.com> Message-ID: fumanchu wrote: > On Apr 17, 7:12 am, t... at finland.com wrote: >> How can I determine the smallest and largest values >> of numeric types (for example int) possible in my >> system? I think there exists a function for this task >> but I don't know it. > > This should work for ints: > > import sys > print sys.maxint One should note that ints bigger than sys.maxint are possible almost seamlessly since Python will use longs for these numbers: Python 2.5 (r25:51908, Mar 13 2007, 08:13:14) [GCC 3.4.4 (cygming special, gdc 0.12, using dmd 0.125)] on cygwin Type "help", "copyright", "credits" or "license" for more information. >>> import sys >>> sys.maxint 2147483647 >>> sys.maxint+1 2147483648L >>> sys.maxint*2 4294967294L >>> sys.maxint**10 2085924830053169311564321191305931199741711560688200050463950578047164169337729650765802242049L Of course performance decreases for longer longs. -- Michael Hoffman From hiruma222 at gmail.com Fri Apr 27 09:38:17 2007 From: hiruma222 at gmail.com (hiruma222 at gmail.com) Date: 27 Apr 2007 06:38:17 -0700 Subject: visit http://www.real-article.com/spyware/index.php Message-ID: <1177681097.128182.315230@n35g2000prd.googlegroups.com> The www.real-article.com website provides a ton of information about spyware. In addition, you will find extensive information on leading spyware to help you on your way to success. Please have a look at our spyware articles, products, resources, and additional information located throughout www.real-article.com. We strive to provide only quality articles, so if there is a specific topic related to spyware that you would like us to cover, please contact us at any time. visit http://www.real-article.com/spyware/index.php From goodTweetieBird at hotmail.com Tue Apr 3 09:47:28 2007 From: goodTweetieBird at hotmail.com (gtb) Date: 3 Apr 2007 06:47:28 -0700 Subject: Finding and copying files with python. In-Reply-To: <1175607107.690245.145130@l77g2000hsb.googlegroups.com> References: <1175606497.896681.119490@l77g2000hsb.googlegroups.com> <1175607107.690245.145130@l77g2000hsb.googlegroups.com> Message-ID: <1175608048.094777.183660@l77g2000hsb.googlegroups.com> On Apr 3, 8:31 am, kyoso... at gmail.com wrote: > On Apr 3, 8:21 am, "gtb" wrote: > > > > > > > > > I wish to copy the highest version number of a file from directory \ > > \ > > \fileserver\D:\scripts to C:\scripts where the file names are of the > > form > > > filename_MM.NN.SS.zip, where MM, NN, and SS can be one to three > > digits. > > > Example directory: > > other.zip > > dx_ver_1.1.63.zip > > dx_ver_1.2.01.zip > > dx_ver_1.12.7.zip > > temp.txt > > > Does python have string matching routines that would find the bottom > > listed zip file and/or file copying routines? > > > A little pointer or two would be much appreciated. > > > Thanks, > > > jh > > You could just use string slicing to cut off the first 7 characters > and have the numbers available to compare. There's also the os.stat > module to find the last modified date of the file. You might be able > to use the glob module to grab a list of the files and then sort the > list too. > > Mike Thanks for posting folks. I didn't make my question clear. Before I sort the files I need to ensure that I am only sorting the files that match the profile of "filename_MM.NN.SS.zip", where MM, NN, and SS can be one to three digits. Thanks again, jh From steve at REMOVE.THIS.cybersource.com.au Thu Apr 19 02:57:52 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Thu, 19 Apr 2007 16:57:52 +1000 Subject: Nested dictionaries trouble References: <1176317876.917874.58040@n59g2000hsh.googlegroups.com> <1176325715.951076.4790@w1g2000hsg.googlegroups.com> <1176923772.011976.116190@p77g2000hsh.googlegroups.com> Message-ID: On Wed, 18 Apr 2007 12:16:12 -0700, IamIan wrote: > I am using the suggested approach to make a years list: > > years = ["199%s" % x for x in range(0,10)] > years += ["200%s" % x for x in range(0,10)] > > I haven't had any luck doing this in one line though. Is it possible? years = ["199%s" % x for x in range(0,10)] + \ ["200%s" % x for x in range(0,10)] Sorry for the line continuation, my news reader insists on breaking the line. In your editor, just delete the "\" and line break to make it a single line. If you don't like that solution, here's a better one: years = [str(1990 + n) for n in range(20)] Or there's this: years = [str(n) for n in range(1990, 2010)] Or this one: years = map(str, range(1990, 2010)) -- Steven. From S.Mientki-nospam at mailbox.kun.nl Sat Apr 28 03:27:28 2007 From: S.Mientki-nospam at mailbox.kun.nl (Stef Mientki) Date: Sat, 28 Apr 2007 09:27:28 +0200 Subject: getting rid of EOL character ? In-Reply-To: <46327f48$1@news.eftel.com.au> References: <268cc$4631f634$83aef404$27224@news1.tudelft.nl> <46327f48$1@news.eftel.com.au> Message-ID: hi John, >>> In the previous language I used, >>> when reading a line by readline, the EOL character was removed. > > Very interesting; how did you distinguish between EOF and an empty line? > Did you need to call an isEOF() method before each read? Yes indeed, and I admit it needs some more coding ;-) > >>> >>> Now I'm reading a text-file with CR+LF at the end of each line, >>> Datafile = open(filename,'r') line = Datafile.readline() >>> >>> now this gives an extra empty line >>> print line >>> >>> and what I expect that should be correct, remove CR+LF, >>> gives me one character too much removed >>> print line[,-2] > > Stef, that would give you a syntax error. I presume that you meant to > type line[:-2] Yes, sorry. > >>> >>> while this gives what I need ??? >>> print line[,-1] >>> >>> Is it correct that the 2 characters CR+LF are converted to 1 character ? > > In text mode (the default), whatever is the line ending on your platform > is converted to a single "newline" '\n' which is the same as LF. Aha, that was the answer I was looking for. thanks for the splendid explanation John, cheers, Stef Mientki From grante at visi.com Thu Apr 26 09:41:56 2007 From: grante at visi.com (Grant Edwards) Date: Thu, 26 Apr 2007 13:41:56 -0000 Subject: Python not giving free memory back to the os get's me in real problems ... References: <1177510121.882503.145560@n15g2000prd.googlegroups.com> <_LidnenBcrz7-rLbnZ2dnUVZ_tCtnZ2d@comcast.com> <59990rF2ja6c7U3@mid.dfncis.de> <132uv54ncsspm91@corp.supernews.com> <46308885.4080405@v.loewis.de> Message-ID: <1331b143bkt7453@corp.supernews.com> On 2007-04-26, Martin v. L?wis wrote: >> I'm a bit fuzzy on this, but I don't think there _is_ a >> practical way to "return memory to the OS" in many OSes. > > That's not true at all. Most C libraries these days manage > to return memory to the operating system. [...] Thanks for providing a real answer. Like I said in my post, my information wasn't very current. -- Grant Edwards grante Yow! Uh-oh!! I'm having at TOO MUCH FUN!! visi.com From reply at group.invalid Mon Apr 2 13:54:39 2007 From: reply at group.invalid (Pom) Date: Mon, 02 Apr 2007 17:54:39 GMT Subject: wx textctrl font style In-Reply-To: <1175528929.407888.98350@y80g2000hsf.googlegroups.com> References: <1175528929.407888.98350@y80g2000hsf.googlegroups.com> Message-ID: kyosohma at gmail.com wrote: > On Mar 31, 3:13 am, Pom wrote: >> 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 !!! > > You could experiment with the "Rich Text" style of the text control > (see the wxPython Demo). You might also mess with refactoring your > code a little and doing a FOR loop. > > # untested code!!! > fonts = [tmpnewfont, tmpnewfont2, tmpnewfont3] > count = 0 > tmppos = self.txtInfo.GetInsertionPoint() > self.txtInfo.write(str(csr[count])+'\n') > for i in range(3): > tmppos2 = self.txtInfo.GetInsertionPoint() > self.txtInfo.SetStyle(tmppos, tmppos2, wx.TextAttr("BLUE", > wx.NullColour, fonts[count])) > tmppos = tmppos2 > count += 1 > self.txtInfo.write(str(csr[count])+'\n') > > > I also noticed a FancyText widget. I've used the HtmlWindow widget for > an About screen before and I thought it was pretty cool if you know > HTML. You might also try dropping an email to the wxPython Users Group > at http://wxpython.org/maillist.php > > Hope this helps! > > Mike > Thx alot ! I know HTML, so I certainly will skip the richtext. I did'nt see that fancytext widget, I'll take a look and decide between that and the htmlwindow. I'm making a simple addressbook, which I can't find like I need it (with mysql db) Kindly regards From kyosohma at gmail.com Tue Apr 24 10:59:15 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: 24 Apr 2007 07:59:15 -0700 Subject: Learning Python - First Project In-Reply-To: <1177371395.909707.24460@e65g2000hsc.googlegroups.com> References: <1177339942.371167.93970@b75g2000hsg.googlegroups.com> <1177367541.059834.18420@o5g2000hsb.googlegroups.com> <1177367890.088488.93290@l77g2000hsb.googlegroups.com> <1177371395.909707.24460@e65g2000hsc.googlegroups.com> Message-ID: <1177426755.121203.319250@n15g2000prd.googlegroups.com> On Apr 23, 6:36 pm, 7stud wrote: > On Apr 23, 5:04 pm, Kevin Haynes wrote: > > > > > Hello > > > I was a python newbie just a month ago and found the following books a great > > help. > > > Beginning Python: From Novice to Professional (Beginning: From Novice to > > Professional) by Magnus L. Hetland (Paperback - 29 Sep 2005)http://www.amazon.co.uk/Beginning-Python-Novice-Professional/dp/15905... > > > WxPython in Action by Noel Rappin and Robin Dunn (Paperback - 30 Mar 2006)http://www.amazon.co.uk/WxPython-Action-Noel-Rappin/dp/1932394621/ref... > > > Kevin > > > On Monday 23 April 2007, 7stud wrote: > > > > Uhhmm...how are you supposed to close a ShapedWindow(under > > > Miscellaneous)? > > I am reading both now, and I would not recommend either one. If you > just skim over the examples and don't play with them, you might > mistakenly believe you know what's going on, but if you actually try > the examples and alter them here and there to figure out how things > really work, you will discover all the mistakes and gaps in both > books. Beginning Python is a good reference, but there's not much for examples, other than the fairly advanced stuff in the back of the book. "Python Programming for the Absolute Beginner" by Dawson was much more fun since you get to create games in python. I'm not sure why you don't like the wxPython one. It was a nice reference. But maybe I liked it as I started out learning C++ and wxPython has similar idioms. If you want to learn the nuts and bolts of the Python language, you'll need to read "Programming Python" by Lutz or the really in-depth book "Core Python Programming" by Chun, which (unfortunately) has lots of info, but not much code. The current wxPython demo is here: http://wxpython.org/download.php (about a third of the way down) Mike From tommy.nordgren at comhem.se Fri Apr 27 12:45:17 2007 From: tommy.nordgren at comhem.se (Tommy Nordgren) Date: Fri, 27 Apr 2007 18:45:17 +0200 Subject: editing scripts on a mac In-Reply-To: References: Message-ID: <9C035D58-C028-4DFD-8C7E-19ED4C0F9B48@comhem.se> On 27 apr 2007, at 18.08, Steve Holden wrote: > I am teaching someone Python by email, and part of our conversation > recently ran as follows: > > him> How do I save a script and run it? > > me > Do you have a text editor? If so, edit the script in that, then > save it > me > in your home directory (the place you can see when you open the > terminal > > him> I do not have a text editor, but here are the answers to > him> questions 1-5. > > Now, frankly, I don't think this answer is correct, since I know OS > X is > a UNIX derivative, but I am loathe to involve a programming noob > with vi > or something similar. So I wondered if one of the c.l.py mac users > could > give brief instructions for firing up a visual text editor of some > sort > and saving a file somewhere it can easily be accessed from a terminal > window (which I presume starts up in his home directory). > > regards > Steve Text Wrangler (www.barebones.com) and Alpha/Tk are both excellent GUI programmers editors that run on Mac. Alpha/Tk is open-sourced as well ------ 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 From johnjsal at NOSPAMgmail.com Thu Apr 12 10:44:00 2007 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Thu, 12 Apr 2007 10:44:00 -0400 Subject: OT: Question about RGB color method In-Reply-To: <461be63b$0$31839$c3e8da3@news.astraweb.com> References: <461be63b$0$31839$c3e8da3@news.astraweb.com> Message-ID: <461e4598$0$23754$c3e8da3@news.astraweb.com> John Salerno wrote: > Sorry for this non-Python question, but since it's computer related I > know you guys will have an answer, and I don't really know where else to > ask. Mainly I'm just curious anyway. > > I'm wondering, why do computers use a RGB color scheme instead of the > primary colors? Is there something you can't do with yellow? It seems > weird that RGB can be combined to make all colors, when that's supposed > to be the job of the primary colors. I'm sure there some technical > computer-related reason that it had to be this way. > > Thanks. Thanks guys! This is fascinating...just something I've never really thought about before. The Wikipedia article will give me something to read while I'm bored at work! :) From steven.bethard at gmail.com Fri Apr 13 15:35:40 2007 From: steven.bethard at gmail.com (Steven Bethard) Date: Fri, 13 Apr 2007 13:35:40 -0600 Subject: attribute save restore In-Reply-To: <7_ydnZt7B8WqSILbnZ2dnUVZ_uOmnZ2d@comcast.com> References: <7_ydnZt7B8WqSILbnZ2dnUVZ_uOmnZ2d@comcast.com> Message-ID: Carl K wrote: > Is there a more elegant way of coding this: > > x=o.p # save .p > o.p=0 > o.m() > o.p=x # restore .p > > seems very push/pop to me - like there should be a way that doesn't need > a var (x) or the save/set lines should be done in one command. With the appropriate context manger, you could write this as:: with setting(o, 'p', 2): o.m() Here's the code:: >>> from __future__ import with_statement >>> @contextlib.contextmanager ... def setting(obj, name, value): ... old_value = getattr(obj, name) ... setattr(obj, name, value) ... try: ... yield obj ... finally: ... setattr(obj, name, old_value) ... >>> class C(object): ... def __init__(self, x): ... self.x = x ... def m(self): ... print self.x ... >>> c = C(1) >>> with setting(c, 'x', 2): ... c.m() ... 2 >>> print c.x 1 Of course, that just wraps up the same push/pop behavior you're doing into a context manager. > (personally I think .m would better be implemented by passing in a > parameter, but that isn't my choice.) Yep, that's the right answer. You should complain to whoever created this API. STeVe From malaclypse2 at gmail.com Tue Apr 24 14:03:39 2007 From: malaclypse2 at gmail.com (Jerry Hill) Date: Tue, 24 Apr 2007 14:03:39 -0400 Subject: Simple sqlite3 question In-Reply-To: <1177434225.721012.271040@r35g2000prh.googlegroups.com> References: <1177434225.721012.271040@r35g2000prh.googlegroups.com> Message-ID: <16651e80704241103m188a095ci81675dddafb7c7a5@mail.gmail.com> On 24 Apr 2007 10:03:45 -0700, cjl wrote: > When I run the script and there is no file named optiondata, one is > created and the correct data is added to it. If I run the script > again then the data from the first run seems to be replaced with the > data from the second run. I expected that the data from the second run > would be appended to the database file, not replace it. It sounds like you're not calling conn.commit() before you close the database. By default sqlite (and any other DBAPI 2.0 compliant sql wrapper) will start in transactional mode. You need to commit() your transactions or they will be rolled back when you close the database connection. If you don't want to call commit on your own, you can switch the database into autocommit mode by setting the isolation level to None when you open the connection, like this: conn = sqlite3.connect('.\optiondata', isolation_level=None) -- Jerry From gagsl-py2 at yahoo.com.ar Fri Apr 6 23:03:19 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sat, 07 Apr 2007 05:03:19 +0200 Subject: Convert xml symbol notation In-Reply-To: <1175929931.687229.122510@p77g2000hsh.googlegroups.com> References: <1175899141.354348.207530@q75g2000hsh.googlegroups.com> <1175923387.811717.279580@n76g2000hsh.googlegroups.com> <1175929931.687229.122510@p77g2000hsh.googlegroups.com> Message-ID: dumbkiwi wrote: > On Apr 7, 5:23 pm, "Gabriel Genellina" wrote: >>Try the htmlentitydefs module. > > Is that a standard module? I can't see it anywhere - googled it. Sure! For quite a while, at least, since Python 1.5 (I can't go earlier in time...) http://svn.python.org/view/python/trunk/Lib/htmlentitydefs.py Added Wed Sep 27 16:22:08 1995 UTC (11 years, 6 months ago) by guido -- Gabriel Genellina From mgi820 at motorola.com Fri Apr 27 13:21:40 2007 From: mgi820 at motorola.com (Gary Duzan) Date: Fri, 27 Apr 2007 17:21:40 +0000 (UTC) Subject: My newbie annoyances so far References: <1177688082.758043.133920@r30g2000prh.googlegroups.com> <_9pYh.1787$uJ6.894@newssvr17.news.prodigy.net> Message-ID: In article <_9pYh.1787$uJ6.894 at newssvr17.news.prodigy.net>, John Nagle wrote: > >(P.S. PEP 3117 is a joke, right?) I expect so, especially given its creation date. Gary Duzan Motorola CHS From DustanGroups at gmail.com Sun Apr 8 08:27:38 2007 From: DustanGroups at gmail.com (Dustan) Date: 8 Apr 2007 05:27:38 -0700 Subject: RFC: Assignment as expression (pre-PEP) In-Reply-To: <1175802680.021987.39220@p77g2000hsh.googlegroups.com> References: <1175802680.021987.39220@p77g2000hsh.googlegroups.com> Message-ID: <1176035258.355141.221290@d57g2000hsg.googlegroups.com> On Apr 5, 2:51 pm, TimeHo... at gmail.com wrote: > I would like to gauge interest in the following proposal: > > Problem: > > Assignment statements cannot be used as expressions. > > Performing a list of mutually exclusive checks that require data > processing can cause excessive tabification. For example, consider > the following python snipet... > > temp = my_re1.match(exp) > if temp: > # do something with temp > else: > temp = my_re2.match(exp) > if temp: > # do something with temp > else: > temp = my_re3.match(exp) > if temp: > # do something with temp > else: > temp = my_re4.match(exp) > > # etc. > > Even with 2-space tabification, after about 20 matches, the > indentation will take up half an 80-column terminal screen. > > Details: > > Python distinguishes between an assignment statement and an equality > expression. This is to force disambiguation of assignment and > comparison so that a statement like: > > if x = 3: > > Will raise an expression rather than allowing the programmer to > accidentally overwrite x. Likewise, > > x == 3 > > Will either return True, False or raise a NameError exception, which > can alert the author of any potential coding mistakes since if x = 3 > (assignment) was meant, assignment being a statement returns nothing > (though it may raise an exception depending on the underlying > assignment function called). > > Because this forced disambiguation is a guiding virtue of the python > language, it would NOT be wise to change these semantics of the > language. > > Proposal: > > Add a new assignment-expression operator to disambiguate it completely > from existing operators. > > Although any number of glyph could be used for such a new operator, I > here propose using pascal/gnu make-like assignment. Specifically, > > let: > > x = 3 > > Be a statement that returns nothing; > > let: > > x == 3 > > Be an expression that, when x is a valid, in-scope name, returns True > or False; > > let: > > x := 3 > > Be an expression that first assigned the value (3) to x, then returns > x. > > Thus... > > if x = 3: > # Rais exception > pass > > if x == 3: > # Execute IFF x has a value equivalent to 3 > pass > > if x := 3: > # Executes based on value of x after assignment; > # since x will be 3 and non-zero and thus represents true, always > executed > pass > > Additional: > > Since python allows in-place operator assignment, (e.g. +=, *=, etc.), > allow for these forms again by prefixing each diglyph with a colon > (:), forming a triglyph. > > E.g. > > if x :+= 3: > # Executes IFF, after adding 3 to x, x represents a non-zero number. > pass > > Also note, that although the colon operator is used to denote the > beginning of a programme block, it should be easily distinguished from > the usage of : to denote a diglyph or triglyph assignment expression > as well as the trinary conditional expression. This is because > firstly, the statement(s) following a colon (:) in existing python > should never begin with an assignment operator. I.e., > > if x: = y > > is currently not valid python. Any attempt at interpreting the > meaning of such an expression in the current implementation of python > is likely to fail. Secondly, the diglyph and triglyph expressions do > not contain spaces, further disambiguating them from existing python. > > Alternative proposals for dyglyph and triglyph representations for > assignment expressions are welcome. > > Implementation details: > > When the python interpreter parser encounters a diglyph or triglyph > beginning with a colon (:) and ending with an equals sign (=), perform > the assignment specified by glyph[1:] and then return the value of the > variable(s) on the left-hand side of the expression. The assignment > function called would be based on standard python lookup rules for the > corresponding glyph[1:] operation (the glyph without the leading > colon). > > Opposition: > > Adding any new operator to python could be considered code bloat. > > Using a colon in this way could still be ambiguous. > > Adding the ability to read triglyph operators in the python > interpreter parser would require too big a code revision. > > Usage is too obscure. > > Using an assignment expression would lead to multiple conceptual > instructions for a single python statement (e.g. first an assignment, > then an if based on the assignment would mean two operations for a > single if statement.) > > Comments: > > [Please comment] > > Jeffrey. If you really really really really really really really really really really really really really really really really really really really really really really really really really really really really really really really really really really really really really really really really really really really really really really really really really really really really really really really really really really really really really really really really really really really really really really really really really really really really really really really want to do something like this, just create a wrapper class: >>> class Wrapper(object): def __init__(self, obj): self.obj = obj def getit(self): return self.obj def setit(self, obj): self.obj = obj return obj >>> import random >>> x = Wrapper(0) >>> if x.setit(random.randrange(2)): print 'yes!' else: print 'hmmm...' hmmm... From half.italian at gmail.com Mon Apr 23 12:49:58 2007 From: half.italian at gmail.com (half.italian at gmail.com) Date: 23 Apr 2007 09:49:58 -0700 Subject: Redirection problem In-Reply-To: <1177344655.365318.50940@q75g2000hsh.googlegroups.com> References: <1177344655.365318.50940@q75g2000hsh.googlegroups.com> Message-ID: <1177346998.656172.127720@b75g2000hsg.googlegroups.com> On Apr 23, 9:10 am, CSUIDL PROGRAMMEr wrote: > I am new to python. so be patient with me > > I am trying to redirect the output of os.popen command to a file. I > want to append to that file. but instead of appending. The file only > shows last command that was writtenn to it. > > filehandle= open("/root/yhpc-2.0/installer/yhpc-log" ,"a+"); > filehandle.write(" Command executed is " + cmd); > try: > pipe= os.popen('%s > /root/yhpc-2.0/installer/yhpc-log' %cmd ); > except : IOError; > filehandle.close(); > > Any suggestion would help. > > filehandle.close(); This works. f = open("test", 'a') stdout = os.popen("ls -l /") f.write(stdout.read()) f.close() ~Sean From mail at timgolden.me.uk Tue Apr 3 03:40:08 2007 From: mail at timgolden.me.uk (Tim Golden) Date: Tue, 03 Apr 2007 08:40:08 +0100 Subject: doing standart window icons unvisible in python In-Reply-To: <1175549454.378661.93570@y66g2000hsf.googlegroups.com> References: <1175549454.378661.93570@y66g2000hsf.googlegroups.com> Message-ID: <461204D8.5060101@timgolden.me.uk> gslm wrote: > Hi! > I want to do close-minimize icons unvisible in python.How can I do > this?I want to do this especially for printing. > And is it possible to provide .exe file for any program in python or > only we can change the file as .pyw? I *think* -- and it's a bit hard to tell from your description -- that you want to print the client area of a window, and not the non-client area (which includes the max/min/close buttons). A lot depends on whether it's your window or someone else's. If it's yours, then you have some control over the styling and do at least have the window handle available to you. If it's someone else's, you have to employ some fairly dark magic to do what I think you want. Depending on what you're after, you might find the PIL ImageGrab module at least a useful tool: http://www.pythonware.com/library/pil/handbook/imagegrab.htm But could you be more precise as to what you're trying to do? TJG From hlubenow2 at gmx.net Sat Apr 14 14:16:36 2007 From: hlubenow2 at gmx.net (hlubenow) Date: Sat, 14 Apr 2007 20:16:36 +0200 Subject: Stdout References: Message-ID: <4di7f4-rk5.ln1@athlon.my> gbastian at pasteur.fr wrote: > Dear Users, > > I am trying to recover through the python function > popen3 the stdout,in,err of a launched process. > > I would like also to recover the stdout which you can > get only through the command: command1 >& filename > > Do you know how I can access to that stdout by python? > > Thanks > > GIacomo Check out module "subprocess" which is meant to replace function "popen3": pr = subprocess.Popen(["command", "-option1", "-option2"], stdin = subprocess.PIPE, stdout = subprocess.PIPE, stderr = subprocess.PIPE, bufsize = 0, close_fds = True) # And then: line = pr.stdout.readline() print line pr.stdin.write("hello to command") HTH H. From horpner at yahoo.com Mon Apr 23 11:19:15 2007 From: horpner at yahoo.com (Neil Cerutti) Date: 23 Apr 2007 17:19:15 +0200 Subject: When are immutable tuples *essential*? Why can't you just use lists *everywhere* instead? References: <1177088796.622928.224890@d57g2000hsg.googlegroups.com> <1177089206.550423.288670@q75g2000hsh.googlegroups.com> <58sf33F2b1q8tU1@mid.individual.net> <1177103370.022138.110320@n59g2000hsh.googlegroups.com> <1177108560.660288.171890@n76g2000hsh.googlegroups.com> Message-ID: On 2007-04-21, Steven D'Aprano wrote: > On Fri, 20 Apr 2007 15:36:00 -0700, seberino at spawar.navy.mil wrote: >>> The article explains that, amongst other things, tuples are >>> faster than lists, so if you are working with constant values >>> (inmutables) they are more indicated than lists. >> >> Thanks. I thought Python's design wasn't so concerned with >> optimizations. Adding a new type "just" for optimization >> reasons seems perhaps unnecessary. I could be wrong. > > It's times like this I want to cry... > > >>>> adict = {(1,2): "parrot"} > > Try replacing that tuple with a list. "Just optimization" my eye! So the question becomes: Why do Python dictionaries require keys to be of an immutable type? -- Neil Cerutti From steven.bethard at gmail.com Fri Apr 20 12:25:08 2007 From: steven.bethard at gmail.com (Steven Bethard) Date: Fri, 20 Apr 2007 10:25:08 -0600 Subject: Fast and capable XML parser? In-Reply-To: References: Message-ID: <6LWdnbnSu_L9dLXbnZ2dnUVZ_jednZ2d@comcast.com> Magnus Lycka wrote: > I'm looking for some library to parse XML code > much faster than the libs built into Python 2.4 > (I'm stuck with 2.4 for quite a while) and I > also need XML Schema validation, and would > appreciate support for e.g. XPath and XInclude. > I also want an API which is more Pythonic than > e.g. a thin wrapper over a C or C++ API. For a more Pythonic API, you probably want to look at cElementTree which is now in the Python 2.5 stdlib. You can get it standalone from here: http://effbot.org/downloads/#cElementTree This implementation doesn't fully support XSLT, XPath, etc. but lxml exposes an ElementTree-style API through lxml.etree, and does, I believe, support many of these other things: http://codespeak.net/lxml/ I don't know too much about lxml's speed, but since it's a wrapper to the libxml2 and libxslt libraries, it should be reasonably fast. STeVe From anton.vredegoor at gmail.com Tue Apr 24 15:20:50 2007 From: anton.vredegoor at gmail.com (Anton Vredegoor) Date: Tue, 24 Apr 2007 21:20:50 +0200 Subject: Would You Write Python Articles or Screencasts for Money? In-Reply-To: References: <462DCCE6.9060908@taupro.com> <1hx2dvj.10ek1v51noh1otN%aleax@mac.com> Message-ID: Steve Holden wrote: >> When cash is involved, it's important to avoid even the slightest >> hint of a suggestion of a suspicion of a conflict of interest; >> that, I guess, is why firms that run contests with cash prizes >> always declare employees and their families "not eligible", and why >> I think the PSF should do likewise in this case. >> > That's a good point, and also a valid reason for restricting the > voting community to PSF members. Thanks, Alex. So in order to avoid a suspicion of a conflict of interest you want to turn the whole thing into private property of the PSF? That is the most ridiculous suggestion I have ever From hlubenow2 at gmx.net Thu Apr 5 11:58:50 2007 From: hlubenow2 at gmx.net (hlubenow) Date: Thu, 05 Apr 2007 17:58:50 +0200 Subject: way to extract only the message from pop3 References: <1175628970.874615.127020@y80g2000hsf.googlegroups.com> Message-ID: flit wrote: > Hello All, > > Using poplib in python I can extract only the headers using the .top, > there is a way to extract only the message text without the headers? As mentioned before, you should use module "email": ------------------------------------ #!/usr/bin/env python import poplib import email import os import sys import string PROVIDER = "pop.YourMailProvider.de" USER = "YourUserName" PASSWORD = "YourPassword" try: client = poplib.POP3(PROVIDER) except: print "Error: Provider not found." sys.exit(1) client.user(USER) client.pass_(PASSWORD) nrof_mails = len(client.list()[1]) for i in range(nrof_mails): lines = client.retr(i + 1)[1] mailstring = string.join(lines, "\n") blockit = 0 msg = email.message_from_string(mailstring) for part in msg.walk(): if part.get_content_maintype() == "text" and blockit == 0: blockit = 1 mycontent = part.get_payload() mycontent = mycontent.decode("quopri_codec") print mycontent print client.quit() ------------------------------------ See You H. From jstroud at mbi.ucla.edu Sun Apr 15 23:49:53 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Mon, 16 Apr 2007 03:49:53 GMT Subject: Getting started with python In-Reply-To: References: <1176598011.463543.96990@q75g2000hsh.googlegroups.com> <1176608302.928513.274400@y5g2000hsa.googlegroups.com> <%LyUh.10121$YL5.5753@newssvr29.news.prodigy.net> Message-ID: Steve Holden wrote: > You'd be worth more if you'd used elif and omitted the continue > statements, but for a first solution it's acceptable. Depends on what you are after. py> s = """ ... for i in xrange(1,101): ... if not i % 15: ... continue ... if not i % 5: ... continue ... if not i % 3: ... continue ... else: ... pass ... """ py> t = timeit.Timer(stmt=s) py> print "%.2f usec/pass" % (1000000 * t.timeit(number=100000)/100000) 40.49 usec/pass py> s = """ ... for i in xrange(1,101): ... if not i % 15: ... pass ... elif not i % 5: ... pass ... elif not i % 3: ... pass ... else: ... pass ... """ py> t = timeit.Timer(stmt=s) py> print "%.2f usec/pass" % (1000000 * t.timeit(number=100000)/100000) 40.88 usec/pass James From thn at mail.utexas.edu Tue Apr 24 17:46:13 2007 From: thn at mail.utexas.edu (Thomas Nelson) Date: 24 Apr 2007 14:46:13 -0700 Subject: When are immutable tuples *essential*? Why can't you just use lists *everywhere* instead? In-Reply-To: References: <1177088796.622928.224890@d57g2000hsg.googlegroups.com> <1177089206.550423.288670@q75g2000hsh.googlegroups.com> <58sf33F2b1q8tU1@mid.individual.net> <1177103370.022138.110320@n59g2000hsh.googlegroups.com> <1177108560.660288.171890@n76g2000hsh.googlegroups.com> Message-ID: <1177451173.176235.216270@t38g2000prd.googlegroups.com> On Apr 23, 10:38 pm, Mel Wilson wrote: > Neil Cerutti wrote: > > The interpreter explains it: "A list is not a hashable object." > > Choosing a hash table instead of some kind of balanced tree seems > > to be just an optimization. ;) > > Even with a balanced tree, if a key in a node changes value, you may > have to re-balance the tree. Nothing in a Python list says that a > dictionary tree would have to be re-balanced if you changed that > particular list. > > Mel. You don't have to look at any implementation. A dictionary maps every key to exactly one object. If the objects were mutable, you could change one key to another key, and then which item would the dictionary pull? (Imaginary code) d = {[1,2,3]: 'hat', [1,2,4]: 'sock' } for key in d: key.pop() print d[[1,2]] #does this print hat or sock? Sets have the same problem. A set can't have duplicates; how could you enforce this with mutable objects? Tom From whamil1 at entergy.com Mon Apr 30 11:41:40 2007 From: whamil1 at entergy.com (Hamilton, William ) Date: Mon, 30 Apr 2007 10:41:40 -0500 Subject: import structures In-Reply-To: <1177946677.365039.311480@e65g2000hsc.googlegroups.com> Message-ID: <588D53831C701746A2DF46E365C018CE01D2CA81@LITEXETSP001.etrsouth.corp.entergy.com> > -----Original Message----- > From: python-list-bounces+whamil1=entergy.com at python.org [mailto:python- > list-bounces+whamil1=entergy.com at python.org] On Behalf Of spohle > Sent: Monday, April 30, 2007 10:25 AM > To: python-list at python.org > Subject: Re: import structures > > On Apr 30, 8:16 am, "Hamilton, William " wrote: > > > > If you've got modules a, b, and c, you can create a wrapper module d > > that imports from each of those. > > > > from a import * > > from b import * > > from c import * > > > > Then, import d and use it as the module name. So if a had a SomeThing > > class, you could do this: > > > > import d > > x = d.SomeThing() > > > > --- > > -Bill Hamilton > > > that doesn't seem to work for me. the from a import * will only give > me a not d.a > "from blah import *" puts everything in blah into the current module's namespace (or so I understand it). This is different from "import blah": with the latter, you have to use "x = blah.SomeThing()". With the former, you can simply say "x = SomeThing()". So, if a has a class SomeThing, and you import it into d using "from a import *", in d you can use SomeThing's methods directly. If you then use "import d" in your main script, you can create a SomeThing instance with "x = d.SomeThing()". --- -Bill Hamilton From gagsl-py2 at yahoo.com.ar Thu Apr 5 19:25:04 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 05 Apr 2007 20:25:04 -0300 Subject: RFC: Assignment as expression (pre-PEP) References: <1175802680.021987.39220@p77g2000hsh.googlegroups.com> <1175807326.466842.219820@p77g2000hsh.googlegroups.com> Message-ID: En Thu, 05 Apr 2007 18:08:46 -0300, darklord at timehorse.com escribi?: > I am trying to write a parser for a text string. Specifically, I am > trying to take a filename that contains meta-data about the content of > the A/V file (mpg, mp3, etc.). > > I first split the filename into fields separated by spaces and dots. > > Then I have a series of regular expression matches. I like > Cartesian's 'event-based' parser approach though the even table gets a > bit unwieldy as it grows. Also, I would prefer to have the 'action' > result in a variable assignment specific to the test. E.g. > > def parseName(name): > fields = sd.split(name) > fields, ext = fields[:-1], fields[-1] > year = '' > capper = '' > series = None > episodeNum = None > programme = '' > episodeName = '' > past_title = false > for f in fields: > if year_re.match(f): > year = f > past_title = True > else: > my_match = capper_re.match(f): > if my_match: > capper = capper_re.match(f).group(1) > if capper == 'JJ' or capper == 'JeffreyJacobs': > capper = 'Jeffrey C. Jacobs' > past_title = True > else: > my_match = epnum_re.match(f): > if my_match: > series, episodeNum = my_match.group('series', > 'episode') > past_title = True > else: > # If I think of other parse elements, they go > here. > # Otherwise, name is part of a title; check for > capitalization > if f[0] >= 'a' and f[0] <= 'z' and f not in > do_not_capitalize: > f = f.capitalize() > if past_title: > if episodeName: episodeName += ' ' > episodeName += f > else: > if programme: programme += ' ' > programme += f > > return programme, series, episodeName, episodeNum, year, capper, > ext > > Now, the problem with this code is that it assumes only 2 pieces of > free-form meta-data in the name (i.e. Programme Name and Episode > Name). Also, although this is not directly adaptable to Cartesian's > approach, you COULD rewrite it using a dictionary in the place of > local variable names so that the event lookup could consist of 3 > properties per event: compiled_re, action_method, dictionary_string. > But even with that, in the case of the epnum match, two assignments > are required so perhaps a convoluted scheme such that if > dictionary_string is a list, for each of the values returned by > action_method, bind the result to the corresponding ith dictionary > element named in dictionary_string, which seems a bit convoluted. And > the fall-through case is state-dependent since the 'unrecognized > field' should be shuffled into a different variable dependent on > state. Still, if there is a better approach I am certainly up for > it. I love event-based parsers so I have no problem with that > approach in general. Maybe it's worth using a class instance. Define methods to handle each matching regex, and keep state in the instance. class NameParser: def handle_year(self, field, match): self.year = field self.past_title = True def handle_capper(self, field, match): capper = match.group(1) if capper == 'JJ' or capper == 'JeffreyJacobs': capper = 'Jeffrey C. Jacobs' self.capper = capper self.past_title = True def parse(self, name): fields = sd.split(name) for field in fields: for regex,handler in self.handlers: match = regex.match(field) if match: handler(self, field, match) break You have to build the handlers list, containing (regex, handler) items; the "unknown" case might be a match-all expression at the end. Well, after playing a bit with decorators I got this: class NameParser: year = '' capper = '' series = None episodeNum = None programme = '' episodeName = '' past_title = False handlers = [] def __init__(self, name): self.name = name self.parse() def handle_this(regex, handlers=handlers): # A decorator; associates the function to the regex # (Not intended to be used as a normal method! not even a static method!) def register(function, regex=regex): handlers.append((re.compile(regex), function)) return function return register @handle_this(r"\(?\d+\)?") def handle_year(self, field, match): self.year = field self.past_title = True @handle_this(r"(expression)") def handle_capper(self, field, match): capper = match.group(1) if capper == 'JJ' or capper == 'JeffreyJacobs': capper = 'Jeffrey C. Jacobs' self.capper = capper self.past_title = True @handle_this(r".*") def handle_unknown(self, field, match): if field[0] >= 'a' and field[0] <= 'z' and field not in do_not_capitalize: field = field.capitalize() if self.past_title: if self.episodeName: self.episodeName += ' ' self.episodeName += field else: if self.programme: self.programme += ' ' self.programme += field def parse(self): fields = sd.split(self.name) for field in fields: for regex,handler in self.handlers: match = regex.match(field) if match: handler(self, field, match) break -- Gabriel Genellina From aahz at pythoncraft.com Wed Apr 18 18:11:48 2007 From: aahz at pythoncraft.com (Aahz) Date: 18 Apr 2007 15:11:48 -0700 Subject: Python Threads - References: Message-ID: In article , S.Mohideen wrote: > >Can you please suggest a technique in Python where we can spawn few number >of worker threads and later map them to a function/s to execute individual >Jobs. You can see an example for a web spider on my Python website. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Help a hearing-impaired person: http://rule6.info/hearing.html From oscartheduck at gmail.com Wed Apr 4 14:43:51 2007 From: oscartheduck at gmail.com (oscartheduck) Date: 4 Apr 2007 11:43:51 -0700 Subject: try... except SyntaxError: unexpected EOF while parsing In-Reply-To: References: <1175708304.034078.139020@e65g2000hsc.googlegroups.com> Message-ID: <1175712231.026226.92240@l77g2000hsb.googlegroups.com> Wow. Thanks, everyone, for the responses. It helps a lot having such a well informed and helpful resource. From robert.rawlins at thinkbluemedia.co.uk Fri Apr 20 09:39:36 2007 From: robert.rawlins at thinkbluemedia.co.uk (Robert Rawlins - Think Blue) Date: Fri, 20 Apr 2007 14:39:36 +0100 Subject: Byte-Array to String In-Reply-To: <1177074008.3412.12.camel@dot.uniqsys.com> References: <000f01c7828f$8b8ce770$a2a6b650$@rawlins@thinkbluemedia.co.uk> <46278FF4.9070505@gmail.com> <004d01c78329$1e5f7a60$5b1e6f20$@rawlins@thinkbluemedia.co.uk> <1177074008.3412.12.camel@dot.uniqsys.com> Message-ID: <000901c78351$56abae70$04030b50$@rawlins@thinkbluemedia.co.uk> Thanks for that Carsten, I've given that a go and I still get similar results to what I've seen in the past whereby it prints a couple of elements I would expect to see but other which I'm not sure about, and what seems to be ALOT of blank characters. 6e 555 5 5 5 en j 5 %OBEX Object Push ? That's what your suggestion returns to me, I'm using the API to scan a Bluetooth device for services, one of which is OBEX Object Push, but the rest of that output is apparent junk. Unfortunately the API doesn?t really give any suggestions at all, take a look here http://bluez.cvs.sourceforge.net/*checkout*/bluez/utils/hcid/dbus-api.txt if you look down under the 'adapter' section, I'm running the method called GetRemoteServiceRecord() which returns the byte array but there really isn?t any suggestion as to how you extract the information from what's returned. I have no idea if we're barking up the right tree here or if we're going about this the wrong way. Thanks again for all your helps guys, Rob -----Original Message----- From: Carsten Haese [mailto:carsten at uniqsys.com] Sent: 20 April 2007 14:00 To: Robert Rawlins - Think Blue Cc: python-list at python.org Subject: RE: Byte-Array to String On Fri, 2007-04-20 at 09:51 +0100, Robert Rawlins - Think Blue wrote: > Morning Steve, > > > > That stuff looks mighty promising, I did play around with the > toString() function yesterday but couldn?t get the damned thing > working. That's because Steven seems to have given you suboptimal advice. The thing you're working with is a dbus.Array of dbus.Byte, not a Python array, so Python's standard array module is not going to help you. When you work with an API function and you don't know what to do with the results of calling that function, the documentation for that API should be your first place to look for help. I don't know what you're referencing, but Google tells me that the python-dbus API is documented here: http://dbus.freedesktop.org/doc/dbus-python/api/ So, what do you do with a dbus.Array full of instances of dbus.Byte? Let's look at their documentation, http://dbus.freedesktop.org/doc/dbus-python/api/dbus.Array-class.html and http://dbus.freedesktop.org/doc/dbus-python/api/dbus.Byte-class.html, respectively. The page about dbus.Array tells us that it inherits from list, so you should be able to do indexed access into it and iterate over it. dbus.Byte inherits from int, and the documentation says that a dbus.Byte can be converted to a character (string of length 1) by calling str or chr on it. So, to get a string from your dbus.Array, you could do something like this: s = "" for b in myDbusArray: s += chr(b) However, it's better (faster) to use the join idiom for building a string char-by-char: s = "".join(chr(b) for b in myDbusArray) That ought to give you the string you're asking for. HTH, Carsten. From franz.steinhaeusler at gmail.com Thu Apr 19 03:47:44 2007 From: franz.steinhaeusler at gmail.com (franz.steinhaeusler at gmail.com) Date: 19 Apr 2007 00:47:44 -0700 Subject: Wanted: Email Client with GUI In-Reply-To: <46265e98$0$16353$88260bb3@free.teranews.com> References: <46265e98$0$16353$88260bb3@free.teranews.com> Message-ID: <1176968864.175372.116150@q75g2000hsh.googlegroups.com> Hello, thanks, Chandler looks good, maybe I will give it a try. Thanks, From s_broscious at comcast.net Wed Apr 11 12:44:17 2007 From: s_broscious at comcast.net (Scott) Date: Wed, 11 Apr 2007 12:44:17 -0400 Subject: pop() clarification Message-ID: As said before I'm new to programming, and I need in depth explaination to understand everything the way I want to know it, call it a personality quirk ;p. With pop() you remove the last element of a list and return its value: Now I know list is a bad name, but for the sake of arguement lets assume its not a built in sequence> >>>list = ['this', 'is', 'an', 'example'] >>>list.pop() 'example' >>>list ['this', 'is', 'an'] I understand all that. What I don't understand is why all the documentation I see says, "When removing a specific element from a list using pop() it must be in this format: list.pop([i]). At first I took that to mean that list.pop(i) would return some type of error, but it doesn't. I can't find any documentation saying that this rule that I keep reading about (again list.pop([i]) ) is the only format to use when removing a specific element because......with the explaination to follow. Now I'm not stupid enough to believe that I'm the first to try: >>>list = ['this', 'is', 'an', 'example'] >>>list.pop(1) and have it return the desired effect of: 'is' >>>list ['this', 'an', 'example'] I guess simplistically all I'm asking is: Is this just a community agreed upon rule for readability purposes? or Is it a rule that's in place for a reason I'll learn later on? Please keep in mind my intro sentence to this post. I would like a very detailed explaination, or at least a link to a very detailed expression. ONLY....of course....if the explaination isn't, well it just is because we all agreed to use it that way. That explaination I'll understand and except, but with a bit of dissatisfaction. From isaac.rodriguez at comcast.net Wed Apr 18 09:01:10 2007 From: isaac.rodriguez at comcast.net (Isaac Rodriguez) Date: 18 Apr 2007 06:01:10 -0700 Subject: Calling private base methods In-Reply-To: <58fiorF2eq6duU1@mid.uni-berlin.de> References: <1176374675.347453.89340@n76g2000hsh.googlegroups.com> <1176404325.211501.26610@w1g2000hsg.googlegroups.com> <1176435087.708516.66470@o5g2000hsb.googlegroups.com> <1176650850.211487.294690@y80g2000hsf.googlegroups.com> <7x7isdwj0i.fsf@ruckus.brouhaha.com> <58fiorF2eq6duU1@mid.uni-berlin.de> Message-ID: <1176901270.023112.208820@q75g2000hsh.googlegroups.com> > After all, that's what duck-typing is about. There is no official > interface declaration, just an implicit protocol. And "private" methods > or members are part of that protocol as well. I don't think so. Duck-typing is about implementing the expected public interface, and has nothing to do with accessing private members of a class, nor overriding those members. - Isaac. From gandalf at designaproduct.biz Wed Apr 4 11:48:48 2007 From: gandalf at designaproduct.biz (Laszlo Nagy) Date: Wed, 04 Apr 2007 17:48:48 +0200 Subject: Windows service and pyc files Message-ID: <4613C8E0.2000306@designaproduct.biz> Hello, I have a win32 service written in Python that starts a plain application, written in Python. The win32 service tries to launch the application in a while loop and logs the return value of the os.system call. That's all. The application is a simple Python program that connects to an https xml/rpc server, and works with the data retrieved from that server. It is written as an application because it must be able to download updates for itself. Here is how it works: a.) connect to server b.) compare current version with the latest c.) if there is a difference, then download all sources from the server, delete all pyc files and exit; otherwise start processing I could not write a self-restarting server, and I did not want to write/install two services for one problem. The win32 service is very small and primitive so probably I will not need to update it. I think the basic idea is good, but... When there is a client update available, my application updates itself cleanly and exists. Then the service tries to restart the application, but it cannot. os.system returns with OS error code -1. The pyc files are NOT generated for the application. However, if I start the application from the command line, then pyc files are created, and then the service will also start the application immediatelly. The win32 service is running as "Localsystem" so it is sure that it has write permission on all files. I cannot log out the error from the application since it is not started. The only error message I have is OSError -1, but it tells me nothing about the nature of the error. Thanks, Laszlo From ah at hatzis.de Sat Apr 28 08:06:41 2007 From: ah at hatzis.de (Anastasios Hatzis) Date: Sat, 28 Apr 2007 14:06:41 +0200 Subject: Which are your favorite UML tools? In-Reply-To: <463265f0$0$19018$426a34cc@news.free.fr> References: <463265f0$0$19018$426a34cc@news.free.fr> Message-ID: <200704281406.41522.ah@hatzis.de> On Friday 27 April 2007 23:48, Bruno Desthuilliers wrote: > Anastasios Hatzis a ?crit : > > Hello, > > > > I'm working on the light-weight MDA tool pyswarm, > > http://pyswarm.sourceforge.net/ (it is about a code-generator for > > Python/PostgreSQL-based software. I plan to add support of UML CASE tools > > other than the one supported currently. > > > > I would like to learn which UML tools you use (if any), > > Any piece of paper and anything that can be used to write on it. Maybe importing paper-based UML into a MDA tool would be easier than the XMI interoperability nightmare I'm facing ;) > > > preferrably if it > > comes to modeling a Python application. > > I stll wait for UML to be able to describe common hi-level dynamic > languages idioms and patterns without requiring more space and time than > source code. Do you have an example for what you mean? As I understand Python itself is already pretty abstract compared to other languages and platforms where UML and also MDA are -for good reasons- popular. I think it depends on the complexity of a Python software if it would be worth to add another abstraction layer. UML and especially MDA are adding their own complexity which has to be compensated by the benefits of the additional abstraction. BTW, I don't know if UML is the appropriate notation (or model level) to describe high level dynamic languages' idioms and patterns. Two days ago I learned of a research project that uses Essential Meta Object Facility (MOF is the meta-meta model of UML) to model their own Python language with extensions or modifications of regular Python to build domain specific languages. Modules in these special Python dialects can be compiled and executed by a normal Python interpreter. I was pretty impressed although I didn't understand all the details how it works. These things are beyound my current skills. :) Best regards, Anastasios From jorgen.maillist at gmail.com Thu Apr 5 14:35:11 2007 From: jorgen.maillist at gmail.com (Jorgen Bodde) Date: Thu, 5 Apr 2007 20:35:11 +0200 Subject: PyDispatcher question In-Reply-To: <46153B2F.5020305@vrplumber.com> References: <11e49df10704051046p65ac623fqcae6d3a010a7e415@mail.gmail.com> <46153B2F.5020305@vrplumber.com> Message-ID: <11e49df10704051135y4c841ec1mbabf347ff17e37dc@mail.gmail.com> Hi Mike, Thanks for the explanation! The Python shell really threw me off here. I thought it would work exactly the same as in the interpreter itself. :-) Even assigning None to the object exibits the same behaviour as "del" does. COOL! This is what I did sofar: from pydispatch import dispatcher class X(object): def __init__(self): dispatcher.connect(self.someSignal, signal = 1) def someSignal(self): print 'Hello world' a = X() dispatcher.send(1) a = None dispatcher.send(1) print '----------------------' b = X() c = X() dispatcher.send(1) With as output; C:\Documents and Settings\Jorg\Desktop>python New1.py Hello world ---------------------- Hello world Hello world Nice! Thanks a lot for the info! - Jorgen On 4/5/07, Mike C. Fletcher wrote: > Jorgen Bodde wrote: > > Hi all, > > > > Hopefully someone can help me. I am fairly new to Python, and I am > > looking into PyDispatcher. I am familiar with the C++ sigslot variant, > > and I wonder how similar PyDispatches is. I run in to the following > > 'problem' (pseudo code, untested here) > > > Here's some real code... > > from pydispatch import dispatcher > import gc > > class X(object): > def __init__( self ): > dispatcher.connect( self.someSignal, signal=1 ) > def someSignal( self ): > print 'hello world' > > obj = X() > dispatcher.send( signal= 1 ) > > del obj > #gc.collect() > > dispatcher.send( signal= 1 ) > > This will print out only one "hello world" on my Python 2.5 Gentoo > machine (it should work the same on any recent Python). Basically your > python shell will tend to keep around an extra copy of the X instance > until you get rid of it explicitly, and that's what keeps the object > "live" and receiving signals if you try the code in the shell. > PyDispatcher is designed so that, by default, when the object goes away > the registration is removed. It uses the weakref module to do this, > rather than __del__ methods, to avoid garbage cycles, btw. > > HTH, > Mike > > -- > ________________________________________________ > Mike C. Fletcher > Designer, VR Plumber, Coder > http://www.vrplumber.com > http://blog.vrplumber.com > > From kyosohma at gmail.com Mon Apr 2 14:50:39 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: 2 Apr 2007 11:50:39 -0700 Subject: Error when trying to pass list into function. In-Reply-To: <1175539402.046635.196310@b75g2000hsg.googlegroups.com> References: <1175539402.046635.196310@b75g2000hsg.googlegroups.com> Message-ID: <1175539839.571378.268450@y80g2000hsf.googlegroups.com> On Apr 2, 1:43 pm, "erikcw" wrote: > Hi, > > I'm getting the following error when I try to pass a list into a > function. > > My List: crea =[(u'218124172', u'536', u'32394'), (u'218320282', > u'1323', u'77931')] > > Traceback (most recent call last): > File "wa.py", line 118, in ? > curHandler.walkData() > File "wa.py", line 49, in walkData > self.results[parent][child]['results'] = self.calculate(crea) > #pass in list of tuples > TypeError: calculate() takes exactly 1 argument (2 given) > > def calculate(dta): > #stub > > How can I make this work? > > Thanks! > Erik You need to do this: def calculate(self, dta): # stub Because when you call a method in a class with this: self.calculate(crea), you pass in an instance of the object (self) AND the list. Mike From Martin.Drautzburg at web.de Sun Apr 22 02:54:19 2007 From: Martin.Drautzburg at web.de (Martin Drautzburg) Date: Sun, 22 Apr 2007 08:54:19 +0200 Subject: Dictionaries and dot notation Message-ID: <23087554.X5dcTmlj7P@beaureve.gmx.net> This may be pretty obvious for most of you: When I have an object (an instance of a class "Foo") I can access attributes via dot notation: aFoo.bar however when I have a dictionary aDict = {"bar":"something"} I have to write aDict["bar"] What if I want to create a datastructure that can be used in dot notation without having to create a class, i.e. because those objects have no behavior at all? I know that accessing an instance variable via bracket notation would really have to be written as: aFoo.__dict__['bar'] but this does not bring me any further, because I would still have to plug in that __dict__ thing into my datastructure, which leads us to the same question as above. Can anyone tell me what I am missing here? From duncan.booth at invalid.invalid Tue Apr 10 04:50:28 2007 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 10 Apr 2007 08:50:28 GMT Subject: tuples, index method, Python's design References: <1175867771.114540.61810@n76g2000hsh.googlegroups.com> <1175884427.779950.267220@y80g2000hsf.googlegroups.com> <1175953520.316208.241490@o5g2000hsb.googlegroups.com> <7xzm5igbrb.fsf@ruckus.brouhaha.com> Message-ID: Antoon Pardon wrote: >> When a new feature is requested, the burden of proof is on the requester >> to show that it has uses. > > I don't agree. Good or bad design is not dependant on what is > implemented and what is not. There is a cost to every new language feature: it has to be implemented, documented, maintained, and above all learned by the users. Good design involves, in part, not adding to these burdens except where there is a benefit at least equal to the cost. >> The use case for not having tuple.index is >> that there are no use cases for having it. If that answer sounds absurd, >> it is because your question is absurd. > > You mean that those who are against tuple.index won't find any use case > convincing enough. > Why not try them? Pose a few useful cases where the existence of tuple.index() would actually give a benefit and see what response you get. You would have to meet a few obvious conditions: the use case would need to be one where a tuple was preferable to a list (the obvious one being where you need to hash it), the tuple would have to be sufficiently long or the calls to 'index' sufficiently frequent to make casting to a list so you can call 'list(obj).index(...)' unattractive, and you actually need a reason to be using 'index' rather than just the 'in' operator. From aisaac at american.edu Tue Apr 24 21:22:07 2007 From: aisaac at american.edu (Alan Isaac) Date: Wed, 25 Apr 2007 01:22:07 GMT Subject: gotcha or bug? random state reset on irrelevant import Message-ID: <33yXh.5839$Fc1.4387@trnddc05> Running test.py will print False. Is this expected/desirable? Thanks, Alan Isaac %%%%%%% test.py %%%%%%%%%%% from random import seed, getstate seed(217) x = getstate() from test2 import Trivial y = getstate() print x == y %%%%% test2.py %%%%%%%%%%%%% from random import seed seed(314) class Trivial: pass From gdonald at gmail.com Fri Apr 13 16:25:35 2007 From: gdonald at gmail.com (Greg Donald) Date: Fri, 13 Apr 2007 15:25:35 -0500 Subject: Python editor/IDE on Linux? In-Reply-To: References: <1176494048.627760.323630@p77g2000hsh.googlegroups.com> Message-ID: <15e66e4e0704131325j12f3c62emae3f929afbe99f3@mail.gmail.com> On 4/13/07, Jarek Zgoda wrote: > Thanks God No problem. > , there's no "PIDA for Emacs". Pet Industry Distributors Association ? -- Greg Donald http://destiney.com/ From grante at visi.com Sun Apr 8 09:43:54 2007 From: grante at visi.com (Grant Edwards) Date: Sun, 08 Apr 2007 13:43:54 -0000 Subject: Console UI References: <1175994720.819372.232380@o5g2000hsb.googlegroups.com> Message-ID: <131hscqlttk9ud9@corp.supernews.com> On 2007-04-08, Ayaz Ahmed Khan wrote: > "Clement" typed: > >> My project is based on console Application. Is there any >> console UI except urwid. If so, can i come to know. > > There is ``curses''. And newt (runs on top of slang). It's not well documented, but it is nice and lightweight. IIRC the python module is called "snack". -- Grant Edwards grante Yow! Spreading peanut at butter reminds me of visi.com opera!! I wonder why? From deets at nospam.web.de Mon Apr 16 07:43:40 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 16 Apr 2007 13:43:40 +0200 Subject: ctypes and pointers References: <58ch42F2fnojeU1@mid.uni-berlin.de> <1176719952.974351.205450@d57g2000hsg.googlegroups.com> Message-ID: <58h5rcF2gtjh6U1@mid.uni-berlin.de> per9000 wrote: > [This might be a double posting, if it isn't my previous post was > lost] > > Look up "restype" in the ctypes library - it sets the return type from > a function. You may want to set it to c_void_p of something similar, > instead of the default int. > > I made a similar discovery in my blog - > http://www.pererikstrandberg.se/blog/index.cgi?page=PythonCansiCombo > . > > This example loads the function find_root from the dll > root_find_lib.dll into the variable "find". the restype of find is > then set to a c_double. This means that the item returned from C is a > C_double and not the default int. > root_find_lib = windll.LoadLibrary("root_find_lib.dll") > find = root_find_lib.find_root > find.restype = c_double I found the solution to be X.from_address(address) where X is some ctypes.Structure Diez From mail at microcorp.co.za Fri Apr 20 01:23:35 2007 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Fri, 20 Apr 2007 07:23:35 +0200 Subject: Do other Python GUI toolkits require this? (OT) References: <462697A6.6010007@codebykevin.com> <465B30B4-5BA0-459A-BE6F-1038874FA74B@jedimindworks.com> Message-ID: <00ed01c78318$681f8b60$03000080@hendrik> "Steve Holden" wrote: > Perhaps in Belgium they prefer climbing mountains over walking up and > down gentle hills? Mountains ? Hills ? In Belgium ?? Its not called the battlefield of Europe for nothing... - Hendrik From grante at visi.com Sun Apr 1 22:17:46 2007 From: grante at visi.com (Grant Edwards) Date: Mon, 02 Apr 2007 02:17:46 -0000 Subject: How can i compare a string which is non null and empty References: <1175469766.979636.65020@e65g2000hsc.googlegroups.com> Message-ID: <1310puahjesd9b9@corp.supernews.com> On 2007-04-01, Plissken.s at gmail.com wrote: > how can i compare a string which is non null and empty? [...] > In java,I do this: > if (str != null) && (!str.equals("")) .... > > how can i do that in python? If you want to litterally do that, it's if (str != None) and (str != ""): However, the standard idiom for doing that in Python is if str: -- Grant Edwards grante Yow! I'm RELIGIOUS!! I at love a man with a visi.com HAIRPIECE!! Equip me with MISSILES!! From Karsten.G.Weinert at googlemail.com Mon Apr 30 09:39:52 2007 From: Karsten.G.Weinert at googlemail.com (Karsten.G.Weinert at googlemail.com) Date: 30 Apr 2007 06:39:52 -0700 Subject: Cgi File Upload without Form In-Reply-To: References: <1177708242.553577.226530@n15g2000prd.googlegroups.com> Message-ID: <1177940392.357662.245650@o5g2000hsb.googlegroups.com> Thanks for your replies, however I think urlllib can not help me here. I have control over the server side (I can write a cgi-script in python), but I have very little control on the client side (I have to use VBA). Kind regards, Karsten. From howe.steven at gmail.com Thu Apr 19 11:51:16 2007 From: howe.steven at gmail.com (Steven Howe) Date: Thu, 19 Apr 2007 08:51:16 -0700 Subject: Byte-Array to String In-Reply-To: <000f01c7828f$8b8ce770$a2a6b650$@rawlins@thinkbluemedia.co.uk> References: <000f01c7828f$8b8ce770$a2a6b650$@rawlins@thinkbluemedia.co.uk> Message-ID: <46278FF4.9070505@gmail.com> Robert Rawlins - Think Blue wrote: > Hello Guys, > > > > I have a byte array passed to me by dbus and I'm looking to convert it into > a string? Is that possible? Sorry for seeming like a putts with these > questions, I'm not used to all these complex data types :-D > > > > The byte array looks something like this when printed to screen. > > > > dbus.Array([dbus.Byte(54), dbus.Byte(0), dbus.Byte(24), dbus.Byte(9), > dbus.Byte(0), dbus.Byte(0), dbus.Byte(10), dbus.Byte(0), dbu > s.Byte(0), dbus.Byte(0), dbus.Byte(0), dbus.Byte(9), dbus.Byte(0), > dbus.Byte(1), dbus.Byte(53), dbus.Byte(3), dbus.Byte(25), dbus. > Byte(16), dbus.Byte(0), dbus.Byte(9), dbus.Byte(2), dbus.Byte(0), > dbus.Byte(53), dbus.Byte(3), dbus.Byte(9), dbus.Byte(1), dbus.By > te(1)], signature=dbus.Signature('y')) > > > > Thanks again, > > > > Rob > * > * When reading about array, I wondered what the hell it was good for. Now I see. It's a tool to build objects to pass to the Operating System or other applications. Something like ctypes. The OS might store data from left to right, or right to left, or not use IEEE standards (which VMS certainly doesn't). So the data you give/get from the system call must be massaged by the application before it's usable. python/lib/module-array.html (5.14 array -- Efficient arrays of numeric values) *array.tostring*( ) /Convert the array to an array of machine values and return the string representation (the same sequence of bytes that would be written to a file by the tofile() method.)/ I wonder if this is the method you are looking for. So you have an object dbus.Array, which, obviously is from a call to the dbus (another application's data) that contains 28 byte arrays. I would assume you know which you want, say the first one. myDbusString01 = dbus.Array[0].tostring() or to get the lot: myDbusStrings = [] #create a new empty list for array in dbus.Array: myDbusStrings.append( array.tostring() ) At this point you should have the array converted. But you will still need a reference as to what you have. The call to the dbus should have some documentation abut what it's returning. Also I'd expect the second example to be very bad programming, as some of the array elements are probably not going to be characters. They could be integers, floats or booleans. So creating a dictionary to handle specific array element handling is probably a better, less error prone, method of attack. Not have the contents and defination of your dbus.array handy, I can't test this, but the approach seems reasonable. Steven Howe -------------- next part -------------- An HTML attachment was scrubbed... URL: From horpner at yahoo.com Wed Apr 25 10:55:23 2007 From: horpner at yahoo.com (Neil Cerutti) Date: 25 Apr 2007 16:55:23 +0200 Subject: When are immutable tuples *essential*? Why can't you just use lists *everywhere* instead? References: <1177088796.622928.224890@d57g2000hsg.googlegroups.com> <1177089206.550423.288670@q75g2000hsh.googlegroups.com> <58sf33F2b1q8tU1@mid.individual.net> <1177103370.022138.110320@n59g2000hsh.googlegroups.com> <1177108560.660288.171890@n76g2000hsh.googlegroups.com> <1177451173.176235.216270@t38g2000prd.googlegroups.com> Message-ID: On 2007-04-25, Steve Holden wrote: > Neil Cerutti wrote: >> That would be documented as undefined behavior, and users >> exhorted not to do such things. >> >> Python's dictionaries are a proven winner--I'm definitely not an >> advocate for changing them. But the general requirement for a >> mapping container *isn't* that keys be immutable, but that you >> either don't mutate keys, or don't do so without also reording >> (rehashing?) the mapping. >> > And which API do you use to "reord(er?) (rehash) the mapping"? A pretty complex an unnecessary one, I'd guess. ;) Since you would most likely need to remove the changed key from the mapping, and then reinsert the new one, it's just as well to leave the whole process entirely up to the user. Which is how Python currently works. ;) -- Neil Cerutti From michael at jedimindworks.com Mon Apr 23 10:13:07 2007 From: michael at jedimindworks.com (Michael Bentley) Date: Mon, 23 Apr 2007 09:13:07 -0500 Subject: Tutorial creates confusion about slices In-Reply-To: References: Message-ID: <5161BBCD-6EE6-4A5F-A398-8036083D4185@jedimindworks.com> On Apr 23, 2007, at 7:38 AM, Antoon Pardon wrote: > The following is part of the explanation on slices in the > tutorial: > > The best way to remember how slices work is to think of the indices as > pointing between characters, with the left edge of the first character > numbered 0. Then the right edge of the last character of a string of n > characters has index n, for example: > > +---+---+---+---+---+ > | H | e | l | p | A | > +---+---+---+---+---+ > 0 1 2 3 4 5 > -5 -4 -3 -2 -1 > > This is all very well with a simple slice like: > > "HelpA"[2:4] => "lp" > > > But it give the wrong idea when using the following extended slice: > > "HelpA"[4:2:-1] => "Ap" > > So this doesn't result in the reverse of the previous expression while > the explanation above suggest it does. > > > So I suggest to drop this. But 'drop' means to let or make (something) fall vertically... :-) At that point in the tutorial, step values had not been discussed. Just a bit lower down on the page you'll find a link to 'Sequence Types' where you'll find an explanation of stepping you'll perhaps find more satisfactory. hth, Michael --- "Those who don't understand UNIX are condemned to reinvent it, poorly." --Henry Spencer From apardon at forel.vub.ac.be Wed Apr 25 06:46:42 2007 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 25 Apr 2007 10:46:42 GMT Subject: Tutorial creates confusion about slices References: <1177496078.319400.324720@r30g2000prh.googlegroups.com> Message-ID: On 2007-04-25, Ant wrote: > On Apr 23, 1:38 pm, Antoon Pardon wrote: >> The following is part of the explanation on slices in the >> tutorial: >> >> The best way to remember how slices work is to think of the indices as > ... >> +---+---+---+---+---+ >> | H | e | l | p | A | >> +---+---+---+---+---+ >> 0 1 2 3 4 5 >> -5 -4 -3 -2 -1 > > For a tutorial this is sound advice. A tutorial is designed to give > readers an easy intro to a topic, which is what this achieves. At this > stage the target audience has no idea that extended slices even exist, > let alone that you can use negative indices with them. OK. But eventually they will come into contact with negative indexes. If they still rely on the above representation for understanding slices that may cause confusions. It is possible that the time lost in clearing up these later confusions will be bigger than the time gained by using this simplification in the tutorial. So I'm not so sure it is sound advice in this case. If the consensus is that something like this should remain, I would suggest replacing: "The best way to remember how slices work is" with: "A way to remember how slices work, it is not entirly correct but may be usefull, is" Or something similar. Wording to that effect makes it more clear that it is a crutch that can be usefull now but that it should be discarded later. -- Antoon Pardon From bbxx789_05ss at yahoo.com Thu Apr 12 02:34:43 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: 11 Apr 2007 23:34:43 -0700 Subject: __file__ In-Reply-To: <1176296122.789218.258830@y80g2000hsf.googlegroups.com> References: <1176250851.946892.273550@l77g2000hsb.googlegroups.com> <1176285795.667520.120230@l77g2000hsb.googlegroups.com> <1176296122.789218.258830@y80g2000hsf.googlegroups.com> Message-ID: <1176359683.471237.284690@d57g2000hsg.googlegroups.com> On Apr 11, 6:55 am, "John Machin" wrote: > On Apr 11, 8:03 pm, "7stud" wrote: > > > > > Hi, > > > Thanks for the response. > > > On Apr 11, 12:49 am, "Gabriel Genellina" > > wrote: > > > > __file__ corresponds to the filename used to locate and load the module, > > > whatever it is. When the module is found on the current directory > > > (corresponding to '' in sys.path), you get just the filename; if sys.path > > > contains a relative path, that's what you get; the same for any absolute > > > path. > > > Whatever path worked to find and load the module, that's stored as > > > __file__. > > > > If you plan to use it, it's a good idea to make it early into an absolute > > > path (using os.path.abspath(__file__)) just in case the current directory > > > changes. > > > That last part doesn't seem to fit with your description above. What > > does the current working directory have to do with the path that was > > used to load a module? I would think the path that was used to load a > > module is constant. > > You are correct, but that is not what GG was talking about. Here is an > example of what he meant: > > While your cwd is /bar, you load module foo from a *relative*( path, > e.g. ./foo.py. If you do the os.path.abspath("./foo.py") immediately > as recommended, you get the correct answer: /bar/foo.py. However if > you change your cwd to /zot, then do the os.path.abspath("./foo.py"), > you get /zot/foo.py which is a nonsense. > > HTH, > John Thanks for all the help. From antroy at gmail.com Thu Apr 12 03:40:41 2007 From: antroy at gmail.com (Ant) Date: 12 Apr 2007 00:40:41 -0700 Subject: redirecting stdout to a file as well as screen In-Reply-To: <1176362072.527678.201150@l77g2000hsb.googlegroups.com> References: <1176362072.527678.201150@l77g2000hsb.googlegroups.com> Message-ID: <1176363641.493358.62560@y5g2000hsa.googlegroups.com> On Apr 12, 8:14 am, "SamG" wrote: > How could i make, from inside the program, to have the stdout and > stderr to be printed both to a file as well the terminal(as usual). One way would be to create a custom class which has the same methods as the file type, and held a list of file-like objects to write to. e.g. class multicaster(object): def __init__(self, filelist): self.filelist = filelist def write(self, str): for f in self.filelist: f.write(str) def writelines(self, str_list): #etc Then assign stdout and stderr to a new instance of one of these objects: mc = multicaster([sys.stdout, sys.stderr, log_file]) sys.stdout = mc sys.stderr = mc HTH From deets at nospam.web.de Sun Apr 15 17:11:52 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sun, 15 Apr 2007 23:11:52 +0200 Subject: Calling private base methods In-Reply-To: <7x7isdwj0i.fsf@ruckus.brouhaha.com> References: <1176374675.347453.89340@n76g2000hsh.googlegroups.com> <1176404325.211501.26610@w1g2000hsg.googlegroups.com> <1176435087.708516.66470@o5g2000hsb.googlegroups.com> <1176650850.211487.294690@y80g2000hsf.googlegroups.com> <7x7isdwj0i.fsf@ruckus.brouhaha.com> Message-ID: <58fiorF2eq6duU1@mid.uni-berlin.de> Paul Rubin schrieb: > Duncan Booth writes: >> The problem is that when people design interfaces they don't (and >> cannot) know all the situations in which the code is going to be used in >> the future. Clearly separating the published interface from the >> implementation details is a good thing, but physically preventing access to >> those details is IMHO a bad thing. > > The idea is to make the implementation details independent from the > calling program. For example, I'm using a library now that does > something highly CPU intensive. To speed up the application, I may > put the library on a completely separate computer, so that the > published API exposed to the caller becomes a wrapper for a network > client, and all those library implementation details are on the other > machine. That's the ultimate in physical access prevention, there's > good reason to do it, and it completely breaks if the calling program > is using anything except the published API. So what? This will happen under under circumstances as well. Think of an interface returning None in an earlier version, then [] to indicate an empty result-set. the point is that privacy is good to indicate that "you shouldn't mess with this unless you know what you do, which includes not to use new versions of the library." I totally agree with Duncan that I've been in plenty situations where exploiting inner workings of some 3rd-party-code made my programming easier, only of course when nothing else helped. After all, that's what duck-typing is about. There is no official interface declaration, just an implicit protocol. And "private" methods or members are part of that protocol as well. Diez From someguywithoutanemailaddress Sun Apr 29 20:23:22 2007 From: someguywithoutanemailaddress (Alvin Bruney [MVP]) Date: Sun, 29 Apr 2007 20:23:22 -0400 Subject: Free Windows Vista Download References: <1177866404.344342.175400@h2g2000hsg.googlegroups.com> Message-ID: That's a misleading post, you should indicate that this is an evaluation copy. -- Regards, Alvin Bruney ------------------------------------------------------ Shameless author plug Excel Services for .NET is coming... OWC Black book on Amazon and www.lulu.com/owc Professional VSTO 2005 - Wrox/Wiley wrote in message news:1177866404.344342.175400 at h2g2000hsg.googlegroups.com... > http://freewindowsvista.blogspot.com/ - Get Windows Vista for Free > From sjmachin at lexicon.net Wed Apr 4 18:48:05 2007 From: sjmachin at lexicon.net (John Machin) Date: 4 Apr 2007 15:48:05 -0700 Subject: Newbie Question about sequence multiplication In-Reply-To: <6cOdnVFCLMXxuYnbnZ2dnUVZ_rCsnZ2d@comcast.com> References: <6cOdnVFCLMXxuYnbnZ2dnUVZ_rCsnZ2d@comcast.com> Message-ID: <1175726885.373889.23850@y80g2000hsf.googlegroups.com> On Apr 5, 8:19 am, "Scott" wrote: > Alright, so I've been trying to teach myself Python which, when compared to > my attempt to learn C++, is going pretty well. > But I've come across an issue that I can't figure out, so I figured I'd ask > the pro's. > > Now it looks pretty weird in this format but it was copied exactly from IDLE > > *****code follows******* > > #What this program is suppose to do is print a sentence centered in a box > > sentence = raw_input('Sentence: ') > > screen_width = 80 > text_width = len(sentence) > box_width = text_width + 6 > left_margin = (screen_width - box_width) // 2 > > print > print ' ' * left_margin + '+' + '-' * (box_width-2) + '+' > print ' ' * left_margin + '| ' + ' ' * text_width + ' |' > print ' ' * left_margin + '| ' + ' ' sentence + ' |' You didn't say which occurrence of 'sentence' was causing the drama, but it appears to be the above statement. The syntax is sequence * factor, where 'factor' is an integer. So both these are wrong: '' sentence # needs an operator between ' ' and sentence ' ' * sentence # sentence is not bound to an integer You need something like this: print ' ' * left_margin + '| ' + sentence + ' |' # plus or minus a space or two > print ' ' * left_margin + '| ' + ' ' * text_width + ' |' > print ' ' * left_margin + '+' + '-' * (box_width-2) + ' |' > print > > ****end code**** > > Now that, even though copied straight from "Beginning Python: From Novice to > Professional", Are you sure? Check the accuracy of your "copy"; check the book's known errata (if any) on the book's website (if any). > returns : > There's an error in your program: invalid syntax > > with the word sentence highlighted (not the sentence when I'm defining the > name, the one in......uhm....the body of the code) > > Now if i put * before sentence as it is with the rest of the variables, it > actually gets to the point where it asks me for the sentence, but after > inputting my sentence I receive: > Traceback (most recent call last): > File "D:/Programming/Python/sequence string multiplication example", line > 16, in > print ' ' * left_margin + '| ' + ' ' * sentence + ' |' > TypeError: can't multiply sequence by non-int of type 'str' > > Why can't I get it to do what it's supposed to do? What am I > missing/misunderstanding? Seeing you asked: 1. Not following the recipe exactly and/or not verifying accuracy of recipe. 2. Not understanding what the * operator is doing in this context (sequence * int); does the book not explain what this does? > Very simply all its supposed to do is something like this (now bear with me > formating might distort this a bit lol) > +------------------------------------+ > | | > | Like This | > | | > +------------------------------------+ > > Any help would be greatly appreciated > > -Scott From codecraig at gmail.com Tue Apr 3 12:26:03 2007 From: codecraig at gmail.com (abcd) Date: 3 Apr 2007 09:26:03 -0700 Subject: Retrieve an item from a dictionary using an arbitrary object as the key Message-ID: <1175617563.169153.150430@d57g2000hsg.googlegroups.com> Hi, I have a class such as, class Type: def __init__(self, val): self.val = val class Person: def __init__(self, name, age): self.name = name self.age = age So I have a dictionary which maps an instance of Type to an instance of Person. Now I need to retrieve a particular Person given a Type object. What method in Type do I need to implement to allow it to be retrieved? For example (this is just an example): t = Type(19) p = Person("bob", 99) x = {t : p} ........ def getPerson(val): return x[Type(val)] getPerson(19) ....should return me the Person with name "bob" and age 99. I am thinking there is some method that is used by the dictionary to know if the key exists, just not sure which. thanks From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Wed Apr 18 06:21:18 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Wed, 18 Apr 2007 12:21:18 +0200 Subject: Python Feature Request: Allow changing base of member indices to 1 References: <1176546465.632410.52630@w1g2000hsg.googlegroups.com> <4620b47b$0$14410$9b622d9e@news.freenet.de> <1176557999.665663.299740@y80g2000hsf.googlegroups.com> <1176559643.450533.296850@n59g2000hsh.googlegroups.com> <58cu2bF2gtuo3U2@mid.individual.net> <1176805485.948822.39540@l77g2000hsb.googlegroups.com> Message-ID: <58m9ouF2h6pn5U1@mid.individual.net> Dustan wrote: > For newbies, it's easier to count starting with 1. It's rather > unintuitive to start at 0. Cool. So Python will become a "newbie language", and everyone that "jumps" from Python to a different language will have to relearn 0-based indices? ;) Regards, Bj?rn -- BOFH excuse #418: Sysadmins busy fighting SPAM. From Usetheaddress at inthesig.com Sun Apr 29 10:21:04 2007 From: Usetheaddress at inthesig.com (Dom Robinson) Date: Sun, 29 Apr 2007 15:21:04 +0100 Subject: SEO - Search Engine Optimization - Seo Consulting References: <1177808356.681710.42980@n76g2000hsh.googlegroups.com> Message-ID: In article , "Alvin Bruney [MVP]" says... > Please don't spam this group > A top-poster replies to a spammer. Now that world has truly gone mad(!) -- Dom Robinson Gamertag: DVDfever email: dom at dvdfever dot co dot uk /* http://DVDfever.co.uk (editor) /* 1132 DVDs, 347 games, 314 CDs, 110 cinema films, 42 concerts, videos & news /* antibodies, steve hillage, burning crusade, sega psp, norah jones, kylie New music charts - http://dvdfever.co.uk/music.shtml Youtube - http://www.youtube.com/profile?user=DVDfeverDom From paddy3118 at googlemail.com Tue Apr 17 00:37:31 2007 From: paddy3118 at googlemail.com (Paddy) Date: 16 Apr 2007 21:37:31 -0700 Subject: multirember&co In-Reply-To: <1176768854.720234.23320@w1g2000hsg.googlegroups.com> References: <1176768854.720234.23320@w1g2000hsg.googlegroups.com> Message-ID: <1176784651.003653.168630@y5g2000hsa.googlegroups.com> On Apr 17, 1:14 am, bearophileH... at lycos.com wrote: > Once in while I too have something to ask. This is a little problem > that comes from a Scheme Book (I have left this thread because this > post contains too much Python code for a Scheme newsgroup):http://groups.google.com/group/comp.lang.scheme/browse_thread/thread/... > > The function multiremberandco is hard (for me still) if done in that > little Scheme subset, but it's very easy with Python. It collects two > lists from a given one, at the end it applies the generic given fun > function to the two collected lists and returns its result: > > def multiremberandco1(el, seq, fun): > l1, l2 = [], [] > for x in seq: > if x == el: > l2.append(el) > else: > l1.append(el) > return fun(l1, l2) > Hi bearophile, Couldn't you also use count rather than the explicit loop to get something like: def multiremberandco1(el, seq, fun): l1, l2 = [], [] c = seq.count(e1) l1 = [el] * c l2 = [el] * (len(seq) - c) return fun(l1, l2) I don't have the book so can't comment on its suitability, but there you go. - Paddy. From soyouthinkimgonnalikethis at hotmail.com Sat Apr 7 17:36:15 2007 From: soyouthinkimgonnalikethis at hotmail.com (Eric Price) Date: Sat, 07 Apr 2007 16:36:15 -0500 Subject: Can't Get Email Interface Working In-Reply-To: Message-ID: >From: Dennis Lee Bieber >To: python-list at python.org >Subject: Re: Can't Get Email Interface Working >Date: Sat, 07 Apr 2007 20:07:53 GMT > >On Sat, 07 Apr 2007 13:42:38 -0500, "Eric Price" > declaimed the following in >comp.lang.python: > > > > Complain to the providers of the server? Or find out what the host > > >name is for the outgoing SMTPd connection, and use it directly. > > > > Complaining isn't going to help. How do I determine the outgoing smtpd > > connection and how do I use it directly? > > You're going to have to go to the people who administer that machine >one way or another... If gethostname() is returning an invalid name, >there is a system misconfiguration either on that host, or in some DNS >system used by that host. Okay, can you tell me what I need to tell them? If I simply say that python's gethostname() isn't returning the correct value, they'll just tell me they don't service python...and it's my problem :) > > Furthermore, on second review of your original post, it is not the >attempt to access SMTPd that is failing (you didn't even get to trying >to connect to an SMTPd on "localhost") -- it is the MIME package trying >to generate a unique boundary string to be used in separating the >alternate parts of your message. I know. > > Do you really NEED to send it in both "plain text" and "html" >formats? If you can get by with just plain text, you could drop the >whole MIME portion. No. I also tried the little script that's in Guido's explanation of smtplib and got the same error for now-obvious reasons. I'll revert to that most probably. TIA, Eric _________________________________________________________________ Exercise your brain! Try Flexicon. http://games.msn.com/en/flexicon/default.htm?icid=flexicon_hmemailtaglineapril07 From silovana.vjeverica at com.gmail Wed Apr 11 15:20:26 2007 From: silovana.vjeverica at com.gmail (Boris Ozegovic) Date: Wed, 11 Apr 2007 21:20:26 +0200 Subject: Python data visualization Message-ID: Hi I don't know if someone is familiar with Java JUNG, framework for data visualization (http://jung.sourceforge.net/), I am interested is there anything lik JUNG for Python? -- Greatest shits: http://www.net.hr/vijesti/page/2007/03/30/0030006.html From jstroud at mbi.ucla.edu Mon Apr 30 07:26:24 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Mon, 30 Apr 2007 04:26:24 -0700 Subject: regexp match string with word1 and not word2 In-Reply-To: <1177920984.247487.54620@c35g2000hsg.googlegroups.com> References: <1177920984.247487.54620@c35g2000hsg.googlegroups.com> Message-ID: Flyzone wrote: > P.S: i can't have more re.search, so [clip] This reminds me of a quote by the Great Researcher Roy Garcia: If it worked the first time, they'd just call it "search". James From lycka at carmen.se Thu Apr 26 08:04:08 2007 From: lycka at carmen.se (Magnus Lycka) Date: Thu, 26 Apr 2007 14:04:08 +0200 Subject: Python not giving free memory back to the os get's me in real problems ... In-Reply-To: <1177510121.882503.145560@n15g2000prd.googlegroups.com> References: <1177510121.882503.145560@n15g2000prd.googlegroups.com> Message-ID: leuchte at gmail.com wrote: > Our (python-)macro uses massively nested loops which are unfortunately > necessary. These loops perform complex calculations in this commercial > tool. To give you a quick overview how long this macros runs: > > The outer loop takes 5-7 hours for one cycle. Each cycle creates one > outputfile. So we would like to perform 3-5 outer cycles en bloc. > Unfortunately one of our computers (768MB RAM) crashes after just ~10% > of the first cycle with the following error message: > > http://img2.freeimagehosting.net/uploads/7157b1dd7e.jpg > > while another computer (1GB RAM) crashes after ~10% of the fourth > loop. While the virtual memory on the 1gb machine was full to the > limit when it crashed the memory usage of the 768mb machine looked > this this: While Python won't return memory to the OS, this is not the same as a memory leak. When your Python program is done using some objects, the memory they needed can be used by other Python objects in the same process. The process size should never grow bigger than the actually needed memory at a point in time. The (not only) Python problem is that the virtual memory of your process will never shrink, once it has attained its maximum size. Since the unused parts of its virtual memory will be paged out to disk, this is probably not big a problem anyway. If you have a long running process that you want to keep slim, it might be worth factoring out the memory intensive parts to separate processes like this in your macros: for x,y,z in outer_loop_sequence: os.system('python the_real_worker.py %s %s %s' % (x,y,z)) This should contain the big memory usage to short-running processes. It should not solve your crash problem though. If your crashes go away if you rig it like this, something was broken, either in your macro, or in the way the application uses Python for macros. You won't spend less memory because you divide the problem to two processes. To actually solve the problem, you need to look closer at your algorithms and data structures. Are you using effective ways of storing data? For instance, I imagine that numarray or whatever those things are called these days are much, much more effective at handling a vector of numerical values than a Python list of e.g. ints. Lists are pretty expensive. Lists of ints are at least twice as big as efficient integer arrays. Are you copying data when you should just share references? Are you hanging on to data longer than you actually need it? I don't see why there would be a big difference if you use Python or e.g. C or C++ to solve this kind of problem. If you use lots of data, you need to understand the data structures and use them effectively. With Python you are get shorter development time and less code to maintain to solve a certain problem. The price for that is typically longer execution time, but disregarding small systems that can't bear the size of the Python runtime, memory should not be a big problem. Python isn't Java. From fuzzyman at gmail.com Wed Apr 4 18:50:08 2007 From: fuzzyman at gmail.com (Fuzzyman) Date: 4 Apr 2007 15:50:08 -0700 Subject: Why NOT only one class per file? In-Reply-To: <1175726335.866564.4730@p77g2000hsh.googlegroups.com> References: <1175721799.714907.52770@o5g2000hsb.googlegroups.com> <1175726335.866564.4730@p77g2000hsh.googlegroups.com> Message-ID: <1175727008.437795.121050@y66g2000hsf.googlegroups.com> On Apr 4, 11:38 pm, "Klaas" wrote: > On Apr 4, 2:52 pm, Thomas Kr?ger wrote: > > > > > At first: if he really like it he can place every class in a single > > file. But there are some reasons why Python "allows" you to place many > > classes in one file: > > > - It's (a little bit) faster, no additional file system lookup is needed. ;) > > - You can define a class in a class. Django, for example, uses this for > > it's data models. If you do this you are forced to have multiple classes > > in on file. Example:http://www.djangoproject.com/documentation/tutorial02/#make-the-poll-... > > That is somewhat specious: inner classes can be defined in java too. > > The main reason is that in java, classes are magical entities which > correspond to one "exportable" unit of code. Thus it makes a great > deal of sense to limit to one _public_ class per file (java also > allows unlimited private and package-private classes defined in a > single file). > > If you want to define a bunch of utility functions in java, you write > a file containing a single class with static methods. > > In python, classes do not have special status. The exportable unit of > code is a module, which, like public classes in java, can contain > functions, static variables, and classes. Similar to java, you are > limited to a single module object per file (modulo extreme trickery). > > If you want to define a bunch of utility functions in python, you > write a file containing a single module with functions. > So Python has one less level of enforced nesting. :-) Fuzzyman http://www.voidspace.org.uk/python/articles.shtml > -Mike From yura+spam at vpcit.ru Wed Apr 25 11:40:56 2007 From: yura+spam at vpcit.ru (=?windows-1252?Q?=3F=3F=3F=3F_=3F=3F=3F?=) Date: Wed, 25 Apr 2007 21:40:56 +0600 Subject: Another Python Game Programming Challenge concludes Message-ID: <462F7688.2020300@vpcit.ru> The fourth Python Game Programming Challenge (PyWeek) has now concluded with judges (PyWeek being peer-judged) declaring the winners: Individual: Which way is up? by Hectigo http://www.pyweek.org/e/Hectic/ Team: Bubble Kong by The Olde Battleaxe http://www.pyweek.org/e/toba4/ Congratulations to them and to the other entrants. You may view the complete listing of entries here: http://www.pyweek.org/4/entries/ and the scores here: http://media.pyweek.org/static/pyweek4_ratings.html and everything else about PyWeek is here: http://www.pyweek.org/ Before anyone asks, the next challenge will be in 6 months. There is no a date set. Richard Jones (the PyWeek guy ;) -- http://mail.python.org/mailman/listinfo/python-announce-list Support the Python Software Foundation: http://www.python.org/psf/donations.html !DSPAM:462b8a38103129399229859! From steve at holdenweb.com Fri Apr 13 08:44:24 2007 From: steve at holdenweb.com (Steve Holden) Date: Fri, 13 Apr 2007 08:44:24 -0400 Subject: Function arguments [was: help] In-Reply-To: References: Message-ID: pierre-yves guido wrote: > hello (I hope my english is not so bad), > Your English is quite good. In future, though, please try to make your subject line say a bit more about the problem - we *all* need help! > I'm doing a training course and I'm a newbie in Python. My problem : > I have a form, and when I click, I make an update. But all the parameters > are all required to make the update. So I'd like to put in my code something > like [optional]... > > My code (simplyfied) : > > prg.ev_ind_update(wf_pk_ev_ind=wf_pk_ev_ind,wf_fonction=wf_fonction,wf_nom=wf_nom) > > and so, when I put nothing in wf_nom, it put me that error :"the parameter > wf_nom...was omitted from the request...". But sometimes, wf_nom is not > required ! > > Thanks to help a poor young boy > When you define a function or a method (using the def statement) you can specify default values for arguments. A simple example: >>> def fun(a, b=3): ... return a*b ... >>> fun(3) 9 >>> fun(7) 21 >>> fun(7, 4) 28 >>> fun(a=7) 21 >>> fun(a=3, b=12) 36 >>> fun(b=99) Traceback (most recent call last): File "", line 1, in TypeError: fun() takes at least 1 non-keyword argument (0 given) >>> You can see several things here: 1. When you call a function you do not *have* to give thte names of the arguments - they can be matched by position. 2. When you define a function you can specify a default value for one or more arguments (these argument have to appear *after* the ones for which no default is defined) 3. If you don't provide a value for an argument that has no default then you will receive an exception, which normally results in a traceback. Hope this helps. Welcome to Python, and its friendly community. 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 spamtrap at dot-app.org Thu Apr 5 06:50:46 2007 From: spamtrap at dot-app.org (Sherm Pendley) Date: Thu, 05 Apr 2007 06:50:46 -0400 Subject: Why NOT only one class per file? References: <1175721799.714907.52770@o5g2000hsb.googlegroups.com> Message-ID: Steven Howe writes: > On class per file was easier to do when Java was developed (remember > it was develop to control vending machines Not quite. Java grew out of a set-top box at Sun, code-named "Oak". >; scary. Reminds me of the movie 'Tron' Vending machines in "Tron" were pussycats compared to the one in "Maximum Overdrive." :-) sherm-- -- Web Hosting by West Virginians, for West Virginians: http://wv-www.net Cocoa programming in Perl: http://camelbones.sourceforge.net From steve at REMOVEME.cybersource.com.au Mon Apr 2 22:15:46 2007 From: steve at REMOVEME.cybersource.com.au (Steven D'Aprano) Date: Tue, 03 Apr 2007 12:15:46 +1000 Subject: How can i compare a string which is non null and empty References: Message-ID: On Mon, 02 Apr 2007 13:48:30 -0700, Steven Howe wrote: > how about just testing it's length? > >>> from types import StringType > > def stringTest(x): > ... if type(x) == StringType: > ... if len(x) == 0: > ... print 'Empty String' > ... else: > ... print 'Not Empty String' > ... else: > ... print 'value not String Type' Too complicated. You don't need to import StringType, nor do you need to explicitly ask for the length. Worse, you reject anything that isn't *precisely* a string. Other string classes, like Unicode and subclasses, are wrongly rejected. Try this instead: def stringTest(x): if isinstance(x, basestr): if x: print "Not an empty string." else: print "An empty string." else: print "Not a string." Here's an even shorter version, saving one line. def stringTest(x): if not isinstance(x, basestring): print "Not a string." elif x: print "Not an empty string." else: print "An empty string." And here's an even shorter version. def stringTest(x): if not isinstance(x, basestring): print "Not a string." else: print {True: "Not a", False: "A"}[bool(x)] + "n empty string." Notice, though, that shorter code is not always better. -- Steven D'Aprano From aleax at mac.com Sun Apr 29 21:50:24 2007 From: aleax at mac.com (Alex Martelli) Date: Sun, 29 Apr 2007 18:50:24 -0700 Subject: While we're talking about annoyances References: <1177837565.317999.244420@c35g2000hsg.googlegroups.com> <1177857049.938363.166170@p77g2000hsh.googlegroups.com> Message-ID: <1hxchgp.7sw7efb72rh2N%aleax@mac.com> Arnaud Delobelle wrote: ... > > >> decorated.sort() ... > > def index(sequence): > > return sorted(range(len(sequence)), key=sequence.__getitem__) ... > But really these two versions of rank are slower than the original one > (as sorting a list is O(nlogn) whereas filling a table with > precomputed values is O(n) ). Wrong, because the original one also had a sort step, of course, so it was also, inevitably, O(N log N) -- I've quoted the .sort step above. > Anyway I would like to contribute my own index function: > > def index(seq): > return sum(sorted(map(list,enumerate(seq)), key=list.pop), []) > > It's short and has the advantage of being self-documenting, which will > save Steven a lot of annoying typing I hope ;) Who said Python > couldn't rival with perl? sum is for summing NUMBERS -- using it on lists is O(N squared). So, this solution is asymptotically VERY slow, as well as obfuscated. Alex From cam.ac.uk at mh391.invalid Fri Apr 13 08:24:31 2007 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Fri, 13 Apr 2007 13:24:31 +0100 Subject: Problem with algorithm In-Reply-To: <1176452247.231807.65060@e65g2000hsc.googlegroups.com> References: <1176434160.047703.214600@q75g2000hsh.googlegroups.com> <1176434937.258002.162220@p77g2000hsh.googlegroups.com> <1176448576.047996.12930@d57g2000hsg.googlegroups.com> <1176452247.231807.65060@e65g2000hsc.googlegroups.com> Message-ID: azrael wrote: > I think that this would be very silly to do. bad kung foo. The > recoursion technique would be more satisfying. You sholud consider > that this would take about 4 lines to write. Also be avare of the > default recoursion depth in python wich is 1000. you can get and set > the recoursion limit hrough importing the "sys" module and using > getrecoursionlimit() and setrecoursionlimit(). Well, you'd have to spell sys.getrecursionlimit() correctly, but yes ;) At least in the past, raising the recursion limit past a certain point would result in the CPython interpreter crashing, so it's not completely scalable. -- Michael Hoffman From michael at jedimindworks.com Thu Apr 12 04:39:02 2007 From: michael at jedimindworks.com (Michael Bentley) Date: Thu, 12 Apr 2007 03:39:02 -0500 Subject: reading from sys.stdin In-Reply-To: <1176366058.261031.111870@p77g2000hsh.googlegroups.com> References: <1176366058.261031.111870@p77g2000hsh.googlegroups.com> Message-ID: On Apr 12, 2007, at 3:20 AM, 7stud wrote: > I can't break out of the for loop in this example: > > ------ > import sys > > lst = [] > for line in sys.stdin: > lst.append(line) > break > > print lst > ----------- > > But, I can break out of the for loop when I do this: > > --------- > import sys > > lst = [] > for line in open("aaa.txt"): > lst.append(line) > break > > print lst > ---------- > > Why doesn't break work in the first example? My guess is because you've not entered an EOF. Try entering ^D (or if you're on Windows I think it's ^Z) while using your first example and see what it does. From martin at v.loewis.de Fri Apr 27 01:26:55 2007 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Fri, 27 Apr 2007 07:26:55 +0200 Subject: Command-line option equiv of PYTHONPATH In-Reply-To: <1177648804.947472.112830@s33g2000prh.googlegroups.com> References: <1177648804.947472.112830@s33g2000prh.googlegroups.com> Message-ID: <4631899F.9080001@v.loewis.de> > The '-I' option adds the path to the list of directories that > contains modules that can be included in a script. I can use it as "#!/ > usr/bin/perl -I" thereby not asking the user of > the script to set the in their environment. > > Is there any equivalent command-line option to the python binary or a > command-line version of PYTHONPATH? To rephrase James Stroud's remark: The equivalent to #/usr/bin/perl -I TEXT is #/usr/bin/python import sys sys.path.append(path_to_my_modules) TEXT HTH, Martin From tgrav at mac.com Fri Apr 20 15:55:45 2007 From: tgrav at mac.com (Tommy Grav) Date: Fri, 20 Apr 2007 15:55:45 -0400 Subject: Newbie question regarding string.split() In-Reply-To: <1177096533.564349.285930@q75g2000hsh.googlegroups.com> References: <1177095062.826018.63590@n59g2000hsh.googlegroups.com> <1177096533.564349.285930@q75g2000hsh.googlegroups.com> Message-ID: <9C4465B8-6A24-4624-9593-DE18714E356E@mac.com> On Apr 20, 2007, at 3:15 PM, kyosohma at gmail.com wrote: > On Apr 20, 1:51 pm, kevinliu23 wrote: >> ['', 'b34bx5b', 'c4a5a6'] >> >> My question is, why is the first element of projectOptions an empty >> string? What can I do so that the first element is not an empty >> string? but the 'b34bx5b' string as I expected? >> >> Thanks so much guys. :) > > The reason you have an empty string at the beginning is because you > are "splitting" on a character that happens to include the first > character in your string. So what you are telling Python to do is to > split the beginning from itself, or to insert a blank so that it is > split. So why does this not happen when you use the empty split() function? [tgrav at Thrym] /Users/tgrav --> python Python 2.4.4 (#1, Oct 18 2006, 10:34:39) [GCC 4.0.1 (Apple Computer, Inc. build 5341)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> a = " 456 556 556" >>> a.split() ['456', '556', '556'] >>> a.split(" ") ['', '456', '556', '556'] >>> What exactly does .split() use to do the splitting? Cheers Tommy From gagsl-py2 at yahoo.com.ar Wed Apr 4 21:04:15 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 04 Apr 2007 22:04:15 -0300 Subject: How to open a txt file from the same folder as my module (w/out changing the working dir) References: Message-ID: En Wed, 04 Apr 2007 20:14:37 -0300, Larry Bates escribi?: > Sergio Correia wrote: >> I have a program in 'C:\Python25\Lib\site-packages\spam\spam.py' >> >> Importing and everything works fine: >>>>> from spam import spam >> >> But the program calls a file located on the same folder (that is: >> C:\Python25\Lib\site-packages\spam\). >> >> How do i do that? > > The problem is that C:\Python25\Lib\site-packages\spam is not > the current working directory when you run the program. If it were, > and if configuration.txt is in that directory it WILL find it. If > you are running this from a shortcut make the working directory > C:\Python25\Lib\site-packages\spam If changing the working directory is not possible/convenient, use the module __file__ attribute (spam.__file__) to obtain the directory where spam.py resides. -- Gabriel Genellina From Marko.Cain.23 at gmail.com Fri Apr 20 10:55:35 2007 From: Marko.Cain.23 at gmail.com (Marko.Cain.23 at gmail.com) Date: 20 Apr 2007 07:55:35 -0700 Subject: HTTP getreply() never returns In-Reply-To: References: <1177009226.847229.34210@n76g2000hsh.googlegroups.com> <1177022299.791968.154520@b75g2000hsg.googlegroups.com> Message-ID: <1177080935.589366.204740@o5g2000hsb.googlegroups.com> On Apr 20, 12:06 am, Steve Holden wrote: > Marko.Cain... at gmail.com wrote: > > On Apr 19, 2:39 pm, Steve Holden wrote: > >> Marko.Cain... at gmail.com wrote: > >>> Hi, > >>> I have the following code which send/receive HTTP request/response: > >>> # where sampleUrl is '127.0.0.1' and > >>> # url is 'www.cnn.com' > >>> h = httplib.HTTP(self.sampleUrl, 8080) > >>> h.putrequest('GET', '/sample?url=' + self.url) > >>> h.endheaders() > >>> errcode, errmsg, headers = h.getreply() > >>> But it never returns from h.getreply(). > >>> I am using python 2.3.4. Can you please tell me what am I missing? > >>> I am sure the url is correctly. I try putting this 'http:// > >>> 127.0.0.1:8080/sample?url=www.cnn.com'andit works. > >>> Thank you for any help. > >[...] > > >> For what it's worth you *do* appear to have formed the calls correctly, > >> so something a little more complex is going on here. > > >> You might consider using WireShark (nee Ethereal) to look at the data > >> passing across the wire when you use the browser and when you use > >> httplib then comparing the data. That won't work on Windows because it > >> disobligingly refuses to let you tap into the loopback (127) network. > > >> regards > >> Steve > > > Thanks. I run the same script hits the same server (a tomcat server): > > One is on Fedora 5 with python 2.4, this works. > > But one is on Red Hat 4 with python 2.3, this one does not work. > > > Can you please tell me how can I make the script works on RHEL 4 > > without upgrading it to python 2.3? > > I can't see anything in > > http://svn.python.org/view/python/trunk/Lib/httplib.py?rev=54581&view... > > that screams it might have fixed a problem. But I'd be tempted to try > and "borrow" a copy of 2.4's httplib, run your program with that in a > directory where it will be found before the standard library 2.3 module > and see if it fixes the problem. > > If so, would it be a usable workaround just to use the 2.4 httplib for > that one program? > Thanks. Can you please tell me how can I 'borrow' a copy of 2.4 httplib and run that in 2.3? > 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 claird at lairds.us Fri Apr 6 10:48:42 2007 From: claird at lairds.us (Cameron Laird) Date: Fri, 6 Apr 2007 14:48:42 +0000 Subject: SNMP agent References: <1175680387.575097.4590@e65g2000hsc.googlegroups.com> <1175686451.614022.171650@b75g2000hsg.googlegroups.com> <2vlfe4-6n.ln1@lairds.us> <1175837468.058463.154230@p77g2000hsh.googlegroups.com> Message-ID: In article <1175837468.058463.154230 at p77g2000hsh.googlegroups.com>, alain wrote: . . . >I still find it strange that, in all these years of existence, no one >felt the need for a SNMP agent in Python. > >Do Pythoneers only write test tools and not real apps? . . . No, but I understand the question. Python has had considerable success with test tools, by the way. On the other hand, SNMP has become such a minor niche that its technologic implementations depend heavily on historical accident. The right combination of expertise-resources-need-... simply hasn't occurred for Python- based SNMP. I'll repeat: Tcl is the basis of Scotty, which, while largely unsupported now, remains quite usable. Perl is in a somewhat more primitive condition. I don't know of any other high-level language which can effectively boast of the ability to write SNMP agents. From aleax at mac.com Wed Apr 4 22:43:28 2007 From: aleax at mac.com (Alex Martelli) Date: Wed, 4 Apr 2007 19:43:28 -0700 Subject: how to remove multiple occurrences of a string within a list? References: <1175624433.206953.214290@n59g2000hsh.googlegroups.com> Message-ID: <1hw28y7.1t2kviz1x7guagN%aleax@mac.com> Amit Khemka wrote: > On 3 Apr 2007 11:20:33 -0700, bahoo wrote: > > Hi, > > > > I have a list like ['0024', 'haha', '0024'] > > and as output I want ['haha'] > > > > If I > > myList.remove('0024') > > > > then only the first instance of '0024' is removed. > > To remove all items with multiple occurances in myList: > > list(set(myList) - set([x for x in myList if myList.count(x)>1])) This approach is unfortunately quite inefficient, because each call to myList.count is O(N), and there are O(N) such calls, so the whole thing is O(N squared). [also, the inner square brackets are not needed, and cause more memory to be consumed than omitting them would]. A "we-don't-need-no-stinkin'-one-liners" more relaxed approach: import collections d = collections.defaultdict(int) for x in myList: d[x] += 1 list(x for x in myList if d[x]==1) yields O(N) performance (give that dict-indexing is about O(1)...). Collapsing this kind of approach back into a "one-liner" while keeping the O(N) performance is not easy -- whether this is a fortunate or unfortunate ocurrence is of course debatable. If we had a "turn sequence into bag" function somewhere (and it might be worth having it for other reasons): def bagit(seq): import collections d = collections.defaultdict(int) for x in seq: d[x] += 1 return d then one-linerness might be achieved in the "gimme nonduplicated items" task via a dirty, rotten trick...: list(x for bag in [bagit(myList)] for x in myList if bag[x] == 1) ...which I would of course never mention in polite company... Alex From theo at van-werkhoven.nl.invalid Sat Apr 28 15:04:40 2007 From: theo at van-werkhoven.nl.invalid (Theo v. Werkhoven) Date: Sat, 28 Apr 2007 21:04:40 +0200 Subject: Program runs in all directories, except one.. References: <1177766565.118899.232620@e65g2000hsc.googlegroups.com> Message-ID: The carbonbased lifeform John Machin inspired comp.lang.python with: > On Apr 28, 9:50 pm, "Theo v. Werkhoven" werkhoven.nl.invalid> wrote: >> Goodday, >> >> strg = array("B",octarray).tostring() > > The above statement appears to be where the error manifests itself. > Possibilities: (1) array is bound to a list (2) the result of > array("B", octarray) has an attribute tostring which is bound to a > list. Option (1) seems less implausible. I'd be replacing that line > by: > > print "octet %r, shift %r, array %r" % (octet, shift, array) > array_b = array("B", octarray) > print "array_b %r" % array_b > print "array_b.tostring %r" % array_b.tostring > strg = array_b.tostring() > > You haven't shown us all of your code -- is array mentioned elsewhere? > What other imports are you doing? Do you have a file called array.py > in the offending directory? [I believe that this wouldn't matter, > because builtin modules like array can't be overridden by a file-based > module of the same name, but I could be wrong] Bingo! #v+ theo:/home/theo/Devel/Python $ ls array* array.py array.pyc theo:/home/theo/Devel/Python $ cat array.py #!/usr/bin/python import sys, os array = [14, 8765, 756, 5345, 98, 5634654, 234123, 9087, 58, 297, 7865] num = 0 while 1: try: print num num = num + array.pop() except: break #v- And that code produces the numbers I was seeing.. > What platform and what version of Python? $ python --version Python 2.5 $ uname -srv Linux 2.6.18.8-0.1-default #1 SMP Fri Mar 2 13:51:59 UTC 2007 $ uname -mip i686 athlon i386 > HTH, > John Thank you very much John. Nice catch. Theo -- theo at van-werkhoven.nl ICQ:277217131 SuSE Linux linuxcounter.org: 99872 Jabber:muadib at jabber.xs4all.nl AMD XP3000+ 1024MB "ik _heb_ niets tegen Microsoft, ik heb iets tegen de uitwassen *van* Microsoft" From slm_guzel at hotmail.com Tue Apr 10 15:43:59 2007 From: slm_guzel at hotmail.com (gslm) Date: 10 Apr 2007 12:43:59 -0700 Subject: Please help!!! Message-ID: <1176234239.436463.195870@n33g2000cwc.googlegroups.com> Hi to all! I want to do a calendar with pictures near months. I have designed the form's view.But unfortunately, I am not be able to save this view as an image file.And so I am not be able to print this image file too. Question: How can I determine the coordinates of a button?Namely How can I use the comand ImageGrab for this purpose? But only I wan to get the button's ares.Because my applicationis on this. Or if it's possible, how can I print the area of this button with the components on it? Thanks... From cam.ac.uk at mh391.invalid Mon Apr 30 06:15:33 2007 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Mon, 30 Apr 2007 11:15:33 +0100 Subject: How do I parse a string to a tuple?? In-Reply-To: References: <1177926452.830059.269230@n59g2000hsh.googlegroups.com> Message-ID: Steven D'Aprano wrote: > On Mon, 30 Apr 2007 02:47:32 -0700, Soren wrote: >> "text1 \n text2 \n text3 \n text4" --> (text1, text2, text3, text4) > > the_string = "text1 \n text2 \n text3 \n text4" > tuple(the_string.split('\n')) > > If you don't need a tuple, and a list will do: > > the_string.split('\n') or the_string.splitlines() > If you want to get rid of the white space after each chunk of text: > > [s.strip() for s in the_string.split('\n')] -- Michael Hoffman From khemkaamit at gmail.com Thu Apr 5 08:35:37 2007 From: khemkaamit at gmail.com (Amit Khemka) Date: Thu, 5 Apr 2007 18:05:37 +0530 Subject: Storing of folder structure in SQL DB In-Reply-To: <1360b7230704050522h6dd82fedseef04ccd43c68adc@mail.gmail.com> References: <1175774302.652656.285260@d57g2000hsg.googlegroups.com> <1360b7230704050522h6dd82fedseef04ccd43c68adc@mail.gmail.com> Message-ID: <1360b7230704050535m551566b7g35a786dfb2fc0da2@mail.gmail.com> On 4/5/07, Amit Khemka wrote: > On 5 Apr 2007 04:58:22 -0700, Sergei Minayev wrote: > An Example: > > import os > root='/my/root/directory' > id =0 > tree={root:(-1, id)} > id+=1 > for path, dirs, files in os.walk(root): > for dir in dirs: > if not tree.has_key(path+'/'+dir): > tree[path+'/'+dir]=(tree[path][1], id) > id+=1 > > It stores ids as a tuple (parent_id, id) in a dictionary(tree). Should > be straight forward to modify to your requirements. Also you can make > the following code more efficient by saving/caching some lookups ! use os.sep instead of '/' ! 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 aleax at mac.com Mon Apr 9 01:19:03 2007 From: aleax at mac.com (Alex Martelli) Date: Sun, 8 Apr 2007 22:19:03 -0700 Subject: shelve error References: <1175746456.995618.186190@e65g2000hsc.googlegroups.com> <1175746966.023613.178830@n76g2000hsh.googlegroups.com> <1175756092.643182.142420@n76g2000hsh.googlegroups.com> <1hw9lxy.ldrc541w507xyN%aleax@mac.com> <1176095310.492686.78880@p77g2000hsh.googlegroups.com> Message-ID: <1hw9v5g.15x8fok1c626v2N%aleax@mac.com> 7stud wrote: ... > In my opinion, the most valuable thing you could do for a next > printing would be to expand the index to 3 times its current length. Suggest that to O'Reilly: they're the one who prepare the index, not me; I only get to point out errors I may notice on it during the roughly 4-5 days I get to review it in the late phases of production. I don't believe any major change in the index can be contemplated between one printing and another, but your complaint, if directed to the appropriate ears, might possibly infuence some future edition. > Also, the book is brand new, yet the cover has completely separated > from the spine of the book, and now the cover is only attached to the > first and last pages with a bit of glue. Similarly, I have no control on any aspect of the physical production of the book: again, telling me about your complaints is absolutely useless, if you want any chance to have an effect, tell O'Reilly. Alex From hq4ever at gmail.com Tue Apr 3 18:57:20 2007 From: hq4ever at gmail.com (Maxim Veksler) Date: Wed, 4 Apr 2007 00:57:20 +0200 Subject: low level networking in python In-Reply-To: <1175615037.137052.70980@w1g2000hsg.googlegroups.com> References: <1175615037.137052.70980@w1g2000hsg.googlegroups.com> Message-ID: On 3 Apr 2007 08:43:57 -0700, kyosohma at gmail.com wrote: > On Apr 3, 10:29 am, "Maxim Veksler" wrote: > > Hello, > > > > I wish to do some low level network stuff using python. > > > > -- > > Cheers, > > Maxim Veksler > > > > "Free as in Freedom" - Do u GNU ? > > I would assume you could use the socket module. This post details > someone else who opened ports with Python: > > http://www.thescripts.com/forum/thread44280.html > > Here's another resource using some python servers: > > http://docs.python.org/lib/socket-example.html > > Finally, a Socket programming howto: > http://www.amk.ca/python/howto/sockets/ > > I'm also told that the Twisted framework is excellent for this sort of > thing. > Thanks for the heads-up. The sockets howto was great help. I'm trying to bind a non-blocking socket, here is my code: """ #!/usr/bin/env python import socket, select from time import sleep s_nb10000 = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s_nb10000.setblocking(0) s_nb10000.bind(('192.168.2.106', 10002)) s_nb10000.listen(5) while 1: conn, addr = s_nb10000.accept() ready_to_read, ready_to_write, in_error = select.select([conn], [], [], 0) print (ready_to_read, ready_to_write, in_error) sleep(100) s_nb10000.close() """ And this is the exception I'm getting: """ python non_blocking_socket.py Traceback (most recent call last): File "non_blocking_socket.py", line 13, in ? conn, addr = s_nb10000.accept() File "/usr/lib/python2.4/socket.py", line 161, in accept sock, addr = self._sock.accept() socket.error: (11, 'Resource temporarily unavailable') """ What am I doing wrong here? p.s. I've looked at twisted before posting this post. I've seen they impelement alot of application level protocols but I didn't see much treatment for low level "raw" network data, not to mention that it's a way way over kill for what I'm asking to achieve. Twisted does have a subproject called "Twisted Pair: Low-level networking" but sadly it's unmaintained and undocumented. > Mike > Maxim. -- Cheers, Maxim Veksler "Free as in Freedom" - Do u GNU ? From danfan1981 at yahoo.com Sat Apr 21 17:02:12 2007 From: danfan1981 at yahoo.com (danfan1981 at yahoo.com) Date: 21 Apr 2007 14:02:12 -0700 Subject: No speedup on multi-processor machine? Message-ID: <1177189332.916296.205280@d57g2000hsg.googlegroups.com> Hi, I am using Python Thread library for my parallel processing course project. I am doing matrix convolution on a multi-processor machine running Solaris. I just found out that no speed-up is obtained with threading. It is probably because of something called GIL in Python. How can I get around that GIL and get speed-up? Thanks in advance. Daniel From http Sun Apr 8 10:51:36 2007 From: http (Paul Rubin) Date: 08 Apr 2007 07:51:36 -0700 Subject: tuples, index method, Python's design References: <1175867771.114540.61810@n76g2000hsh.googlegroups.com> <1175884427.779950.267220@y80g2000hsf.googlegroups.com> <1175953520.316208.241490@o5g2000hsb.googlegroups.com> Message-ID: <7xzm5igbrb.fsf@ruckus.brouhaha.com> Carsten Haese writes: > > Maybe we can add such methods to the PyPy tuples for some time, to > > experimentally see if they make the language worse :-) > > Adding useless features always makes a product worse. What's your use > case for tuple.index? Do you not see the gratuituous inconsistency between tuples and lists as a useless feature? What is the use case for keeping it? From nagle at animats.com Thu Apr 19 18:14:53 2007 From: nagle at animats.com (John Nagle) Date: Thu, 19 Apr 2007 22:14:53 GMT Subject: Python un-plugging the Interpreter In-Reply-To: References: <005f01c782a3$ae84d710$fa936540@cisco.com> Message-ID: DillonCo wrote: > On Thursday 19 April 2007, S.Mohideen wrote: > >> 2) Making the program to run at par with the compiled version of C/C++ >>program- this is the main benefit which can be derived out of this. > > > Python is a rather slow language because of how it works. Even if you got rid > of the VM (as noted by others, Python compiles into VM code), Python would > still be slower than C, and probably by a large margin. > > Look at the "+" operator for instance. In C, this translates directly to an > add instruction that takes something like 1 cycle. Very fast. In python, it > translates (very) roughly to: ... Most of the time, though, all that flexibility isn't being used. The idea of the type inference system compilers like Shed Skin is to figure out when it's one of the simple cases. Many cases are easy. If a smart compiler sees for i in range(n) : ... # something and there are no other assignments to "i", then it's clear that "i" can be represented as an integer, without "boxing" into a general object. That's a big win. There are many other similar optimizations. For example, if a Python object is always referenced using the "obj.attr" form, and never with "obj[str]" or "getattr" or "setattr", you can represent it with fixed slots assigned at compile time, and dispense with the hash mechanism for attribute lookup. The generality should be there if it's needed, but when it's not, the excess baggage should be removed. That's how you get the performance of the language up. This doesn't require type declarations. There are arguments over whether type declarations would help optimization. They might make it easier, but they're not fundamentally necessary. John Nagle From Karsten.G.Weinert at googlemail.com Mon Apr 30 10:31:30 2007 From: Karsten.G.Weinert at googlemail.com (Karsten.G.Weinert at googlemail.com) Date: 30 Apr 2007 07:31:30 -0700 Subject: Cgi File Upload without Form In-Reply-To: References: <1177708242.553577.226530@n15g2000prd.googlegroups.com> Message-ID: <1177943490.669714.176360@y5g2000hsa.googlegroups.com> On 30 Apr., 15:51, "Dave Borne" wrote: > > Since I want to upload the data programmatically, a form based > > solution is not good. > > Karsten, > Could you explain this statement? When I want to move data to a > server in a CGI environment, a form post is the easiest way I can > think of. What are the specific restrictions making forms a problem? > > -Dave Hello Dave, what I was thinking was: a form post is meant to be used manually. But maybe I am wrong here and I can teach my VBA program to fill in forms automatically. If I were using python as client, I could fill in forms with urllib. However, I using python only server-side. Kind regards, Karsten. From g.brandl at gmx.net Mon Apr 9 03:43:12 2007 From: g.brandl at gmx.net (Georg Brandl) Date: Mon, 09 Apr 2007 09:43:12 +0200 Subject: tuples, index method, Python's design In-Reply-To: <7xwt0mcneq.fsf@ruckus.brouhaha.com> References: <1175867771.114540.61810@n76g2000hsh.googlegroups.com> <1175884427.779950.267220@y80g2000hsf.googlegroups.com> <1175953520.316208.241490@o5g2000hsb.googlegroups.com> <7xzm5igbrb.fsf@ruckus.brouhaha.com> <7x8xd2iq53.fsf@ruckus.brouhaha.com> <7xwt0mcneq.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin schrieb: > Steven D'Aprano writes: >> I think the problem is that Python developers are split between those who >> see tuples as immutable lists, and those who see them as records/structs. > > I think the construction > > def f(*a): ... > > shows that the "immutable list" interpretation is firmly ensconced in > the language. IIRC, for this use case of tuples there was a practical reason rather than an interpretation one. It is also on the list of potential changes for Python 3000. Georg From gigs at hi.t-com.hr Thu Apr 5 17:59:08 2007 From: gigs at hi.t-com.hr (Gigs_) Date: Thu, 05 Apr 2007 23:59:08 +0200 Subject: tkinter canvas mvc Message-ID: Hi all! I have just finished my tkinter text editor, learning tkinter purpose. Now I want to learn canvas so I want to make my paint program, I think that this will be the best to do over model-view-controler pattern which I need to learn also. Is there any good tutorial for mvc in python or can someone explain me little bit about mvc? or maybe some code snippet in mvc, that will be nice. Thanks in advance! From mail at timgolden.me.uk Tue Apr 17 08:15:02 2007 From: mail at timgolden.me.uk (Tim Golden) Date: Tue, 17 Apr 2007 13:15:02 +0100 Subject: Deleting or Empty a File In-Reply-To: <004001c78041$c022e390$4068aab0$@rawlins@thinkbluemedia.co.uk> References: <004001c78041$c022e390$4068aab0$@rawlins@thinkbluemedia.co.uk> Message-ID: <4624BA46.5080503@timgolden.me.uk> Robert Rawlins - Think Blue wrote: > I'm looking to clear those log files we were discussing earlier chaps, > > What the best method to do this? Delete the file completely? Or just empty > its content? Not sure there is a "best method". For simplicity I'd just delete it and let the logger recreate, but there's nothing to stop you from doing: open ("blah.log", "w").close () if you want. TJG From fsckedagain at gmail.com Wed Apr 11 15:28:08 2007 From: fsckedagain at gmail.com (fscked) Date: 11 Apr 2007 12:28:08 -0700 Subject: ValueError: too many values to unpack In-Reply-To: References: <1176311618.617765.120560@p77g2000hsh.googlegroups.com> Message-ID: <1176319688.666986.183980@o5g2000hsb.googlegroups.com> On Apr 11, 10:26 am, Laszlo Nagy wrote: > fscked ?rta:> Trying to use CSV to read in a line with 11 fields and I keep getting > > this error. I have googled a bit and have been unable to figure it out. > > Probably you have more than 11 values in some (or all) of the rows in > the CSV file. Try this code: > > L = (1,2,3,4,5) > a1,a2,a3 = L > > If you are sure that you only need a certain number of values, "the > first N columns": > > a1,a2,a3 = L[:3] > > Then you still can have a "not enough values to unpack" error, guess > what that means. ;-) > > Laszlo Hmm, well I have counted the fields in the CSV and verified there are only 11. Here is the offending code: myfile = open('ClientsXMLUpdate.csv') csvreader = csv.reader(myfile) for boxid, mac, activated, hw_ver, sw_ver, heartbeat, name, address, phone, country, city in csvreader: mainbox = SubElement(root, "{Boxes}box") mainbox.attrib["city"] = city mainbox.attrib["country"] = country mainbox.attrib["phone"] = phone mainbox.attrib["address"] = address mainbox.attrib["name"] = name mainbox.attrib["pl_heartbeat"] = heartbeat mainbox.attrib["sw_ver"] = sw_ver mainbox.attrib["hw_ver"] = hw_ver mainbox.attrib["date_activated"] = activated mainbox.attrib["mac_address"] = mac mainbox.attrib["boxid"] = boxid I just don't get it... :/ From exarkun at divmod.com Mon Apr 16 19:35:55 2007 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Mon, 16 Apr 2007 19:35:55 -0400 Subject: Queue enhancement suggestion In-Reply-To: <7x4pngluel.fsf_-_@ruckus.brouhaha.com> Message-ID: <20070416233555.19381.230869852.divmod.quotient.2292@ohm> On 15 Apr 2007 23:12:34 -0700, Paul Rubin <"http://phr.cx"@nospam.invalid> wrote: >I'd like to suggest adding a new operation > > Queue.finish() > >This puts a special sentinel object on the queue. The sentinel >travels through the queue like any other object, however, when >q.get() encounters the sentinel, it raises StopIteration instead >of returning the sentinel. It does not remove the sentinel from >the queue, so further calls to q.get also raise StopIteration. >That permits writing the typical "worker thread" as > > for item in iter(q.get): ... > >without having to mess with the task-counting stuff that recently got >added to the Queue module. The writing end of the queue simply >calls .finish() when it's done adding items. > >Someone in an earlier thread suggested > > # writing side > sentinel = object() > q.put(sentinel) > > ... > # reading side > for item in iter(q.get, sentinel): ... > >however that actually pops the sentinel, so if there are a lot of >readers then the writing side has to push a separate sentinel for >each reader. I found my code cluttered with > > for i in xrange(number_of_worker_threads): > q.put(sentinel) > >which certainly seems like a code smell to me. Instead of putting multiple sentinels, just pre-construct the iterator object. work = iter(q.get, sentinel) Re-use the same iterator in each thread, and you'll get the behavior you're after. Jean-Paul From boris.smirnov at gmail.com Mon Apr 16 06:07:31 2007 From: boris.smirnov at gmail.com (boriq) Date: 16 Apr 2007 03:07:31 -0700 Subject: Rapyd-Tk Pmw Notebook tutorial Message-ID: <1176718051.347720.200710@p77g2000hsh.googlegroups.com> Hello, could anybody be so kind and write me a small tutorial about "how to create a Pmw notebook with 3 tabs each containing 5 checkboxes" with the help of Rapyd-Tk? Thanks in advance rg, boris From martin at v.loewis.de Sun Apr 1 10:56:19 2007 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sun, 01 Apr 2007 16:56:19 +0200 Subject: tag replacement in toxml() In-Reply-To: References: Message-ID: <460FC813.4040803@v.loewis.de> > import xml.dom.minidom > from xml.dom.minidom import getDOMImplementation > impl = getDOMImplementation() > myDoc = impl.createDocument(None, "example", None) > myRoot = myDoc.documentElement > myNode1 = myDoc.createElement("node") > myNode2 = myDoc.createElement("nodeTwo") > myText = myDoc.createTextNode("Here is the problem") > myNode2.appendChild(myText) > myNode1.appendChild(myNode2) > myRoot.appendChild(myNode1) > print myDoc.toxml() > > The result is: > '\nHere is the <b>problem</>' > > > My question is how I can avoid that toxml() replaces the tags? Gabriel already answered the question: you need to add a 'b' element, which has a text child with the text 'problem'; this b element needs to be a sibling of the text node 'Here is the '. This still won't give you the output "Here is the problem", as that will insert a closing tag. If you really want to produce the text '\nHere is the problem' you cannot use an XML library to do so: this text is not well-formed XML (because is illegal syntax). Regards, Martin From a-alpha at otenet.gr Tue Apr 24 23:36:20 2007 From: a-alpha at otenet.gr (M M) Date: Wed, 25 Apr 2007 06:36:20 +0300 Subject: Angelina Joli Paris Hilton MARISA MILLER Message-ID: Angelina Joli Paris Hilton MARISA MILLER www.alphasearch.gr -------------- next part -------------- An HTML attachment was scrubbed... URL: From gdamjan at gmail.com Tue Apr 10 18:37:05 2007 From: gdamjan at gmail.com (Damjan) Date: Wed, 11 Apr 2007 00:37:05 +0200 Subject: About Trolltech QT OpenSource license. References: <1176233376.712861.67160@o5g2000hsb.googlegroups.com> <1176242640.630110.121120@y5g2000hsa.googlegroups.com> Message-ID: <461c114f$0$90263$14726298@news.sunsite.dk> > @ Kevin and Jarek : > thanks for the enlightening of that GPL thing. So, if i understand, i > create my Python software using Qt as my GUI, i earn the money for it > with the obligation to release my source code and somewhere in my > files i explicilty write that this software is under the GPL lisence, > is that correct ?? And i am legal all the way out ?? This is correct... but you should also understand the GPL license aswell. > So why these people at Trolltech have the word "Commercial" at their > mouth all the time ?? I can understand of course that money is all > about but becauce they released Qt under GPL they simply cannot > prevent anyone from gaining money using it. That is a mistake, the oposite of libre software is non-libre or proprietary. -- damjan From paddy3118 at googlemail.com Mon Apr 16 08:45:48 2007 From: paddy3118 at googlemail.com (Paddy) Date: 16 Apr 2007 05:45:48 -0700 Subject: Python editor/IDE on Linux? In-Reply-To: <1176686273.987650.146430@l77g2000hsb.googlegroups.com> References: <1176575715.649316.130430@n76g2000hsh.googlegroups.com> <1176626030.729710.321520@d57g2000hsg.googlegroups.com> <1176634241.244351.41990@b75g2000hsg.googlegroups.com> <1176686273.987650.146430@l77g2000hsb.googlegroups.com> Message-ID: <1176727548.215586.230510@p77g2000hsh.googlegroups.com> On Apr 16, 2:17 am, "Daniel Gee" wrote: > didn't know that one. Perhaps I'll look into Gvim (I still like to cut > and paste with the mouse, even if I left that off my list). In gvim you can use a mouse-1-drag to select text then mouse-2 at the position you want to copy the text to. - Paddy. From http Tue Apr 17 01:22:47 2007 From: http (Paul Rubin) Date: 16 Apr 2007 22:22:47 -0700 Subject: Queue enhancement suggestion References: <7x4pngluel.fsf_-_@ruckus.brouhaha.com> Message-ID: <7xabx7wp5k.fsf@ruckus.brouhaha.com> Antoon Pardon writes: > The problem is this doesn't work well if you have multiple producers. > One producer can be finished while the other is still putting values > on the queue. Right, you'd wait for all the producers to finish, then finish the queue: for p in producer_threads: p.join() q.finish() > The solution I have been thinking on is the following. > > Add an open and close operation. Only threads that have the queue > open can access it. The open call should specify whether you > want to read or write to the queue or both. When all writers > have closed the queue and the queue is empty a q.get will > raise an exception. This may be done by putting a sentinel > on the queue when the last writer closed the queue. That's an idea, but why would readers need to open the queue? From jstroud at mbi.ucla.edu Fri Apr 6 01:03:16 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Thu, 05 Apr 2007 22:03:16 -0700 Subject: "index" method only for mutable sequences?? In-Reply-To: References: Message-ID: C.L. wrote: > I was looking for a function or method that would return the index to the first > matching element in a list. Coming from a C++ STL background, I thought it might > be called "find". My first stop was the Sequence Types page of the Library > Reference (http://docs.python.org/lib/typesseq.html); it wasn't there. A search > of the Library Reference's index seemed to confirm that the function did not > exist. A little later I realized it might be called "index" instead. Voila. > > My point is that the docs list and describe it as a method that only exists for > MUTABLE sequences. Why only for mutables? The class of objects I would expect it > to cover would be all ordered sequences, or, to phrase it a little more > pointedly, anything that supports ordered INDEXing. My understanding is that > dict's don't fall into that class of objects since their ordering is not > documented or to be depended on. However, tuple's do support ordered indexing, > so why don't tuple's have an index method? > > P.S.: I know I haven't yet gotten an answer to my "why" question yet, but, > assuming it's just an oversight or an example of design without the big picture > in mind, an added benefit to fixing that oversight would be that the "index" > method's documentation could be moved from the currently odd seeming location on > the "Mutable Sequence Types" page to a place someone would look for it logically. > > P.P.S.: As much as the elementary nature of my question would make it seem, this > isn't my first day using Python. I've used it on and off for several years and I > LOVE Python. It is only because of my love for the language that I question its > ways, so please don't be overly defensive when I guess that the cause for this > possible oversight is a lack of design. > > Corey Lubin > > The amount of typing wasted to defend design decisions such as this can boggle one's mind. Just use lists unless you have on overwhelming reason to do otherwise. James From http Tue Apr 17 00:44:08 2007 From: http (Paul Rubin) Date: 16 Apr 2007 21:44:08 -0700 Subject: multirember&co References: <1176768854.720234.23320@w1g2000hsg.googlegroups.com> Message-ID: <7xd523y5if.fsf@ruckus.brouhaha.com> bearophileHUGS at lycos.com writes: > So I have tried to create two iterables for the fun function scanning > seq once only, but I haven't succed so far (to do it I have tried to > use two coroutines with the enhanced generators, sending el to one or > to the other according to the value of x == el, this time I don't show > my failed versions), do you have suggestions? I think there is not any way short of using something like list or tee, if you want both output iterators to be available simultaneously. Say there are 17 occurrences of el in the input iterator. The only way to know this is to scan through the whole iterator. But now all of its elements have to be available again at the output. From steve at holdenweb.com Mon Apr 9 14:35:15 2007 From: steve at holdenweb.com (Steve Holden) Date: Mon, 09 Apr 2007 14:35:15 -0400 Subject: Hosting Companies: Help for Python Users? Message-ID: I know there are quite a few hosting companies now who represent themselves as Python-friendly. Rather than trawl through the Wiki pages, however, and email each one separately I am sending this request to the comp.lang.python list (and putting it on my blog) in the hope of attracting those companies who are more involved with the Python community. There is a particular problem, highlighted recently by this comment from Dennis Lee Beiber: > Too many 3rd-party modules still aren't available in 2.5 > versions for my tastes... This applies particularly (though not exclusively) to the Windows platform, for various reasons -- the most common one is that Linux developers frequently don't have a Windows machine available to help them test their builds and ensure that distributions are available. I am trying to address this problem, initially by making hosted Windows machines available for use as buildbots. I already have agreement from Grig Gheorghiu (who maintains the PSF's buildbots) to try and support these efforts, and from Microsoft to consider providing appropriate software. What I *don't* have is hosting companies offering me space on machines in their racks. If anyone reading this can help out I'd appreciate it if they would get in touch with me (replying to the newsgroup post or commenting on the blog entry should do it). These machines would need remote desktop access so they could be managed without physical presence. The intention is to try and shorten the "version lag" so that new versions of Python can be better supported more quickly. I don't guarantee that this will happen overnight, but I'd like to make 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 subscriber123 at gmail.com Thu Apr 5 14:24:23 2007 From: subscriber123 at gmail.com (Subscriber123) Date: Thu, 5 Apr 2007 14:24:23 -0400 Subject: how to remove multiple occurrences of a string within a list? In-Reply-To: <1175624433.206953.214290@n59g2000hsh.googlegroups.com> References: <1175624433.206953.214290@n59g2000hsh.googlegroups.com> Message-ID: <4c0048df0704051124l6ad692a5w10a963efc2a2e47f@mail.gmail.com> for item in listA: while item in listB: listB.remove(item) where listA is the list of things you want to remove from listB On 3 Apr 2007 11:20:33 -0700, bahoo wrote: > > Hi, > > I have a list like ['0024', 'haha', '0024'] > and as output I want ['haha'] > > If I > myList.remove('0024') > > then only the first instance of '0024' is removed. > > It seems like regular expressions is the rescue, but I couldn't find > the right tool. > > Thanks! > bahoo > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From ptmcg at austin.rr.com Mon Apr 16 08:52:32 2007 From: ptmcg at austin.rr.com (Paul McGuire) Date: 16 Apr 2007 05:52:32 -0700 Subject: pyparsing Catch-22 In-Reply-To: <1176726354.351375.180460@p77g2000hsh.googlegroups.com> References: <1176686782.270354.164630@l77g2000hsb.googlegroups.com> <1176696704.924584.75720@e65g2000hsc.googlegroups.com> <1176711506.989627.282880@o5g2000hsb.googlegroups.com> <1176712052.901344.36610@l77g2000hsb.googlegroups.com> <1176726354.351375.180460@p77g2000hsh.googlegroups.com> Message-ID: <1176727952.905485.218970@o5g2000hsb.googlegroups.com> On Apr 16, 7:25 am, "Paul McGuire" wrote: > > long-windedness snipped Oh, P.S., There is a list parser example included in the pyparsing examples directory, called parsePythonValue.py. It will parse nested lists, dicts, and tuples. -- Paul From timr at probo.com Thu Apr 26 02:30:10 2007 From: timr at probo.com (Tim Roberts) Date: Thu, 26 Apr 2007 06:30:10 GMT Subject: Simple sqlite3 question References: <1177434225.721012.271040@r35g2000prh.googlegroups.com> Message-ID: cjl wrote: > >I am using python 2.5.1 on windows. I have the following code: > >conn = sqlite3.connect('.\optiondata') This is unrelated to your question, but you have a slash problem there. \o doesn't happen to be a valid escape character, but if you had used "testdata" as the filename, it would have failed. You should use one of these alternatives: conn = sqlite3.connect('.\\optiondata') conn = sqlite3.connect(r'.\optiondata') conn = sqlite3.connect('./optiondata') conn = sqlite3.connect('optiondata') -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From srikrishnamohan at gmail.com Thu Apr 26 00:56:43 2007 From: srikrishnamohan at gmail.com (km) Date: Thu, 26 Apr 2007 10:26:43 +0530 Subject: distance map Message-ID: Hi all, Is there any module to make a network diagram given a 2-D matrix of distances ? any hints regards, KM -------------- next part -------------- An HTML attachment was scrubbed... URL: From irmen.NOSPAM at xs4all.nl Wed Apr 4 12:50:46 2007 From: irmen.NOSPAM at xs4all.nl (Irmen de Jong) Date: Wed, 04 Apr 2007 18:50:46 +0200 Subject: low level networking in python In-Reply-To: References: <1175615037.137052.70980@w1g2000hsg.googlegroups.com> Message-ID: <4613d7a2$0$331$e4fe514c@news.xs4all.nl> Maxim Veksler wrote: > I'm trying to bind a non-blocking socket, here is my code: > """ > #!/usr/bin/env python > > import socket, select > from time import sleep > > s_nb10000 = socket.socket(socket.AF_INET, socket.SOCK_STREAM) > s_nb10000.setblocking(0) > > s_nb10000.bind(('192.168.2.106', 10002)) > s_nb10000.listen(5) > > while 1: > conn, addr = s_nb10000.accept() > ready_to_read, ready_to_write, in_error = select.select([conn], [], > [], 0) > print (ready_to_read, ready_to_write, in_error) > sleep(100) > > s_nb10000.close() > """ > > And this is the exception I'm getting: > """ > python non_blocking_socket.py > Traceback (most recent call last): > File "non_blocking_socket.py", line 13, in ? > conn, addr = s_nb10000.accept() > File "/usr/lib/python2.4/socket.py", line 161, in accept > sock, addr = self._sock.accept() > socket.error: (11, 'Resource temporarily unavailable') > """ > > What am I doing wrong here? Nothing. Any operation on a non-blocking socket that is usually blocking (this includes accept(), bind(), connect(), recv with MSG_WAITALL) can possibly return a socket.error with errno set to EAGAIN. ('resource temporarily unavailable'). If this happens you should use a select() on the socket to wait until it's done with the requested operation. --Irmen > > p.s. > I've looked at twisted before posting this post. I've seen they > impelement alot of application level protocols but I didn't see much > treatment for low level "raw" network data, not to mention that it's a > way way over kill for what I'm asking to achieve. Twisted does have a > subproject called "Twisted Pair: Low-level networking" but sadly it's > unmaintained and undocumented. > >> Mike >> > > Maxim. > > From cam.ac.uk at mh391.invalid Wed Apr 25 06:32:59 2007 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Wed, 25 Apr 2007 11:32:59 +0100 Subject: Coding conventions for class names In-Reply-To: <1177492705.232244.312520@c18g2000prb.googlegroups.com> References: <1177492705.232244.312520@c18g2000prb.googlegroups.com> Message-ID: Kay Schluehr wrote: > My question is: does anyone actually follow guidelines here Yes. > and if yes > which ones and are they resonable ( e.g. stable with regard to > refactoring etc. )? All of them that I know of. What does it mean to be "stable with regard to refactoring etc."? -- Michael Hoffman From bressert at gmail.com Fri Apr 6 15:15:32 2007 From: bressert at gmail.com (bressert at gmail.com) Date: 6 Apr 2007 12:15:32 -0700 Subject: SWIG, Python, C++, and Coca-Cola Message-ID: <1175886932.067217.17700@w1g2000hsg.googlegroups.com> Hi Everyone, Recently I have been working on building a module for Python from C++ code, with SWIG, and towards the end of compiling the various sets of code I'm getting an error. [comp:~/swig_project] user% swig -c++ -python example.i [comp:~/swig_project] user% g++ -c example.cpp [comp:~/swig_project] user% g++ -c example_wrap.cxx -I/scisoft/i386/ Packages/Python-2.4.3/Python.framework/Versions/2.4/include/python2.4/ example_wrap.cxx: In function 'PyObject* _wrap_main(PyObject*, PyObject*)': example_wrap.cxx:735: error: 'main' was not declared in this scope The beginning of example.i looks like the following: %module filename %{ #define file_plugin "plugins/file.h" #if foo_OS!=2 #include #endif #include "../Foo.h" using namespace foo_library; %} The error that is being picked up in reference to 'main' is contained in the following excerpt, generated by SWIG (example_wrap.cxx): /*----------------------------------------------- @(target):= _filename.so ------------------------------------------------*/ #define SWIG_init init_filename #define SWIG_name "_filename" #define cimg_plugin "plugins/file.h" #if foo_OS!=2 #include #endif #include "../Foo.h" using namespace foo_library; #ifdef __cplusplus extern "C" { #endif static PyObject *_wrap_main(PyObject *self, PyObject *args) { PyObject *resultobj; int arg1 ; char **arg2 = (char **) 0 ; int result; PyObject * obj1 = 0 ; if(!PyArg_ParseTuple(args,(char *)"iO:main",&arg1,&obj1)) goto fail; if ((SWIG_ConvertPtr(obj1,(void **) &arg2, SWIGTYPE_p_p_char,SWIG_POINTER_EXCEPTION | 0 )) == -1) SWIG_fail; result = (int)main(arg1,arg2); resultobj = PyInt_FromLong((long)result); return resultobj; fail: return NULL; } Any clues as to what is happening here or what to do next? If you know, your help would greatly help. Thanks in advance! From saif.shakeel at gmail.com Tue Apr 3 05:13:17 2007 From: saif.shakeel at gmail.com (saif.shakeel at gmail.com) Date: 3 Apr 2007 02:13:17 -0700 Subject: Parsing Problems Message-ID: <1175591597.120154.240820@q75g2000hsh.googlegroups.com> Hi, I have just started learning python.I need to parse an XML file and present the contents in a particular format.The format is called as "ini" file.I have written some code.A section of the format needs the data to be present in format as given below: [Services] supported=0x10,0x1A,0x3B,0x20,0x27,0x28,0x34,0x36,0x3E,0xA2,0xA5,0x2D, 0x22,0xA9,0x04,0xAA,0xAE My code for this section parses the xml file and gives : [Services] Supported=['0x3e', '0x28', '0x3b', '0x22', '0x20', '0x27', '0xaa', '0x10', '0xae', '0x34', '0x36', '0x2d', '0xa9', '0xa5', '0x4', '0xa2', '0x1a'] {forget the numericals matching}.As you can see there are single quotes around numericals ,which is not desired .I think the problem lies in me using a list for storing and later printing out values.I have attached few lines of code,not sure how clear it can be to you: for l in range(0,len(ser_par), 1): if ser_par[l].getAttribute('Semantics')==u'serviceId': if tag_exists(ser_par[l].childNodes,'VALUE'): val = ser_par[l].getElementsByTagName('VALUE') value = str(val[0].getAttribute('value')) valu = hex(int(value)) rval.append(valu) ser_par_num = ser_par_num + 1 prim_num = prim_num + 1 service_num = service_num + 1 variant_num = variant_num + 1 ser = list(set(rval)) print "\n[Services]" print "Supported="+str(ser) How can i get rid of those single quotes. Thanking you shakeel From kyosohma at gmail.com Mon Apr 16 16:46:41 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: 16 Apr 2007 13:46:41 -0700 Subject: looking for library to read ppt files In-Reply-To: References: <1176747406.722209.126900@w1g2000hsg.googlegroups.com> Message-ID: <1176756401.108945.230880@y5g2000hsa.googlegroups.com> On Apr 16, 1:42 pm, Larry Bates wrote: > Aljosa Mohorovic wrote: > > i'm looking for a way to read ppt (powerpoint) files using python and > > to convert slides into jpeg files. > > any links or tips how to do this? > > Not really a Python question but Google turned up: > > http://www.sharewareconnection.com/ppt-to-jpeg-jpg-tiff-bmps-converte...http://www.print-driver.com/howto/converting/convert_microsoft_powerp... > > -Larry I suppose you could also use the win32 module and the COM object to grab the info from the slide and then use the PIL module to create a jpeg. Sounds like a lot of head banging to me, but it might be an interesting project. For info on accessing PowerPoint with Python, see links below: http://www.thescripts.com/forum/thread592690.html http://www.thescripts.com/forum/thread19132.html http://www.p-nand-q.com/python/ms_office.html Also see Hammond's "Python Programming on Win32" book or Chun's Core Python Programming". Both have some examples of accessing MS Apps. PIL can be found at: http://www.pythonware.com/products/pil/ Mike From duncan.booth at invalid.invalid Fri Apr 27 10:45:09 2007 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 27 Apr 2007 14:45:09 GMT Subject: conditional print statement ? References: <2c923$462fb3e0$d443bb3a$18429@news.speedlinq.nl> <1177590681.015153.67800@b40g2000prd.googlegroups.com> <1177683110.005910.99250@t38g2000prd.googlegroups.com> Message-ID: Paul McGuire wrote: > The Enable/Disable decorators on the Python wiki (http:// > wiki.python.org/moin/PythonDecoratorLibrary?highlight=%28decorator > %29#head-8298dbf9ac7325d9ef15e7130e676378bbbda572) help you do > something very similar, without having to replicate the function being > enabled/disabled. > > @(disabled,enabled)[Print_Info] > def printOrNot(arg): > print arg > Pardon me for asking, but isn't that a syntax error? Decorator syntax is: "@" dotted_name ["(" [argument_list [","]] ")"] NEWLINE and you don't have a dotted_name. From paddy3118 at netscape.net Thu Apr 26 17:44:13 2007 From: paddy3118 at netscape.net (Donald 'Paddy' McCarthy) Date: Thu, 26 Apr 2007 21:44:13 GMT Subject: EuroPython vs PyconUK In-Reply-To: <4630D480.7050308@gmail.com> References: <4630D480.7050308@gmail.com> Message-ID: EuGeNe Van den Bulke wrote: > I do realize that the UK is not really part of Europe (no polemic :P) > but I am nevertheless curious about the logic behind creating another > major Python event in Europe. Wasn't EuroPython enough? > > Like many I am sure, I probably won't be able to attend both (and I > really enjoyed the Geneva experience so definitely want to renew "it"). > How would you go about selecting which conference to attend? > > They are only 2 months apart, 6 would have been easier for the > attendees! Could the organizers liaise one way or another to make > Pythoneers life as easy and fun as the language and give as much > information out as possible as early as possible (early bird early) for > people to make the best decision? > > I know marketing matters but ... > > EuGeNe -- http://www.3kwa.com Growth! From steve at REMOVE.THIS.cybersource.com.au Sun Apr 29 04:12:14 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Sun, 29 Apr 2007 18:12:14 +1000 Subject: While we're talking about annoyances Message-ID: Am I the only one who finds that I'm writing more documentation than code? I recently needed to write a function to generate a rank table from a list. That is, a list of ranks, where the rank of an item is the position it would be in if the list were sorted: alist = list('defabc') ranks = [3, 4, 5, 0, 1, 2] To do that, I needed to generate an index table first. In the book "Numerical Recipes in Pascal" by William Press et al there is a procedure to generate an index table (46 lines of code) and one for a rank table (five lines). In Python, my index function is four lines of code and my rank function is five lines. I then wrote three more functions for verifying that my index and rank tables were calculated correctly (17 more lines) and four more lines to call doctest, giving a total of 30 lines of code. I also have 93 lines of documentation, including doctests, or three lines of documentation per line of code. For those interested, here is how to generate an index table and rank table in Python: def index(sequence): decorated = zip(sequence, xrange(len(sequence))) decorated.sort() return [idx for (value, idx) in decorated] def rank(sequence): table = [None] * len(sequence) for j, idx in enumerate(index(sequence)): table[idx] = j return table You can write your own damn documentation. *wink* -- Steven. From mike.klaas at gmail.com Wed Apr 4 18:38:55 2007 From: mike.klaas at gmail.com (Klaas) Date: 4 Apr 2007 15:38:55 -0700 Subject: Why NOT only one class per file? In-Reply-To: References: <1175721799.714907.52770@o5g2000hsb.googlegroups.com> Message-ID: <1175726335.866564.4730@p77g2000hsh.googlegroups.com> On Apr 4, 2:52 pm, Thomas Kr?ger wrote: > > At first: if he really like it he can place every class in a single > file. But there are some reasons why Python "allows" you to place many > classes in one file: > > - It's (a little bit) faster, no additional file system lookup is needed. ;) > - You can define a class in a class. Django, for example, uses this for > it's data models. If you do this you are forced to have multiple classes > in on file. Example:http://www.djangoproject.com/documentation/tutorial02/#make-the-poll-... That is somewhat specious: inner classes can be defined in java too. The main reason is that in java, classes are magical entities which correspond to one "exportable" unit of code. Thus it makes a great deal of sense to limit to one _public_ class per file (java also allows unlimited private and package-private classes defined in a single file). If you want to define a bunch of utility functions in java, you write a file containing a single class with static methods. In python, classes do not have special status. The exportable unit of code is a module, which, like public classes in java, can contain functions, static variables, and classes. Similar to java, you are limited to a single module object per file (modulo extreme trickery). If you want to define a bunch of utility functions in python, you write a file containing a single module with functions. -Mike From claird at lairds.us Thu Apr 5 12:50:10 2007 From: claird at lairds.us (Cameron Laird) Date: Thu, 5 Apr 2007 16:50:10 +0000 Subject: SNMP agent References: <1175680387.575097.4590@e65g2000hsc.googlegroups.com> <1175686451.614022.171650@b75g2000hsg.googlegroups.com> Message-ID: <2vlfe4-6n.ln1@lairds.us> In article <1175686451.614022.171650 at b75g2000hsg.googlegroups.com>, alain wrote: >On Apr 4, 1:30 pm, alf wrote: > >> twistedmatrix.org? > >I already took a look at it but the agent functionality is somewhat >primitive. I need something production-ready. > >Alain > 'Doesn't exist. I understand the sentiment; in principle, it shouldn't be hard to write a library which supports construction of SNMP agents in Python. I'm aware of no one who has done so publicly, though. Myself, I like using the Tcl-based Scotty. For severely-constrained performance, though, you'll likely have to go to C, in some form. From mcPas.De.Spam at mclaveauPas.De.Spam.com Tue Apr 10 02:25:32 2007 From: mcPas.De.Spam at mclaveauPas.De.Spam.com (Michel Claveau) Date: Tue, 10 Apr 2007 08:25:32 +0200 Subject: TASK KILL References: <1176184419.825885.285540@b75g2000hsg.googlegroups.com> Message-ID: > Will TASKKILL kills a thread when thread id is given ?? Or does it > kill only a process?? > > How to ensure that a thread is killed? Hi! Sorry, TASKKILL is only for process. For help on TASKKILL : TASKKILL /? Other infos with TASKLIST (TASKLIST /?) If the object who use process is a service (kif-kif daemon), you can use SC (see SC /?) For thread, the concept is fuzzy. Thread can be manage by OS, by software (e.g. by Python, for Python's threads), or by middlewares. There are no universal way. -- @-salutations Michel Claveau From dillonco at comcast.net Thu Apr 19 18:10:19 2007 From: dillonco at comcast.net (DillonCo) Date: Thu, 19 Apr 2007 18:10:19 -0400 Subject: Better dict of dicts In-Reply-To: References: Message-ID: <200704191810.20002.dillonco@comcast.net> On Thursday 19 April 2007, Bill Jackson wrote: > I have a dictionary of dictionaries where the keys are typically very > long tuples and repeated in each inner dictionary. The dictionary > representation is nice because it handles sparseness well...and it is > nice to be able to look up values based on a string rather than a > number. However, since my keys are quite long, I worry that I am > wasting a lot of memory. I'm looking for better data structures. I think you may want to look into that rarely used function "intern" (under "on-essential Built-in Functions"). Basically, Python keeps a cache of certain strings are are frequently used so comparisons and dictionary lookups only require a pointer comparison. You could then subclass dict (though using "DictMixin" could be better) like: class IDict(DictMixin): def __setitem__(self, key, value): key=intern(key) self.__dict[key]=value That's totally untested and incomplete, but you hopefully get the idea. Python (or at least CPython) seems to auto intern some strings occasionally (you could look at the source if you care about the exact rules). Example: >>> a="1234567890" >>> b="1234567890" >>> a is b True So you don't have all that much to worry about. From bcwhite at pobox.com Wed Apr 18 23:09:01 2007 From: bcwhite at pobox.com (bcwhite at pobox.com) Date: 18 Apr 2007 20:09:01 -0700 Subject: Future Python Gui? In-Reply-To: <4caef$4626b6f4$4275d90a$19707@FUSE.NET> References: <1176859699.906386.326720@b75g2000hsg.googlegroups.com> <1176923448.998078.170760@e65g2000hsc.googlegroups.com> <46267C84.8040505@codebykevin.com> <1176941169.750013.216660@e65g2000hsc.googlegroups.com> <4caef$4626b6f4$4275d90a$19707@FUSE.NET> Message-ID: <1176952141.007295.272000@e65g2000hsc.googlegroups.com> > The wrapper I maintain works differently, and includes the notebook widget. I've seen the page. You can get to it via Google's cache; just put the url in the box and the one search result returned usually has a "cached" link. However, that file is completely useless without instructions on how to use it, and there are no instructions within the page or file. That is: - exactly where does it get installed - what else needs to get installed (eg. some dll) - where do you find these other things - where does that something else get installed - how do you import this module - how does use of Tkinter change (if at all) once imported I know all this stuff is obvious to those that have been working with it for a while, but for those of us just getting started with Python, it's immensely frustrating that we're assumed to know all these steps. -- Brian From python-url at phaseit.net Mon Apr 30 08:56:33 2007 From: python-url at phaseit.net (Cameron Laird) Date: Mon, 30 Apr 2007 12:56:33 +0000 (UTC) Subject: Python-URL! - weekly Python news and links (Apr 30) Message-ID: QOTW: "That is just as feasible as passing a cruise ship through a phone line." - Carsten Haese, on transporting a COM object across a network. Less vividly but more formally, as he notes, "A COM object represents a connection to a service or executable that is running on one computer. Transferring that connection to another computer is impossible." "[D]on't burn bandwith by banal banter, post the examples!" - John Machin See the great cities of Europe, learn Python, and play the "Where's Alex (Guido/...)?" game: attend a conference in Paris, Vilnius, Firenze, Birmingham, ...: http://groups.google.com/group/comp.lang.python/browse_thread/thread/e12536c746c593a8/ Pygame is now having weekly (!) sprints to fix bugs on Wednesdays. http://aspn.activestate.com/ASPN/Mail/Message/pygame-users/3441195 http://www.unixreview.com/documents/s=10116/ur0701j/ Exception-handling is important. You need to learn 'most everything about it you can. See, for example, this thread about disaggregating IOError: http://groups.google.com/group/comp.lang.python/browse_thread/thread/ed5b8e52d2642537/ Reasons to enjoy Python--but read the comments: http://blog.cbcg.net/articles/2007/04/22/python-up-ruby-down-if-that-runtime-dont-work-then-its-bound-to-drizzown ======================================================================== 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, Planet Python indexes much of the universe of Pybloggers. http://www.planetpython.org/ 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/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 should get through. To receive a new issue of this posting in e-mail each Monday morning (approximately), ask 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 jkrukoff at ltgc.com Fri Apr 13 17:56:27 2007 From: jkrukoff at ltgc.com (John Krukoff) Date: Fri, 13 Apr 2007 15:56:27 -0600 Subject: Any way to refactor this? In-Reply-To: <461ff01c$0$29118$426a74cc@news.free.fr> Message-ID: <001501c77e16$96c212f0$0201a8c0@naomi> Bruno Desthuilliers wrote: > John Salerno a ?crit : > > Setting aside, for the moment, the utility of this method or even if > > there's a better way, I'm wondering if this is an efficient way to do > > it. I admit, there was some copying and pasting, which is what prompts > > me to ask the question. Here's the method. (I hope it looks ok, because > > it looks really weird for me right now) > > > > def _create_3D_xhatches(): > > for x in xrange(-axis_length, axis_length + 1): > > if x == 0: continue > > visual.cylinder(pos=(x,-hatch_length,0), > > axis=(0,hatch_length*2,0), radius=hatch_radius) > > visual.cylinder(pos=(x,0,-hatch_length), > > axis=(0,0,hatch_length*2), radius=hatch_radius) > > visual.cylinder(pos=(-hatch_length,x,0), > > axis=(hatch_length*2,0,0), radius=hatch_radius) > > visual.cylinder(pos=(0,x,-hatch_length), > > axis=(0,0,hatch_length*2), radius=hatch_radius) > > visual.cylinder(pos=(-hatch_length,0,x), > > axis=(hatch_length*2,0,0), radius=hatch_radius) > > visual.cylinder(pos=(0,-hatch_length,x), > > axis=(0,hatch_length*2,0), radius=hatch_radius) > > > > Since each call to cylinder requires a slightly different format, I > > figured I had to do it this way. > > From a purely efficiency POV, there are some obviously possible > improvements. The first one is to alias visual.cylinder, so you save on > lookup time. The other one is to avoid useless recomputation of > -hatch_length and hatch_length*2. > > def _create_3D_xhatches(): > cy = visual.cylinder > for x in xrange(-axis_length, axis_length + 1): > if x == 0: continue > b = -hatch_length > c = hatch_length*2 > cy(pos=(x, b, 0), axis=(0, c, 0), radius=hatch_radius) > cy(pos=(x, 0, b), axis=(0, 0, c), radius=hatch_radius) > cy(pos=(b, x, 0), axis=(c, 0, 0), radius=hatch_radius) > cy(pos=(0, x, b), axis=(0, 0, c), radius=hatch_radius) > cy(pos=(b, 0, x), axis=(c, 0, 0), radius=hatch_radius) > cy(pos=(0, b, x), axis=(0, c, 0), radius=hatch_radius) > > A second step would be to try and generate the permutations by code > instead of writing them all by hand, but I suppose the order is > significant... > There's still an obvious pattern, which is that the position of 'c' in > the axis tuple mirrors the position of 'b' in the pos tuple. There might > be some way to use this to let the computer handle some part of the > repetition... > > My 2 cents... > -- > http://mail.python.org/mailman/listinfo/python-list Because it was fun, and the previous refactoring made the pattern easy to see, here's the way not to do this. (Requires python 2.5 for trinary operator) # From the ASPN cookbook def permutations(L): if len(L) <= 1: yield L else: a = [L.pop(0)] for p in permutations(L): for i in range(len(p)+1): yield p[:i] + a + p[i:] def _create_3D_xhatches(): for x in xrange(-axis_length, axis_length + 1): if x <> 0: # Use None as placeholder for comparison. for pos in permutations([x, None, 0]): visual.cylinder(pos = [-hatch_length if coord is None else coord for coord in pos], axis = [hatch_length * 2 if coord is None else 0 for coord in pos], radius = hatch_radius) Undoubtedly slower, nearly impossible to read, but has minimum of code duplication! If I was answering this question for real, I'd suggest the same arguments as tuple solution that was suggested earlier, i.e.: def _create_3D_xhatches(): list_of_kwargs = [ {pos:[ x, -hatch_length, 0], axis:[0, 2 * hatch_length, 0 ]}, {pos:[ x, 0, -hatch_length], axis:[0, 0, 2 * hatch_length ]}, And so on for all permutations... ] for x in xrange(-axis_length, axis_length + 1): if x == 0: continue for kwargs in list_of_kwargs: visual.cylinder( radius = hatch_radius, **kwargs ) As it pulls out the two obviously common components, the function call and the radius parameter. --------- John Krukoff jkrukoff at ltgc.com From karsten.borgwardt at gmail.com Thu Apr 12 15:21:53 2007 From: karsten.borgwardt at gmail.com (karsten.borgwardt at gmail.com) Date: 12 Apr 2007 12:21:53 -0700 Subject: Several images onto one 2D-plot in matplotlib? Message-ID: <1176405713.392944.6860@b75g2000hsg.googlegroups.com> Hi! I have got the following problem: I want to plot a 2D-function in matplotlib, and then I want to insert (small) png-Images at certain locations within the plot. Any suggestions how to do that? Thanks a lot! yggobk From http Wed Apr 4 22:48:14 2007 From: http (Paul Rubin) Date: 04 Apr 2007 19:48:14 -0700 Subject: how to remove multiple occurrences of a string within a list? References: <1175624433.206953.214290@n59g2000hsh.googlegroups.com> Message-ID: <7xzm5ny1sh.fsf@ruckus.brouhaha.com> "bahoo" writes: > I have a list like ['0024', 'haha', '0024'] > and as output I want ['haha'] > > If I > myList.remove('0024') > > then only the first instance of '0024' is removed. [x for x in myList if x != '0024'] From grahn+nntp at snipabacken.dyndns.org Tue Apr 3 09:21:12 2007 From: grahn+nntp at snipabacken.dyndns.org (Jorgen Grahn) Date: 3 Apr 2007 13:21:12 GMT Subject: Inserting '-' character in front of all numbers in a string References: <1175269107.769945.241500@r56g2000hsd.googlegroups.com> Message-ID: On 30 Mar 2007 08:38:27 -0700, 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. ... > "2a 3ab" into "-2a -3ab". Are you sure you want getopt, or are you just reusing it because you don't know enough about string parsing and REs? -2a -3ab is a bit limited: if you run out of digits and have to use 10, 11, ... then getopt will treat '-10ab' as '-1' without argument and -0 with 'ab' as argument. It will probably choke on the argumentless -1, too. /Jorgen -- // Jorgen Grahn R'lyeh wgah'nagl fhtagn! From howe.steven at gmail.com Fri Apr 6 02:54:12 2007 From: howe.steven at gmail.com (Steven Howe) Date: Thu, 05 Apr 2007 23:54:12 -0700 Subject: Why NOT only one class per file? In-Reply-To: <1175819151.572750.229030@y66g2000hsf.googlegroups.com> References: <1175721799.714907.52770@o5g2000hsb.googlegroups.com> <1175819151.572750.229030@y66g2000hsf.googlegroups.com> Message-ID: <4615EE94.2070400@gmail.com> Now we're at the '_/How many Angels can dance on the head of a pin/_' question (like anything with wings would waste time dancing. Ever seen eagles mate (not the football players)? Dance it's not, but it looks like /sex on a roller coaster only better/! Get me a pair of wings!). Religious war over please! They get me long winded (as you'll note if you keep reading). So, back to the original questions, now long forgotten. The questions (there were three) were: (1) Why does Java require each class be in a separate file? (2) Why Python has no such rule? And (3) Is there a reason I should do one or the other (I assume that means either, (3)(a) one class per file, regardless of language and/or (3)(b) Java or Python). -------------------------------------------------- -------------------------------------------------- Answers: Question (1): There appear to be four answers to this question. (a) Don't know (most answers, but with some religious dogma attached. JAVA bad; PYTHON good and I worship PHP. Move the adj. around to suit your tastes). (b) KISS principle. /Keep It Simple, Stupid/. This is probably the right answer. Back then SUN, or as some of us remember '/Stanford University Network/' employed some sharp people (I must admit, my main reason for disliking SUN and CISCO was where they started. I was from UC Berkeley. It should have been UCBUN, or Uncle Buns; but that's just wouldn't sell. See how well BSD or 'bastard' sells). (c) Early Java development technology not up to n+1 classes in a single file. Reasonable from an old programmer's point of view. Those old IPC workstation didn't have that much memory. Small compiling jobs and executable loads would have been preferred if not required. I remember my first IPC had 4 Megabytes of RAM (boy did I have to beg for that box!) My Compaq 386/20 MHz computer, running MSDOS 3.1 only had 1 Meg and a Hercules graphics card (16 colors. I must have been good that year). I must have been a star, as most other's new hires were using '*/Bleeding Edge/*' computers (and if you don't know the reference, your just too young; think Gateway or Dell's cheap, hobbled products). File and more importantly, virus transfers where by /SneakerNet/. You young people have it too good; just one message via Exchange and you can infect a million computers in a thousand countries in moments. We had to work at it before we could take a day off as IT reloaded our computers. Thank God or Bill Gates, that companies keep buying a broken product. (d) Last. It was developed for vending machines (as someone pointed out, it started life as 'OAK'). Small memory foot print and a limited feature set were no brainers. '/We Taka the coins in, We dropa the Twinky out'. /The net's early domination by Unix variants and the Macintosh made Java's '/jack of all trades'/ a good solution. It was the main reason Microsoft tried (and failed) to '/Embrace and Extend'/ Java (Novell watch your ass; Microsoft wants to embrace and extend up your backside. SUN, just like a good Catholic girl said NO! (Or not in public! as the IBM/SCO trial seems to show)). So, pick an answers. It's God's fault/feature (sorry, I forget SUN != Microsoft), a programming dogma, hardware related or just old fashion growing pains. Probably some of each is the truth. Question (2): Python is a later generation language then Java. Without a SUN, Digital or Microsoft to push it, it had to serve it's users better. Design limitations, due to hardware (see HP and Korn shell) weren't a consideration. The main issue I could see, when I was first introduced to the Python language, was the reduction of overhead and limited ways of doing the same task (1/ Perl ^ n in my experience). The need to prettify code so other could read it, or more importantly, so other's couldn't read it (for job security), wasn't there. Python really is easy to learn, like Pascal was suppose to be. Python, like Java was OO from the word go (ok gcc for you purists), but was not syntactically a descendant of C++, so non-C++ programmers didn't need to pay homage to AT&T (and God's only son, Bell Labs, from whence the Holy Ghost, Unix was created, destroyed and reborn as BSD. Is there a movie with Mell Gibson there? Remember, I said it first!). Freedom of vendors often means best of breed wins (i.e. most useful feature are includes). Freedom of vendors also means it hard to get into your shop (no one ever got fired for buying IBM after all). That takes care of why, I hope. _No doubt_ there's a few opinions left to be expressed. Who knows, they might stay on topic as well or better them I. Question (3): (3)(a) Is there a reason I should practice the 'One Class per File' rule? Answer is *yes,* when it makes your programming task easier and *no,* when it makes your programming task harder (And yes, I could be a damn good congressman too!). For development, I think the n+1 class is the right choice. It lets you start easy with a prototype class, one with little more then placeholders and then using inheritances, build up the functionality (you can see my Object Oriented Life started with C++, not a silver or ruby spoon. I still have the first edition of "**The C++ Programming Language"** by Bjarne Stroustrup; an almost unreadable book (six or eight beers make it easier, if not clearer; after twelve you don't care). Don't ask to buy it. It's going into my casket when I'm creamated, along with the first edition of '*The C Programming Language*' by Kernighan and Ritchie and my second best porn collection; might be tight in that casket, but what a FIRE!). Using this method, program growth history is preserved. Some would say that's the job of version control. But you can see where sandbox development records got IBM and version controls blind usage in Mircosoft's attempt at (5+ years) Vista. Somethings should be forgotten, sooner rather than later. For a developed, deployable product and JIT compilers, n+1 classes with dead overridden inheritances, are wasted cycles, wasted space and wasted download bandwidth. It just doesn't make sense. /Clean em up, move'em out/. That's what version control is for. (3)(b) Python or Java. Emmm, Dumb question (some question are, despite the feel good gurus your boss will bring in when he wants to cut your salary, double your workload or both while cutting you coffee rations). The answer depends on your boss's preference. Learn both and hope you can convience him the one you're best at, is the right choice (good luck; boss's are generally a generation or two behind and you. After all, you where hired because of your fresh knowledge and viewpoint. We don't want that going to another company. When you feel this is situation is all wrong, read the novel Catch-22 and join th club). And please don't remind him that you'll be there to support the language he doesn't know. That's a ticket backwards and a new resume (yours). -------------------------------------------------- -------------------------------------------------- Now for some fun. I have a wicked (so I'm told) and rude sense of humor. Humor me, or you, if you please ... You'll notice I didn't evangelize or denigrate Python, Jython, Java, PHP or C++ (/OK, C++ just a little; after all, I am a fallen CatholiC++/. /And a few jabs at Microsoft. The devil should always be mentioned, especially when he's hard to avoid/). So now here's the the motto or jingle of the dying and upstart languages languages: Perl: "Badges? We don't need any stinky badges!" FORTRAN: "GOTO 40" and FORTRAN-90: "GOTO 40-ish, please!" Basic: "Directory? What's a directory?" Pascal (need I say more?) and COBOL on or off Ng: "Your in the wrong column, again!" And the upstarts language mottos: Ruby: I don't care if the slippers are suppose to be sliver; I'm paying for Technicolor dammit; those slippers will be RUBY! C-Sharp: Bitter on the tongue and leaves a bad after taste. Could I have a Java light instead? or C-Sharp's first cousin by bastardy with open source virgins (in time they'll realize that pains in their behinds should have been expected) ... Mono: much like the disease, ready to infect anything it touches. You should avoid it as fast as you can run. And ... Not to forget the forgetable ... PHP or for neophytes Perl Hypertext Protocol, also referred to as '2nd Wind' or 'Last Gasp' can't be bad for you! Did I miss anything? No? Then I have no /Smalltalk/ left, so you should go /Forth/ and program. But remember JAVA & SCRIPT can grow infinitely, especially when taken to the exp( GOOGLE ) plexed. sph -------------------------------------- P.S. Python RULES! --------------------------------------- P.S.S. Still waiting for GWT via Python Google; I hate stepping backwards; can't tell what I'm stepping in, but GWT feels like dog poop; warm amd squishy but it stinks. Mom tells you to stay outside and clean your shoes. Flies think your sweet. --------------------------------------- Carl Banks wrote: > On Apr 4, 5:23 pm, "Chris Lasher" wrote: > >> A friend of mine with a programming background in Java and Perl places >> each class in its own separate file in . I informed him that keeping >> all related classes together in a single file is more in the Python >> idiom than one file per class. He asked why, and frankly, his valid >> question has me flummoxed. >> > > A: Because you don't have to. > > Less smart aleck: Python allows programmers to put more than one class > per file. Given that freedom, most people didn't obey one-to-one > correspondence between classes and files. Therefore, it's the more > common idiom in Python. > > > >> I tried to rationalize this Python idiom by claiming a file--a single >> module--makes for a great container of code which is logically tied >> together, such as a class and its subclasses. He posited that >> directories (packages) can tie the files together just as well, >> > > Which is not incorrect. > > > >> and by >> having the classes as separate files, he can "diff" them to see how >> they differ, something he wouldn't be able to do with the code all in >> one file. >> > > I agree with Bruno: feeling the need to do this is a big red flag that > the code is way too cut-and-paste. > > (diff'ing different versions is useful, of course, but you can > usefully diff modules with many classes in them.) > > > >> I also offered that having related classes under one file gives more >> direct access to those classes, e.g.: >> > > [snip examples] > > >> He doesn't find my arguments convincing, so I thought I'd ask here to >> see why the Python idiom is the way it is: why should we NOT be >> placing classes in their own separate files? >> > > There's no overwhelming reason not to, IMO. As long you have some > organization, be it with packages or modules, everything's ok. Most > things you have to gain or lose by doing one way or the other are of > minor importance. > > > Carl Banks > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From duncan.booth at invalid.invalid Sat Apr 14 12:45:18 2007 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 14 Apr 2007 16:45:18 GMT Subject: Python Feature Request: Add the "using" keyword which works like "with" in Visual Basic References: <1176547372.584539.89170@q75g2000hsh.googlegroups.com> Message-ID: "BJ?rn Lindqvist" wrote: > ? Not having to bother with petty things like that is an advantage. > Javascript has with-statements that are equivalent to your > using-statements but from what I've seen most programmers avoid them. > They don't increase readability one bit. That is at least partly because Javascript with statements are badly broken. Consider the following code: function setit(a) { with (a) { x = 1; }; return a; } var x; delete x; alert(setit({'x':0}).x); alert(setit({'y':0}).x); alert(x); If 'a' has a property 'x' setit updates the property, otherwise it searches out the scope chain until it finds an object with an 'x' property and finally creates one on the global object if there isn't one. So the output in this case is the sequence '1', 'undefined', '1'. From mail at timgolden.me.uk Mon Apr 16 10:28:16 2007 From: mail at timgolden.me.uk (Tim Golden) Date: Mon, 16 Apr 2007 15:28:16 +0100 Subject: Writing Log CSV (Efficiently) In-Reply-To: <002a01c78032$27190620$754b1260$@rawlins@thinkbluemedia.co.uk> References: <7554276584215132819@unknownmsgid> <6e42ec490704160700i20469453j6af39db62dd6b427@mail.gmail.com> <17955.33861.211843.361355@montanaro.dyndns.org> <002a01c78032$27190620$754b1260$@rawlins@thinkbluemedia.co.uk> Message-ID: <46238800.1000302@timgolden.me.uk> Robert Rawlins - Think Blue wrote: > The log at its highest rate of write may be looking at an operation a > second I think I can probably type stuff in faster than that if I try :) You probably don't have a performance issue there. , I've not got much experience with this kind of thing so I'm not sure > if that's 'a lot' or not, it just seems like it at the moment. It might not > get as busy as that, I'm not sure and its difficult to simulate as this > isn't likely to be a steady flow of traffic, they'll come in big fat lumps > every now and then. Sounds like you don't really need to profile that, but if you did, Python's a great language for knocking together that kind of test harness; combine the time, random and csv modules and you've got a "big fat lumps every now and then" simulation. (At which point I get jumped on by the serious model types for being so blase with their discipline!) TJG From steve at holdenweb.com Wed Apr 18 12:30:48 2007 From: steve at holdenweb.com (Steve Holden) Date: Wed, 18 Apr 2007 12:30:48 -0400 Subject: X root Operator help In-Reply-To: References: <1176898887.530470.222830@p77g2000hsh.googlegroups.com> Message-ID: Michael Hoffman wrote: > lucidparadox wrote: >> I'm currently new to Python and I haven't been able to find the >> operator/math function to find the square root or even the x root of a >> number. > > For square root, use math.sqrt(y) > > For x root use y**(1/x) > [...] >>> 1/3 0 >>> 3.14159 ** (1/3) 1.0 >>> So the cube root of pi is 1? I don't think so. For generic roots use y ** (1.0 / x) until future versions of Python produce floating point results from all divisions as necessary. 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 alexandre.bergel at gmail.com Thu Apr 12 03:17:43 2007 From: alexandre.bergel at gmail.com (alexandre.bergel at gmail.com) Date: 12 Apr 2007 00:17:43 -0700 Subject: Dyla 2007: 3rd Workshop on Dynamic Languages and Applications Message-ID: <1176362263.135292.279670@n59g2000hsh.googlegroups.com> Dear colleges, You might want to consider Dyla'07 as a good venue to present your work and your favourite programming language. Regards, Alexandre ************************************************************************** Call for Papers Dyla 2007: 3rd Workshop on Dynamic Languages and Applications July 31, 2007, Berlin (Collocated with ECOOP 2007) http://dyla2007.unibe.ch ************************************************************************** Objective ========= The goal of this workshop is to act as a forum where we can discuss new advances in the conception, implementation and application of object-oriented languages that radically diverge from the statically typed class-based reflectionless doctrine. The goal of the workshop is to discuss new as well as older "forgotten" languages and features in this context. Topics of interest include, but are certainly not limited to: - agents, actors, active object, distribution, concurrency and mobility - delegation, prototypes, mixins - first-class closures, continuations, environments - reflection and meta-programming - (dynamic) aspects for dynamic languages - higher-order objects & messages - ... other exotic dynamic features which you would categorize as OO - multi-paradigm & static/dynamic-marriages - (concurrent/distributed/mobile/aspect) virtual machines - optimisation of dynamic languages - automated reasoning about dynamic languages - "regular" syntactic schemes (cf. S-expressions, Smalltalk, Self) - Smalltalk, Python, Ruby, Scheme, Lisp, Self, ABCL, Prolog, ... - ... any topic relevant in applying and/or supporting dynamic languages. We solicit high-quality submissions on research results and/or experience. Submitted papers must be unpublished and not submitted for publication elsewhere. Submissions should not exceed 10 pages, LNCS format (www.springer.com/lncs). Submission ========== Prospective attendees are requested to submit a position paper or an essay (max 10 pages, references included) on a topic relevant to the workshop to Alexandre Bergel (Alexandre.Bergel at cs.tcd.ie). Submissions are demanded to be in .pdf format and should arrive before May 13, 2007. A selection of the best papers will be made, which will require an extension for an inclusion in a special issue in Electronic Communications of the EASST (eceasst.cs.tu-berlin.de). For this purpose, a new deadline will be set after the workshop. Moreover, Springer publishes a Workshop-Reader (as in the case of previous ECOOPs) which appears after the Conference and which contains Workshop-Reports (written by the organizers) and not the position papers submitted by the participants. Important dates =============== Submission due: May 13, 2007 Notification of Authors: May 31, 2007 ECOOP'07 Early Registration Date: June 15th. Workshop: July 31, 2007 Organisers ========== Alexandre Bergel Wolfgang De Meuter St?phane Ducasse Oscar Nierstrasz Roel Wuyts Program committee ================= Alexandre Bergel (LERO & Trinity College Dublin, Ireland) Johan Brichau (Universit? catholique de Louvain, Belgium) Pascal Costanza (Vrije Universiteit Brussel, Belgium) Wolfgang De Meuter (Vrije Universiteit Brussel, Belgium) St?phane Ducasse (University of Annecy, France) Erik Ernst (University of Aarhus, Denmark) Robert Hirschfeld (Hasso-Plattner-Institut, University of Potsdam, Germany) Oscar Nierstrasz (University of Bern, Switzerland) Matthew Flatt (University of Utah, USA) Dave Thomas (Bedarra Research Labs, Canada) Laurence Tratt (King's College London, UK) Roel Wuyts (IMEC & Universit? Libre de Bruxelles, Belgium) -- _,.;:~^~:;._,.;:~^~:;._,.;:~^~:;._,.;:~^~:;._,.;: Alexandre Bergel http://www.software-artist.eu ^~:;._,.;:~^~:;._,.;:~^~:;._,.;:~^~:;._,.;:~^~:;. From garcia.marc at gmail.com Mon Apr 30 09:01:37 2007 From: garcia.marc at gmail.com (garcia.marc at gmail.com) Date: 30 Apr 2007 06:01:37 -0700 Subject: Reading Data From an Excel Sheet In-Reply-To: <1177922130.251948.107740@p77g2000hsh.googlegroups.com> References: <1177922130.251948.107740@p77g2000hsh.googlegroups.com> Message-ID: <1177938097.766156.278810@y5g2000hsa.googlegroups.com> On Apr 30, 10:35 am, sagar wrote: > Hi all, > I want a python script which takes in input an EXCEL sheet > and then reads the data in it. > Any code snippets will be fine and this i want this in windows > XP . > > Thanks in Advance > Sagar Meesala Here you have an example: http:// dataparser.cvs.sourceforge.net/dataparser/source/input_adapters/ excel.py?revision=1.1.1.1&view=markup Marc Garcia is the best expert in GNU/Linux Debian, Apache, MySQL, and Python! From larry.bates at websafe.com Thu Apr 19 14:44:11 2007 From: larry.bates at websafe.com (Larry Bates) Date: Thu, 19 Apr 2007 13:44:11 -0500 Subject: NFS Help In-Reply-To: <1177007562.103413.310390@o5g2000hsb.googlegroups.com> References: <1177007562.103413.310390@o5g2000hsb.googlegroups.com> Message-ID: Clement wrote: > how to get the file from NFS share in python...... > NFS share is mounted on your local directory, you get to it the same way you would any other file (e.g. go to the mount point and get the file). -Larry From ptmcg at austin.rr.com Fri Apr 13 11:16:48 2007 From: ptmcg at austin.rr.com (Paul McGuire) Date: 13 Apr 2007 08:16:48 -0700 Subject: Problem with algorithm In-Reply-To: <1176474468.803037.170160@p77g2000hsh.googlegroups.com> References: <1176434160.047703.214600@q75g2000hsh.googlegroups.com> <1176434937.258002.162220@p77g2000hsh.googlegroups.com> <1176448576.047996.12930@d57g2000hsg.googlegroups.com> <1176473989.420067.190970@l77g2000hsb.googlegroups.com> <1176474468.803037.170160@p77g2000hsh.googlegroups.com> Message-ID: <1176477408.805654.202320@n59g2000hsh.googlegroups.com> On Apr 13, 9:27 am, "Jia Lu" wrote: > > If you just expand the length to five million* or so, one of those > > strings will contain all the works of Shakespeare. > > Oops, you have this formula in math? > > Actually I want to scan a range of network for some certain files. Sorry, Jia Lu, I don't. I was actually just joking, alluding to the old saying that goes "if you had an infinite number of monkeys typing randomly on an infinite number of typewriters, they will eventually type out the works of Shakespeare." "Typewriters"! who uses typewriters any more?! -- Paul From larry.bates at websafe.com Fri Apr 20 12:13:50 2007 From: larry.bates at websafe.com (Larry Bates) Date: Fri, 20 Apr 2007 11:13:50 -0500 Subject: Fast and capable XML parser? In-Reply-To: References: Message-ID: <4628E6BE.60100@websafe.com> Magnus Lycka wrote: > I'm looking for some library to parse XML code > much faster than the libs built into Python 2.4 > (I'm stuck with 2.4 for quite a while) and I > also need XML Schema validation, and would > appreciate support for e.g. XPath and XInclude. > I also want an API which is more Pythonic than > e.g. a thin wrapper over a C or C++ API. > > It should be available on at least Linux, > Solaris and AIX. > > Some uses involve parsing lots of (often small) > XML files at reasonable speed, i.e. several > hundred files per second. That means that we > can't use anything like an os.system call to > xmllint for XML Schema validation--it gets too > slow. I also suspect that the standard Python > libs (in Python 2.4 at least) are slower than > we'd like them to be. (Not that it matters if > they don't support XML Schema validation.) > > Any suggestions? I don't know if it meets ALL of your requirements but this might help: http://www.reportlab.org/pyrxp.html -Larry From apardon at forel.vub.ac.be Fri Apr 20 04:08:12 2007 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 20 Apr 2007 08:08:12 GMT Subject: Do other Python GUI toolkits require this? References: <462697A6.6010007@codebykevin.com> Message-ID: On 2007-04-20, Nigel Rowe wrote: > On Thu, 19 Apr 2007 19:11, Antoon Pardon wrote in comp.lang.python: >> On 2007-04-19, Michael Bentley wrote: > > > >>> The learning curve is rather steep IMO, but worth it. >> >> Just a throw in remark, that you may ignore if you wish, but a steep >> learning curve means that the subject is easily familiarized and that >> the learning period is short. >> >> You seem to use it as if it is the opposite. >> > > Who says the axes are labeled "familiarity" and "learning period"? I > just assume they are labeled (y-axis) "Effort" and (x-axis) "Knowledge" > (or "skill" or ....). You can assume all you want, but no serious person processing numbers would choose axes like that. -- Antoon Pardon From python.technofreak at gmail.com Sat Apr 14 00:09:31 2007 From: python.technofreak at gmail.com (Parthan SR) Date: Sat, 14 Apr 2007 09:39:31 +0530 Subject: Python editor/IDE on Linux? In-Reply-To: <9d6d3deb0704132108w36c5e6e3i57706090682393c1@mail.gmail.com> References: <9e2f512b0704131918p25cb9b44sb3e5cebaf31d7dd6@mail.gmail.com> <9d6d3deb0704132108w36c5e6e3i57706090682393c1@mail.gmail.com> Message-ID: <9d6d3deb0704132109l10336abdh619253a5193c63f3@mail.gmail.com> OMG, all of you forgot IDLE ? http://www.python.org/idle/ It is very good for the starters and it looks simple. There are also Eric http://www.die-offenbachs.de/detlev/eric.html and SPE IDE http://pythonide.stani.be/ And there is always the uber cool editor (aka OS), Emacs :) -- With Regards Parthan "Technofreak" http://technofreakatchennai.wordpress.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From anton.vredegoor at gmail.com Mon Apr 16 19:40:50 2007 From: anton.vredegoor at gmail.com (Anton Vredegoor) Date: Tue, 17 Apr 2007 01:40:50 +0200 Subject: combination function in python In-Reply-To: <1176683797.421863.16980@o5g2000hsb.googlegroups.com> References: <1176615838.830315.160210@b75g2000hsg.googlegroups.com> <1176629911.409257.149780@l77g2000hsb.googlegroups.com> <1176669548.436118.176300@e65g2000hsc.googlegroups.com> <1176683797.421863.16980@o5g2000hsb.googlegroups.com> Message-ID: mensanator at aol.com wrote: > Isn't that what docstrings are for? Can't you leave > the function name noverk() and add something to the > effect of "this function calculates combinations"? > Then it would show up in searches, wouldn't it? Yes, a doc string would help finding it in searches, however since this thread now contains a collection of function names it will suffice. There is also the other consideration of being able to easily read code that others write. Functions that try to do the same thing having the same name would help. If we had some module in the standard distro that would contain comb and fac and maybe a few other functions people could start using the same name to point to the same thing etc. >>>> def noverk(n,k): >>>> ? ? ?return reduce(lambda a,b: a*(n-b)/(b+1),xrange(k),1) >> This is a rather concise function which has the added advantage that it >> returns 0 when k>n. > > import gmpy > print gmpy.comb(4,8) > > ## 0 There is more to it than that. If I see the way the function computes the values it gives me hints about how I could write a function that lists all combinations. For example the fact that one can divide the product 'on the fly' -I mean without computing the totals above and below the division bar- tells me something about how to tackle the problem of generating the corresponding combinatorial structure. I *love* combinatorial structures. Little functions like this have more than once helped me to understand them better. Math is not so much my way of describing things, I like executable pseudo code better. Sometimes I had to read math formulas and have become somewhat used to that notation -it has its uses too- but if things are written down in code I can rely on the *computer* to execute the code instead of my brain which unfortunately is not as reliable. These advantages are lost when one just imports some optimized code library. > Perhaps you should use the name > > comb_works_just_like_the_gmpy_version_only_slower() Or maybe 'comb_in_executable_pseudocode', but maybe some other implementations posted in this thread would be better suited for that. Anyway, I have the impression you just don't get the point of people posting various functions so that one can determine which algorithms work best or so that one can include each others ideas and create better functions that combine the best elements of all posted code. Cutting and pasting Python functions works a lot better in Usenet than importing C libraries. If no one posts code -even if it's not completely working code- how are we to learn from each other? The fact that someone else somewhere already saw the light and wrote the perfect function in optimized C or Fortran code should not stop us from 'reinventing the wheel' -as you call it- because one can get more proficient in wheel making in the process and every now and then it even leads to better wheels. Don't even get me started about this archaic scheme of writing code only for 'work' instead of for gaining insight that you seem to promote. > But when there *is* no documentation, that becomes a problem, > doesn't it? This thread is also documentation and I hope it will encourage people to post more code and share thoughts. > Unless you don't know how to write the functions you need > in which case you're better off relying on external > modules. Have you ever wondered why Python even *has* > a standard library? Why doesn't everyone just write > the functionality they need? The main virtue of Pythons standard library should be that it shows one how to do things and that it introduces a common naming scheme. That was what got me interested in python in the first place: Now I got to see how things work! No more dark secrets and proprietary code! Sometimes it's better to sacrifice clarity for speed and write optimized lower level code but that doesn't mean there aren't large trade offs involved. In the future if computers will become faster it would be wise to drop the optimized code libraries again and reintroduce the Python versions of the same because by then the Python versions would be fast enough and it would also result in a smaller code base (but a more functional and flexible and readable one). What are you doing on this planet anyway if it's not trying to understand things? >> Since I'm also interested in the >> functions themselves -in this case- I'd rather have a >> few lines of code in my source than importing an >> optimized code library. > > Well, some people prefer optimized libraries because > they have real work to do, not just acedemic excercizes. Real work is just an excuse for having a larger slice of the cake than other people. Other people can be just as or even more essential in the whole process of developing code than those who get paid. A reason against using third party libraries in general is not wanting to include too many external dependencies that would force the user to download all kinds of things from different places which could change their urls or web interfaces. It would also introduce more points where version conflicts or license conflicts could occur. > So it doesn't matter whether anyone can find noverk(), > does it? It does matter a lot in the long run if people can compare their code to the code other people write. If still other people profit from these public exchanges and then adopt a condescending attitude towards the grass roots processes -either because of misguided adoration for the best programmers or because they think themselves to be the best or maybe because of some archaic work related value system- that would dampen the enthusiasm a bit. >> You could take it up with the gmpy author and >> induce him to get gmpy included in the standard distro if you are so >> inclined. > > Alex Martelli knows more about that subject than I and > it would be pointless for me to bug him about it. Perhaps even your kind of misguided criticism would be better than such a fatalistic attitude. A. From tjreedy at udel.edu Sat Apr 7 13:46:51 2007 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 7 Apr 2007 13:46:51 -0400 Subject: How to tell when a file is opened References: <1175960486.759715.317140@y80g2000hsf.googlegroups.com> Message-ID: "Adam" wrote in message news:1175960486.759715.317140 at y80g2000hsf.googlegroups.com... | Hello, | | I want to know if it possible to tell when a file is opened. Just by Python? (Hack the file and open and possibly os.open code) or by any program? (Hack the OS -- good luck!) From tinaweb at bestemselv.com Wed Apr 25 03:01:39 2007 From: tinaweb at bestemselv.com (Tina I) Date: Wed, 25 Apr 2007 09:01:39 +0200 Subject: Catching a specific IO error In-Reply-To: References: Message-ID: Gabriel Genellina wrote: > You can get the 2 as the errno exception attribute. BTW, 2 == errno.ENOENT > > try: > export = open(self.exportFileName , 'w') > except IOError, e: > if e.errno==errno.ENOENT: > # handle the "No such file or directory" error > # calling an error handling method. > > See http://docs.python.org/lib/module-exceptions.html > > --Gabriel Genellina Perfect! Just what I was looking for. Thank you! :) Tina From bcwhite at pobox.com Tue Apr 17 21:28:19 2007 From: bcwhite at pobox.com (bcwhite at pobox.com) Date: 17 Apr 2007 18:28:19 -0700 Subject: Future Python Gui? Message-ID: <1176859699.906386.326720@b75g2000hsg.googlegroups.com> I've been trying to find out what the future of Python is with regard to Tk. It seems there are several interfaces that make use of new functionality, including "Tile" and "Ttk". If I want to write a program that will run under the standard Python distribution of the future, what extension module should I work with today? Thanks! -- Brian From steve at holdenweb.com Mon Apr 16 22:37:50 2007 From: steve at holdenweb.com (Steve Holden) Date: Mon, 16 Apr 2007 22:37:50 -0400 Subject: strange behaviour with keyword arguments and inheritance In-Reply-To: <1176775837.140883.287360@n76g2000hsh.googlegroups.com> References: <1176771364.964642.209300@b75g2000hsg.googlegroups.com> <1176773781.729037.139650@y5g2000hsa.googlegroups.com> <1176775837.140883.287360@n76g2000hsh.googlegroups.com> Message-ID: Jun.Jin.act+group.python at gmail.com wrote: > On Apr 17, 9:36 am, livibetter wrote: >> On Apr 17, 8:56 am, "matthewperpick" wrote: >> >>> Check out this toy example that demonstrates some "strange" behaviour >>> with keyword arguments and inheritance. >>> ================================= >>> class Parent: >>> def __init__(self, ary = []): >>> self.ary = ary >> This should work: >> >> class Parent: >> def __init__(self, ary = []): >> self.ary = list(ary) >> >> And FYIhttp://groups.google.com/group/comp.lang.python/browse_thread/thread/... > > livibetter has a better solution. the reason is that you need to > create a new list object everytime, am I right? > Yes, specifically on every *call*. 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 adam at atlas.st Tue Apr 24 07:54:37 2007 From: adam at atlas.st (Adam Atlas) Date: 24 Apr 2007 04:54:37 -0700 Subject: Python for Vcard Parsing in UTF16 In-Reply-To: <132l7inssigkted@corp.supernews.com> References: <132l7inssigkted@corp.supernews.com> Message-ID: <1177415676.987577.162260@c18g2000prb.googlegroups.com> On Apr 21, 7:28 pm, R Wood wrote: > I know nothing about Python except that it interests me and has interested me > since I first learned the Rekall database frontend (Linux) runs on it. I just > ordered Learning Python and if that works out satisfactorily I'm going to go > back for Programming Python. In the meantime, I thought I would pose the > question to this newsgroup: would Python be useful for a parsing exercise like > this one? Here's a little function that takes some `str`-type data (i.e. what you'd get from doing open(...).read()) and, assuming it's a Vcard, detects its encoding and converts it to a canonical `unicode` object. def fix_encoding(s): m = u'BEGIN:VCARD' for c in ('ascii', 'utf_16_be', 'utf_16_le', 'utf_8'): try: u = unicode(s, c) except UnicodeDecodeError: continue if m in u: return u return None From apardon at forel.vub.ac.be Fri Apr 20 05:06:56 2007 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 20 Apr 2007 09:06:56 GMT Subject: Do other Python GUI toolkits require this? References: <462697A6.6010007@codebykevin.com> <1obf23tjhhpi8rotsuh0kde2ejf47p5k9l@4ax.com> Message-ID: On 2007-04-20, Roel Schroeven wrote: > Antoon Pardon schreef: >> On 2007-04-19, Wayne Brehaut wrote: >>> So the remark that " a steep learning curve means that the subject is >>> easily familiarized and that the learning period is short" is >>> completely incorrect on two points (i.e., all points that are >>> relevant): first, steep always implies much to learn in a relatively >>> short time (what else could the slope of a curve possibly mean >>> "mathematicallY" or logically?); >> >> No it doesn't imply that at all. A learning curve doesn't show some >> goal of a person who was given just so much time to familiarize himself >> with some material. A learning curve shows the progres that is made >> in familiarizing one self while studying. A steep curve means a >> lot of actual learning in a short time. > > >> A learning curve is conventionally the graph of a function of > >> "quantity to be learned" vs. time, > > > No it doesn't. A learning curve is the graph that somehow quantifies > > what is actually learned vs time. > > Do you have any reference to back that up? http://en.wikipedia.org/wiki/Experience_curve_effects Where you will also learn that learning curves by what values are generally plotted go downwards. -- Antoon Pardon From jzgoda at o2.usun.pl Tue Apr 10 16:23:21 2007 From: jzgoda at o2.usun.pl (Jarek Zgoda) Date: Tue, 10 Apr 2007 22:23:21 +0200 Subject: About Trolltech QT OpenSource license. In-Reply-To: <1176233376.712861.67160@o5g2000hsb.googlegroups.com> References: <1176233376.712861.67160@o5g2000hsb.googlegroups.com> Message-ID: king kikapu napisa?(a): > I saw at the forum here that a lot of debate is coming from the > "strange" interpretation of it's Open Source Edition lisence. > After a lot of reading i was under the impression (and many others > with me) that even a stand alone developer working in-house at company > cannot use Qt OS Edition and must buy the commercial lisence. This is a bullsh*t. Qt is free (as in "free speech") on GPL. Nothing stops you from using it in any commercial project if only it fits the licensing terms (i.o.w. it's free software). This specially applies to inhouse development, as in such case there's no "distribution". > I sent an emai to them today and i think their response is > interesting, so i appose it here; > > ##################################################### > Thank you for your inquiry regarding the Qt Open Source Edition. > > The open source edition may be used for either your own private use or > for an application used only internally by your company if the > application is developed by you on company time. With internal > company use under the GPL it is absolutely imperative that the > application not be distributed outside of the legal entity. If this > happens then the GPL source distribution requirements (as well as all > other GPL > requirements) will take effect. The internal use by the company falls > under the "private modification" exception to the GPL. > > Please note that if you begin your application development with the > GPL version, that application must be GPL licensed and Trolltech does > not permit developers to start with the Qt Open Source Edition and > later convert to a commercial license. > > Good luck with your development and please contact sales at trolltech.com > if your company wishes to purchase a commercial Qt license at some > point in the future. Hey, there's no such statement here. Where did you get this "must buy the commercial lisence"? Plus, this (sales)person forgot to state clearly, that GPL covers only distribution, not the cost of software. If you manage to get some hot cash for selling sources of your GPL-ed program, the license would not try to stop you from doing that. ;) -- Jarek Zgoda http://jpa.berlios.de/ From jackson at hotmail.com Fri Apr 27 15:51:14 2007 From: jackson at hotmail.com (Bill Jackson) Date: Fri, 27 Apr 2007 12:51:14 -0700 Subject: Import Problems In-Reply-To: References: Message-ID: Bill Jackson wrote the following on 04/27/2007 12:49 PM: > # importtest/test2/__init__.py > from someclass import * > from test2 import * Sorry typo here: # importtest/test2/__init__.py from someclass import * from mytest import * From oliphant.travis at ieee.org Mon Apr 9 13:08:28 2007 From: oliphant.travis at ieee.org (Travis Oliphant) Date: Mon, 09 Apr 2007 11:08:28 -0600 Subject: Database in memory In-Reply-To: <1176124752.172926.129850@w1g2000hsg.googlegroups.com> References: <1176124752.172926.129850@w1g2000hsg.googlegroups.com> Message-ID: Jim wrote: > I have an application that will maintain an in-memory database in the > form of a list of lists. Does anyone know of a way to search for and > retreive "records" from such a structure? > Actually, the new NumPy can work as a very-good fast and efficient simple in-memory database (or memory-mapped data-base for that matter). The elements of a NumPy array can be arbitrary records. You would search using logical combinations of comparision. I think the ability for NumPy (which now handles arbitrary records) to be used as a data-base is under-appreciated. Mind you, it is SQL-less. NumPy only provides the "tables" it does not provide the fancy logic on-top of the tables. So, perhaps it would be better to say that NumPy could serve as the foundation for a simple data-base application. -Travis From grante at visi.com Wed Apr 25 17:48:15 2007 From: grante at visi.com (Grant Edwards) Date: Wed, 25 Apr 2007 21:48:15 -0000 Subject: Controlling gnuplot via subprocess.Popen References: <599hu0F2k8k1qU1@mid.uni-berlin.de> Message-ID: <132vj4vk6n74v21@corp.supernews.com> On 2007-04-25, Peter Beattie wrote: > I am trying to plot something in gnuplot 4.2 using co-ordinates a Python > 2.5 program computes. Here's what I'm doing: > > py> from subprocess import * > py> plot = Popen("c:/progs/gp/bin/wgnuplot.exe", stdin=PIPE) > py> plot.stdin.write("plot x*x") > > The first command dutifully opens gnuplot, but the second doesn't do > anything. Could someone favour me with an explanation as to the whyness? wgnuplot.exe doesn't read commands from stdin. However, pgnuplot.exe does (that's why it exists). It's probably easier to just use the gnuplot-py module: http://gnuplot-py.sourceforge.net/ The "released" 1.7 version still uses Numeric. I believe that it's been converted over to numpy, so if you prefer numpy over Numeric, you can grab an SVN snapshot. -- Grant Edwards grante Yow! My face is new, my at license is expired, and I'm visi.com under a doctor's care!!!! From fdemmer at gmail.com Thu Apr 26 10:29:57 2007 From: fdemmer at gmail.com (Florian Demmer) Date: 26 Apr 2007 07:29:57 -0700 Subject: Interrupting ftplib.storbinary() Message-ID: <1177597797.296812.226620@t39g2000prd.googlegroups.com> Hi! I have a number of ftp uploads running in parallel using ftplib.storbinary and threading and in case one of them fails I need to interrupt all the others (but not exit the program completely)... do you guys have an idea how i could implement the interruption as cleanly as possible? thanks! From bbxx789_05ss at yahoo.com Mon Apr 16 04:18:27 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: 16 Apr 2007 01:18:27 -0700 Subject: pyparsing Catch-22 In-Reply-To: <1176696704.924584.75720@e65g2000hsc.googlegroups.com> References: <1176686782.270354.164630@l77g2000hsb.googlegroups.com> <1176696704.924584.75720@e65g2000hsc.googlegroups.com> Message-ID: <1176711506.989627.282880@o5g2000hsb.googlegroups.com> Basic Pyparsing Words and Literals From Karsten.G.Weinert at googlemail.com Fri Apr 27 17:10:42 2007 From: Karsten.G.Weinert at googlemail.com (Karsten.G.Weinert at googlemail.com) Date: 27 Apr 2007 14:10:42 -0700 Subject: Cgi File Upload without Form Message-ID: <1177708242.553577.226530@n15g2000prd.googlegroups.com> Hello, what is the simplest way to upload a file (or a long string) to a server using cgi/python? Since I want to upload the data programmatically, a form based solution is not good. I am not experienced with SOAP/WSDL and I believe that would be more difficult than necessary. The client program I have to use does not support FTP. Any hint appreciated, kind regards, Karsten. From elicriffield at gmail.com Tue Apr 10 17:43:40 2007 From: elicriffield at gmail.com (Eli Criffield) Date: 10 Apr 2007 14:43:40 -0700 Subject: XML-RPC SSL and client side certs? Message-ID: <1176241420.420028.276030@y5g2000hsa.googlegroups.com> Does anyone have an example setup of a XML-RPC sever using client side certs for authentication? And instead of having a list of certs allowed to connect, I'd like to allow any cert signed by my CA. It doesn't seem like it would be to hard to do and I'll probably spend some time setting it up here soon, but would be interested if anyone else has already written a solution like this or has used one (in python of course). Eli Criffield From joshua at eeinternet.com Wed Apr 11 14:30:43 2007 From: joshua at eeinternet.com (Joshua J. Kugler) Date: Wed, 11 Apr 2007 10:30:43 -0800 Subject: About Trolltech QT OpenSource license. References: <1176233376.712861.67160@o5g2000hsb.googlegroups.com> <1176237050.409742.8760@30g2000cwc.googlegroups.com> Message-ID: <461d1ce8$0$16403$88260bb3@free.teranews.com> On Tuesday 10 April 2007 12:52, Kevin Walzer wrote: > Yes. Nothing in the GPL prevents you from developing and marketing an > application for as high a price as you can get from it. > > HOWEVER: > > you will have to distribute the source code to your application to > anyone who purchases a binary from you. > > AND: > > they will be permitted under the GPL to redistribute your application, > source code and all. The GPL would allow them to buy your application > from you and then redistribute it at no cost to others. To add to the train of thought: While anyone who buys your GPL program (and acquires the source) will be able to distribute copies of the source code to MyGreatProgram, you can via *trademark law* (COMPLETELY different area than copyright law) prevent them from calling it MyGreatProgram, or even from saying publically "This program is just like MyGreatProgram." A name can be owned (proprietary, if you will), even if the software itself is under the GPL. Alfresco and MySQL are under the GPL, but if you made massive (or any?) modifications to the source code, or wrote your own versions from the ground up, and then tried to distribute them as Alfresco or MySQL, I think you would hear from their lawyers. :) I hope that doesn't add to the confusion, but provides further clarification. 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 kwatch at gmail.com Mon Apr 30 22:42:32 2007 From: kwatch at gmail.com (kwatch) Date: 30 Apr 2007 19:42:32 -0700 Subject: module name available in 'from ... import ...' statement In-Reply-To: References: <1177975194.782804.155070@n76g2000hsh.googlegroups.com> Message-ID: <1177987352.377652.147240@c35g2000hsg.googlegroups.com> Thanks Carsten and Gabriel, the answer is 'sys.modules'. ---------------------------------------- import sys, os from path import sep # ImportError: No module named path sys.modules['path'] = os.path from path import sep # (no error) ---------------------------------------- I can now import from my module which is generated by 'new' module. ---------------------------------------- # create a module import new foo = new.module('foo') foo.pi = 3.14159 foo.x2 = lambda x: 2*x # register it to sys.modules import sys sys.modules['foo'] = foo # import from that module from foo import pi, x2 ---------------------------------------- Great. > Not that this can't be done, but why do you think you have to create > this 'foo' module on the fly? What is the actual problem you're trying > to solve? I have a package which has several small modules and I want to integrate them into a file, with keeping compatibility. current: mylib/ __init__.py html.py xhtml.py xml.py : : future: mylib.py -- regards, kwatch "Gabriel Genellina" wrote: > En Mon, 30 Apr 2007 20:19:54 -0300,kwatch escribi?: > > > Could you teach me the condition of module name which is available > > in 'from ... import ...' statement? > > > The goal what I want to do is to create a module by 'new' module > > and specify that module name in 'from ...' statement. > > You can create the module with imp.new_module, populate it, and then > insert it inside sys.modules: > > py> from imp import * > py> m = new_module("foo") > py> m > > py> m.a = 1 > py> def test(): > ... print "Function test inside foo module" > ... > py> m.test = test > py> import sys > py> sys.modules["foo"]=m > py> m > > py> foo > Traceback (most recent call last): > File "", line 1, in > NameError: name 'foo' is not defined > py> import foo > py> foo.test() > Function test inside foo module > > But, why do you want to do this exactly? > > -- > Gabriel Genellina From acb at uchicago.edu Sun Apr 22 22:27:47 2007 From: acb at uchicago.edu (Aaron Brady) Date: Sun, 22 Apr 2007 21:27:47 -0500 Subject: inspect.getblock() Message-ID: inspect.getblock() seems to halt prematurely. This code only prints 6 lines of the 12 line input file. assume it's by design, but the docs don't mention getblock. docstring is "Extract the block of code at the top of the given list of lines," which should be "code *from* the top." ###whatiscompile2.py import inspect r = open('thebogusfile.txt').read() code = compile( r, 'thebogusfile.txt', 'exec' ) exec code print '***' print inspect.getsource(code) ###thebogusfile.txt def f(a, b): print a, print b, c = a + b print c, return a + b def g(): print 'g' print f( 3, 4 ), g() ###stdout 3 4 7 7 g *** def f(a, b): print a, print b, c = a + b print c, return a + b -------------- next part -------------- def f(a, b): print a, print b, c = a + b print c, return a + b def g(): print 'g' print f( 3, 4 ), g() -------------- next part -------------- import inspect r = open('the bogus file.txt').read() code = compile( r, 'the bogus file.txt', 'exec' ) exec code print '***' print inspect.getsource(code) From spamtrap at dot-app.org Wed Apr 25 20:34:06 2007 From: spamtrap at dot-app.org (Sherm Pendley) Date: Wed, 25 Apr 2007 20:34:06 -0400 Subject: bitwise shift? References: <462FEE8B.2030701@lexicon.net> Message-ID: John Machin writes: > On 26/04/2007 7:10 AM, Sherm Pendley wrote: > >> Shift left is *not* the same as multiplying by k. It is the same as multi- >> plying by 2^k. > > Where I come from, ^ is the exclusive-or operator. Of course YMMV in WV :-) Make that YMMV in VB. :-( Funny thing is, I haven't written in VB since '95 or thereabouts. Let that be a lesson for the youngsters - touch not the unclean beast called VB, lest its vileness stain thy code for all time! sherm-- -- Web Hosting by West Virginians, for West Virginians: http://wv-www.net Cocoa programming in Perl: http://camelbones.sourceforge.net From wswilson at gmail.com Wed Apr 11 10:48:57 2007 From: wswilson at gmail.com (wswilson) Date: 11 Apr 2007 07:48:57 -0700 Subject: passing class by reference does not work?? In-Reply-To: <1hweafl.1ddq337v3ylmtN%aleax@mac.com> References: <1176301439.769248.247720@y5g2000hsa.googlegroups.com> <1hweafl.1ddq337v3ylmtN%aleax@mac.com> Message-ID: <1176302937.627362.263820@q75g2000hsh.googlegroups.com> On Apr 11, 10:40 am, a... at mac.com (Alex Martelli) wrote: > wswilson wrote: > > Here is my code: > > > class A(): > > val = 0 > > > def b(item, a): > > a.val = a.val + 1 > > return item + a.val > > > def c(): > > d = [1, 2, 3] > > print [b(item, A()) for item in d] > > > c() > > > I expected this to output [2, 4, 6]. However, it outputs [2, 3, 4] > > which is not what I wanted. I thought that if I passed the A() > > instance in my list comprehension in c(), then the changes I made to > > a.val in b() would be reflected in the A() instance next time the list > > comprehension called b(). But, obviously that is not happening. I'm > > kinda new at python so I may be missing something obvious here. > > Yep: > > a.val = a.val + 1 > > sets in INSTANCE variable a the value computed on the RHS. A.val (the > CLASS variable) is never changed. You're not "passing the class", of > course, but rather an instance of the class. > > To increment A.val, you need to assign to the class variable, or write > some method in class A which assigns to the class variable. If you > want, you can change class A only, leaving all of the rest of your code > untouched, with a property (but then A needs to be newstile), e.g.: > > class A(object): > _val = 0 > def getval(self): return A._val > def setval(self, value): A._val = value > val = property(getval, setval) > > now your code should work as intended: any read access to a.val returns > A._val, and any setting of a.val actually sets A._val, as you appear to > desire. > > Alex Thanks, that should work well. I appreciate it. From donn at u.washington.edu Mon Apr 16 12:42:16 2007 From: donn at u.washington.edu (Donn Cave) Date: Mon, 16 Apr 2007 09:42:16 -0700 Subject: tuples, index method, Python's design References: Message-ID: In article , "Hendrik van Rooyen" wrote: > "Donn Cave" wrote: > > > > > Well, yes - consider for example the "tm" tuple returned > > from time.localtime() - it's all integers, but heterogeneous > > as could be - tm[0] is Year, tm[1] is Month, etc., and it > > turns out that not one of them is alike. The point is exactly > > that we can't discover these differences from the items itself - > > so it isn't about Python types - but rather from the position > > of the item in the struct/tuple. (For the person who is about > > to write to me that localtime() doesn't exactly return a tuple: QED) > > This is the point where the whole thing falls apart in my head and > I get real confused - I can't find a reason why, list or tuple, the first > item can't be something, the second something else, etc... Of course, you may do what you like. Don't forget, though, that there's no "index" method for a tuple. Donn Cave, donn at u.washington.edu From robert.rawlins at thinkbluemedia.co.uk Mon Apr 16 09:20:42 2007 From: robert.rawlins at thinkbluemedia.co.uk (Robert Rawlins - Think Blue) Date: Mon, 16 Apr 2007 14:20:42 +0100 Subject: Writing Log CSV (Efficiently) Message-ID: <000c01c7802a$08e42660$1aac7320$@rawlins@thinkbluemedia.co.uk> Hello Guys, I'm looking to write a Log file which will be CSV based, and there is a good possibility that it'll get quite busy once its up and running, so I'm looking for the most efficient way to achieve it. Whilst I'm sure i could do something like this. myfile = open("Logs/Application.txt", "w") myfile.write('col1, col2, col3, col4, col5') myfile.close But I'm a little apprehensive that open() and close() on a very regular basis is just going to cause issues. I'm also a little worried that we'll end up with 'race' type conditions and things going missing. So my next thought was to just have an open object for the file, and then perform multiple rights, until I need to send the report file somewhere else, at which point I would close it. This in itself causes more issues as we're running in a buffer which is just going to eat my memory, and as this is on an embedded system which may lose power, we'd be kissing good bye to all the logs until that point. What would you guys suggest to be the most efficient way to handle this? Thanks, Rob -------------- next part -------------- An HTML attachment was scrubbed... URL: From __peter__ at web.de Fri Apr 6 02:29:25 2007 From: __peter__ at web.de (Peter Otten) Date: Fri, 06 Apr 2007 08:29:25 +0200 Subject: Looping issues References: <1175796069.501575.157410@w1g2000hsg.googlegroups.com> <7dWdnYepWOY6oojbnZ2dnUVZ_ompnZ2d@comcast.com> Message-ID: Larry Bates wrote: > If the files aren't terribly large (not tested): > > correct_lines=open(r"C:\Python25\Scripts\Output" \ > ????????????????????"\correct_settings.txt",?"r").readlines() > > current_lines=open(r"C:\Python25\Scripts\Output\output.txt", > ????????????????????"r").readlines() > > for line in current_settings: > ????if?line?in?correct_lines: > ????????print?line?+?"?found" You only have to read the "inner" file into memory, and a set is more efficient than a list here: current_settings = open(...) correct_settings = set(open(...)) for line in current_settings: if line in correct_settings: print line.rstrip(), "found" Of course your suggestion of difflib is spot-on. Peter From henriklied at gmail.com Thu Apr 5 17:19:56 2007 From: henriklied at gmail.com (Henrik Lied) Date: 5 Apr 2007 14:19:56 -0700 Subject: Problems with os.spawnv Message-ID: <1175807996.524018.146070@n76g2000hsh.googlegroups.com> Hi there! I'm trying to convert a video in a background process. The scenario I'm after: 1. The user uploads a video 2. The video is saved in my media directory, and the database is populated with the references 3. The video gets converted to FLV - but the user shouldn't have to wait around for this to happen So, I thought to myself that spawnv would be a good fit for this. The problem is that it doesn't fire of the command. Here's my test script: http://dpaste.com/hold/7981/ Why won't this work? The while-loop is printed, but the os command isn't executed. I've also tried to specify the whole path to mencoder (/opt/local/bin/mencoder), but to no use. From steve at REMOVE.THIS.cybersource.com.au Wed Apr 11 10:58:53 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Thu, 12 Apr 2007 00:58:53 +1000 Subject: tuples, index method, Python's design References: <1175867771.114540.61810@n76g2000hsh.googlegroups.com> <1175884427.779950.267220@y80g2000hsf.googlegroups.com> <1175953520.316208.241490@o5g2000hsb.googlegroups.com> <7xzm5igbrb.fsf@ruckus.brouhaha.com> <1176200361.260546.280510@n76g2000hsh.googlegroups.com> <1176214831.3430.49.camel@dot.uniqsys.com> Message-ID: On Wed, 11 Apr 2007 13:13:20 +0000, Antoon Pardon wrote: >> Lists are designed for sequences of homogeneous items, e.g.: >> >> L = [1, 2, 4, 8, 16, 32] >> while tuples are designed to be more like structs or records, with >> heterogeneous items, e.g.: >> >> T = ("Fred", 32, 12.789, {}, None, '\t') > > I think you are confused. Anything is possible. > Last time I heard this homogeneous items stuf, > it had nothing to do with the types being the same. They were homogeneous > because they somehow belonged together and heterogeneous because they > just happened to live together. Similarity of type played no part in > calling the data homogeneous or heterogeneous. Nevertheless, regardless of whether the items have the same type or different types, you don't need an index method for heterogeneous items. Like I said, think of a tuple as a struct. Even if the fields of the struct all have the same type, there is little reason to ever ask "which field has such-and-such a value?". Anyway, that's was the reasoning. As I've said, tuples do double-duty as both immutable lists and struct-like objects. I wouldn't object to them growing index and count methods -- but you won't see me volunteering to write the code for that, because I don't care that much. So how about it? All you people who desperately want tuples to grow an index method -- will any of you donate your time to write and maintain the code? -- Steven. From gagsl-py2 at yahoo.com.ar Thu Apr 5 02:51:38 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 05 Apr 2007 03:51:38 -0300 Subject: problem with my urllib.urlopen() function References: Message-ID: En Thu, 05 Apr 2007 02:40:38 -0300, Xell Zhang escribi?: > hello all, > I am a newbie in Python. > In my module, if I call urllib.urlopen() function like: > url = "http://www.google.com/" > source = urllib.urlopen(url) > > Then in the output there will be an exception: > Exception exceptions.AttributeError: "'NoneType' object has no attribute > 'print_exc'" in urllib.FancyURLopener instance at 0x00D59AA8>> ignored > > > I do not know why, if I did something wrong? It works OK for me (I don't get any exception). Such messages happen when any __del__ method raises any exception; it can't be handled normally so Python just logs the error on the console. Can you provide a complete and small example showing the problem? -- Gabriel Genellina From gdonald at gmail.com Thu Apr 5 17:48:27 2007 From: gdonald at gmail.com (Greg Donald) Date: Thu, 5 Apr 2007 16:48:27 -0500 Subject: ipython env Message-ID: <15e66e4e0704051448l3f4cb5cesead7ea356729671f@mail.gmail.com> Anyone know what's up with environment variables when using ipython? When I type 'env' and hit return I get a dictionary full of useful information (trimmed for brevity): In [1]: env Out[1]: {'EDITOR': '/usr/bin/vim', [...] '_': '/Library/Frameworks/Python.framework/Versions/Current/bin/ipython', '__CF_USER_TEXT_ENCODING': '0x1F5:0:0'} But then when try to access the information in the dictionary it doesn't seem to exist: In [2]: env['EDITOR'] --------------------------------------------------------------------------- exceptions.NameError Traceback (most recent call last) /Users/destiney/ NameError: name 'env' is not defined Thanks, -- Greg Donald http://destiney.com/ From steve at REMOVE.THIS.cybersource.com.au Thu Apr 26 19:40:35 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Fri, 27 Apr 2007 09:40:35 +1000 Subject: My python annoyances so far References: <1177541453.471959.120830@c18g2000prb.googlegroups.com> <59bf34F2k27v5U1@mid.individual.net> <1177603623.774892.230390@t38g2000prd.googlegroups.com> Message-ID: On Thu, 26 Apr 2007 10:45:22 -0700, Steven Howe wrote: > flifus at gmail.com wrote: >>> Well, why do some things in the library have to be functions, and >>> other things have to be class methods? >>> > Perhaps because some things are more naturally function like? For > 'instance' (pardon the pun), functions shouldn't retain data. They > perform an operation, return data and quit. Why ever not? How the function performs the operation is an implementation detail you shouldn't care about. Functions that cache the result of long time-consuming complications are _good_. You might also consider generators and iterators and co-routines. None of those could exist if functions couldn't store data. [snip] > Another example are with respect to 'int' and 'float' operations. Why > should int(x) be a class? That's a terrible example, because in fact int and float _are_ classes (actually types, which are conceptually the same as classes but implemented differently). -- Steven. From myheartinamerica at gmail.com Mon Apr 16 13:21:32 2007 From: myheartinamerica at gmail.com (myheartinamerica) Date: 16 Apr 2007 10:21:32 -0700 Subject: swig win32 scons In-Reply-To: <1176743478.092658.24540@l77g2000hsb.googlegroups.com> References: <1176743478.092658.24540@l77g2000hsb.googlegroups.com> Message-ID: <1176744092.185130.208230@q75g2000hsh.googlegroups.com> It turns out I didn't need the DEF file for exports. From mansonmuni at alexandria.cc Wed Apr 18 18:50:14 2007 From: mansonmuni at alexandria.cc (Glen) Date: Wed, 18 Apr 2007 22:50:14 GMT Subject: Beginner: Formatting text output (PyQt4) Message-ID: Hello again, I don't blame anyone for not answering my last post, since I obviously hadn't spent much time researching, but I've come a little ways and have another question. How can I better format text output to a QTextEdit object? I'm inserting 5 columns into each row. When I write the info to a file, it looks like the following: 42: 115 26: 114 35: 112 19: 108 16: 107 45: 107 40: 106 5: 105 41: 104 2: 103 9: 102 48: 102 15: 101 22: 101 27: 101 39: 101 43: 101 10: 100 6: 99 34: 99 32: 98 49: 98 20: 97 30: 97 8: 96 17: 96 38: 96 12: 95 14: 95 37: 95 4: 94 13: 94 44: 94 36: 93 3: 92 24: 92 28: 92 31: 91 29: 89 7: 88 1: 87 18: 85 46: 85 33: 84 11: 83 23: 83 47: 82 25: 80 21: 79 50: 56 52: 39 51: 38 53: 36 54: 25 55: 18 When I write the contents of the file to my TextEdit object it comes out uneven, something like this: 42: 115 26: 114 35: 112 19: 108 16: 107 45: 107 40: 106 5: 105 41: 104 2: 103 9: 102 48: 102 15: 101 22: 101 27: 101 39: 101 43: 101 10: 100 6: 99 34: 99 32: 98 49: 98 20: 97 30: 97 8: 96 17: 96 38: 96 12: 95 14: 95 37: 95 4: 94 13: 94 44: 94 36: 93 3: 92 24: 92 28: 92 31: 91 29: 89 7: 88 1: 87 18: 85 46: 85 33: 84 11: 83 23: 83 47: 82 25: 80 21: 79 50: 56 52: 39 51: 38 53: 36 54: 25 55: 18 What seems to be happening is that the font that pyqt is using is not fixed width, so I did this: qTxtFormat = QTextCharFormat() qTxtFormat.setFontFixedPitch(True) ui.textEdit.setCurrentCharFormat(qTxtFormat) Also, I tried using the pyqt formatting such as the following: qStr = QtCore.QString( QtCore.QString( str(tL2[i][0]) ).rightJustified(2) + ':' + QtCore.QString( str(tL2[i][1]) ).rightJustified(4) ) This still gives me uneven columns. Any suggestions? Thanks, Glen From deets at nospam.web.de Sun Apr 15 06:47:58 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sun, 15 Apr 2007 12:47:58 +0200 Subject: OverflowError: mktime argument out of range ??? In-Reply-To: References: Message-ID: <58ee6vF2gtdc4U1@mid.uni-berlin.de> Jorgen Bodde schrieb: > Hi List > > I am working on an app to store guitar songs I am practicing, and for > the fun of it I want to store the date of songs when they were > originally made. So far so good.. > > However, my taste of music is "Rag Time Blues" and that os OLD, very > OLD music. So it happened I entered a song from the date " 28 dec > 1928". > > It appears time.mktime cannot handle these 'extremities' ? I get an > overflow error. is there by any chance a solution to this? I do know > modern languages support at least 1900 as date (and now that I come to > think of it, songs from J.S. Bach are excluded from entering as well) > .. > > This is what I try: > >>>> time.mktime((1928, 12,28, 0, 0, 0, 0, 0, 0)) > Traceback (most recent call last): > File "", line 1, in > OverflowError: mktime argument out of range > > The only solution I can think of is making a custom time class that > handles all years, dates and months, but that is plain silly. I want > to be able to use the long date formatting etc, and that would mean > rewriting that part as well. import datetime datetime.date(1928, 12, 28) Diez From johnjsal at NOSPAMgmail.com Fri Apr 13 16:26:05 2007 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Fri, 13 Apr 2007 16:26:05 -0400 Subject: Any way to refactor this? Message-ID: <461fe75c$0$11278$c3e8da3@news.astraweb.com> Setting aside, for the moment, the utility of this method or even if there's a better way, I'm wondering if this is an efficient way to do it. I admit, there was some copying and pasting, which is what prompts me to ask the question. Here's the method. (I hope it looks ok, because it looks really weird for me right now) def _create_3D_xhatches(): for x in xrange(-axis_length, axis_length + 1): if x == 0: continue visual.cylinder(pos=(x,-hatch_length,0), axis=(0,hatch_length*2,0), radius=hatch_radius) visual.cylinder(pos=(x,0,-hatch_length), axis=(0,0,hatch_length*2), radius=hatch_radius) visual.cylinder(pos=(-hatch_length,x,0), axis=(hatch_length*2,0,0), radius=hatch_radius) visual.cylinder(pos=(0,x,-hatch_length), axis=(0,0,hatch_length*2), radius=hatch_radius) visual.cylinder(pos=(-hatch_length,0,x), axis=(hatch_length*2,0,0), radius=hatch_radius) visual.cylinder(pos=(0,-hatch_length,x), axis=(0,hatch_length*2,0), radius=hatch_radius) Since each call to cylinder requires a slightly different format, I figured I had to do it this way. Thanks. From paul at boddie.org.uk Thu Apr 19 05:49:12 2007 From: paul at boddie.org.uk (Paul Boddie) Date: 19 Apr 2007 02:49:12 -0700 Subject: Compiling python from soruce vs RPM ? In-Reply-To: <1176950392.192425.90980@b58g2000hsg.googlegroups.com> References: <1176911689.026633.230390@l77g2000hsb.googlegroups.com> <1176934250.650536.239040@p77g2000hsh.googlegroups.com> <1176950392.192425.90980@b58g2000hsg.googlegroups.com> Message-ID: <1176976152.885919.139080@n76g2000hsh.googlegroups.com> On 19 Apr, 04:39, howa wrote: > > One more question: > > How to uninstall using the source package? > > the source package doesn't come with `make uninstall`? Right. That's another pitfall of most source distributions (ie. the Python sources from python.org) compared to system packages (ie. the package built from a source RPM or equivalent system source package). If you want a really quick solution to this which seems to work much of the time, look at checkinstall: http://asic-linux.com.mx/~izto/checkinstall/ This tool will make system packages by taking control of the usual build process, and you can then install and uninstall those system packages. Paul From jstroud at mbi.ucla.edu Wed Apr 4 04:13:20 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Wed, 04 Apr 2007 01:13:20 -0700 Subject: Tkinter, how to get a button's bg color In-Reply-To: References: <1175648943.553642.201330@y66g2000hsf.googlegroups.com> Message-ID: John McMonagle wrote: > upftftip at gmail.com wrote: >> I am new to Tkinter. Following an example, I executed the following: >> >> window = Tk() >> b = Button(window) >> b.configure(bg = '#FF00FF') >> b.grid(row = 0, column = 0) >> >> how can I later get the value of this button's background color? >> >> Thanks. >> > > b.cget('bg') > > Even more fun is b['bg'] James From sjmachin at lexicon.net Sat Apr 28 17:54:38 2007 From: sjmachin at lexicon.net (John Machin) Date: 28 Apr 2007 14:54:38 -0700 Subject: Platform-dependent module search order? In-Reply-To: References: <1177766565.118899.232620@e65g2000hsc.googlegroups.com> Message-ID: <1177797278.380434.145410@n59g2000hsh.googlegroups.com> On Apr 29, 5:04 am, "Theo v. Werkhoven" wrote: > The carbonbased lifeform John Machin inspired comp.lang.python with: > > > > > On Apr 28, 9:50 pm, "Theo v. Werkhoven" > werkhoven.nl.invalid> wrote: > >> Goodday, > > >> strg = array("B",octarray).tostring() > > > The above statement appears to be where the error manifests itself. > > Possibilities: (1) array is bound to a list (2) the result of > > array("B", octarray) has an attribute tostring which is bound to a > > list. Option (1) seems less implausible. I'd be replacing that line > > by: > > > print "octet %r, shift %r, array %r" % (octet, shift, array) > > array_b = array("B", octarray) > > print "array_b %r" % array_b > > print "array_b.tostring %r" % array_b.tostring > > strg = array_b.tostring() > > > You haven't shown us all of your code -- is array mentioned elsewhere? > > What other imports are you doing? Do you have a file called array.py > > in the offending directory? [I believe that this wouldn't matter, > > because builtin modules like array can't be overridden by a file-based > > module of the same name, but I could be wrong] > > Bingo! > #v+ > theo:/home/theo/Devel/Python $ ls array* > array.py array.pyc > > theo:/home/theo/Devel/Python $ cat array.py > #!/usr/bin/python > > import sys, os > > array = [14, 8765, 756, 5345, 98, 5634654, 234123, 9087, 58, 297, 7865] > num = 0 > > while 1: > try: > print num > num = num + array.pop() > except: > break > #v- > And that code produces the numbers I was seeing.. > > > What platform and what version of Python? > > $ python --version > Python 2.5 > > $ uname -srv > Linux 2.6.18.8-0.1-default #1 SMP Fri Mar 2 13:51:59 UTC 2007 Very interesting. My first reaction to Theo's posting was to make a confident declaration like Carsten did, but I couldn't simulate this behaviour on Windows with Python 2.5.1 (or 2.1.3 for that matter) and moreover the docs say: """ Details of the module searching and loading process are implementation and platform specific. It generally involves searching for a ``built- in'' module with the given name and then searching a list of locations given as sys.path. """ (from http://docs.python.org/ref/import.html) I'm now curious about the rationale for having/permitting such a difference. Here's what I get on Windows XP Pro SP2 with Python 2.5.1: 8<------------------------------------------- C:\junk>type array.py print "Gotcha!" C:\junk>type arrayimport.py import sys, pprint print 'sys.path:' pprint.pprint(sys.path) import array print 'array: %r' % array C:\junk>\python25\python arrayimport.py sys.path: ['C:\\junk', 'C:\\python25\\lib\\site-packages\\cheesecake-0.6.1-py2.5.egg', 'C:\\python25\\lib\\site-packages\\setuptools-0.6c5-py2.5.egg', 'C:\\python25\\python25.zip', 'C:\\python25\\DLLs', 'C:\\python25\\lib', 'C:\\python25\\lib\\plat-win', 'C:\\python25\\lib\\lib-tk', 'C:\\python25', 'C:\\python25\\lib\\site-packages'] array: 8<---------------------------------------------------------------------- From soren.skou.nielsen at gmail.com Mon Apr 30 05:47:32 2007 From: soren.skou.nielsen at gmail.com (Soren) Date: 30 Apr 2007 02:47:32 -0700 Subject: How do I parse a string to a tuple?? Message-ID: <1177926452.830059.269230@n59g2000hsh.googlegroups.com> Hi! I have a string that contains some text and newline characters. I want to parse the string so that the string just before a newline character goes in as an element in the tuple. ex: "text1 \n text2 \n text3 \n text4" --> (text1, text2, text3, text4) Is there an easy way to do this? Thanks!, Soren From jorgen.maillist at gmail.com Sun Apr 15 06:41:21 2007 From: jorgen.maillist at gmail.com (Jorgen Bodde) Date: Sun, 15 Apr 2007 12:41:21 +0200 Subject: OverflowError: mktime argument out of range ??? Message-ID: <11e49df10704150341p1a9056e7hfba36a523517fad3@mail.gmail.com> Hi List I am working on an app to store guitar songs I am practicing, and for the fun of it I want to store the date of songs when they were originally made. So far so good.. However, my taste of music is "Rag Time Blues" and that os OLD, very OLD music. So it happened I entered a song from the date " 28 dec 1928". It appears time.mktime cannot handle these 'extremities' ? I get an overflow error. is there by any chance a solution to this? I do know modern languages support at least 1900 as date (and now that I come to think of it, songs from J.S. Bach are excluded from entering as well) .. This is what I try: >>> time.mktime((1928, 12,28, 0, 0, 0, 0, 0, 0)) Traceback (most recent call last): File "", line 1, in OverflowError: mktime argument out of range The only solution I can think of is making a custom time class that handles all years, dates and months, but that is plain silly. I want to be able to use the long date formatting etc, and that would mean rewriting that part as well. Any help is appreciated! - Jorgen From vbr at email.cz Wed Apr 18 11:14:55 2007 From: vbr at email.cz (vbr at email.cz) Date: Wed, 18 Apr 2007 17:14:55 +0200 (CEST) Subject: =?us-ascii?Q?Re=3A=20Combinate=202=20lists=20to=20a=20dict=20=3F?= In-Reply-To: <1176908596.222474.33440@n76g2000hsh.googlegroups.com> Message-ID: <1421.3143-15822-1229766022-1176909295@email.cz> > Hi all. > > I have 2 lists, > a = [1,2,3] > b = ["ooo","aaa","ppp"] > > What is the fastest way to make a dict like {1:"ooo",2:"aaa", > 3:"ppp"} ? > > Thanx >>> dict(zip(a,b)) {1: 'ooo', 2: 'aaa', 3: 'ppp'} works for me, but not sure, if it is the fastest way; a, b have to be of the same length, otherwise the shorter is used. vbr From cor at clsnet.nl Sun Apr 15 19:57:13 2007 From: cor at clsnet.nl (Cor Gest) Date: 15 Apr 2007 23:57:13 +0000 Subject: is laziness a programer's virtue? References: <1176654319.273907.167280@q75g2000hsh.googlegroups.com> <1176678011.470381.261290@b75g2000hsg.googlegroups.com> Message-ID: <87bqhpjina.fsf@atthis.clsnet.nl> Some entity, AKA dbenson at eecs.wsu.edu, wrote this mindboggling stuff: (selectively-snipped-or-not-p) > Of course, for functional languages, 'lazy' means something rather > different... > lazy means: just get a post-grad to do the grunt-work for free. Cor -- The biggest problem LISP has is that it does not appeal to dumb people If this failed to satisfy you try reading the Hyper-Spec or woman frig (defvar MyComputer '((OS . "GNU/Emacs") (IPL . "GNU/Linux"))) Read the mailpolicy before mailing http://www.clsnet.nl/mail.html From carl at personnelware.com Thu Apr 26 19:41:07 2007 From: carl at personnelware.com (Carl K) Date: Thu, 26 Apr 2007 18:41:07 -0500 Subject: mysql "rows affected" Message-ID: <1bCdnU80YoYXpazbnZ2dnUVZ_gKdnZ2d@comcast.com> using MySQLdb, I do cursor.execute("update...") How can I tell how many rows were affected ? Carl K From Eric_Dexter at msn.com Tue Apr 10 08:37:50 2007 From: Eric_Dexter at msn.com (Eric_Dexter at msn.com) Date: 10 Apr 2007 05:37:50 -0700 Subject: pluie documentation in english In-Reply-To: <461b479a$0$27407$ba4acef3@news.orange.fr> References: <1176109628.413745.285120@n76g2000hsh.googlegroups.com> <1176114900.964184.46880@y80g2000hsf.googlegroups.com> <461b479a$0$27407$ba4acef3@news.orange.fr> Message-ID: <1176208670.469370.241330@w1g2000hsg.googlegroups.com> On Apr 10, 3:14 am, "M?ta-MCI" wrote: > Bonjour ! > > Avec Internet-Explorer 6 : > > Dans Internet-explorer, par le menu, faire : Outils + Options_internet > Aller sur le dernier onglet (Avanc?), et cocher : autoriser le contenu actif > > (d?sol? pour le fran?ais, mais mon anglais est vraiment trop mauvais). > > Et, merci pour l'info, ?a m'a permis d'ajouter un item ? la F.A.Q. > > @-salutations > -- > Michel Claveau with windows the .py files are executable as a link so that it doesn't have to comunicate with the program it can just hang out and be a web page.. I like the grid I was looking at is there a way to add lines after the web page has been created??? avec des fen?tres les dossiers de py sont ex?cutables comme lien de sorte qu'il pas ait d? comunicate avec le programme que ce peut juste tra?ner et ?tre une page Web. J'aime la grille que je regardais est l? une mani?re d'ajouter des lignes apr?s que la page Web ait ?t? cr??e ? ? ? .. From brenNOSPAMbarn at NObrenSPAMbarn.net Mon Apr 9 14:01:44 2007 From: brenNOSPAMbarn at NObrenSPAMbarn.net (OKB (not okblacke)) Date: Mon, 09 Apr 2007 18:01:44 GMT Subject: tuples, index method, Python's design References: <1175867771.114540.61810@n76g2000hsh.googlegroups.com> <1175884427.779950.267220@y80g2000hsf.googlegroups.com> <1175953520.316208.241490@o5g2000hsb.googlegroups.com> <7xzm5igbrb.fsf@ruckus.brouhaha.com> <7x8xd2iq53.fsf@ruckus.brouhaha.com> Message-ID: Carsten Haese wrote: > I won't presume to speak for Guido, but if I had to connect the > dots between "tuples are immutable" and "tuples will rarely need an > index method", I'd do it like this: Consider an object X and a > tuple T. Tuples have "X in T" tests, so you can check if there > exists some N such that T[N]==X. The lack of the index method means > you won't know the value of N, but what would knowing N give you? > You can't modify T, so all you can do is read T[N], but you already > know that that's going to return X, so you might as well just use > X. > > Any use case for actually having to know N would have to involve an > operation where you end up explicitly using an index other than N, > such as slicing T from 0 to N-1, or looking at T[2*N] or something > like that. Of course such operations might be useful, but > algorithms that need an operation like that would self-document > their design more clearly by using a list instead of a tuple. This is a reasonable argument, but all such arguments miss what I think is an important use case for tuples: you want a list, but you need to use it as a dictionary key. -- --OKB (not okblacke) Brendan Barnwell "Do not follow where the path may lead. Go, instead, where there is no path, and leave a trail." --author unknown From Martin.Drautzburg at web.de Sat Apr 21 16:16:56 2007 From: Martin.Drautzburg at web.de (Martin Drautzburg) Date: Sat, 21 Apr 2007 22:16:56 +0200 Subject: Namespaces/introspection: collecting sql strings for validation Message-ID: <1921780.hifcbgjtIO@beaureve.gmx.net> I would like to validate sql strings, which are spread all over the code, i.e. I run ("prepare") them against a database to see if it happy with the statements. Spelling errors in sql have been a major pain for me. The statements will not be assembled from smaller pieces, but they will not neccessarily be defined at module level. I could live with class level, but method level would be best. And I definitely don't want to parse the source file, but I am willing to mark the strings so it is easier to tell sql from non-sql. So the code will look like this class Foo:(...): def aQuery(...): stmt = """ -- checkSql select 1 from dual """ executeQuery() at the end of the file I would like to write something like if (...): validateSql() The validateSql() is the problem. It would be imported from elsewhere. and has to do some serious magic. It would have to lookup its caller's module, find all the classes (and methods, if we go that far) extract the constants, check if any of them are an SQL statement and validate it. The problem is the first part: how can I lookup the callers module and the classobjs defined in there? Or finding any constant strings in the caller's module would also be just fine. Or is there a completely different way to do such a thing? From rschroev_nospam_ml at fastmail.fm Sat Apr 21 09:54:05 2007 From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven) Date: Sat, 21 Apr 2007 13:54:05 GMT Subject: Do other Python GUI toolkits require this? (OT) In-Reply-To: References: <462697A6.6010007@codebykevin.com> <465B30B4-5BA0-459A-BE6F-1038874FA74B@jedimindworks.com> Message-ID: <1IoWh.132640$iW7.819313@phobos.telenet-ops.be> Hendrik van Rooyen schreef: > "Roel Schroeven" wrote: > >> Hendrik van Rooyen schreef: >>> "Steve Holden" wrote: >>> >>> >>>> Perhaps in Belgium they prefer climbing mountains over walking up and >>>> down gentle hills? >>> Mountains ? Hills ? In Belgium ?? >>> >>> Its not called the battlefield of Europe for nothing... >> I'm not sure if this adds anything of interest (well actually I'm pretty >> sure it doesn't), but our king Albert I was a fanatic mountain climber, >> until he died from a fall in 1934. >> > > Thanks - I was not aware of that. > Adds a whole new dimension to the phrase: > > "The Fall of a King" > > What was he climbing when he fell, btw? A rock in Marche-les-Dames, see the picture at http://nl.wikipedia.org/wiki/Afbeelding:Roy-m%C3%A5tche.jpg That's in the Walloon region; Flanders is of course much more flat than that. -- If I have been able to see further, it was only because I stood on the shoulders of giants. -- Isaac Newton Roel Schroeven From jura.grozni at gmail.com Fri Apr 13 15:54:08 2007 From: jura.grozni at gmail.com (azrael) Date: 13 Apr 2007 12:54:08 -0700 Subject: Python editor/IDE on Linux? In-Reply-To: Message-ID: <1176494048.627760.323630@p77g2000hsh.googlegroups.com> try wing ide. i tried it and i love it. it's available for windows as well for linux On Apr 13, 9:11 pm, Christoph Haas wrote: > On Fri, Apr 13, 2007 at 11:20:23AM -0700, Jack wrote: > > I wonder what everybody uses for Python editor/IDE on Linux? > > I use PyScripter on Windows, which is very good. Not sure if > > there's something handy like that on Linux. I need to do some > > development work on Linux and the distro I am using is Xubuntu. > > We should do a weekly poll. :) Seriously - this question is coming up > very frequently and everybody has their preference. > > Large list:http://wiki.python.org/moin/IntegratedDevelopmentEnvironments > > My (current) favorite: > pida (exists as a ready package on Debian as derivates like Xubuntu) > > pida because it embeds the 'vim' editor which I love and adds useful > features without really getting in my way. And it's the only IDE I found > that supports bazaar-ng (bzr) repositories. > > Christoph From rw at smsnet.pl Fri Apr 20 06:28:22 2007 From: rw at smsnet.pl (Rob Wolfe) Date: 20 Apr 2007 03:28:22 -0700 Subject: using tkinter to display html In-Reply-To: References: <1176988173.015892.273660@e65g2000hsc.googlegroups.com> Message-ID: <1177064902.230394.133830@d57g2000hsg.googlegroups.com> Stephen M. Gava wrote: > On Thu, 19 Apr 2007 06:09:33 -0700, kyosohma wrote: > > > On Apr 19, 6:29 am, "Stephen M. Gava" > > wrote: > >> Hi all, > >> > >> I prefer using tkinter to wxpython (so sue me :) and i need to display > >> a lot of html in a particular app. does anyone know if one of the > >> existing add on tk html widgets have been wrapped for tkinter already? > >> > >> TIA for any reply, > >> Stephen > > > > The following thread has various ideas in it: > > http://mail.python.org/pipermail/python-list/2001-October/107989.html > > thanks mike, i found that thread before i posted here, it doesn'rt answer > my question though. Why not? Did you try to use tkhtml [1]_ with python wrapper [2]_. IMHO it works pretty nice. .. [1] http://www.hwaci.com/sw/tkhtml/ .. [2] http://tix.sourceforge.net/Tixapps/src/Python/TkHtml.py -- HTH, Rob From bbxx789_05ss at yahoo.com Thu Apr 12 14:58:45 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: 12 Apr 2007 11:58:45 -0700 Subject: Calling private base methods In-Reply-To: References: <1176374675.347453.89340@n76g2000hsh.googlegroups.com> Message-ID: <1176404325.211501.26610@w1g2000hsg.googlegroups.com> On Apr 12, 5:04 am, Duncan Booth wrote: > "7stud" wrote: > > On Apr 12, 2:47 am, "Jorgen Bodde" wrote: > >> Is it possible to call a private base method? I come from a C++ > >> background, and I liked this construction as my base class has helper > >> methods so that I do not have to duplicate code. > > > I'd like to see some C++ code that does that! > > Easy: > > #define private public > #include > #undef private > > then call the private methods as much as you want. lol. I don't see any private methods being created there. From mail at microcorp.co.za Tue Apr 17 01:44:55 2007 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Tue, 17 Apr 2007 07:44:55 +0200 Subject: script for seconds in given month? References: <1176740556.859125.221980@l77g2000hsb.googlegroups.com> <1176744505.863580.182390@e65g2000hsc.googlegroups.com> Message-ID: <011801c780b3$878b40a0$03000080@hendrik> "Paul McGuire" wrote: > On Apr 16, 11:22 am, "edfialk" wrote: > > Hi, does anyone happen to know of a script that would return the > > number of seconds in a month if I give it a month and a year? > > > > My python is a little weak, but if anyone could offer some suggestions > > I think I could handle it myself, or if anyone happens to know of a > > script already written that performs this I would be extremely > > grateful. > > > > Thanks! > > -Ed > > Do you need to handle leap seconds too? (not a joke) > > -- Paul >From some assembler, here are some values. Stick them in a two dicts for normal and leap year. the first one is a cumulative table, I included it in case you can use it... ; SECONDS TABLES (LITTLE ENDIAN) MSECTAB_NORM: DB 080H,033H,0E1H,001H ;MONTH ZERO HAS FULL YEAR SECONDS DB 000H,000H,000H,000H ;JANUARY DB 080H,0DEH,028H,000H ;FEBRUARY DB 080H,0C8H,04DH,000H ;MARCH DB 000H,0A7H,076H,000H ;APRIL DB 000H,034H,09EH,000H ;MAY DB 080H,012H,0C7H,000H ;JUNE DB 080H,09FH,0EEH,000H ;JULY DB 000H,07EH,017H,001H ;AUGUST DB 080H,05CH,040H,001H ;SEPTEMBER DB 080H,0E9H,067H,001H ;OCTOBER DB 000H,0C8H,090H,001H ;NOVEMBER DB 000H,055H,0B8H,001H ;DECEMBER MSECTAB_LEAP: DB 000H,085H,0E2H,001H ;MONTH ZERO HAS FULL LEAP YEAR SECONDS DB 000H,000H,000H,000H ;JANUARY DB 080H,0DEH,028H,000H ;FEBRUARY DB 000H,01AH,04FH,000H ;MARCH DB 080H,0F8H,077H,000H ;APRIL DB 080H,085H,09FH,000H ;MAY DB 000H,064H,0C8H,000H ;JUNE DB 000H,0F1H,0EFH,000H ;JULY DB 080H,0CFH,018H,001H ;AUGUST DB 000H,0AEH,041H,001H ;SEPTEMBER DB 000H,03BH,069H,001H ;OCTOBER DB 080H,019H,092H,001H ;NOVEMBER DB 080H,0A6H,0B9H,001H ;DECEMBER ; NUMBER OF SECONDS IN MONTH (LITTLE ENDIAN) MSTAB_NORM: DB 000H,000H,000H,000H ;MONTH ZERO HAS NO SECONDS DB 080H,0DEH,028H,000H ;JANUARY DB 000H,0EAH,024H,000H ;FEBRUARY DB 080H,0DEH,028H,000H ;MARCH DB 000H,08DH,027H,000H ;APRIL DB 080H,0DEH,028H,000H ;MAY DB 000H,08DH,027H,000H ;JUNE DB 080H,0DEH,028H,000H ;JULY DB 080H,0DEH,028H,000H ;AUGUST DB 000H,08DH,027H,000H ;SEPTEMBER DB 080H,0DEH,028H,000H ;OCTOBER DB 000H,08DH,027H,000H ;NOVEMBER DB 080H,0DEH,028H,000H ;DECEMBER MSTAB_LEAP: DB 000H,000H,000H,000H ;MONTH ZERO HAS NO SECONDS DB 080H,0DEH,028H,000H ;JANUARY DB 080H,03BH,026H,000H ;FEBRUARY DB 080H,0DEH,028H,000H ;MARCH DB 000H,08DH,027H,000H ;APRIL DB 080H,0DEH,028H,000H ;MAY DB 000H,08DH,027H,000H ;JUNE DB 080H,0DEH,028H,000H ;JULY DB 080H,0DEH,028H,000H ;AUGUST DB 000H,08DH,027H,000H ;SEPTEMBER DB 080H,0DEH,028H,000H ;OCTOBER DB 000H,08DH,027H,000H ;NOVEMBER DB 080H,0DEH,028H,000H ;DECEMBER ; ***************************************************************** hth - Hendrik From bj_666 at gmx.net Mon Apr 30 13:49:43 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Mon, 30 Apr 2007 19:49:43 +0200 Subject: regexp match string with word1 and not word2 References: <1177920984.247487.54620@c35g2000hsg.googlegroups.com> <1177946458.620210.68690@u30g2000hsc.googlegroups.com> Message-ID: In <1177946458.620210.68690 at u30g2000hsc.googlegroups.com>, Flyzone wrote: > for y in range(0, len(skip_lst) ): > if (re.search(skip_lst[y], line)): > skip=1 > break Please try to avoid unnecessary indexes:: for regexp in skip_list: if re.search(regexp, line): skip = True break And if you don't intent to count the `skip`\s a `True` seems to be more readable. Ciao, Marc 'BlackJack' Rintsch From timr at probo.com Wed Apr 4 03:11:33 2007 From: timr at probo.com (Tim Roberts) Date: Wed, 04 Apr 2007 07:11:33 GMT Subject: way to extract only the message from pop3 References: <1175628970.874615.127020@y80g2000hsf.googlegroups.com> Message-ID: "flit" wrote: > >Using poplib in python I can extract only the headers using the .top, >there is a way to extract only the message text without the headers? Only by using Python code. The other responses gave you good pointers toward that path, but I thought I would point out the reason why. The POP3 protocol is surprisingly primitive. There are only two commands to fetch a message: RETR, which fetches the headers and the entire message, and TOP, which fetches the headers and the first N lines of the message. The key point is that both commands fetch the headers. -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From kyosohma at gmail.com Mon Apr 30 09:33:18 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: 30 Apr 2007 06:33:18 -0700 Subject: Reading From an Excel Sheet In-Reply-To: <1177921521.652523.35850@e65g2000hsc.googlegroups.com> References: <1177921521.652523.35850@e65g2000hsc.googlegroups.com> Message-ID: <1177939998.157392.31230@y5g2000hsa.googlegroups.com> On Apr 30, 3:25 am, sagar wrote: > Hi all, > I want to write a python script which reads in data from the > excel sheet .Can any one help out in this ...any help will be > appreciated. > > Thanks in Advance > Sagar Meesala "Core Python Programming" by Chun and "Python Programming on Win32" by Hammond & Robinson both have sections on interfacing with MS Office and COM objects. Both are good references to boot. Mike From rNOSPAMon at flownet.com Sun Apr 22 12:31:52 2007 From: rNOSPAMon at flownet.com (Ron Garret) Date: Sun, 22 Apr 2007 09:31:52 -0700 Subject: Select weirdness References: <462b3e47$0$326$e4fe514c@news.xs4all.nl> Message-ID: In article <462b3e47$0$326$e4fe514c at news.xs4all.nl>, Irmen de Jong wrote: > Ron Garret wrote: > > Here's my code. It's a teeny weeny little HTTP server. (I'm not really > > trying to reinvent the wheel here. What I'm really doing is writing a > > dispatching proxy server, but this is the shortest way to illustrate the > > problem I'm having): > > > > from SocketServer import * > > from socket import * > > from select import select > > > > class myHandler(StreamRequestHandler): > > def handle(self): > > print '>>>>>>>>>>>' > > while 1: > > sl = select([self.rfile],[],[])[0] > > if sl: > > l = self.rfile.readline() > > if len(l)<3: break > > print l, > > pass > > pass > > print>>self.wfile, 'HTTP/1.0 200 OK' > > print>>self.wfile, 'Content-type: text/plain' > > print>>self.wfile > > print>>self.wfile, 'foo' > > self.rfile.close() > > self.wfile.close() > > print '<<<<<<<<<<<<' > > pass > > pass > > > You shouldn't use a select() of your own inside the handle method. > The socketserver takes care of that for you. I don't understand why socketserver calling select should matter. (And BTW, there are no calls to select in SocketServer.py. I'm using Python2.5.) > What you need to do is read the input from the socket until you've reached > the end-of-input marker. That marker is an empty line containing just "\r\n" > when dealing with HTTP GET requests. > > Any reason don't want to use the BasicHTTPServer that comes with Python? Yes, but it's a long story. What I'm really doing is writing a dispatching proxy. It reads the HTTP request and then redirects it to a number of different servers depending on the URL. The servers are all local and served off of unix sockets, not TCP sockets (which is why I can't just configure Apache to do this). The reason I'm running this weird configuration (in case you're wondering) is because this is a development machine and multiple copies of the same website run on it simultaneously. Each copy of the site runs a customized server to handle AJAX requests efficiently. > > Anyway, try the following instead: > That won't work for POST requests. rg From martin at v.loewis.de Thu Apr 26 04:49:58 2007 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Thu, 26 Apr 2007 10:49:58 +0200 Subject: Coding conventions for class names In-Reply-To: <1177492705.232244.312520@c18g2000prb.googlegroups.com> References: <1177492705.232244.312520@c18g2000prb.googlegroups.com> Message-ID: <463067B6.2020405@v.loewis.de> Kay Schluehr schrieb: > set, int, float, list, object,... > > Don't see any of the basic types following the capitalized word > convention for classes covered by PEP 08. These aren't classes, they are types. PEP 8 doesn't specify any convention for types; it is common to either apply the conventions for functions to them, or the conventions for classes. Regards, Martin From b.r.willems at gmail.com Sat Apr 14 12:46:15 2007 From: b.r.willems at gmail.com (Bart Willems) Date: Sat, 14 Apr 2007 12:46:15 -0400 Subject: Simple integer comparison problem In-Reply-To: References: Message-ID: > if points > 89 and points <= 100: > return "A" > elif points > 89 and points <= 89: > return "B" > elif points > 69 and points <= 79: > return "C" > elif points > 59 and points <= 69: > return "D" > else: > return "F" The previous posters already pointed out your int problem. However, the if-statement can be written with a lot less clutter: if points > 100: return "Illegal score" elif points > 89: return "A" elif points > 79: return "B" elif points > 69: return "C" elif points > 59: return "D" else: return "F" I have a feeling that there's a Python-solution that is shorter yet better readable, I just can't figure it out yet... From markscala at gmail.com Sun Apr 22 11:17:46 2007 From: markscala at gmail.com (markscala at gmail.com) Date: 22 Apr 2007 08:17:46 -0700 Subject: function minimization In-Reply-To: <1177250114.342886.160520@o5g2000hsb.googlegroups.com> References: <1177250114.342886.160520@o5g2000hsb.googlegroups.com> Message-ID: <1177255066.913792.158640@y5g2000hsa.googlegroups.com> On Apr 22, 9:55 am, "marksc... at gmail.com" wrote: In the meantime, I found mpfit, but this is not working with python2.5. Any advice? thanks From steveo at syslang.net Thu Apr 5 17:08:14 2007 From: steveo at syslang.net (Steven W. Orr) Date: Thu, 5 Apr 2007 17:08:14 -0400 (EDT) Subject: elementary tuple question. (sorry) Message-ID: I have a tuple that I got from struct.unpack. Now I want to pass the data from the returned tuple to struct.pack >>> fmt 'l 10l 11i h 4h c 47c 0l' >>>struct.pack(fmt, tup) Traceback (most recent call last): File "", line 1, in ? struct.error: required argument is not an integer What's the idiom to pass the data in tup? 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 aspineux at gmail.com Sun Apr 8 07:40:38 2007 From: aspineux at gmail.com (aspineux) Date: 8 Apr 2007 04:40:38 -0700 Subject: Nice "bug" to loose a contest In-Reply-To: <1176029528.528010.210230@n59g2000hsh.googlegroups.com> References: <1176029528.528010.210230@n59g2000hsh.googlegroups.com> Message-ID: <1176032438.921825.42730@b75g2000hsg.googlegroups.com> This code works like the python one, I dont use buffered stdio f... functions, but the more 'system call' read and write int main() { char buf[120]; int len; while (len=read(1, buf, sizeof(buf))) { write(1, buf, len); } return 0; } I dont understand what is appening, but you have to know their is a link between stdin and stdout in 'terminal mode', when you make a read on stdin, stdout is automatically flushed, this link disappears when onr is not liked to a terminal. This is to facilitate user input, to avoid to put a flush after each write, in fact before any user input. Hope someone else will give the trick On 8 avr, 12:52, "stdazi" wrote: > Hello, > > Yesterday, I was at a programming competition. We programmed on Linux > liveCD's and Python was one of the allowed languages (among C and > Java). I cared just about the algorithmic approach so I used Python. > One of the main rules is, that the code reads its standard input and > dumps the result on the standard output. Here happened my bigger > programming mistake ever - I used the following approach : > > ==== > import sys > print sys.stdout.readlines() # TYPO ! stdin != stdout > ==== > > So the WEIRD issue is, that it worked and, executing the following > code I get : > > ==== > azi at magicb0x ~ $ python la.py > test > test #2 > ['test \n', 'test #2\n'] > azi at magicb0x ~ $ > ==== > > Ok, as the algorithm worked perfectly, and all the test cases we were > given were positive, I've continued with the next problem, copy/ > pasting the above idiom... When they tested the code, they used file > redirection like : > > == > python la.py < /somefile > == > > And, my code resulted in no output/input (=> 0 points), which can be > proved here too : > > ==== > azi at magicb0x ~ $ python la.py < /etc/passwd > > === > > Some friend of mine told me that's the Unix way, (stdout can act like > stdin) so I tried some C code : > > === > 1 #include > 2 > 3 int main() { > 4 char buf[120]; > 5 while (fgets(buf, sizeof(buf), stdout) != NULL) { > 6 puts(buf); > 7 } > 8 return 0; > 9} > === > > The code returns with no delay, so I'm really wondering where is that > nice sys.{stdin,stdout} feature inplemented as pydoc doesn't mention > anything. I'd spot the mistake before submitting the problem solutions > if it was written in C :) > > Thanks! From aleax at mac.com Tue Apr 24 01:22:15 2007 From: aleax at mac.com (Alex Martelli) Date: Mon, 23 Apr 2007 22:22:15 -0700 Subject: Namespaces/introspection: collecting sql strings for validation References: <1921780.hifcbgjtIO@beaureve.gmx.net> <1177282603.660437.181440@e65g2000hsc.googlegroups.com> <3179196.dXgDsb4XXT@beaureve.gmx.net> Message-ID: <1hx1ndz.1qpn3e68xm47cN%aleax@mac.com> Martin Drautzburg wrote: > George Sakkis wrote: > > > Yes, there is: use an ORM to do the SQL generation for you. Check out > > SQLAlchemy, it will buy you much more than what you asked for. > > Might look, though in general I don't like OR mappers much. Having SQL > generated feels as strange as having python code generated. Too much > magic, too many layers. I think it is better to simply learn SQL. Amen, brother; this opinion is definitely an outdated and minority one, today, but I do tend to share it (and yet I'm programming in Django a lot these days... ah well, consistency, hobgoblin, little minds, &c:-). Alex From maxerickson at gmail.com Sun Apr 8 18:23:29 2007 From: maxerickson at gmail.com (Max Erickson) Date: Sun, 8 Apr 2007 22:23:29 +0000 (UTC) Subject: Python Web Servers and Page Retrievers References: <4c0048df0704081442w7a25ee2bqe2b13229dc37769e@mail.gmail.com> Message-ID: Subscriber123 wrote: > urllib, or urllib2 for advanced users. For example, you can > easily set your own headers when retrieving and serving pages, > such as the User-Agent header which you cannot set in either > urllib or urllib2. Sure you can. See: http://www.diveintopython.org/http_web_services/user_agent.html (though the behavior was changed for python 2.3 to make setting the user agent work better) max From bbxx789_05ss at yahoo.com Thu Apr 12 17:46:33 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: 12 Apr 2007 14:46:33 -0700 Subject: Question About Creating Lists In-Reply-To: References: Message-ID: <1176414392.977660.16610@o5g2000hsb.googlegroups.com> On Apr 12, 3:29 pm, "Scott" wrote: > I'm sorry if most of my question's seem "petty", but as I've said before, I > need to know the petty just because I need to know. > > This question is more along the lines of just having you guys either agree > or disgree with me, and if disagreeing to give the reasoning behind it, to > further my understanding of lists. > Please forgo the psychological self analysis from your future posts. > Am I safe in assuming that if the list your building contains number's it > will be written as follows: > > >>>my_list = [1, 2, 3, 4, 5] > > But the minute you throw in something that's not a number it has to be > written as: > > >>>my_list = [1, 2, 3, 4, 'five'] > >>> my_list > > [1, 2, 3, 4, 'five'] > > Unless five was defined, then it could be written as: > > >>>five = 5 > >>>my_list = [1, 2, 3, 4, five] > >>> my_list > > [1, 2, 3, 4, 5] > > Is this the correct way of thinking? Or am I, by thinking this is the case, > crippling myself in my potential as a programmer I don't think your question has anything to do with lists. Maybe this will help: there is a distinction between what are called "literals" and "variables". A variable is created like this: num = 10 num is a variable. It's called a variable because it's value can "vary": num = 20 On the other hand the value 10 cannot vary, so it is not a variable. What is it? It's called a "literal". Here are some examples of literals: 10 --- integer literal 3.5 --- float literal "hello" --- string literal Literals are the values you can assign to variables. Finally, any name without quotes around it is variable and it refers to a value which python will substitute in place of that name(that doesn't apply to python keywords like if, while, etc.) From CRhode at LacusVeris.com Sat Apr 14 10:16:24 2007 From: CRhode at LacusVeris.com (Chuck Rhode) Date: Sat, 14 Apr 2007 09:16:24 -0500 Subject: nonstandard XML character entities? References: <7xfy73ae08.fsf@ruckus.brouhaha.com> <46207e75$0$5795$9b622d9e@news.freenet.de> Message-ID: Chuck Rhode wrote this on Sat, 14 Apr 2007 09:04:45 -0500. My reply is below. Fixed text wrap: > import xml.etree.ElementTree # or elementtree.ElementTree prior to 2.5 > ElementTree = xml.etree.ElementTree > import htmlentitydefs > class XmlFile(ElementTree.ElementTree): > def __init__(self, file=None, tag='global', **extra): > ElementTree.ElementTree.__init__(self) > parser = ElementTree.XMLTreeBuilder( > target=ElementTree.TreeBuilder(Element)) > parser.entity = htmlentitydefs.entitydefs > self.parse(source=file, parser=parser) > return -- .. Chuck Rhode, Sheboygan, WI, USA .. Weather: http://LacusVeris.com/WX .. 32? ? Wind Calm From paddy3118 at googlemail.com Sun Apr 15 06:04:44 2007 From: paddy3118 at googlemail.com (Paddy) Date: 15 Apr 2007 03:04:44 -0700 Subject: Python editor/IDE on Linux? In-Reply-To: <1176626030.729710.321520@d57g2000hsg.googlegroups.com> References: <1176575715.649316.130430@n76g2000hsh.googlegroups.com> <1176626030.729710.321520@d57g2000hsg.googlegroups.com> Message-ID: <1176631484.468824.46420@q75g2000hsh.googlegroups.com> On Apr 15, 9:33 am, "Daniel Gee" wrote: > In Linux I just use Gedit. In windows I settle for Notepad2. With > python having help built into the interpreter, anything more than line > numbering, simple syntax highlighting, and auto-indent when you hit > enter just doesn't seem necessary. Vim has b and c, but not a. I'm not sure of what you are numbering, but vim does have: * Line numbering. * Syntax highlighting. * Auto-indenting. > > Using Kate for Python would probably be very similar to using Gedit > (from my limited experience with Kate). From tjreedy at udel.edu Wed Apr 25 17:21:56 2007 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 25 Apr 2007 17:21:56 -0400 Subject: bitwise shift? References: Message-ID: "desktop" wrote in message news:f0of5a$nn9$1 at news.net.uni-c.dk... |I have found a code example with this loop. | | for k in range(10, 25): | n = 1 << k; | | | I have never read Python before but is it correct ... One of the super-nice feature of Python is the interactive mode, also available with IDLE and other IDEs. that lets you explore the meaning of Python code faster than you can ask here. Use it and learn. >>> for k in range(10, 25): print 1 << k 1024 2048 4096 8192 16384 32768 65536 131072 262144 524288 1048576 2097152 4194304 8388608 16777216 From jackson at hotmail.com Fri Apr 27 15:49:39 2007 From: jackson at hotmail.com (Bill Jackson) Date: Fri, 27 Apr 2007 12:49:39 -0700 Subject: Import Problems Message-ID: Once again, I am having issues with imports... Until now, I thought the general guidelines were to rarely use 'from x import y' syntax, except when you really want to copy names over. However, I have run into issues by following this guideline. So... 1) What is going wrong in the example below? 2) What is a good way to handle imports for packages w/subdirectories? Here is a sample directory structure: importtest/ __init__.py test2/ __init__.py someclass.py mytest.py Here are the definitions of the files: # importtest/__init__.py from test2 import * # importtest/test2/__init__.py from someclass import * from test2 import * # importtest/test2/someclass.py class SomeClass: pass # importtest/test2/mytest.py import importtest print importtest.SomeClass On import I get the following: >>> import importtest Traceback (most recent call last): File "", line 1, in ? File "/home/user/lib/python/importtest/__init__.py", line 1, in ? from test2 import * File "/home/user/lib/python/importtest/test2/__init__.py", line 2, in ? from mytest import * File "/home/user/lib/python/importtest/test2/mytest.py", line 3, in ? print importtest.SomeClass AttributeError: 'module' object has no attribute 'SomeClass' >>> The problem seems to be an 'order' issue. importtest/test2/__init__.py has loaded someclass.py, but it doesn't seem to have copied its contents into importtest/__init__.py....perhaps it is because it hasn't finished all of its imports. Is this correct? So what is a good way to deal with this? In files which contain implementations, I thought it was best not to use 'from x import y', but this seems to be the only way to get this to work: # importtest/test2/mytest.py from someclass import SomeClass print SomeClass Is this the guideline? Use 'from x import y' for modules within your package. Use 'import y' for modules outside your package. Help. From steve at holdenweb.com Wed Apr 25 10:27:55 2007 From: steve at holdenweb.com (Steve Holden) Date: Wed, 25 Apr 2007 10:27:55 -0400 Subject: Would You Write Python Articles or Screencasts for Money? In-Reply-To: References: <462DCCE6.9060908@taupro.com> <1hx2dvj.10ek1v51noh1otN%aleax@mac.com> Message-ID: Anton Vredegoor wrote: > Antoon Pardon wrote: > >>>> That's a good point, and also a valid reason for restricting the >>>> voting community to PSF members. Thanks, Alex. >>> So in order to avoid a suspicion of a conflict of interest you want to >>> turn the whole thing into private property of the PSF? >>> >>> That is the most ridiculous suggestion I have ever >> I kind of understand why they would want to do this. If you have >> no limitations on who may vote, such a contest can easily turn >> into a contest of who can mobilize the biggest clan of supporters. > > Sure, any democratic process can be derailed by a coordinated effort of > people with a different mentality. To prevent such things by killing the > democratic process oneself right at the beginning of a project is a > peculiar way of avoiding this risk. > I'm sorry, but while the PSF is a democratically-run organization its franchise doesn't extend beyond the membership. You might as well suggest that America isn't being democratic because it doesn't allow the French to vote for its president. >> Now maybe there are better ways to avoid this kind of unwanted >> effect but I wouldn't call Steve's suggestion ridiculous. > > It's about as ridiculous as proving that a stiff parrot is dead by > grabbing it by the legs and repeatedly hitting it's head on the counter. > So you are now saying my behavior is completely appropriate? regards Steve -- Steve Holden +1 571 484 6266 +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 Apr 4 20:48:26 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 04 Apr 2007 21:48:26 -0300 Subject: Hellow World:) References: <765964.71169.qm@web63102.mail.re1.yahoo.com> Message-ID: En Thu, 29 Mar 2007 16:19:24 -0300, void pointer escribi?: > Hi All ..I am looking for PDF version of " Practical Python" and a > language to stick to .....Should I find that book ,I wil lconsder this > Python :) Try another book from this list, some have a downloadable version: http://wiki.python.org/moin/IntroductoryBooks -- Gabriel Genellina From paulgeeleher at gmail.com Tue Apr 24 05:15:51 2007 From: paulgeeleher at gmail.com (sophie_newbie) Date: 24 Apr 2007 02:15:51 -0700 Subject: Getting python script to write to input box on another window Message-ID: <1177406151.797865.141440@r30g2000prh.googlegroups.com> Hi, I'm wondering if there is a way to get a python script to write text to an input box in a window of another program that is running? For example a text box in a web browser window? Thanks! From mail at microcorp.co.za Sat Apr 14 04:00:30 2007 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Sat, 14 Apr 2007 10:00:30 +0200 Subject: Append data to a list within a dict References: Message-ID: <034601c77e6b$11bc44e0$03000080@hendrik> "Tina I" wrote: > Hello group, > > Say I have the following dictionary: > > ListDict = { > 'one' : ['oneone' , 'onetwo' , 'onethree'], > 'two' : ['twoone' , 'twotwo', 'twothree'], > 'three' : ['threeone' , 'threetwo', threethree']} > > Now I want to append 'twofour' to the list of the 'two' key but I can't > figure out how to that? > Some pointers would be greatly appreciated. > Just do it: ListDict['two'].append('twofour') This works because ListDict['two'] is a list... - Hendrik From kyosohma at gmail.com Mon Apr 30 10:10:37 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: 30 Apr 2007 07:10:37 -0700 Subject: Python ODBC In-Reply-To: <1177864453.282136.233030@n59g2000hsh.googlegroups.com> References: <1177864453.282136.233030@n59g2000hsh.googlegroups.com> Message-ID: <1177942237.735428.214700@u30g2000hsc.googlegroups.com> On Apr 29, 11:34 am, Harlin Seritt wrote: > Is there a Python odbc module that will work on Linux? I have a jdbc > connection to a DB2 server. I am looking hopefully for an open source > solution and not a commercial one. > > Thanks, > > Harlin I would think the odbc module would work. We've used SQLRelay here at work too. Here's a link on the database modules for Python: http://www.python.org/topics/database/modules.html And here's a few links on db2 with Python: http://www-128.ibm.com/developerworks/db2/library/tutorials/db2linux/db2proj/updated/python_db2_interface.htm http://sourceforge.net/projects/pydb2/ http://www-128.ibm.com/developerworks/edu/i-dw-db2pylnx-i.html Hope that helps. Mike From johnzenger at gmail.com Thu Apr 19 13:21:12 2007 From: johnzenger at gmail.com (John Zenger) Date: 19 Apr 2007 10:21:12 -0700 Subject: Using the Python interpreter In-Reply-To: <1176942756.283173.234750@n76g2000hsh.googlegroups.com> References: <1176942756.283173.234750@n76g2000hsh.googlegroups.com> Message-ID: <1177003272.566550.6440@b58g2000hsg.googlegroups.com> On Apr 18, 8:32 pm, tkp... at hotmail.com wrote: > Instead of starting IDLE as I normally do, I started the Python > interpreter and tried to run a program. I got a Python prompt (>>>), > and then tried unsuccessfully to run a Python script named Script1.py > that runs perfectly well in IDLE. Here's what I did: > > >>>Script1.py > > Traceback (most recent call last): > File "", line 1, in ? > NameError: name Script1 is not defined > > >>>python Script1.py > > File "", line 1 > python Script1.py > SyntaxError: invalid syntax > > I can load it (and have it execute) by typing > > >>>import Script1 > > 0 > 1 > 2 > 3 > 4 > > and if I edit it, I can then execute it by reloading it > > >>>import Script1 > > 0 > 1 > 2 > 3 > 4 > > > But this seems contrived - is there no way to repeatedly run Script1 > from the interpreter without reloading it? > > Thomas Philips You want execfile: >>> execfile("Script1.py") See http://pyref.infogami.com/execfile From larry.bates at websafe.com Mon Apr 2 13:12:25 2007 From: larry.bates at websafe.com (Larry Bates) Date: Mon, 02 Apr 2007 12:12:25 -0500 Subject: Is any way to split zip archive to sections? In-Reply-To: References: Message-ID: <46113979.6000906@websafe.com> Tim Williams wrote: > On 30/03/07, Durumdara wrote: >> 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)? >> > > If you are iterating through a list of files to be backed up, and > adding them to a ZIP one-by-one then you could use something like this > which adds each file until the zip is over 15mb - then it closes the > ZIP and creates the next one. > > Not tested or optimised :) > --------------------------------------------------------------------------------------------------- > > import zipfile > > archive_num = 1 > outfile = zipfile.ZipFile('/zips/archive%s.zip' % archive_num, "w") > zsize = 0 > > for full_name in filelist: > full_name_path = os.path.join(full_name, full_path) > > if zsize > 15728640 : # 15mb > outfile.close() > archive_num += 1 > outfile = zipfile.ZipFile('/zips/archive%s.zip' % archive_num, "w") > zsize= 0 > > outfile.write( full_name_path , full_name_path , > zipfile.ZIP_DEFLATED) # add the file > zsize += outfile.getinfo(full_name_path).compress_size # get > compressed size of file > > outfile.close() You can do slightly better as following: change to (not tested): import os import stat import zipfile archive_num = 1 outfile = zipfile.ZipFile('/zips/archive%s.zip' % archive_num, "w") zsize = 0 for full_name in filelist: full_name_path = os.path.join(full_name, full_path) if outfile.fp.tell() > 15728640: # 15mb outfile.close() archive_num += 1 outfile = zipfile.ZipFile('/zips/archive%s.zip' % archive_num, "w") outfile.write(full_name_path,full_name_path,zipfile.ZIP_DEFLATED) There is still a couple of "issues": 1) Files larger than 15Mb may not be able to be compressed to fall below the limit. 2) If you are near the 15Mb limit and the next file is very large you have the same problem. -Larry From robert.kern at gmail.com Wed Apr 4 13:19:21 2007 From: robert.kern at gmail.com (Robert Kern) Date: Wed, 04 Apr 2007 12:19:21 -0500 Subject: os.popen--which one to use? In-Reply-To: References: <1175626813.785146.326220@n59g2000hsh.googlegroups.com> Message-ID: Kevin Walzer wrote: > danmcleran at yahoo.com wrote: >> Check out subprocess. It's meant to be a replacement for all of the >> above. > > OK, I've done this. What is the benefit of subprocess? Code that will work on most platforms and into the Python 3.0, when the popen* zoo will disappear in favor of subprocess. -- 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 carsten at uniqsys.com Tue Apr 10 11:44:16 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Tue, 10 Apr 2007 11:44:16 -0400 Subject: tuples, index method, Python's design In-Reply-To: <740c3aec0704100810g5f962e8eu614fbaedecf3608e@mail.gmail.com> References: <1175867771.114540.61810@n76g2000hsh.googlegroups.com> <1175884427.779950.267220@y80g2000hsf.googlegroups.com> <1176210960.3430.20.camel@dot.uniqsys.com> <740c3aec0704100810g5f962e8eu614fbaedecf3608e@mail.gmail.com> Message-ID: <1176219856.3430.76.camel@dot.uniqsys.com> On Tue, 2007-04-10 at 17:10 +0200, BJ?rn Lindqvist wrote: > On 4/10/07, Carsten Haese wrote: > > i = p.index(current_player) > > opponents = p[:i-1] + p[i+1:] > > > > An alternative is this: > > > > opponents = tuple(x for x in p if x is not current_player) > > > > You may disagree, but in my opinion, the alternative is better because > > it is a more natural translation of the concept that the opponents of > > the current player are all players that are not the current player. > > Your alternative is wrong because it wont raise ValueError if > current_player is not present in the tuple. Please revise your > "solution." You have a point. Here is my revised solution: assert current_player in p opponents = tuple(x for x in p if x is not current_player) The added advantage is that AssertionError is better than IndexError for conveying that a severe program bug has occurred. -Carsten From bignose+hates-spam at benfinney.id.au Tue Apr 3 07:48:18 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Tue, 03 Apr 2007 21:48:18 +1000 Subject: Question about text in Python References: <4610c366$0$15022$5a62ac22@per-qv1-newsreader-01.iinet.net.au> <57cbejF2cataiU1@mid.individual.net> <4611af55$0$15038$5a62ac22@per-qv1-newsreader-01.iinet.net.au> <87wt0ugplk.fsf@benfinney.id.au> Message-ID: <87ejn1he65.fsf@benfinney.id.au> Steven D'Aprano writes: > On Tue, 03 Apr 2007 12:26:47 +1000, Ben Finney wrote: > > > "Steve" writes: > > > >> Yes it is [a homework question]. > >> > >> Where else to ask for help but here. > > > > That's between you, your teacher, and your teaching institute's > > plagiarism guidelines. > > Plagiarism is a serious example of fraud, which is not only a crime > but is unethical as well. You don't need to be a student or an > academic to commit plagiarism. Anybody can commit plagiarism. > > If we applied the plagiarism guidelines that university students > labour under to the rest of us, perhaps we'd be a little less quick > to toss accusations of plagiarism around so easily. I agree with the severity of such an accusation, which is why I didn't make it in this case. -- \ "[T]he question of whether machines can think [...] is about as | `\ relevant as the question of whether submarines can swim." -- | _o__) Edsger W. Dijkstra | Ben Finney From dd55 at cornell.edu Sun Apr 22 15:27:45 2007 From: dd55 at cornell.edu (Darren Dale) Date: Sun, 22 Apr 2007 15:27:45 -0400 Subject: python style guide inconsistencies Message-ID: I was just searching for some guidance on how to name packages and modules, and discovered some inconsistencies on the www.python.org. http://www.python.org/doc/essays/styleguide.html says "Module names can be either MixedCase or lowercase." That page also refers to PEP 8 at http://www.python.org/dev/peps/pep-0008/, which says "Modules should have short, all-lowercase names. ... Python packages should also have short, all-lowercase names ...". Which is most up to date? Is this the right place to point out that one of those pages needs to be updated? Thanks, Darren From carsten at uniqsys.com Thu Apr 26 22:12:54 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Thu, 26 Apr 2007 22:12:54 -0400 Subject: I25 barcode generator? In-Reply-To: <46311C0B.10506@fmed.uba.ar> References: <46311C0B.10506@fmed.uba.ar> Message-ID: <20070427020406.M99949@uniqsys.com> On Thu, 26 Apr 2007 18:39:23 -0300, Gerardo Herzig wrote > Hi. Im looking for an I25 barcode generator. I found a couple of > nice EAN barcode generators, but this application needs an I25 > barcode. Since this will be an web application, i need to do it in > the server side. In python, off course :) What format do you want to generate? EPS, PDF, PNG? I don't know of a readily available generator in Python, but judging from http://www.adams1.com/pub/russadam/i25code.html, it shouldn't be too hard to make one. -Carsten From M.Waack at gmx.de Wed Apr 4 04:52:48 2007 From: M.Waack at gmx.de (Mathias Waack) Date: Wed, 04 Apr 2007 08:52:48 GMT Subject: optparse option prefix Message-ID: We've integrated python into a legacy application. Everything works fine (of course because its python;). There's only one small problem: the application reads the commandline and consumes all arguments prefixed with a '-' sign. Thus its not possible to call a python module from the commandline with a parameter list containing options prefixed by '-' or '--' signs. Thats not a major problem, but it prevents us from using th optparse module. Is there a way to change to prefix, so one could use a '+' (for instance) to mark command line options for optparse? Regards Mathias From b.r.willems at gmail.com Mon Apr 2 21:16:02 2007 From: b.r.willems at gmail.com (Bart Willems) Date: Mon, 02 Apr 2007 21:16:02 -0400 Subject: reverse engineering Excel spreadsheet In-Reply-To: <1175481426.182703.250400@q75g2000hsh.googlegroups.com> References: <460fd6d0.0@entanet> <1175481426.182703.250400@q75g2000hsh.googlegroups.com> Message-ID: <_PhQh.31$DX7.20@newsfe12.lga> John Machin wrote: > I'm a bit puzzled by your notion of creating a dependency graph > *without* first extracting the "relationships (functions)" [which you > could do only by parsing the formulas and macros]. Not really. The range object in the Excel object model has a Dependents attribute, although for creating a graph you might want to rely on DirectDependents for obvious reasons. There's no reason to parse You can use that for each cell to get a list of the cells that have their formulas depending on the cell you are interrogating. There's also a Precedents and DirectPrecedents property if you want to walk the trees in the other direction. :-) More important, get some *serious* books about Excel VBA programming (I can recommend Walkenbach's Power Programming). Excel has a an extremely complex object model that can do almost anything for you - writing code against Excel without knowledge of that data will mean that you'll be writing 100 lines of Python code (for instance, to parse formulas) to do something that could have been done in 5 lines of Visual Basic code (or Python for that matter, but I can make a better point by using VBA :) ). Best Regards, Bart From sjmachin at lexicon.net Fri Apr 6 18:19:25 2007 From: sjmachin at lexicon.net (John Machin) Date: 6 Apr 2007 15:19:25 -0700 Subject: printing longs In-Reply-To: <1175896458.592054.159470@n76g2000hsh.googlegroups.com> References: <1175896458.592054.159470@n76g2000hsh.googlegroups.com> Message-ID: <1175897965.233984.100000@y80g2000hsf.googlegroups.com> On Apr 7, 7:54 am, "garyp" wrote: > Python 2.3.4 (#1, Oct 26 2004, 16:42:40) > [GCC 3.4.2 20041017 (Red Hat 3.4.2-6.fc3)] on linux2 > > >>> x = int("80000000", 16) > >>> x = x | 0x80000000 > > :1: FutureWarning: hex/oct constants > sys.maxint will return > positive values in Python 2.4 and up As your subject says, you are working with longs, so don't mix in an int (0x8000000, which is negative in Python 2.3 and earlier) -- use 0x8000000L instead. > > >>> print "%x" % ( x ) > -80000000 "%x" % x is enough. > > How do I get python to print the usual answer: 8000000, not -80000000 "usual" in what context? Cheers, John From ptmcg at austin.rr.com Sat Apr 14 19:48:30 2007 From: ptmcg at austin.rr.com (Paul McGuire) Date: 14 Apr 2007 16:48:30 -0700 Subject: Useful decorator In-Reply-To: <7xtzvik417.fsf@ruckus.brouhaha.com> References: <7xtzvik417.fsf@ruckus.brouhaha.com> Message-ID: <1176594510.535932.92030@d57g2000hsg.googlegroups.com> On Apr 14, 5:03 pm, Paul Rubin wrote: > In the course of writing a bunch of generator-oriented code I kept > wanting to temporarily truncate the output of generators for debugging, > i.e. I might have a function like > > def generate_bazillion_items(): > for line in bazillion_line_file: > yield itemify(line) > > where I wanted to test the program on just the first 20 lines of the > file. After a number of rounds of editing the program to wrap an > xrange(20) loop I went to using islice(bazillion_line_file, 20), but > even more handy was to write this decorator: > > def truncate(n): > from itertools import islice > def trunc(gen): # truncate generator to n items > return lambda *a,**kw: islice(gen(*a,**kw), n) > return trunc > > Then to chop bazillion_items to 20 items, I just write: > > @truncate(20) > def generate_bazillion_items(): > for line in bazillion_line_file: > yield itemify(line) > > When I want to run the whole file, I comment out the @truncate line, > and if I want to debug again, I just uncomment it. You should add this to the Python Wiki at http://wiki.python.org/moin/PythonDecoratorLibrary -- Paul From apardon at forel.vub.ac.be Tue Apr 24 05:47:09 2007 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 24 Apr 2007 09:47:09 GMT Subject: Tutorial creates confusion about slices References: Message-ID: On 2007-04-24, Michael Bentley wrote: > > On Apr 24, 2007, at 1:39 AM, Antoon Pardon wrote: > >> I suspect that if you give this explanation to someone and explain >> that there is also a step parameter, chances are he will answer >> correctly if you ask him, what he thinks the following will result >> in: >> >> >> "This is an example line"[12:19:2] >> >> >> >> If you ask him what the following will result in: >> >> "This is an example line"[19:12:-1] >> >> Chances are he will give the wrong answer. > > To be honest, bro -- I'd expect him to have enough intelligence to > experiment for a second and figure it out. This isn't rocket science > -- you can plainly see what's happening -- so learn it and move on. I don't think that the possibility to experiment and see for oneself is a good reason to keep a possible confusing explanation in a tutorial. > Or better yet, quietly submit a patch... Why should I? If the reactions would have been one of agreement that this is confusing and that the explanation should be changed, I would have considered submitting a patch. But most people that reacted seem to defend the current text in some way or another. So if most people seem to feel there is no need for a change why should I then submit a patch? -- Antoon Pardon From rowan at sylvester-bradley.org Mon Apr 16 08:05:37 2007 From: rowan at sylvester-bradley.org (rowan at sylvester-bradley.org) Date: 16 Apr 2007 05:05:37 -0700 Subject: How to tell whetehr Python script called as CGI or from command line? Message-ID: <1176725137.128549.131130@p77g2000hsh.googlegroups.com> I'm writing a Python script that can either be called as a Cron job or as a web page (i.e. as a CGI in response to an HTTP request). This is to process the mailboxes on my web server (to which I don't have command line access) to remove old messages. How do I find out whether the script has been called as a Cron job or as a CGI? I need to know this so I can format the output correctly, e.g. if this is a web request I need to start the output with "Content-type: text/html\n \n", to do newlines by "

" or "
" etc. Can I just access some header line which will always have a value in a web request, but which will be None if running from the command line or as a Cron job, or something similar? How? Thanks - Rowan From paddy3118 at googlemail.com Sun Apr 8 06:36:42 2007 From: paddy3118 at googlemail.com (Paddy) Date: 8 Apr 2007 03:36:42 -0700 Subject: block scope? In-Reply-To: References: Message-ID: <1176028602.262335.66070@n76g2000hsh.googlegroups.com> On Apr 7, 4:48 am, James Stroud wrote: > Neal Becker wrote: > > One thing I sometimes miss, which is common in some other languages (c++), > > is idea of block scope. It would be useful to have variables that did not > > outlive their block, primarily to avoid name clashes. This also leads to > > more readable code. I wonder if this has been discussed? > > Probably, with good code, block scope would be overkill, except that I > would welcome list comprehensions to have a new scope: > > py> i > ------------------------------------------------------------ > Traceback (most recent call last): > File "", line 1, in > : name 'i' is not defined > > py> [i for i in xrange(4)] > [0, 1, 2, 3] > py> i # hoping for NameError > 3 Yep, i think that we need consistent scope rules for listexps and genexps. Isn't it coming in 3.0? If it is, then maybe it will be back-ported to Python 2.6. In Python 2.5 we have the following: >>> [k for k in (j for j in range(5))] [0, 1, 2, 3, 4] >>> k 4 >>> j Traceback (most recent call last): File "", line 1, in NameError: name 'j' is not defined >>> - Paddy. From martin at v.loewis.de Sat Apr 7 05:05:08 2007 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sat, 07 Apr 2007 11:05:08 +0200 Subject: Understanding Python's interpreter In-Reply-To: <20070407052239.38f9b21e.rafaelc@dcc.ufmg.br> References: <20070407032024.bb27f5ee.rafaelc@dcc.ufmg.br> <20070407052239.38f9b21e.rafaelc@dcc.ufmg.br> Message-ID: <46175EC4.2030704@v.loewis.de> >> Why harder? Once you read the file, they're just numbers. Anyway, being >> harder to program the *interpreter* is not a problem, if you gain >> something like speed or eficiency for the interpreted language. > > Well, it's harder to get 4 bytes and create an int out of it in a > portable way than just call strtol or scanf That's not necessarily true for C. To deal with ASCII-printed integers in C, you need to deal with memory management, and variable-sized buffer. For example, if you want to print to memory, you need to overallocate memory, print to it, and then shrink the extra allocation (e.g. by copying the string elsewhere). For 4-byte integers in binary, no memory-management issue arises. You know exactly how much memory you will need. > Since I've never seen a .pyc bigger than a few kilobytes, I thought an > ascii file would take more space, but it wouldn't be anything really > prohibitive. That would probably defeat the point of .pyc files entirely: you already *have* an ASCII version of it, the .py file. So why create a second file? > It's not anything important, I was just saying that I had to write a > little more code to make an integer such as 0xff into '\0\0\0\377' than > it would need to just print the integer. Well, unless there's already a > python function that does just that and I didn't know about. It's was > just an example on how writting in ascii is easier. Sure: Take a look at the struct module. Regards, Martin From steveo at syslang.net Fri Apr 20 12:42:40 2007 From: steveo at syslang.net (Steven W. Orr) Date: Fri, 20 Apr 2007 12:42:40 -0400 (EDT) Subject: I need a string/list/generator/comprehension incantation. Message-ID: I really tried. I give up. I got this one last time (for which I'm very grateful). import calendar months = dict([(month,ii) for ii,month in enumerate(calendar.month_abbr)][1:]) Now I want something that's going to give me a string whose value is the set of all of the first letters of months. Order is not important. And for extra credit, I need the string whose value is the set of all of the letters of months minus the first letter. E.g., 'ADFJMONS', 'acbeglonprutvy' Thanks in advance to all the wizards out there. :-) -- 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 bbxx789_05ss at yahoo.com Wed Apr 4 22:13:46 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: 4 Apr 2007 19:13:46 -0700 Subject: Newbie Question about sequence multiplication In-Reply-To: <1175726885.373889.23850@y80g2000hsf.googlegroups.com> References: <6cOdnVFCLMXxuYnbnZ2dnUVZ_rCsnZ2d@comcast.com> <1175726885.373889.23850@y80g2000hsf.googlegroups.com> Message-ID: <1175739226.176472.96280@p77g2000hsh.googlegroups.com> On Apr 4, 4:48 pm, "John Machin" wrote: >copied straight from "Beginning Python: From Novice to >Professional", > > > Any help would be greatly appreciated > I suggest you get another book. I am currently reading that book, and unless you are an experienced programmer that can detect all the mistakes, and you have another book like "Python in a Nutshell" to fill in all the gaps, I don't think you can learn python from that book. I recently looked at Learning Python in the bookstore, and it seems a lot better. Unfortunately, it doesn't reflect the major changes in python over the last couple of years, but I would still recommend it over Beginning Python: From Novice to Professional. From gregturn at mindspring.com Wed Apr 4 12:56:42 2007 From: gregturn at mindspring.com (Goldfish) Date: 4 Apr 2007 09:56:42 -0700 Subject: how to remove multiple occurrences of a string within a list? In-Reply-To: <46138418$0$3275$426a74cc@news.free.fr> References: <1175624433.206953.214290@n59g2000hsh.googlegroups.com> <46138418$0$3275$426a74cc@news.free.fr> Message-ID: <1175705802.330354.156890@q75g2000hsh.googlegroups.com> I don't think I would use sets at all. They change the semantic meaning of the original list. What if you have duplicate entries that you want to keep? Converting to a set and back will strip out the duplicates of that. From QncyMI at netscape.net Mon Apr 30 22:49:49 2007 From: QncyMI at netscape.net (Major Quaternion Dirt Quantum) Date: 30 Apr 2007 19:49:49 -0700 Subject: Video: Professor of Physics Phd at Cal Tech says: 911 Inside Job In-Reply-To: <1177869819.781641.88780@n59g2000hsh.googlegroups.com> References: <1177467203.719625.93920@u32g2000prd.googlegroups.com> <1177780530.539758.275660@c35g2000hsg.googlegroups.com> <1177792809.503415.182480@o5g2000hsb.googlegroups.com> <1177793419.474675.156860@y80g2000hsf.googlegroups.com> <1177869819.781641.88780@n59g2000hsh.googlegroups.com> Message-ID: <1177987789.499847.307440@q75g2000hsh.googlegroups.com> Jones' report seems to support this idea, that there was molten metal under the pile, some where. there is another thing, documented with multiple photos, that seems to be related, although they weren't *still* molten. > > how is it that the metal was still molten, > > after weeks? > I say it's time to bring in the Mythbusters!! *That* will put and end > to all of this. thus: Kepler made the first astronomical use of a rough calculus, to determine his orbital constraints; Newton algebraized them into another formula with different parameters, probably using Hooke's idea, or stealing it. thus quoth: Not until Kepler used the observations of Tycho Brahe was it discovered that orbits were elliptical, confirmed by Isaac Newton. http://www.rwgrayprojects.com/synergetics/plates/figs/plate01.html thus: why do Dick, Borat, Osama, Harry P., Rumsfeld and Tony B. want us to underwrite the 3rd British Invasion of Sudan, so badly?... anyway, Bertrand Russel published a jeremyad in the Bulletin of the Atomic Scientists, while the USA was the only thermonukey power, that we should bomb the SU into the Stone Age; that's your British "pacifist," whether before or after he went nuts because of Godel's proof. thus: if you can't prove that all Fermat numbers are pairwise coprime, again! Darfur 'Mini-Summit' http://www.larouchepub.com/other/1998/rice_2546.html thus: uh yeah; Borat wants you in Sudan, why, Baby?... Harry Potter wants you in Iran -- yeah, Baby; shag'US with a spoon? --DARFURIA CONSISTS OF ARABs & nonARABs; NEWS-ITEM: we are marching to Darfuria, Darfuria, Darfuria! Harry Potter IIX, ?Ordeal @ Oxford//Sudan ^ Aircraft Carrier! http://larouchepub.com/other/2007/3410caymans_hedges.html ALgoreTHEmovieFORpresident.COM: http://larouchepub.com/eirtoc/site_packages/2007/al_gore.html From therve at gmail.com Thu Apr 5 05:17:12 2007 From: therve at gmail.com (therve at gmail.com) Date: 5 Apr 2007 02:17:12 -0700 Subject: Equivalent of PyEval_ThreadsInitialized for 2.3? Message-ID: <1175764632.039660.282590@y66g2000hsf.googlegroups.com> I ran into a problem with PyGILState_Release under Python < 2.4.2, that forced me to call PyEval_InitThreads() in my extension module. 2.4.2 had a fix for that problem :"It is now safe to call PyGILState_Release() before PyEval_InitThreads()" (from the NEWS file). I can live with this call, but I was wondering if there isn't a better way. As PyEval_ThreadsInitialized is not available either, it seems there is no way to know if threads have been initialized. Thanks! -- Thomas From yinglcs at gmail.com Mon Apr 9 17:06:11 2007 From: yinglcs at gmail.com (yinglcs at gmail.com) Date: 9 Apr 2007 14:06:11 -0700 Subject: How can I import functions from another python file Message-ID: <1176152771.761958.310740@w1g2000hsg.googlegroups.com> Hi, i have 2 python files in *different directory* , how can I import python functions from 1 python file to another? i get this error: import task ImportError: No module named task/ Thank you. From larry.bates at websafe.com Mon Apr 23 16:19:46 2007 From: larry.bates at websafe.com (Larry Bates) Date: Mon, 23 Apr 2007 15:19:46 -0500 Subject: Launch another application In-Reply-To: <1177358570.341152.171670@n76g2000hsh.googlegroups.com> References: <1177358570.341152.171670@n76g2000hsh.googlegroups.com> Message-ID: KDawg44 wrote: > Hi, > > I would like to launch another application and pass some arguments to > it from python. WHen the user clicks on the button, i want it to > execute: > > binaryApplication fileName > > Is there a way to do this as if I was doing it from a shell in > python? Would it be using something like popen? this app does not > need to return anything to the python app i am writing and the python > app does not need to wait for it (to close or do anyting else). > > Thanks. > Take a look at the subprocess module it is newer and is intended to replace popen (which still works if you prefer to use it). -Larry From s_ozdere at mynet.com Tue Apr 24 06:36:20 2007 From: s_ozdere at mynet.com (sibel) Date: 24 Apr 2007 03:36:20 -0700 Subject: work at home from internet.and earn 4000USD every month Message-ID: <1177410980.285087.312450@u32g2000prd.googlegroups.com> Yan?tla T?m?n? Yan?tla ??inde ?let Ek Olarak ?let ??p G?nderilen Taslak Mesaj ?nceki | sonraki Yazd?r ?leti?im ? Reklam Copyright ? 2007 MYNET A.?. Telif Haklar? MYNET A.?.' ye Aittir. I recently joined AGLOCO because of a friend recommended it to me. I am now promoting it to you because I like the idea and I want you to share in what I think will be an exciting new Internet concept. AGLOCO's story is simple: Do you realize how valuable you are? Advertisers, search providers and online retailers are paying billions to reach you while you surf. How much of that money are you making? NONE! AGLOCO thinks you deserve a piece of the action. AGLOCO collects money from those companies on behalf of its members. (For example, Google currently pays AOL 10 cents for every Google search by an AOL user. And Google still has enough profit to pay $1.6 billion dollars for YouTube, an 18-month old site full of content that YouTube's users did not get paid for! AGLOCO will work to get its Members their share of this and more. AGLOCO is building a new form of online community that they call an Economic Network. They are not only paying Members their fair share, but they're building a community that will generate the kind of fortune that YouTube. But instead of that wealth making only a few people rich, the entire community will get its share. What's the catch? No catch - no spyware, no pop-ups and no spam - membership and software are free and AGLOCO is 100% member owned. Privacy is a core value and AGLOCO never sells or rents member information. So do both both of us a favor: Sign up for AGLOCO right now! If you use this link to sign up, I automatically get credit for referring you and helping to build AGLOCO. document.write('http://www.agloco.com/ r/'+memberCode+''); http://www.agloco.com/r/BBCF3659 Thanks From larry.bates at websafe.com Fri Apr 27 13:07:44 2007 From: larry.bates at websafe.com (Larry Bates) Date: Fri, 27 Apr 2007 12:07:44 -0500 Subject: use urllib library to have an upload status bar In-Reply-To: <1177688613.085156.116170@o40g2000prh.googlegroups.com> References: <1177688613.085156.116170@o40g2000prh.googlegroups.com> Message-ID: shirish wrote: > Hi all, > Before I start, please know that I'm no developer, just a user. > This is also a cross-post as I have tried to post the same at python- > bugs mailing list, just don't know if it gets in or not. > > We have a bug-reporting system in ubuntu called apport. Apparently > apport uses a python library called urllib. As of now, apport does a > bouncing bar while uploading which doesn't give the user idea as to > how much is being uploaded. Refer https://bugs.launchpad.net/ubuntu/+source/apport/+bug/91521 > . I did try to see if this issue has been addressed or not but came > nowhere. It would be nice to know if there are some solutions, or is > there a roadmap where this feature would be integrated in the library. > Looking forward to suggestions, additions, flames & constructive > criticism of the same. Keep up the good work. Cheers! > the generic http browser upload doesn't give you any opportunity to have a callback so you can update the screen with any progress. There are some Java solutions available, but IMHO it will take a major change to browser's http upload implementation to make this possible. -Larry From Eric_Dexter at msn.com Mon Apr 9 05:41:34 2007 From: Eric_Dexter at msn.com (Eric_Dexter at msn.com) Date: 9 Apr 2007 02:41:34 -0700 Subject: pluie documentation in english In-Reply-To: References: <1176109628.413745.285120@n76g2000hsh.googlegroups.com> Message-ID: <1176111694.261768.8210@w1g2000hsg.googlegroups.com> On Apr 9, 4:25 am, Michel Claveau wrote: > Hi! > Bonjour ! > > Thanks very well for translation. > Merci beaucoup pour la traduction. > > I add a link on the index page of the site. > J'ai ajout? un lien vers le document, dans la page d'accueil. > > Site:http://www.ponx.org/ponx/guie.htm > > But... I hope complete the (french) doc in next days. > Mais... J'esp?re pouvoir compl?ter la documentation dans les jours qui > viennent. > > -- > @-salutations > > Michel Clave looking forward to seeing it From tjreedy at udel.edu Thu Apr 19 16:37:02 2007 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 19 Apr 2007 16:37:02 -0400 Subject: What makes an iterator an iterator? References: <1hwr9pv.13v4ci6106qn0aN%aleax@mac.com><1176936067.315082.17970@y80g2000hsf.googlegroups.com><1hws6rd.u0a6hd78fhhpN%aleax@mac.com> <1176961515.450458.189530@p77g2000hsh.googlegroups.com> Message-ID: "7stud" wrote in message news:1176961515.450458.189530 at p77g2000hsh.googlegroups.com... | On Apr 18, 8:38 pm, "Terry Reedy" wrote: | > | > One very good way to get an iterator from an iterable is for .__iter__ to | > be a generator function. | | Ahhh. That eliminates having to deal with next().next constructs. There never was any 'having' to deal with such a thing. I suggest completely forgetting .next().next and variants. | Nice. | | > snip all examples of bad code that violate the iterator rule | > by improperly writing .next as a generator function | | What iterator rule states that .next can't be a generator function? How about the programming rule that a function should return what you want it to return, or at least something 'close'? I gave the iterator rule in brief at the top of my posting, but here is again with several more words: the next method of an iterator for an actual or virtual collection has no input other than self (and internally stored information). Each time it is called, its output is either 'another' object in the collection, if there is at least one, or a StopIteration exception. For sequences, 'another' most be the next item after the last one returned (if any). Whether or not duplicates are allowed depends on the collection type. Each call of a generator function returns a new generator object. It never raises StopIteration. So making .next a generator function defines the collection as an infinite virtual collection (sequence or multiset) of generators. If that is what is intended (which it is not in the examples posted), fine. Otherwise, it is a mistake. | My book says an iterator is any object with a .next method that is | callable without arguments (Python in a Nutshell(p.65) says the same | thing). A complete interface specification specifies information flows in both directions, as I did before and again here. | I've read recommendations that an iterator should additionally contain | an __iter__() method, but I'm not sure why that is. In particular PEP | 234 says: [snip] should [snip] In my view, the 'should' should be taken strongly, so that the iterator is also an iterable. It is certainly idiomatic to follow the advice. Then one can write code like def f(iterable): iterator = iter(iterable) instead of def f(iterable): try: iterator = iter(iterable) except AttributeError: pass Terry Jan Reedy From cam.ac.uk at mh391.invalid Sat Apr 28 09:01:07 2007 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Sat, 28 Apr 2007 14:01:07 +0100 Subject: Numbers and truth values In-Reply-To: References: Message-ID: Szabolcs wrote: > Why is 1 == True and 2 == True (even though 1 != 2), Not what I get. Python 2.5 (r25:51908, Mar 13 2007, 08:13:14) [GCC 3.4.4 (cygming special, gdc 0.12, using dmd 0.125)] on cygwin Type "help", "copyright", "credits" or "license" for more information. >>> 2 == True False -- Michael Hoffman From larry.bates at websafe.com Thu Apr 19 18:06:02 2007 From: larry.bates at websafe.com (Larry Bates) Date: Thu, 19 Apr 2007 17:06:02 -0500 Subject: Better dict of dicts In-Reply-To: <-cudnX2k8KPLfLrbnZ2dnUVZ_uvinZ2d@ptd.net> References: <1177018181.493650.297900@e65g2000hsc.googlegroups.com> <-cudnX2k8KPLfLrbnZ2dnUVZ_uvinZ2d@ptd.net> Message-ID: John Bauman wrote: > Adam Atlas wrote: >> On Apr 19, 5:24 pm, Bill Jackson wrote: >>> I have a dictionary of dictionaries where the keys are typically very >>> long tuples and repeated in each inner dictionary. The dictionary >>> representation is nice because it handles sparseness well...and it is >>> nice to be able to look up values based on a string rather than a >>> number. However, since my keys are quite long, I worry that I am >>> wasting a lot of memory. >> >> I wouldn't worry about it. Try doing hash('string_2') in the >> interpreter -- the output thereof is what's really being used as the >> key. It doesn't use up any more memory than the integer 2. >> > Are you sure about that? Most dictionaries need to store the actual key, > in case of a collision, so when you lookup a key they can tell which > you're really looking for. Maybe this will help: http://wiki.python.org/moin/DictionaryKeys -Larry From etingof at gmail.com Mon Apr 9 07:36:01 2007 From: etingof at gmail.com (etingof at gmail.com) Date: 9 Apr 2007 04:36:01 -0700 Subject: SNMP agent In-Reply-To: <1175680387.575097.4590@e65g2000hsc.googlegroups.com> References: <1175680387.575097.4590@e65g2000hsc.googlegroups.com> Message-ID: <1176118561.740602.312810@y66g2000hsf.googlegroups.com> Consider taking a look at pysnmp-4 -- it has been designed with Agent role in mind. Here's an example Agent script: http://pysnmp.sourceforge.net/examples/4.x/v3arch/agent/cmdrsp.html > I have a Python app and i would like to add someSNMPagent > functionality to it. From python at rcn.com Mon Apr 30 03:28:40 2007 From: python at rcn.com (Raymond Hettinger) Date: 30 Apr 2007 00:28:40 -0700 Subject: fastest way to find the intersection of n lists of sets In-Reply-To: <1177883328.835058.138990@p77g2000hsh.googlegroups.com> References: <1177883328.835058.138990@p77g2000hsh.googlegroups.com> Message-ID: <1177918120.675261.264420@e65g2000hsc.googlegroups.com> [Prateek] > I have 3 variable length lists of sets. I need to find the common > elements in each list (across sets) really really quickly. . . . > l1 = reduce(operator.add, list(x) for x in l1) > l2 = reduce(operator.add, list(x) for x in l2) > l3 = reduce(operator.add, list(x) for x in l3) > s = frozenset(l1) & frozenset(l2) & frozenset(l3) I would write it like this: def multi_union(listofsets): result = set() for s in listofsets: result |= s return result def multi_intersection(listofsets): return reduce(set.intersection, sorted(listofsets, key=len)) s = multi_intersection(map(multi_union, [l1, l2, l3])) > I'm assuming frozensets are (somehow) quicker than sets because > they're immutable. Frozensets share the same implementation code as regular sets. They are not more efficient. > Any code suggestions? Maybe using something in the new fancy-schmancy > itertools module? The sets.py module shows how to implement set operations using itertools. In general, real set objects should do as well or better than anything you can cook-up using itertools. Real set objects have the advantage of knowing the hash values of their elements. Accordingly, binary set operations can run without any calls to element.__hash__(). Raymond Hettinger From 12cc104 at gmail.com Sun Apr 22 22:13:53 2007 From: 12cc104 at gmail.com (proctor) Date: 22 Apr 2007 19:13:53 -0700 Subject: recursion depth problem In-Reply-To: References: <1177267774.416169.276780@e65g2000hsc.googlegroups.com> <1177271382.859369.104790@q75g2000hsh.googlegroups.com> <1177278499.378120.246560@o5g2000hsb.googlegroups.com> Message-ID: <1177294433.069230.289280@y5g2000hsa.googlegroups.com> On Apr 22, 7:34 pm, Steven Bethard wrote: > proctor wrote: > > On Apr 22, 2:06 pm, Steven Bethard wrote: > >> proctor wrote: > >>> On Apr 22, 1:24 pm, Michael Bentley wrote: > >>>> On Apr 22, 2007, at 1:49 PM, proctor wrote: > >>>>> i have a small function which mimics binary counting. it runs fine as > >>>>> long as the input is not too long, but if i give it input longer than > >>>>> 8 characters it gives > >>>>> RuntimeError: maximum recursion depth exceeded in cmp > >>>>> i'm not too sure what i am doing improperly. is there really a lot of > >>>>> recursion in this code? > >>>>> ================== > >>>>> import sys > >>>>> def ch4(item, n=0): > >>>>> if n < len(item): > >>>>> if item[n] == '0': > >>>>> item[n] = '1' > >>>>> print ''.join(item) > >>>>> ch4(item) > >>>>> elif item[n] == '1': > >>>>> item[n] = '0' > >>>>> ch4(item, n+1) > >>>>> ch4(list(sys.argv[1])) > >>>>> ================== > >>>> Yes. There really is *that* much recursion in that code. 502 levels > >>>> with input length of 8 characters, 1013 with 9 characters, 2035 with > >>>> 10 characters... There's a pattern there ;-) > >>> ok, thanks michael! > >>> is there a way to avoid it here? how could i write this better, (if > >>> at all)? > >> Google for permutation-like recipies: > > >> http://www.google.com/search?q=Python+permutations > > >> Use the code from the first hit:: > > >> >>> for x in xselections('01', 8): > >> ... print ''.join(x) > >> ... > >> 00000000 > >> 00000001 > >> 00000010 > >> ... > >> 11111101 > >> 11111110 > >> 11111111 > > >> Explaining to your teacher why your code uses generators when you > >> haven't been taught them yet is left as an exercise to the reader. ;-) > > >> STeVe > > > this is really nice, thanks steve. much slicker than my code. > > > for interest sake: is my method unredeemable? > > Let's just say that I don't currently see an obvious way of redeeming > it. ;-) > > STeVe lol. okay. proctor. From nagle at animats.com Sun Apr 1 12:07:55 2007 From: nagle at animats.com (John Nagle) Date: Sun, 01 Apr 2007 09:07:55 -0700 Subject: Shed Skin Python-to-C++ Compiler 0.0.21, Help needed In-Reply-To: <1175413310.295953.230840@e65g2000hsc.googlegroups.com> References: <576vhbF2ca1guU1@mid.individual.net> <1175376373.241744.6220@y80g2000hsf.googlegroups.com> <1175413310.295953.230840@e65g2000hsc.googlegroups.com> Message-ID: Kay Schluehr wrote: > Indeed. The only serious problem from an acceptance point of view is > that Mark tried to solve the more difficult problem first and hung on > it. Instead of integrating a translator/compiler early with CPython, > doing some factorization of Python module code into compilable and > interpretable functions ( which can be quite rudimentary at first ) > together with some automatically generated glue code and *always have > a running system* with monotone benefit for all Python code he seemed > to stem an impossible task, namely translating the whole Python to C++ > and created therefore a "lesser Python". Trying to incrementally convert an old interpreter into a compiler is probably not going to work. > Otherwise it > wouldn't be a big deal to do what is necessary here and even extend > the system with perspective on Py3K annotations or other means to ship > typed Python code into the compiler. Shed Skin may be demonstrating that "annotations" are unnecessary cruft and need not be added to Python. Automatic type inference may be sufficient to get good performance. The Py3K annotation model is to some extent a repeat of the old Visual Basic model. Visual Basic started as an interpreter with one default type, which is now called Variant, and later added the usual types, Integer, String, Boolean, etc., which were then manually declared. That's where Py3K is going. Shed Skin may be able to do that job automatically, which is a step forward and more compatible with existing code. Doing more at compile time means doing less work at run time, where it matters. This looks promising. John Nagle From bbxx789_05ss at yahoo.com Thu Apr 5 23:20:27 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: 5 Apr 2007 20:20:27 -0700 Subject: "index" method only for mutable sequences?? In-Reply-To: References: Message-ID: <1175829627.861937.310460@b75g2000hsg.googlegroups.com> C.L. wrote: > I was looking for a function or method that would return the index to the first > matching element in a list. Coming from a C++ STL background, I thought it might > be called "find". My first stop was the Sequence Types page of the Library > Reference (http://docs.python.org/lib/typesseq.html); it wasn't there. A search > of the Library Reference's index seemed to confirm that the function did not > exist. A little later I realized it might be called "index" instead. Voila. > > My point is that the docs list and describe it as a method that only exists for > MUTABLE sequences. Why only for mutables? The class of objects I would expect it > to cover would be all ordered sequences, or, to phrase it a little more > pointedly, anything that supports ordered INDEXing. My understanding is that > dict's don't fall into that class of objects since their ordering is not > documented or to be depended on. However, tuple's do support ordered indexing, > so why don't tuple's have an index method? > > P.S.: I know I haven't yet gotten an answer to my "why" question yet, but, > assuming it's just an oversight or an example of design without the big picture > in mind, an added benefit to fixing that oversight would be that the "index" > method's documentation could be moved from the currently odd seeming location on > the "Mutable Sequence Types" page to a place someone would look for it logically. > > P.P.S.: As much as the elementary nature of my question would make it seem, this > isn't my first day using Python. I've used it on and off for several years and I > LOVE Python. It is only because of my love for the language that I question its > ways, so please don't be overly defensive when I guess that the cause for this > possible oversight is a lack of design. > > Corey Lubin Looking around google a little bit, people have been asking that same questions since at least 1992. Here is what the BDFL has to say: Guido van Rossum (Guido.van.Rossum at cwi.nl) Wed, 04 Dec 91 18:48:34 +0100 >In reply to: Steven D. Majewski: "Why no index for tuples or strings ?" > >Most of the functions that operate on mutable sequences but NOT on >immutable ones are obviously there because they DO CHANGE the sequence. >BUT: why no string.index() or tuple.index() ? > >Is this just an oversight ? >If not, what is the reason? Umm, there isn't a real good reason. One thing I can say in my defense is that string and tuple objects have no methods at all, all operations on these are done with built-in operations like "+" and "[...]", so adding an "index" method would be a bit of a change in the structure. For tuples, I suspect such a function would rarely be used; I think that is most cases where x.index() would be useful, x is generally a list, whose contents varies in time, rather than a tuple (which cannot change easily). For strings, there is a built-in module "string" which exports a function "index" which searches for substrings, so you can say string.index('one two three', 'two') --Guido van Rossum, CWI, Amsterdam From bearophileHUGS at lycos.com Sat Apr 7 11:49:50 2007 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 7 Apr 2007 08:49:50 -0700 Subject: tuples, index method, Python's design In-Reply-To: References: <1175867771.114540.61810@n76g2000hsh.googlegroups.com> <1175884427.779950.267220@y80g2000hsf.googlegroups.com> <1175953520.316208.241490@o5g2000hsb.googlegroups.com> Message-ID: <1175960990.140745.226360@b75g2000hsg.googlegroups.com> Carsten Haese: > Adding useless features always makes a product worse. What's your use > case for tuple.index? Ruby is a bit younger than Python, it has shown that few things may be better done in a different way. An advantage of PyPy is that it allows faster and simpler ways to perform language experiments. So you can even try things first and judge them later. You can find usercases later. This may help rejuvenate Python a bit :-) Bye, bearophile From s.mientki at id.umcn.nl Fri Apr 27 09:57:43 2007 From: s.mientki at id.umcn.nl (stef) Date: Fri, 27 Apr 2007 15:57:43 +0200 Subject: getting rid of EOL character ? In-Reply-To: References: <268cc$4631f634$83aef404$27224@news1.tudelft.nl> Message-ID: > > line = line.rstrip("\r\n") should take care of it. If you leave out > the parameter, it will strip out all whitespace at the end of the > line, which is what I do in most cases. thanks for the solution Michael, cheers, Stef From bobjohnson11 at gmail.com Sun Apr 29 21:53:51 2007 From: bobjohnson11 at gmail.com (RobJ) Date: 29 Apr 2007 18:53:51 -0700 Subject: Master's Thesis Help Needed Message-ID: <1177898031.790447.253360@n76g2000hsh.googlegroups.com> Awhile ago I asked for your help in getting some ideas about setting up an on-line course to learn how to use Python web frameworks. The first section - Beginning Pylons is up and running and I would appreciate your going through the course and taking my pre and post- workshop surveys. The link to the site is: http://pyschool.robj.webfactional.com/ Thanks in advance for your help! Rob J From mcfletch at vrplumber.com Sat Apr 7 10:21:14 2007 From: mcfletch at vrplumber.com (Mike C. Fletcher) Date: Sat, 07 Apr 2007 10:21:14 -0400 Subject: Understanding Python's interpreter In-Reply-To: References: <20070407032024.bb27f5ee.rafaelc@dcc.ufmg.br> <20070407052239.38f9b21e.rafaelc@dcc.ufmg.br> Message-ID: <4617A8DA.30309@vrplumber.com> Steve Holden wrote: > Rafael Almeida wrote: > ... > Because they aer smarter than you, without wishing to be too rude. > Replace that with "more experienced", please. Otherwise it is a bit rude, despite your wishes. We've always been newbie positive on Python-list, and new compiler writers are just as important educational targets as new Python programmers. Have fun, Mike -- ________________________________________________ Mike C. Fletcher Designer, VR Plumber, Coder http://www.vrplumber.com http://blog.vrplumber.com From a-alpha at otenet.gr Sat Apr 14 01:49:02 2007 From: a-alpha at otenet.gr (A - A) Date: Sat, 14 Apr 2007 08:49:02 +0300 Subject: Alessandra Ambrosio Message-ID: Alessandra Ambrosio www.alphasearch.gr -------------- next part -------------- An HTML attachment was scrubbed... URL: From bbxx789_05ss at yahoo.com Wed Apr 4 13:27:28 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: 4 Apr 2007 10:27:28 -0700 Subject: Indentifying the LAST occurrence of an item in a list In-Reply-To: <1175707250.349825.223470@p77g2000hsh.googlegroups.com> References: <1175702329.330032.250750@w1g2000hsg.googlegroups.com> <1175707250.349825.223470@p77g2000hsh.googlegroups.com> Message-ID: <1175707648.135485.164750@w1g2000hsg.googlegroups.com> On Apr 4, 11:20 am, "7stud" wrote: > On Apr 4, 10:55 am, "Terry Reedy" wrote: > > > wrote in message > > >news:1175702329.330032.250750 at w1g2000hsg.googlegroups.com... > > | For any list x, x.index(item) returns the index of the FIRST > > | occurrence of the item in x. Is there a simple way to identify the > > | LAST occurrence of an item in a list? My solution feels complex - > > | reverse the list, look for the first occurence of the item in the > > | reversed list, and then subtract its index from the length of the list > > | - 1, i.e. > > | > > | LastOcc = len(x) - 1 - x[::-1].index(item) > > | > > | Is there a simpler solution? > > How about: > > l = [1, 2, 1, 3, 1, 5] > target = 1 > for index, val in enumerate(l): > if val==1: > lastIndexOf = index > > print lastIndexOf Nahh. Horrible solution. You should start at the end of the list. From rNOSPAMon at flownet.com Mon Apr 23 17:07:29 2007 From: rNOSPAMon at flownet.com (Ron Garret) Date: Mon, 23 Apr 2007 14:07:29 -0700 Subject: Select weirdness References: Message-ID: In article , Donn Cave wrote: > In article , > Ron Garret wrote: > > > The answer is obvious: select is looking only at the underlying socket, > > and not at the rfile buffers. > > > > So... is this a bug in select? Or a bug in my code? > > Yes. > > I don't see any specific followup to this point, but it is or > at least should be a well known limitation of C library I/O and > select. select() is an operating system function that has no > way to know the state of your process I/O buffers, nor do the C > stdio buffers don't come with a standard way to inspect that state. > Therefore, if you mix C I/O with select(), you're more or less out > of luck. This applies directly to Python, because it calls the > operating system select() function and it uses C stdio buffers for > its file object (and entices you to make this mistake by supporting > a file object as an input to select().) > > This conflict can be relieved after a fashion by eliminating the > buffer. The now unbuffered C fgets / Python readline won't store > extra lines that select can't see, but the semantics of the operation > are still a poor fit with the usual application of select. The > number of system-level I/O calls is significantly greater as you > transfer data one byte at a time, which may add a lot of overhead > if you transfer a lot of data, and your readline() function still > can't return until it gets that '\n', so a half line can block your > application. > > It isn't a lot of work to read data with operating system functions > that are compatible with select - os.read(), socket.recv() - and > break it up into lines on your own, and this completely and efficiently > resolves the problem. Yep, this is pretty much the conclusion I've come to. As an editorial comment, I think it's quite confusing for Python's select to accept file objects without complaint if it's not going to do the Right Thing with them. rg From john106henry at hotmail.com Fri Apr 6 15:32:22 2007 From: john106henry at hotmail.com (John Henry) Date: 6 Apr 2007 12:32:22 -0700 Subject: Debugging multithreaded program using Eclipse/Pydev Message-ID: <1175887942.192837.187600@n76g2000hsh.googlegroups.com> I am back against the wall trying to migrate my multithreaded application from Python 2.3 to 2.5. The part of the code that's failing has to do with queues (2.3 queues and 2.5 queues are not the same). Since WingIDE doesn't support multithread debugging (they've been saying that one day they might support that - and that was 2003), I am starting to look for alternatives. >From what I can gather, it appears the only *real* option I have is to debug under Eclipse/Pydev. I did a google search of this newsgroup and didn't turn up too many hits. Before I invest the time to learn Eclipse/Pydev, I like to hear from somebody that have gone this path. Have you been successful in using Eclipse/Pydev to debug multi- threaded Python applications? Is so, what was the learning curve like to you? Thanks, From flyzone at technologist.com Mon Apr 30 04:16:24 2007 From: flyzone at technologist.com (Flyzone) Date: 30 Apr 2007 01:16:24 -0700 Subject: regexp match string with word1 and not word2 Message-ID: <1177920984.247487.54620@c35g2000hsg.googlegroups.com> Hello, i have again problem with regexp :-P I need to match all lines that contain one word but not contain another. Like to do "grep one | grep -v two:" The syntax of the string is: (any printable char)two:(any printable char)one(any printable char) Example: Apr 30 00:00:09 v890neg0 two: [ID 702911 daemon.one] findings: blablabla I tried with: .*[^t][^w][^o].*one.* but is not working, the string is always match and in other tries using "less logic" i get always some different match :-( P.S: i can't have more re.search, so i just need ONE regexp From anton.vredegoor at gmail.com Sat Apr 21 05:11:12 2007 From: anton.vredegoor at gmail.com (Anton Vredegoor) Date: Sat, 21 Apr 2007 11:11:12 +0200 Subject: TK-grid problem, please help In-Reply-To: <3CgWh.23821$PL.17381@newsread4.news.pas.earthlink.net> References: <3CgWh.23821$PL.17381@newsread4.news.pas.earthlink.net> Message-ID: Ray wrote: > hi, I have a question about how to use .grid_forget (in python/TK) > > I need to work on grid repeatly. everytime when a button is pressed, > the rows of grid is different. such like, first time, it generate 10 > rows of data. > 2nd time, it maybe only 5 rows. so I need a way to RESET the grid data > every time. how can I do it? by grid_forger()?, then would anyone can > help on > how to use grid_forget() > the sample code as following: I'm not sure if it solves your problem but this modification of your code at least *looks* like it works better. The entries are completely destroyed so that the next time you call the function they can be recreated. The trick I am using is to use a list in the arguments of the function but that is a bit of a hack, the list 'remembers' its state from the last time the function was called, I think one should use classes for bookkeeping such things instead. from Tkinter import * def mygrid(text,M = []): ######## how to use grid_forget() to clean the grid??########### while M: x = M.pop() x.destroy() rows = [] count=int(text) for i in range(count): cols = [] for j in range(4): e = Entry(frame3, relief=RIDGE) M.append(e) e.grid(row=i, column=j, sticky=NSEW) e.insert(END, '%d.%d' % (i, j)) cols.append(e) rows.append(cols) root=Tk() frame1=Frame(root, width=150, height=100) frame1.pack() text=Entry(frame1) text.pack(side=LEFT) button=Button(frame1, text='generate grid', command=(lambda: mygrid(text.get()))) button.pack() frame2=Frame(root, width=150, height=100) frame2.pack() button2=Button(frame2, text='exit', command=root.quit) button2.pack() frame3=Frame(root, width=150, height=300) frame3.pack() root.mainloop() A. From shamzz at gmail.com Wed Apr 11 04:48:52 2007 From: shamzz at gmail.com (shamzz at gmail.com) Date: 11 Apr 2007 01:48:52 -0700 Subject: No zlib in Python 2.4.4 In-Reply-To: References: <1176278576.196716.104760@p77g2000hsh.googlegroups.com> Message-ID: <1176281332.740637.219950@q75g2000hsh.googlegroups.com> On Apr 11, 9:14 am, Marc 'BlackJack' Rintsch wrote: > In <1176278576.196716.104... at p77g2000hsh.googlegroups.com>, shamzz wrote: > > Shouldn't zlib be compiled as a Python module automatically in Python > > 2.4.4. I'm guessing Python is doing some kind of check and not > > compiling zlib for some reason? > > It only gets compiled if the header files can be found. Is the zlib-dev > or zlib-devel package installed? Thanks for the fast reply... this seems to be going off topic from Python so sorry about that. But yep, I've just installed (through YAST) the zlib-devel and zlib- devel-32 packages (zlib and zlib-32bit are already installed). I then did a make clean/configure/make/make install with the Python source, but it's still not compiling with zlib. I've downloaded the latest (source) version of zlib 1.2.3, is it possible to manually compile it from the zlib source into Python? Thanks for your help, Shams. From larry.bates at websafe.com Wed Apr 11 11:29:09 2007 From: larry.bates at websafe.com (Larry Bates) Date: Wed, 11 Apr 2007 10:29:09 -0500 Subject: descriptor object for an attribute? In-Reply-To: <1176304695.336308.151810@n76g2000hsh.googlegroups.com> References: <1176304695.336308.151810@n76g2000hsh.googlegroups.com> Message-ID: <461CFEC5.5000008@websafe.com> Eric Mahurin wrote: > Is there a standard way to get a descriptor object for an arbitrary > object attribute - independent of whether it uses the descriptor/ > property protocol or not. I want some kind of handle/reference/ > pointer to an attribute. I know I could make my own class to do this > (using the __dict__ of the object and the attribute name), but I would > like to use something standard (at least a protocol) if it exists. > All that is needed in the protocol is getter and setter methods (like > __get__ and __set__ in a descriptor). Of course it would be nice to > have a better syntax than those method names of the descriptor (I've > seen unary + for the getter and += for the setter somewhere on the > web). > > Now the question I'm going to get is: why? I've used ruby (everything > is also already a reference to an object) for several years and been > through this discussion. I realize that 90% of the time you want some > kind of reference/pointer, there is a better way. But there are those > occassions where the most elegant solution is with the concept of a > reference. An obvious example in python today is a descriptor object > - it looks just like a reference (but is not a pointer) - having > getter and setter methods. > > The times in C/C++ where the elegant solution is with a pointer to a > pointer is also another example. That is the situation I'm dealing > with now. I'm using a singly linked list (as opposed to a normal list/ > array for performance/memory reasons). If you want to insert/delete a > node at a certain point in the list, the best thing to have access to > would be "link" (attribute or even local variable) where you want to > insert/delete. Without a reference, you'd end up with a less than > ideal solution: a) do the operation based on the previous node and > special case the situation where you want to operate at the head (no > previous node), b) do the operation based on the previous node and add > a dummy head node, or c) make the list doubly linked, do the operation > based on the current node, and either special case the head or add a > dummy head node. Really I'm dealing with a directed graph structure, > but part of it uses singly linked lists (the children of a parent). > Having a handle on any of the links in the graph would be a useful > thing. > I believe you are looking for setattr(obj, attr, value) and getattr(obj, attr) functions. Since everything in python its a pointer to an object, I wasn't able to understand EXACTLY what you were asking (an example would help). -Larry From aleax at mac.com Mon Apr 9 10:57:21 2007 From: aleax at mac.com (Alex Martelli) Date: Mon, 9 Apr 2007 07:57:21 -0700 Subject: Classes with initialization References: <1176103583.032209.304710@p77g2000hsh.googlegroups.com> <1176127365.448101.224930@n76g2000hsh.googlegroups.com> Message-ID: <1hwakit.5ywnw7183d4w3N%aleax@mac.com> wrote: ... > > Also: can someone enlighten me as to when code in class scope is run, > > exactly? It's run as a part of the execution of the class statement. > > if a class A has a metaclass M, then M.__init__ does not seem to get > > the code in A's class scope in its arguments AFAICS, so I guess that > > code is run before the class is created? Right. Nutshell 2nd ed, p 83 under "The class statement": """ The nonempty sequence of statements that follows the class statement is known as the class body. A class body executes immediately as part of the class statement's execution. Until the body finishes executing, the new class object does not yet exist and the classname identifier is not yet bound (or rebound). "How a Metaclass Creates a Class" on p. 118 provides more details about what happens when a class statement executes. """ The key to the latter part of the explanation (which actually starts on p. 117:-) is that the class body executes in a temporary dictionary, say d; that d is then used to help determine the meclass M (it may direct it by having a key '__metaclass__'); then, d is passed as one of the three arguments to the call to M (preceded by the classname string and the tuple of the class's bases) -- lastly, the classname is bound or rebound to the result of that call. > As I understand it, class code doesn't get run until you create an > instance of the class and call a method with that instance. I don't No, this delay applies to code that's part of methods defined in the class, but not to code that appears directly in classbody. Easy to check: >>> class Greet(object): ... print 'hello world' ... hello world >>> As you see, although no instance of the class has yet been created, the print statement that's directly in classbody has already run. If you want to check that it runs _before_ the metaclass gets called, set a custom metaclass that also does a print in its __init__, and see in what order the print statements execute... Alex From bdesth.quelquechose at free.quelquepart.fr Thu Apr 19 15:32:20 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Thu, 19 Apr 2007 21:32:20 +0200 Subject: comparison with None In-Reply-To: References: <3IqdnfRnCNWPC7vbnZ2dnUVZ_jqdnZ2d@rcn.net> Message-ID: <4627ba61$0$3196$426a74cc@news.free.fr> Steven Howe a ?crit : (snip) > I've read and found that 'None' comparisons is not always a good idea. > Better to: > from types import NoneType > > x = None > if type( x ) == NoneType: > # true > < code > > else: > # false; do something else. > < more code > Actually, None is garanteed to be a singleton, so the idiomatic way is to use an identity test: if x is None: # code here But this doesn't answer the OP... HTH From anton.vredegoor at gmail.com Wed Apr 25 07:06:35 2007 From: anton.vredegoor at gmail.com (Anton Vredegoor) Date: Wed, 25 Apr 2007 13:06:35 +0200 Subject: Would You Write Python Articles or Screencasts for Money? In-Reply-To: References: <462DCCE6.9060908@taupro.com> <1hx2dvj.10ek1v51noh1otN%aleax@mac.com> Message-ID: Antoon Pardon wrote: >>> That's a good point, and also a valid reason for restricting the >>> voting community to PSF members. Thanks, Alex. >> So in order to avoid a suspicion of a conflict of interest you want to >> turn the whole thing into private property of the PSF? >> >> That is the most ridiculous suggestion I have ever > > I kind of understand why they would want to do this. If you have > no limitations on who may vote, such a contest can easily turn > into a contest of who can mobilize the biggest clan of supporters. Sure, any democratic process can be derailed by a coordinated effort of people with a different mentality. To prevent such things by killing the democratic process oneself right at the beginning of a project is a peculiar way of avoiding this risk. > Now maybe there are better ways to avoid this kind of unwanted > effect but I wouldn't call Steve's suggestion ridiculous. It's about as ridiculous as proving that a stiff parrot is dead by grabbing it by the legs and repeatedly hitting it's head on the counter. A. From gagsl-py2 at yahoo.com.ar Thu Apr 12 19:26:53 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 12 Apr 2007 20:26:53 -0300 Subject: Lists and Tuples and Much More References: Message-ID: En Thu, 12 Apr 2007 19:38:55 -0300, Scott escribi?: > List's and Tuple's > I don't see the distinction between the two. I mean, I understand that a > list is mutable and a tuple is immutable. > The thing that I dont understand about them is what, besides that, > seperates > the two. Perhaps this old post from 2001 can explain a bit: http://groups.google.com/group/comp.lang.python/browse_thread/thread/7eaf9fe92b4c7e47/#78e78f179a893526 Or perhaps this one from 1998: http://groups.google.com/group/comp.lang.python/browse_thread/thread/358ef18309812fbb/14199e16f119a020 > Now you can add to a list, but not a tuple so: > >>>> my_list.append(my_tuple) #or extend for that matter right? > [1, 2, 3, 4, 5, 6, (1, 2, 3, 4, 5, 6)] > > Is that pretty much accurate? And which is better on resources....I'm > guessing a tuple seeing as it doesn't change. Yes. Tuples are immutable - once created, they can't change. > And the last example brings up another question. What's the deal with a > tupple that has a list in it such as: > >>>> my_tupple = (1, 2, 3, 4, 5, [6, 7, 8, 9]) > > Now I read somewhere that you could change the list inside that tupple. > But > I can't find any documentation that describes HOW to do it. The only > things > I CAN find on the subject say, "Don't do it because its more trouble than > it's worth." But that doesn't matter to me, because I want to know > everything. The *contents* of the list can be changed, but not the list itself: my_tupple[5].append(10) del my_tupple[5][2] my_tupple will always contain *that* list, whatever you put inside it. (Do not confuse the list object -a container- with the objects contained inside it) > Now there comes append. I read everywhere that append only add's 1 > element > to the end of your list. But if you write: >>>> my_list = [1, 2, 3, 4, 5, 6] my_list contains 6 elements: len(my_list)==6 >>>> my_list.append([7, 8, 9, 10]) >>>> my_list > [1, 2, 3, 4, 5, 6, [7, 8, 9, 10]] my_list now contains 7 elements: len(my_list)==7 Its seventh element happens to be a list itself, but that doesn't matter: my_list sees it as a single object like any other. > Is that because list's, no matter what they contain, are counted as 1 > element? Exactly. Lists or whatever object you want, if you append it to my_list, my_list grows by one element. It doesn't care *what* it is - it's a new element. > And how would you sort the list that's in the list? I guess that goes in > conjunction with the section above, but still: >>>> my_list = [6, 4, 3, 5, 2, 1] >>>> my_list.append([7, 9, 8, 10]) >>>> my_list.sort() >>>> my_list > [1, 2, 3, 4, 5, 6, [7, 9, 8, 10]] To sort my_list, you call the sort method on my_list: my_list.sort() To sort "the list that's in the list", i.e. my_list[6], you call the sort method on "the list that's in the list": my_list[6].sort() > This is, again, something I'm finding nothing on. You call a method on any object using any_object.method_name(some, parameters, may_be=required) any_object may be any arbitrary expression, like my_list[6] above > Maybe I'm just not looking in the right spots. The only things I have as > learning aids are: this newsgroup ;p, http://diveintopython.org, > http://python.org/, Beggining Python: From Novice to Professional, and > (now > don't laugh) Python for Dummies. That's fine - just keep programming, and have fun. -- Gabriel Genellina From skip at pobox.com Wed Apr 4 09:00:08 2007 From: skip at pobox.com (skip at pobox.com) Date: Wed, 4 Apr 2007 08:00:08 -0500 Subject: heap doesn't appear to work as described In-Reply-To: <17938.58082.317522.331513@montanaro.dyndns.org> References: <1175641694.226975.258820@n76g2000hsh.googlegroups.com> <17938.58082.317522.331513@montanaro.dyndns.org> Message-ID: <17939.41304.954608.389974@montanaro.dyndns.org> skip> Check the heapq docs for the constraints the Python heapq module skip> maintains: s/constraints/invariants/ Skip From parimala.kalavala at gmail.com Mon Apr 16 06:40:42 2007 From: parimala.kalavala at gmail.com (PARIMALA KALAVALA) Date: Mon, 16 Apr 2007 16:10:42 +0530 Subject: how to combine two applications in pygtk Message-ID: <67eb1c790704160340r65bb9438w726fc0632f1638f4@mail.gmail.com> hi, I want to know how to integrate two applications in pygtk. Should we add any header files in the main program or import any modules. also if we need to import any modules then how to convert the application in a module. Pls reply to this mail as soon as possible. Thank you. -------------- next part -------------- An HTML attachment was scrubbed... URL: From nospam at invalid.com Sat Apr 14 00:48:22 2007 From: nospam at invalid.com (Jack) Date: Fri, 13 Apr 2007 21:48:22 -0700 Subject: Python editor/IDE on Linux? References: Message-ID: <8ZadnS79krqFwL3bnZ2dnUVZ_sWdnZ2d@comcast.com> That's a good one. I got to find out what's special with Emacs :) > I'll let you in on a little secret. We all use Emacs. Those who claim to > use vim are just trying to prevent you from ever becoming a successful > Python programmer, and therefore reduce competition. > -- > Michael Hoffman From phil at riverbankcomputing.co.uk Thu Apr 12 06:34:48 2007 From: phil at riverbankcomputing.co.uk (Phil Thompson) Date: Thu, 12 Apr 2007 11:34:48 +0100 Subject: Pyqt programming question In-Reply-To: <1176372437.336751.75840@d57g2000hsg.googlegroups.com> References: <1176369822.364743.243700@n76g2000hsh.googlegroups.com> <1176372437.336751.75840@d57g2000hsg.googlegroups.com> Message-ID: <200704121134.48442.phil@riverbankcomputing.co.uk> On Thursday 12 April 2007 11:07 am, Marcpp wrote: > On 12 abr, 11:48, Phil Thompson wrote: > > On Thursday 12 April 2007 10:23 am, Marcpp wrote: > > > I have a program (python + pyqt), with a button I'll would to open a > > > new dialog window to input text, when press save or ok, this text is > > > returned to the principal program. > > > I've seek in internet but i don't find anything. > > > > Use QInputDialog.getText() > > > > Phil > > I can't do it, have you any example? Look at the standarddialogs.py example that it included with PyQt. Phil From s_broscious at comcast.net Wed Apr 4 18:19:15 2007 From: s_broscious at comcast.net (Scott) Date: Wed, 4 Apr 2007 18:19:15 -0400 Subject: Newbie Question about sequence multiplication Message-ID: <6cOdnVFCLMXxuYnbnZ2dnUVZ_rCsnZ2d@comcast.com> Alright, so I've been trying to teach myself Python which, when compared to my attempt to learn C++, is going pretty well. But I've come across an issue that I can't figure out, so I figured I'd ask the pro's. Now it looks pretty weird in this format but it was copied exactly from IDLE *****code follows******* #What this program is suppose to do is print a sentence centered in a box sentence = raw_input('Sentence: ') screen_width = 80 text_width = len(sentence) box_width = text_width + 6 left_margin = (screen_width - box_width) // 2 print print ' ' * left_margin + '+' + '-' * (box_width-2) + '+' print ' ' * left_margin + '| ' + ' ' * text_width + ' |' print ' ' * left_margin + '| ' + ' ' sentence + ' |' print ' ' * left_margin + '| ' + ' ' * text_width + ' |' print ' ' * left_margin + '+' + '-' * (box_width-2) + ' |' print ****end code**** Now that, even though copied straight from "Beginning Python: From Novice to Professional", returns : There's an error in your program: invalid syntax with the word sentence highlighted (not the sentence when I'm defining the name, the one in......uhm....the body of the code) Now if i put * before sentence as it is with the rest of the variables, it actually gets to the point where it asks me for the sentence, but after inputting my sentence I receive: Traceback (most recent call last): File "D:/Programming/Python/sequence string multiplication example", line 16, in print ' ' * left_margin + '| ' + ' ' * sentence + ' |' TypeError: can't multiply sequence by non-int of type 'str' Why can't I get it to do what it's supposed to do? What am I missing/misunderstanding? Very simply all its supposed to do is something like this (now bear with me formating might distort this a bit lol) +------------------------------------+ | | | Like This | | | +------------------------------------+ Any help would be greatly appreciated -Scott From kw at codebykevin.com Wed Apr 18 10:54:29 2007 From: kw at codebykevin.com (Kevin Walzer) Date: Wed, 18 Apr 2007 10:54:29 -0400 Subject: Future Python Gui? In-Reply-To: <1176859699.906386.326720@b75g2000hsg.googlegroups.com> References: <1176859699.906386.326720@b75g2000hsg.googlegroups.com> Message-ID: bcwhite at pobox.com wrote: > I've been trying to find out what the future of Python is with regard > to Tk. It seems there are several interfaces that make use of new > functionality, including "Tile" and "Ttk". > > If I want to write a program that will run under the standard Python > distribution of the future, what extension module should I work with > today? > > Thanks! > > -- Brian > Tile is available right now in Tk as an extension package, and a Tkinter wrapper for it can be found here: http://tkinter.unpythonic.net/wiki/TileWrapper Tile will be integrated into Tk's core when 8.5 is released. It's supposed to enter beta testing Real Soon Now. However, I imagine that Python/Tkinter will depend on Tk 8.4 for the foreseeable future--certainly 8.5 won't be supported officially before a full, stable release is made. Perhaps in Python 2.6? -- Kevin Walzer Code by Kevin http://www.codebykevin.com From kelvin.you at gmail.com Mon Apr 16 06:03:26 2007 From: kelvin.you at gmail.com (=?utf-8?B?5Lq66KiA6JC95pel5piv5aSp5rav77yM5pyb5p6B5aSp5rav5LiN6KeB5a62?=) Date: 16 Apr 2007 03:03:26 -0700 Subject: How to generate a continuous string Message-ID: <1176717806.754728.9600@y80g2000hsf.googlegroups.com> How to generate a continuous string, like this "aaaaaaaaaaaaaaaaaaaaaaa" the number of characters is dynamic. Is there a module or function implement this string ? such as: duplicate_string(char, num) From goodTweetieBird at hotmail.com Fri Apr 27 18:24:21 2007 From: goodTweetieBird at hotmail.com (gtb) Date: 27 Apr 2007 15:24:21 -0700 Subject: if __name__ == 'main': & passing an arg to a class object In-Reply-To: <1177711182.787219.272900@s33g2000prh.googlegroups.com> References: <1177708104.277756.245360@t38g2000prd.googlegroups.com> <1177711182.787219.272900@s33g2000prh.googlegroups.com> Message-ID: <1177712660.853729.242170@c18g2000prb.googlegroups.com> Sorry for the wrong implication. I should have said I 'mimicked the style'. No, not used to Java at all, and obviously not versed in python either (do I get points for tcl?). Maxq generates jython scripts and when I saw the .class files I assumed it was the work of the python compiler as what is visible to me appears to be python syntax. The example above { MaxQTest("MaxQTest").Run() } is actually par of what is generated by maxq first rattle out of the box when you specify a compact script. Since I am a neophyte to java, maxq, and python, what is what is not clear to me and I apologize for imposing on the the forum with this mixed bag of problems. However, I have learned a great deal (to me) of python in the past couple of days, just gotta break the tcl and autoIt habit of dollarSigning things. RE: http://python.org/doc/tut/, I keep it and http://docs.python.org/ref/ref.html both open all the time. :^) Best Regards, gtb From ladasky at my-deja.com Fri Apr 27 20:56:17 2007 From: ladasky at my-deja.com (John Ladasky) Date: 27 Apr 2007 17:56:17 -0700 Subject: Numeric + wxPython, can't understand a bug... Message-ID: <1177721777.885907.18780@n59g2000hsh.googlegroups.com> Hi, folks, This probably has to do with Numeric and not with wxPython, but I mention both for completeness. My OS: Win2000 Python: 2.3.4 wx: 2.6.1.0, Unicode version Numeric: 23.8 Here's the minimal code: ================================================ height = 50 width = 60 L = [] for y in range(height): for x in range(width): L.append(wx.Point(3+(2*x+y%2)*4, 3+7*y)) print width, height, len(L) pos = reshape(array(L), (height, width)) And here's the output: ================================================ 60 50 3000 pos = reshape(array(L), (height, width)) ValueError: total size of new array must be unchanged I've used exactly this approach to create 2D arrays from lists of numbers, with no problems. Why does this fail with wx.Point objects? Why is it telling me that I'm changing the array size, when the dimensions indicate that I am NOT? Typecasting the array as containing PyObject items does not change the error message... Thanks for any advice! +-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-+ | Ladasky Home Solar, Inc.: blowing sunshine up your | | power grid since March 24, 2005. Fiat lux! | +-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-+ | Uptime Downtime kWh generated kWh consumed | | 744 days 13 hours 12886 14321 | +-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-+ From Graham.Dumpleton at gmail.com Wed Apr 18 19:31:50 2007 From: Graham.Dumpleton at gmail.com (Graham Dumpleton) Date: 18 Apr 2007 16:31:50 -0700 Subject: Third party script debugging on remote server ... In-Reply-To: <1176938153.119084.214700@d57g2000hsg.googlegroups.com> References: <1176938153.119084.214700@d57g2000hsg.googlegroups.com> Message-ID: <1176939110.773939.83160@p77g2000hsh.googlegroups.com> After calling whatever it is that is writing to standard output/error, do: import sys sys.stdout.flush() sys.stderr.flush() This should cause any buffered data to be immediately flushed to the main Apache error log, ie., don't look in any virtual host logs, check the main one. Graham On Apr 19, 9:15 am, dbee wrote: > Right. I've got a really, really annoying/difficult/time consuming > problem with my development environment. I'm using django to build a > web app with paypal integration. My server is hosted remotely, and it > is receiving IPN (payment notifications) POST requests from Paypal. > I've checked on google and irc and this is my last shot at solving > this before I go mad ... :-( > > The problem is that I can't debug those POST requests. Browser > debugging is out of the question obviously cause I'm not at the > computer, ( and it doesn't have X ). > > I've tried cgitb but that doesn't seem to work at all ... > > import cgitb; cgitb.enable(display=0,logdir='/tmp/',format='plain') > import cgitb; cgitb.enable() > > ... neither of those commands have any effect. Although I do log other > parts of the script to /tmp, so I know that it's reachable... > > mod_pythonabsolutely refuses to error_log to the apache error_log. I > have restarted it and it still won't flush whatever error buffer it > may ( or may not ) have stored. > > I can re-constitute the requests in my browser using a GET request. > But frankly, that's kinda messy - there are lots of paypal IPN > combinations and I may have to integrate other applications with > paypal. So ideally speaking I'm looking for a proper debugging > environment for this kind of thing ... > > Basically, I either wantmod_pythonto start error_logging properly, > or I want some type of working traceback environment to be available. > Help ! > > Server version: Apache/2.0.52 > Server built: Aug 13 2006 03:29:43 > CentOS4.x: (RedHat Clone)mod_python.i386 3.1.3-5.1 > installed > > # httpd.conf > > > > ServerName mydomain.biz > ServerAliaswww.mydomain.biz > SetHandlermod_python > PythonPath "['/home/babo/django'] + sys.path" > PythonHandler django.core.handlers.modpython > SetEnv DJANGO_SETTINGS_MODULE mydomain.settings > > > SetHandler None > Options None > > > > > My python.conf: ( seems pretty normal ) > > # > #Mod_pythonis a module that embeds the Python language interpreter > # within the server, allowing Apache handlers to be written in Python. > # > > LoadModule python_module modules/mod_python.so > > # Override type-map handler for /var/www/manual > > > SetHandler default-handler > > > > # This will cause files beneath /var/www/html with the extension .spam > # to be handled by the Python script /var/www/html/eggs.py > # > # > # AddHandler python-program .spam > # PythonHandler eggs > # > > # This will cause all requests to the /python heirachy of your > # webserver to be handled by the python script /path/to/myhandler.py > # > # > # SetHandler python-program > # PythonPath "sys.path + ['/path/to']" > # PythonHandler myhandler > # > > # This will cause all requests to the /python heirachy of your > # webserver to be handled bymod_python'sPublisher handler > # (seehttp://localhost/manual/mod/mod_python/hand-pub.html) > # > # This will cause the output of all requests to files beneath > # /var/www/html with the extension .flt to be filtered through > # the Python script /var/www/html/filter.py > # > # > # PythonOutputFilter filter MYFILTER > # AddOutputFilter MYFILTER .flt > # From maxime.p at gmail.com Sun Apr 1 10:56:04 2007 From: maxime.p at gmail.com (Ulysse) Date: 1 Apr 2007 07:56:04 -0700 Subject: Extract information from HTML table In-Reply-To: <1175431924.800332.325820@n76g2000hsh.googlegroups.com> References: <1175429635.278697.92690@b75g2000hsg.googlegroups.com> <1175431924.800332.325820@n76g2000hsh.googlegroups.com> Message-ID: <1175439364.515873.142340@p15g2000hsd.googlegroups.com> On Apr 1, 2:52 pm, irs... at gmail.com wrote: > On Apr 1, 3:13 pm, "Ulysse" wrote: > > > Hello, > > > I'm trying to extract the data from HTML table. Here is the part of > > the HTML source : > > > .... > > > Do you know the way to do it ? > > Beautiful Soup is an easy way to parse HTML (that may be broken).http://www.crummy.com/software/BeautifulSoup/ > > Here's a start of a parser for your HTML: > > soup = BeautifulSoup(txt) > for tr in soup('tr'): > dateTd, textTd = tr('td')[1:] > print 'Date :', dateTd.contents[0].strip() > print textTd #element still needs parsing > > where txt is the string in your message. I have seen the Beautiful Soup online help and tried to apply that to my problem. But it seems to be a little bit hard. I will rather try to do this with regular expressions... From pavlovevidence at gmail.com Wed Apr 4 16:17:13 2007 From: pavlovevidence at gmail.com (Carl Banks) Date: 4 Apr 2007 13:17:13 -0700 Subject: BeautifulSoup vs. real-world HTML comments In-Reply-To: References: <1175711322.448629.20300@y80g2000hsf.googlegroups.com> Message-ID: <1175717833.872281.6300@l77g2000hsb.googlegroups.com> On Apr 4, 2:43 pm, Robert Kern wrote: > Carl Banks wrote: > > On Apr 4, 2:08 pm, John Nagle wrote: > >> BeautifulSoup can't parse this page usefully at all. > >> It treats the entire page as a text chunk. It's actually > >> HTMLParser that parses comments, so this is really an HTMLParser > >> level problem. > > > Google for a program called "tidy". Install it, and run it as a > > filter on any HTML you download. "tidy" has invested in it quite a > > bit of work understanding common bad HTML and how browsers deal with > > it. It would be pointless to duplicate that work in the Python > > standard library; let HTMLParser be small and tight, and outsource the > > handling of floozy input to a dedicated program. > > Well, BeautifulSoup is just such a dedicated library. No, not really. > However, it defers its > handling of comments to HTMLParser. That's the problem. Well, it's up to the writers of Beautiful Soup to decide how much bad HTML they want to accept. ISTM they're happy to live with the limitations of HTMLParser, meaning that they do not consider Beautiful Soup to be a library dedicated to reading every piece of bad HTML out there. (Though it's not like I read their mailing list. Maybe they aren't happy with HTMLParser.) Carl Banks From ocollioud at gmail.com Tue Apr 3 13:09:48 2007 From: ocollioud at gmail.com (olive) Date: 3 Apr 2007 10:09:48 -0700 Subject: XML DTD analysis, diffing ... In-Reply-To: References: <1175603926.371027.69390@e65g2000hsc.googlegroups.com> Message-ID: <1175620188.724407.274170@o5g2000hsb.googlegroups.com> Thank you Stephane, it is almost what I want. I'm going to improve it a little and then provide the code back. Where is the best place ? Olive. From steve at holdenweb.com Thu Apr 12 09:21:28 2007 From: steve at holdenweb.com (Steve Holden) Date: Thu, 12 Apr 2007 09:21:28 -0400 Subject: tuples, index method, Python's design In-Reply-To: References: <1175953520.316208.241490@o5g2000hsb.googlegroups.com> <7xzm5igbrb.fsf@ruckus.brouhaha.com> <1176200361.260546.280510@n76g2000hsh.googlegroups.com> <740c3aec0704100824m132c45fbi5c4c3ec0c0fa3a67@mail.gmail.com> Message-ID: <461E3258.2020607@holdenweb.com> Antoon Pardon wrote: > On 2007-04-11, Terry Reedy wrote: >> "BJrn Lindqvist" wrote in message >> news:740c3aec0704100824m132c45fbi5c4c3ec0c0fa3a67 at mail.gmail.com... >> On 4/10/07, Steve Holden wrote: >>> One might perversely allow extension to lists and tuples to allow >>> >>> [3, 4] in [1, 2, 3, 4, 5, 6] >>> >>> to succeed, but that's forcing the use case beyond normal limits. >> I'd love to have that! There are at least one million use cases for >> finding a sequence in a sequence and implementing it yourself is >> non-trivial. Plus then both list and tuple's index methods would work >> *exactly* like string's. It would be easier to document and more >> useful. A big win. >> >> ======================= >> It would be ambiguous: [3,4] in [[1,2], [3,4], [5,6]] is True now. >> >> Strings are special in that s[i] can only be a (sub)string of length 1. >> 'b' in 'abc' is True. This makes looking for longer substrings easy. >> >> However, [2] in [1,2,3] is False. IE, list[i] is not normally a list. So >> looking for sublists is different from looking for items. > > Well I think this illustrates nicely what can happen if you design by > use cases. > > Let us assume for a moment that finding out if one list is a sublist of > a second list gets considered something usefull enough to be included > in Python. Now the in operator can't be used for this because it > would create ambiguities. So it would become either a new operator > or a new method. But whatever the solution it would be different > from the string solution. > That's because strings are different from other sequences. See below. > Now if someone would have thought about how "st1 in st2" would > generalize to other sequemce if st1 contained more than one > character they probably would have found the possible inconsistency > that could create and though about using an other way than using > the in-operator for this with strings. A way that wouldn't create > ambiguities when it was considered to be extended to other sequences. > The fact is that strings are the only sequences composed of subsequences of length 1 - in other words the only sequences where type(s) == type(s[0:1]) is an invariant condition. This was discussed (at my instigation, IIRC) on python-dev when Python (2.4?) adopted the enhanced semantics for "in" on strings - formerly only tests for single characters were allowed - but wasn't thought significant enough to deny what was felt to be a "natural" usage for strings only. 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 boyee118 at gmail.com Wed Apr 4 12:07:48 2007 From: boyee118 at gmail.com (boyeestudio) Date: Thu, 5 Apr 2007 00:07:48 +0800 Subject: How to process the nested String for sybase sql statement? Message-ID: now,I want to insert some data to the sybase database, some variable such as i,j,k,name,k,j I have defined before. I write the sql statement here But I meet some errors,How to write this nested String for sql query? For example: >>>import Sybase >>> db = Sybase.connect('boyee','sa','',"test'') >>> c = db.cursor() ...... >>> values = "%d,%d,%d,%s,%d,%d" % (i,j,k,name,k,j) >>> c.execute("'insert into productinfo(productid,spid,corpid,productname,type1, type2) value(@value)',{'@value':values}") Traceback (most recent call last): File "", line 1, in ? File "C:\Python24\lib\site-packages\Sybase.py", line 774, in execute self.description = fetcher.start(self.arraysize) File "C:\Python24\lib\site-packages\Sybase.py", line 517, in start return self._start_results() File "C:\Python24\lib\site-packages\Sybase.py", line 645, in _start_results self._raise_error(Error, 'ct_results') File "C:\Python24\lib\site-packages\Sybase.py", line 506, in _raise_error raise exc(text) Sybase.Error: ct_results Any reply is enjoyable,Thank a lot! -------------- next part -------------- An HTML attachment was scrubbed... URL: From collinstocks at gmail.com Thu Apr 5 14:09:18 2007 From: collinstocks at gmail.com (Collin Stocks) Date: Thu, 5 Apr 2007 14:09:18 -0400 Subject: way to extract only the message from pop3 In-Reply-To: <1175628970.874615.127020@y80g2000hsf.googlegroups.com> References: <1175628970.874615.127020@y80g2000hsf.googlegroups.com> Message-ID: <4c0048df0704051109j24e24457v453cd68136e0096a@mail.gmail.com> so get two strings: only headers, and the whole message. find the length of the headers, and chop that off the beginning of the whole message: message=whole_message[len(headers):None] You can omit the word None: it is just there for clarity purposes. On 3 Apr 2007 12:36:10 -0700, flit wrote: > > Hello All, > > Using poplib in python I can extract only the headers using the .top, > there is a way to extract only the message text without the headers? > > like remove the fields below: > " > Return-Path: > X-Original-To: > Received: from [ > by (Postfix) with ESMTP id B32382613C > for Tue, 3 Apr 2007 09:54:28 -0300 (BRT) > Date: Tue, 03 Apr 2007 09:52:15 -0300 > From: <@> > To: > Subject: test > Message-Id: > MIME-Version: 1.0 > Content-Type: text/plain; charset="US-ASCII" > Content-Transfer-Encoding: 7bit > X-Mailer: Becky! ver. 2.24.02 [en] > X-UIDL: !Dn!!HKT!!/k > Status: RO > " > and only get this: > > this is a text message.. > .. > > Thanks > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From andy.rockford at gmail.com Sun Apr 29 15:11:04 2007 From: andy.rockford at gmail.com (Andy) Date: 29 Apr 2007 12:11:04 -0700 Subject: Counting Message-ID: <1177873864.502180.283390@u30g2000hsc.googlegroups.com> Hi, the file below will print all the keywords in a file and also the line # of the keyword. What I couldn't figure out is to count those keywords per line. For example - "Line #1 has 3 keywords" Can I do like - total[j] = total[j] + numwords(k) "Line number %d has %d keywords" % (j, total[j]) Seems sort of "illegal" in Python? ------------------------------------------------- import keyword, sys, string, fileinput def numwords(s): list = string.split(s) return len(list) # Get the file name either from the command-line or the user if len(sys.argv) != 2: name = raw_input("Enter the file name: ") else: name = sys.argv[1] inp = open(name,"r") linelist = inp.readlines() total, words,lines = 0, 0, 0 for i in range(len(linelist)): line = linelist[i] tempwords = line.split() for k in tempwords: if keyword.iskeyword(k): total = total + numwords(k) j = i + 1 print" The word * %s * belongs in line number: %d" % (k, j) print "Total keywords in this file are: %d" %(total) From martin at v.loewis.de Wed Apr 11 18:47:18 2007 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Thu, 12 Apr 2007 00:47:18 +0200 Subject: help building debug .pyd files In-Reply-To: References: <1176329238.588406.144210@w1g2000hsg.googlegroups.com> Message-ID: <461d6576$0$6946$9b622d9e@news.freenet.de> > You should read the file PCBuild/readme.txt. > It explains how to build python from source, and has long explanations > about the same list of modules you are asking for. > > And it works: I regularly use the debug build of python for my own > projects. Also, as of Python 2.5, you don't have to hunt around anymore for all these add-on libraries: they are all checked into the Python subversion repository (of course, earlier releases would give precise URLs, too, except that the hosting sites would sometimes break these URLs). Regards, Martin From mail at timgolden.me.uk Mon Apr 30 04:40:53 2007 From: mail at timgolden.me.uk (Tim Golden) Date: Mon, 30 Apr 2007 09:40:53 +0100 Subject: Dict Copy & Compare In-Reply-To: <00da01c78b01$3e80b900$bb822b00$@rawlins@thinkbluemedia.co.uk> References: <00da01c78b01$3e80b900$bb822b00$@rawlins@thinkbluemedia.co.uk> Message-ID: <4635AB95.4010309@timgolden.me.uk> Robert Rawlins - Think Blue wrote: > I'm looking for a little advice on dicts, firstly I need to learn how to > copy a dict, I suppose I could just something like. > Self.newdict = self.olddict > But I fear that this only creates a reference rather than an actual copy, > this means that as soon as I clear out the old one, the new one will > effectively be empty. What's the best way to ACTUALY copy a dict into a new > variable? Unless you have specialised needs, you can just say: d2 = dict (d1) which will initialise d2 from d1's key/value pairs: d1 = dict (a=1, b=2) d2 = dict (d1) d2['a'] = 5 print d1 print d2 > Next up I'm looking to compare two different dictionaries, then loop through > the unique results that are in each and print them out. Is there a more > efficient way of doing this other than a loop with an if/else statement? This comes up not infrequently on the list. I think there's even a few recipes in the cookbook. One (fairly recent) technique is to use set versions of your dictionary keys, but it depends on what you want to do next. From my example above: # relies on the fact that dictionary iterators # iterate over the keys of the dict. s1 = set (d1) s2 = set (d2) # do whatever set-ops you want, eg s3 = s1 | s2 for key in s3: print "Key:", key print "d1 =>", d1[key] print "d2 =>", d2[key] TJG From cam.ac.uk at mh391.invalid Sat Apr 21 14:18:12 2007 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Sat, 21 Apr 2007 19:18:12 +0100 Subject: Shebang or Hashbang for modules or not? In-Reply-To: <1176308951.932721.197630@y80g2000hsf.googlegroups.com> References: <1176308951.932721.197630@y80g2000hsf.googlegroups.com> Message-ID: Chris Lasher wrote: > Should a Python module not intended to be executed have shebang/ > hashbang (e.g., "#!/usr/bin/env python") or not? I'm used to having a > shebang in every .py file but I recently heard someone argue that > shebangs were only appropriate for Python code intended to be > executable (i.e., run from the command line). Personally I include it in all of them, as part of boilerplate in a template. -- Michael Hoffman From steveo at syslang.net Fri Apr 27 17:33:22 2007 From: steveo at syslang.net (Steven W. Orr) Date: Fri, 27 Apr 2007 17:33:22 -0400 (EDT) Subject: how to create/ref globals in an alternate namespace? In-Reply-To: References: Message-ID: On Friday, Apr 27th 2007 at 14:07 -0700, quoth James Stroud: =>Steven W. Orr wrote: =>> I have two seperate modules doing factory stuff which each have the =>> similar function2: =>> =>> In the ds101 module, def DS101CLASS(mname,data): =>> cname = mname+'DS101' =>> msg_class = globals()[cname] =>> msg = msg_class(data) =>> return msg =>> =>> and in the fdu module, =>> =>> def FDUCLASS(mname,data): =>> cname = mname+'FDU' =>> msg_class = globals()[cname] =>> msg = msg_class(data) =>> return msg =>> =>> I was thinking I'd be clever and create a common function: =>> def procCLASS(mname, objname, data): =>> cname = mname+objname =>> msg_class = globals()[cname] =>> msg = msg_class(data) =>> return msg =>> =>> but the call to globals fouls it all up. Is there a way to write it so =>> that the call to globals can be parameterized to be in the context of a =>> specific module? =>> =>> Also, I need to go the other way, a la, =>> globals()[name] = nclass =>> =>> Is this doable? =>> =>> TIA =>> => =>Why do you need all of the msg_class(es) global? Why not put them into a =>module and import the module where you need them? This would be the =>conventional way to avoid such problems. The idea is that DS101 is being called in a loop in the ds101 module to create a lot of msg_classes. The same is true for the FDUCLASS function; it creates a lot of classes in a loop. In addition, I have two other functions, almost alike, in two seperate modules (mdefs is a structure with all of the stuff needed to drive the loops) def __InitDS101Classes(): for m in mdefs: mdef = mdefs[m] name = mdefs[m]['name']+'DS101' nclass = new.classobj(name,(DS101,),{}) nclass.mdef = mdef nclass.mid = m globals()[name] = nclass def __InitFDUClasses(): for m in mdefs: mdef = mdefs[m] name = mdefs[m]['name']+'FDU' nclass = new.classobj(name,(FDU,),{}) nclass.mdef = mdef nclass.mid = m globals()[name] = nclass I'm trying to see if by being clever, I can factor out the common code of the four different functions and still end up with what they create ending up in the namespaces where they are intended to reside in. Does this make sense or am I way off base? -- 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 C.delete_this.Sanders at BoM.GOv.AU Mon Apr 16 23:00:16 2007 From: C.delete_this.Sanders at BoM.GOv.AU (Charles Sanders) Date: Tue, 17 Apr 2007 13:00:16 +1000 Subject: strange behaviour sys.argv In-Reply-To: References: <1176772070.349541.80890@y5g2000hsa.googlegroups.com> Message-ID: <46243841$0$75690$c30e37c6@lon-reader.news.telstra.net> Michael Hoffman wrote: > schnupfy wrote: > >> I am not used to python and I am wondering about this thing: > > This is not a Python question. It is a question about how to use bash. > [snip] Michael is correct, it is a bash thing, nothing to do with python. bash (and other *nix like shells) generally break arguments on white space. Quoting (both single and double) overrides this with (slightly) different rules for different shells. > /root/mk/services.py 192.168.1.101 critical "192.168.1.101 > 192.168.1.101 SNMPv2-MIB::sysUpTime.0 14:13:02:57.06 SNMPv2- > MIB::snmpTrapOID.0 SNMPv2-SMI::enterprises.789.0.13 SNMPv2- > SMI::enterprises.789.0.2"cfCannotTakeover == 1 priority == critical" > SNMP-COMMUNITY-MIB::snmpTrapAddress.0 192.168.1.101 SNMP-COMMUNITY- > MIB::snmpTrapCommunity.0 "public"" Assuming this has been folded and actually is one long line (which the output confirms), you have passed the python script seven arguments '192.168.1.101' (blank seperated) 'critical' (also blank seperated) a string extending from just after the first double quote to just before the second, ie starting with '192.168.1.101' and ending with '789.0.2', with the immediately following (no white space) unquoted text 'fCannotTakeover' appended '==' (blank seperated) 'priority" '==' a string starting with critical, with the quoted string from 'SNMP-COMMUNITY' to 'Community.0 ' (including the blank), the unquoted string 'public', and the null quoted string "" all appended. > TRAP='192.168.1.101 192.168.1.101 SNMPv2-MIB::sysUpTime.0 > 14:13:02:57.06 SNMPv2-MIB::snmpTrapOID.0 SNMPv2-SMI::enterprises. > 789.0.13 SNMPv2-SMI::enterprises.789.0.2"cfCannotTakeover == 1 > priority == critical" SNMP-COMMUNITY-MIB::snmpTrapAddress.0 > 192.168.1.101 SNMP-COMMUNITY-MIB::snmpTrapCommunity.0 "public"' > HOST=$(echo "$TRAP" | awk '{print $1}') > SEVERITY='critical' > /root/mk/services.py $HOST $SEVERITY \"$TRAP\" Here, the variables are expanded, and then split into arguments on white space unless quoted. The backslashes protect the double quotes so they are treated as normal characters, so the $TRAP variable is also split into arguments on white space. Quotes resulting from the substitution of $TRAP are also protected (ie are treated as ordinary characters). The result is '192.168.1.101" (From $HOST) 'critical' (From $SEVERITY) '"192.168.1.101' (Leading '"' from \", rest from $TRAP, blank seperated) '192.168.1.101' (from $TRAP, blank seperated) 'SNMPv2-MIB::sysUpTime.0' and so on for the rest of the $TARP string, splitting it at white space. The last part of $TRAP, '"public"', has a double quote appended from the \". Python is giving exactly what the shell has given it in both cases. Charles From abgrund at silberdrache.net Sat Apr 21 17:47:55 2007 From: abgrund at silberdrache.net (=?iso-8859-1?B?Qmr2cm4gS2VpbA==?=) Date: 21 Apr 2007 14:47:55 -0700 Subject: Building browser-like GET request In-Reply-To: References: Message-ID: <1177192075.699770.304600@d57g2000hsg.googlegroups.com> On 21 Apr., 23:28, Gilles Ganault wrote: > I'd like to download pages from a site, but it checks whether > the requests are coming from a live user or a script; If the latter, > the server returns a blank page. > > Using a proxy (Paros), I can see what information my script and > FireFox send, and there are a lot of information that Python is > missing: Well, I am brand new to Python, so it takes me a lot of guessing, but since it seems you're using urlib2: On http://docs.python.org/lib/module-urllib2.html is written that you may add custom headers to your http requests. Either by calling "addheader()" or by passing a dictionary with headers to the constructor. I hope that helped and I wasn't telling things you already new. As a sidenote: For the task you describe I'd rather use an actual sniffer - such as Wireshark (http://en.wikipedia.org/wiki/Wireshark), than logs of a Proxy... Not sure wether Wireshark works under Windows, though. Good luck! From tejovathi.p at gmail.com Mon Apr 9 07:39:11 2007 From: tejovathi.p at gmail.com (Teja) Date: 9 Apr 2007 04:39:11 -0700 Subject: Kill thread In-Reply-To: References: <1176110066.940676.173020@e65g2000hsc.googlegroups.com> Message-ID: <1176118751.002731.118620@b75g2000hsg.googlegroups.com> On Apr 9, 3:01 pm, Michel Claveau wrote: > Hi! > > If you have the PID of the process (example: 1234), use this > command-line : > TASKKILL/F /PID 1234 > > -- > @-salutations > > Michel Claveau Hi Michel, Thnks for the reply....But TASKKILL kills the process entirely..Not the thread. I want only the thread to be killed. Actually I am starting the thread in main thread. I jus want to kill the child thread and keep the main thread running. With TASKKILL, the main thread is also exited...I dont want it to happen.. Wht do i do?? Awaiting for a reply Teja.P From faulkner891 at gmail.com Sat Apr 14 15:20:34 2007 From: faulkner891 at gmail.com (faulkner) Date: 14 Apr 2007 12:20:34 -0700 Subject: Python Feature Request: (?) Group all file-directory-related stdlib functions in one place In-Reply-To: <1176546615.450418.268090@y5g2000hsa.googlegroups.com> References: <1176546615.450418.268090@y5g2000hsa.googlegroups.com> Message-ID: <1176578434.186547.283320@o5g2000hsb.googlegroups.com> On Apr 14, 6:30 am, samj... at gmail.com wrote: > Please check for sanity and approve for posting at python-dev. > > Currently file-directory-related functionality in the Python standard > library is scattered among various modules such as shutil, os, > dircache etc. So I request that the functions be gathered and > consolidated at one place. Some may need renaming to avoid conflicts > or for clarification. checkout the py3k svn branch and submit a patch [extending or conforming to pep355] to python-dev. From aboudouvas at panafonet.gr Fri Apr 13 16:49:52 2007 From: aboudouvas at panafonet.gr (king kikapu) Date: 13 Apr 2007 13:49:52 -0700 Subject: Python editor/IDE on Linux? In-Reply-To: <461fe88c$0$6420$426a74cc@news.free.fr> References: <1176488840.672572.101830@y80g2000hsf.googlegroups.com> <461fe88c$0$6420$426a74cc@news.free.fr> Message-ID: <1176497392.626173.116460@y80g2000hsf.googlegroups.com> I experiment with Ubuntu nowadays, and i find my Windows combination a realy win also there, Eclipse and PyDev. From yinglcs at gmail.com Fri Apr 20 10:42:42 2007 From: yinglcs at gmail.com (yinglcs at gmail.com) Date: 20 Apr 2007 07:42:42 -0700 Subject: How to upgrade python from 2.3 to 2.4 In-Reply-To: <1177057315.585286.178620@n76g2000hsh.googlegroups.com> References: <1177016635.483952.27450@y5g2000hsa.googlegroups.com> <1177057315.585286.178620@n76g2000hsh.googlegroups.com> Message-ID: <1177080162.669091.162880@o5g2000hsb.googlegroups.com> On Apr 20, 3:21 am, Ramashish Baranwal wrote: > On Apr 20, 2:03 am, "ying... at gmail.com" wrote: > > > Hi, > > > Red hat 4 comes with python 2.3, and I am trying to upgrade to python > > 2.4. So I download and compile the source of python2.4. > > > But as I run it I get the following error, can you please tell me how > > to fix it? > > > # /root/src/Python-2.4.4/python ./nov/scripts/stressTestServlet.py ./ > > nov/scripts/stressTestInputFile 10 127.0.0.1 > > Traceback (most recent call last): > > File "./nov/scripts/stressTestServlet.py", line 6, in ? > > import time > > ImportError: No module named time > > The best way to do it will be to use your operating system package > manager. If you have yum (a package manager for red hat distributions) > installed, it might be as simple as- > > # yum update python > > HTH > Ram I don't have yum. So I download and compile python. So how can I run the python in the new version? From cam.ac.uk at mh391.invalid Tue Apr 24 10:51:27 2007 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Tue, 24 Apr 2007 15:51:27 +0100 Subject: defining user exceptions In-Reply-To: <1177425815.272197.258400@t39g2000prd.googlegroups.com> References: <1177425815.272197.258400@t39g2000prd.googlegroups.com> Message-ID: CSUIDL PROGRAMMEr wrote: > I am trying to write a user defined exception that will catch for > failed dependencies when a rpm is installed > > try: > rpm -ivh xxx.rpm --force; > except RPMError: > print RPM failed dependency > > > Can some one tell me how to define this RPMError. I looked at python > docs but they were not useful. http://docs.python.org/tut/node10.html#SECTION0010500000000000000000 -- Michael Hoffman From bayer.justin at googlemail.com Thu Apr 12 05:52:42 2007 From: bayer.justin at googlemail.com (bayer.justin at googlemail.com) Date: 12 Apr 2007 02:52:42 -0700 Subject: SQLite problems Message-ID: <1176371562.110295.217360@l77g2000hsb.googlegroups.com> Hi there, I run Python 2.5 on a Mac OS X system with SQLite 3.2.8 installed via fink. Today I stumbled over the problem, that the sqlite3 module and sqlite3 from fink do not seem to work well together. I brought it down to this: >>> from sqlite3 import Connection >>> c = Connection("foo.bar") # does not yet exist >>> c.execute("CREATE TABLE foo (id integer)") >>> c.execute("INSERT INTO foo VALUES (1)") >>> c.execute("SELECT * FROM foo") >>> c.execute("SELECT * FROM foo").fetchmany() [(1,)] >>> c.execute("INSERT INTO foo VALUES (2)") >>> c.execute("SELECT * FROM foo").fetchmany(2) [(1,), (2,)] Then in sqilte: $ sqlite3 foo.bar SQLite version 3.2.8 Enter ".help" for instructions sqlite> select * from foo; SQL error: unsupported file format If I create the database file with sqlite and open it from within python, I cannot run any queries on that database, but no error is thrown - it just passes silently. Any ideas? Regards, -Justin From jjcrump at myuw.net Wed Apr 11 16:15:15 2007 From: jjcrump at myuw.net (Jon Crump) Date: Wed, 11 Apr 2007 13:15:15 -0700 (PDT) Subject: python newbie beautifulSoup question Message-ID: Hello world, Is it possible to feed findAll() a list of tags WITH attributes? This psuedocode obviously doesn't work, but it reflects what I want to do: soup.findAll([('td', {'class':'foobar'}), ('li', {'class':'baz'}), ('a', {'name' : re.compile('^it.*$')})]) Any clues, examples, or suggestions for further study, gratefully received. Jon From steven.bethard at gmail.com Tue Apr 10 13:29:50 2007 From: steven.bethard at gmail.com (Steven Bethard) Date: Tue, 10 Apr 2007 11:29:50 -0600 Subject: Why is __getslice__ still implemented? In-Reply-To: <87wt0kduo3.fsf@wilson.homeunix.com> References: <87irc4wpxp.fsf@wilson.homeunix.com> <87wt0kduo3.fsf@wilson.homeunix.com> Message-ID: Torsten Bronger wrote: > Hall?chen! > > Steven Bethard writes: > >> Torsten Bronger wrote: >> >>> [...] >>> >>> [...] It forces people to implement a deprecated function after >>> all. I think the docs should say that you still have to override >>> __getslice__ when subclassing from a built-in type, unless I >>> really don't understand the issue correctly. >> [...] If you have a specific suggestion for what doc should be >> updated and how, that would be helpful. Please post it to: >> >> http://sourceforge.net/tracker/?group_id=5470&atid=105470 > > Done. Thanks! STeVe From kyosohma at gmail.com Fri Apr 6 10:40:33 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: 6 Apr 2007 07:40:33 -0700 Subject: Getting Stack Trace on segfault In-Reply-To: References: Message-ID: <1175870433.686482.44640@d57g2000hsg.googlegroups.com> On Apr 6, 7:13 am, James Stroud wrote: > Hello All, > > The built-in mac osx vecLib is segfaulting in some cases--A very fun > fact to find out the hard way over two nights of work. I also spent an > embarrassing amount of time figuring out just where. Although I'm in > quite a self-congratulatory mood right now, in the future, I feel like I > could save a lot of time by coercing the interpreter to spew forth > method calls to stderr. Is this possible? > > I would hope to produce something hauntingly reminiscent of > > [] my_function > [my_function] another_function > [my_function -> another_function] yet_a_deeper_function > > Presentation, of course, is irrelevant. > > I read the docs on pdb, but it did not seem to do what I want--unless, > of course, I missed something. > > James Hi, I've never done that before, but I found a recipe that claims to do it with meta-classes. Check it out: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/198078 I hope this gives you some ideas. Mike From larry.bates at websafe.com Thu Apr 19 12:39:50 2007 From: larry.bates at websafe.com (Larry Bates) Date: Thu, 19 Apr 2007 11:39:50 -0500 Subject: Python COM iterator In-Reply-To: References: Message-ID: <46279B56.4020901@websafe.com> Carsten Haese wrote: >> [...] >>> On Tue, 2007-04-17 at 16:54 -0500, Larry Bates wrote: >>>> Does anyone know if there is a way to make a Python COM object >>>> act like a proper iterator in VB/Delphi? >> [...] > > After more googling, staring at win32com's code, and a fair bit of trial > and error, I've come up with the following working example: > > # server.py > import pythoncom > > class HelloWorld: > _reg_clsid_ = "{CAB8BED1-9174-4AAD-ABC5-F377951CB71B}" > _reg_desc_ = "Python Test COM Server" > _reg_progid_ = "Python.TestServer" > _public_methods_ = ['Next'] > _com_interfaces_ = [pythoncom.IID_IEnumVARIANT] > > def __init__(self): > self.numbers=[1,2,3,4,5,6,7,8] > > def Next(self, count): > assert count==1 > try: > return (self.numbers.pop(0),) > except IndexError: > return () > > def _NewEnum(self): > import win32com.server.util > return win32com.server.util.wrap(self) > > if __name__=='__main__': > import win32com.server.register > win32com.server.register.UseCommandLine(HelloWorld) > > # client.py > import win32com.client > comobj = win32com.client.Dispatch("Python.TestServer") > for x in comobj: > print x > > This works for me on Python 2.5 and pywin32 Build 210, but I don't know > whether clients in VB or Delphi are able to use this iterator. > > -Carsten > > I tested in VB and by golly it works! What is odd is that this looks NOTHING like what we got from the docs earlier. No GetEnumerator method, no MoveNext method. I'm glad it works, but I'm a little puzzled as to why it works. Thanks loads. -Larry From rdm at rcblue.com Sat Apr 7 07:09:56 2007 From: rdm at rcblue.com (Dick Moores) Date: Sat, 07 Apr 2007 04:09:56 -0700 Subject: Saving output of Turtle Graphics? Message-ID: <20070407111001.091461E4009@bag.python.org> I accidentally stumbled across the Turtle Graphics module (turtle.py) the other day and have been having some fun with it. Now I'm wondering if there is a way to build into a script the saving of each window just before it is cleared. For example, here are a couple that I've saved by screen capture: They were produced by this script: ========================================================= # randomTriangles.py import turtle as T from random import * def twoRndN(low=0, high=1): """ generate two random floats x, y in the range [low, high) such that x <= y """ x, y = uniform(low, high), uniform(low, high) if x <= y: return x, y else: return y, x T.setup(width=1000, height=700, startx=0, starty=0) T.title("Random Triangles with random R,G,B") colorRange = "all" if colorRange == "random": lowR, highR = twoRndN() lowG, highG = twoRndN() lowB, highB = twoRndN() count = 0 for n in range(300): wdth = randrange(0,7,3) T.width(wdth) T.speed("fastest") if colorRange == "dark": R = uniform(.1, .5) G = uniform(.1, .5) B = uniform(.1, .5) elif colorRange == "pastel": R = uniform(.5, .9) G = uniform(.5, .9) B = uniform(.5, .9) elif colorRange == "all": R = uniform(0, 1) G = uniform(0, 1) B = uniform(0, 1) # set RGB for one color of your choice elif colorRange == "manual": R = .45 G = .2 B = .2 elif colorRange == "random": R = uniform(lowR, highR) G = uniform(lowG, highG) B = uniform(lowB, highB) T.color(R,G,B) T.begin_fill() # 2 connected lines will fill as a triangle for x in range(2): coord = (randint(-500,500), randint(-350,350)) T.goto(coord) T.end_fill() count += 1 if count > 5: clr = randint(0,5) if clr == 0: T.clear() count = 0 T.done() ============================================== (The docs for Turtle graphics for Tk are at ) But how could I have saved them "automatically"? The script as shown will clear (T.clear() -- the 3rd line from the bottom) the window after producing 6 to maybe 15 superimposed triangles, so clearing will take place maybe 30 times. How can I save as images each of the 30 windows just before they are cleared? Thanks, Dick Moores From andriu_m at hotmail.com Sat Apr 7 20:11:03 2007 From: andriu_m at hotmail.com (=?iso-8859-1?B?QW5kculzIE0u?=) Date: Sun, 08 Apr 2007 00:11:03 +0000 Subject: [OT] MSN client for console project Message-ID: Hey, there. I just wanted to tell you that Im designing an MSN client for console in Python. I know that the protocol kinda sucks, but Im afraid the chicks I meet in here just don't use Jabber. The 'never seen' thing I am planning for it, is picture support. I do not mean to have the possibility of seeing other people's pictures (cause It is not the purpuse to use SVGAlib), but for them to see one of out choice. It's being written in Python, as I said above; using Ncurses, and based on MsnLib and ideas from other clients just as CenterICQ y Pebrot. Please, to all you interested in knowing more, do not hesitate to contact me. Saludos. Andr?s M. _________________________________________________________________ Consigue aqu? las mejores y mas recientes ofertas de trabajo EE.UU. http://latino.msn.com/empleos From bj_666 at gmx.net Fri Apr 20 04:13:27 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Fri, 20 Apr 2007 10:13:27 +0200 Subject: Python un-plugging the Interpreter References: <005f01c782a3$ae84d710$fa936540@cisco.com> Message-ID: In , John Nagle wrote: > Many cases are easy. If a smart compiler sees > > for i in range(n) : > ... # something > > and there are no other assignments to "i", then it's clear that > "i" can be represented as an integer, without "boxing" into a > general object. How is it clear that `i` is restricted to integers? That works only if you assume `range` refers to the built-in `range()` function. So the smart compiler has to check all possible control flows up to this point and be sure `range` was not bound to something different. Ciao, Marc 'BlackJack' Rintsch From tejovathi.p at gmail.com Tue Apr 10 01:53:39 2007 From: tejovathi.p at gmail.com (Teja) Date: 9 Apr 2007 22:53:39 -0700 Subject: TASK KILL Message-ID: <1176184419.825885.285540@b75g2000hsg.googlegroups.com> Will TASKKILL kills a thread when thread id is given ?? Or does it kill only a process?? How to ensure that a thread is killed? From Emile.Boudreau at cognos.com Tue Apr 3 15:06:50 2007 From: Emile.Boudreau at cognos.com (Boudreau, Emile) Date: Tue, 3 Apr 2007 15:06:50 -0400 Subject: Extracting a file from a tarball In-Reply-To: <1175622111.3456.47.camel@dot.uniqsys.com> References: <09042D621CD4AA479C678463F3A646D0F73DD5@sottemail1.ent.ad.cognos.com> <1175622111.3456.47.camel@dot.uniqsys.com> Message-ID: <09042D621CD4AA479C678463F3A646D0F73E62@sottemail1.ent.ad.cognos.com> Your hint of checking "tar.getnames()" was exatly what I needed. It returns the path to where the file will be extracted (ie. Src/ver/qfw/symbols.xml). After knowing this fact it was quite simple to extract the file. Thanks, problem solved!!! Emile Boudreau x5754 -----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 Carsten Haese Sent: Tuesday, April 03, 2007 1:42 PM To: python-list at python.org Subject: Re: Extracting a file from a tarball On Tue, 2007-04-03 at 13:26 -0400, Boudreau, Emile wrote: > I am trying to extract one file from a tarball, without success. This > is the code I'm using to open the tarball and extract the file: > > tar = tarfile.open(component+'-win32-app-'+bestVersion+'-dev.tar.gz', > 'r') > extractedFile = tar.extractfile('symbols.xml') > > And this is my error: > > Traceback (most recent call last): > File "C:\CognosInstalls\AutoTest\PollDir.py", line 121, in > main() > File "C:\CognosInstalls\AutoTest\PollDir.py", line 119, in main > extract('c:\\', 'I:\\daily\\'+components[i], components[i]) > File "C:\CognosInstalls\AutoTest\PollDir.py", line 27, in extract > filelike = tar.extractfile('symbols.xml') > File "C:\Python25\lib\tarfile.py", line 1488, in extract > tarinfo = self.getmember(member) > File "C:\Python25\lib\tarfile.py", line 1171, in getmember > raise KeyError("filename %r not found" % name) > KeyError: "filename 'symbols.xml' not found" > > I know that the tarball contants this file "symbols.xml" What does tar.getnames() return? -Carsten -- 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. From paul at boddie.org.uk Thu Apr 19 13:59:32 2007 From: paul at boddie.org.uk (Paul Boddie) Date: 19 Apr 2007 10:59:32 -0700 Subject: Compiling python from soruce vs RPM ? In-Reply-To: <1177000809.846880.323090@l77g2000hsb.googlegroups.com> References: <1176911689.026633.230390@l77g2000hsb.googlegroups.com> <1176934250.650536.239040@p77g2000hsh.googlegroups.com> <1176950392.192425.90980@b58g2000hsg.googlegroups.com> <1176976152.885919.139080@n76g2000hsh.googlegroups.com> <1177000809.846880.323090@l77g2000hsb.googlegroups.com> Message-ID: <1177005572.153250.80490@p77g2000hsh.googlegroups.com> On 19 Apr, 18:40, howa wrote: > > but i have the source package being installed...so any method/script > to remove them? > > since finally i want to install via RPM ... You could use checkinstall to make a package, install it (forcibly if necessary), then remove it. That might wipe away the things installed when you did "make install" since checkinstall should note which files were to be installed, add them to its manifest, then construct the package such that those files will be removed when the package is uninstalled. No promises, though... Paul From agibov at gmail.com Thu Apr 26 04:12:07 2007 From: agibov at gmail.com (adima) Date: 26 Apr 2007 01:12:07 -0700 Subject: str() and repr() question Message-ID: <1177575127.034458.243760@t38g2000prd.googlegroups.com> Hi All! Sorry, my English isnt good, but get a try to describe my problem. Today we wrote next script: import os, glob, time, string files_to_test = ( "J:\\BWNEW\\!Unerase\\test.test", "L:\\Temp\Nick\ \test.test", "F:\\TRANSIT\\nick\\test.test") outfile="c:\\temp\\statistic" def DoTestTime(file): StartTime = time.time() filehandle = open(file) alllines = filehandle.read() filehandle.close() FileSize = os.path.getsize(file) EndTime = time.time() return time.ctime() , "\tDisk\t" , file[:3] , "\tfile size (bytes) = \t" , FileSize , "\taccess time =\t" , EndTime - StartTime if __name__ == "__main__": out = open(outfile, 'w') for EachFile in files_to_test: str = DoTestTime(EachFile) print type(str) for s in str: print s out.write(str(s)) out.close() When I executed it, the output was C:\test\py>File_Stat.py Thu Apr 26 12:08:33 2007 Traceback (most recent call last): File "C:\test\py\File_Stat.py", line 26, in ? out.write(str(s)) TypeError: 'tuple' object is not callable When I replace "str" with "repr" in out.write(str(s)), script executed normally. Where is the problem here? Thanks in advance. From steve at holdenweb.com Fri Apr 13 08:52:40 2007 From: steve at holdenweb.com (Steve Holden) Date: Fri, 13 Apr 2007 08:52:40 -0400 Subject: Need help with the get() method of a Text entry In-Reply-To: <1176414612.620268.200780@e65g2000hsc.googlegroups.com> References: <1176409717.585710.184960@y80g2000hsf.googlegroups.com> <1176414612.620268.200780@e65g2000hsc.googlegroups.com> Message-ID: <461F7D18.5070403@holdenweb.com> Chad wrote: > On Apr 12, 5:03 pm, James Stroud wrote: >> James Stroud wrote: >>> Chad wrote: >>>> I have a simple little program that brings up asks the user to enter a >>>> note, then is supposed to place that note into a text file when the >>>> user hits the submit button. However, when the user hits the submit >>>> button, absolutely nothing happens. IDLE doesn't give an error >>>> message and the note is not entered into the text file. For >>>> troubleshooting puposes, I wanted to see if IDLE would at least print >>>> the user's input; it doesn't do that either. Can someone please help >>>> me? [...] [James second-guesses himself twice] > > Thank you, that worked very well. > I thought it was particularly helpful of James to do the debugging for you without waiting for you to point out the errors in his first and second submissions. You just don't *get* help like that most places nowadays. 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 REMOVE.THIS.cybersource.com.au Thu Apr 19 03:04:56 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Thu, 19 Apr 2007 17:04:56 +1000 Subject: What makes an iterator an iterator? References: <1176885910.102141.39750@p77g2000hsh.googlegroups.com> Message-ID: On Wed, 18 Apr 2007 01:45:10 -0700, Paul McGuire wrote: >> For the record, this is what I actually wanted: a four-line self-sorting >> dictionary: >> >> class SortedDict(dict): >> def __iter__(self): >> for key in sorted(self.keys()): >> yield key [snip] > Very neat. Why not this? > > class SortedDict(dict): > def __iter__(self): > return iter(sorted(self.keys())) Good question. I don't have a good answer except for "because I didn't think of it". -- Steven. From martin at v.loewis.de Fri Apr 20 01:35:25 2007 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Fri, 20 Apr 2007 07:35:25 +0200 Subject: Better dict of dicts In-Reply-To: References: <4627E28C.1050406@v.loewis.de> Message-ID: <4628511D.8080605@v.loewis.de> > Now suppose there is little overlap between the keys for the outer > dictionary and the inner dictionaries...but still much overlap between > the various inner dictionaries. Then, there is no point in using an > intern function for the outer dictionary, but still a benefit for the > inner dictionary. Thus, something like the following would be appropriate: > > a[k1][local_intern(k2)] = value > > Have I understood this properly? Correct. Notice that this thing is a time-space-tradeoff resolved in favor of space - quite uncommon, as people these days always chose to resolve them in favor of time. Interning a tuple will take some time, as it is a dictionary lookup (requiring to hash the tuple); then you will pass the interned tuple again for another dictionary lookup. So make sure that you don't apply local_intern() twice to the very same tuple object. E.g. when you also store the tuple in a variable, don't do var = (..., ..., ...) a[foo][local_intern(var)] = foovar print a[foo][local_intern(var)] instead do var = local_intern((..., ..., ...)) a[foo][var] = foovar print a[foo][var] Strictly speaking, you can omit the interning on read operation, as that won't affect the keys stored in the dictionary. However, performing the lookup with the interned key gives you speed back, as then dictionary lookup won't need to compare the tuples, but will find that the search key is identical to the stored key, so the keys are certainly equal. Regards, Martin From frank.wagner.1983 at googlemail.com Tue Apr 17 10:48:54 2007 From: frank.wagner.1983 at googlemail.com (Johnny Blonde) Date: 17 Apr 2007 07:48:54 -0700 Subject: rewrite for achieving speedup Message-ID: <1176821334.217154.36350@y80g2000hsf.googlegroups.com> Hello Group! I really tried hard for two hours to rewrite the following expression (python 2.4): -------------------------- teilnehmer = [] for r in Reisen.select(AND(Reisen.q.RESVON <= datum, Reisen.q.RESBIS >= datum)): for g in r.BUCHUNGEN: for t in g.aktiveTeilnehmer: teilnehmer.append(t) -------------------------- to something like -------------------------- teilnehmer = [x for x in ........] -------------------------- Reisen is a SQLObject class, Reisen.select(...), aktiveTeilnehmer and BUCHUNGEN all are of the type SelectResults. unfortunately i just can?t figure it out to make it work. i hope someone maybe can help me? I hope to gain performance by rewriting it... Thanks a lot for your help! Regards, Frank From cam.ac.uk at mh391.invalid Thu Apr 26 06:50:44 2007 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Thu, 26 Apr 2007 11:50:44 +0100 Subject: Coding conventions for class names In-Reply-To: <1177575349.010881.174590@c18g2000prb.googlegroups.com> References: <1177492705.232244.312520@c18g2000prb.googlegroups.com> <1177575349.010881.174590@c18g2000prb.googlegroups.com> Message-ID: Kay Schluehr wrote: > What happens when an enthusiast re-implements a stdlib module e.g. > decimal s.t. it becomes a builtin module? Will the stdlib module serve > as a wrapper to conform the current API or will the builtin module > conform to the current interface. Well, the best example is probably the transition from sets.Set to __builtin__.set. The API changed but only slightly. So far sets.Set retains the old implementation--it is not a wrapper for __builtin__.set. Future modules may be implemented differently. -- Michael Hoffman From tom at finland.com Tue Apr 3 11:57:53 2007 From: tom at finland.com (tom at finland.com) Date: Tue, 03 Apr 2007 15:57:53 GMT Subject: Stack experiment Message-ID: <5QuQh.152$9L1.108@read3.inet.fi> Hi! Im new to Python and doing exercise found from internet. It is supposed to evaluate expression given with postfix operator using Stack() class. class Stack: def __init__(self): self.items = [] def push(self, item): self.items.append(item) def pop(self): return self.items.pop() def isEmpty(self): return (self.items == []) def evaluatePostfix(expr): import re tokenList = re.split(" ([^0-9])", expr) stack = Stack() for token in tokenList: if token == '' or token == ' ': continue if token == '+': sum = stack.pop() + stack.pop() stack.push(sum) elif token == '*': product = stack.pop() * stack.pop() stack.push(product) else: stack.push(int(token)) return stack.pop() print evaluatePostfix("56 47 + 2 *") Errormsg: Traceback (most recent call last): File "C:\*\postfix1.py", line 31, in print evaluatePostfix("56 47 + 2 *") File "C:\*\postfix1.py", line 28, in evaluatePostfix stack.push(int(token)) ValueError: invalid literal for int() with base 10: '56 47' How can I avoid the error and get desired result? From flyzone at technologist.com Wed Apr 18 05:13:18 2007 From: flyzone at technologist.com (Flyzone) Date: 18 Apr 2007 02:13:18 -0700 Subject: exception just to avoid output error (newbie) Message-ID: <1176887598.528960.240820@d57g2000hsg.googlegroups.com> Hi I'm trying to delete some files, but i get an exception error if the file don't exist. I can use an {if fileexist(file) then delete}, but it will get cpu time. So i catch the exception with: try: os.remove(filename) except EnvironmentError: error=1 If i just want to avoid the output error, is this the right way to write the code? I don't care of get if is in error, but an "except EvironmetError" without the ":" will give me a sytax error. Am I too much complicated? :-) Thanks in advance From nogradi at gmail.com Thu Apr 19 17:34:58 2007 From: nogradi at gmail.com (Daniel Nogradi) Date: Thu, 19 Apr 2007 23:34:58 +0200 Subject: Python un-plugging the Interpreter In-Reply-To: <005f01c782a3$ae84d710$fa936540@cisco.com> References: <005f01c782a3$ae84d710$fa936540@cisco.com> Message-ID: <5f56302b0704191434x76b91182o5ca5461f30c2948f@mail.gmail.com> > Hi All, > I was thinking about the feasbility of adjusting Python as a > compiled language. Being said that I feel these are the following advantages > of doing so -- > 1) Using the powerful easy-to -use feature of Python programming language > constructs. > 2) Making the program to run at par with the compiled version of C/C++ > program- this is the main benefit which can be derived out of this. > 3) Highly re-use existing Python code for High performance application. > 4) Acheive true parallelism and performance by getting rid of the > middle-man Interpreter and GIL. > > I know this must be appearing like a foolish idea. But I would like to know > the opinion of people who might have thought about it. Have a look at pypy: http://codespeak.net/pypy/dist/pypy/doc/news.html Especially the statement: "Rumors have it that the secret goal is being faster-than-C which is nonsense, isn't it?" Daniel From soren.skou.nielsen at gmail.com Fri Apr 27 08:31:30 2007 From: soren.skou.nielsen at gmail.com (Soren) Date: 27 Apr 2007 05:31:30 -0700 Subject: Multiple select in wx.GenericDirCrtl Message-ID: <1177677090.037403.209940@n15g2000prd.googlegroups.com> Hi! Is it possible to do multiple file selections in a wx.GenericDirCtrl?? Thanks, Soren From adrian_p_smith at yahoo.com Sun Apr 22 11:01:50 2007 From: adrian_p_smith at yahoo.com (Adrian Smith) Date: 22 Apr 2007 08:01:50 -0700 Subject: python cgi problem with textarea In-Reply-To: <1177247362.014926.12500@n76g2000hsh.googlegroups.com> References: <1177222084.696307.128620@n59g2000hsh.googlegroups.com> <1177247362.014926.12500@n76g2000hsh.googlegroups.com> Message-ID: <1177254110.057238.315240@o5g2000hsb.googlegroups.com> On Apr 22, 10:09 pm, placid wrote: > i just tried it and its working. here it is > > http://yallara.cs.rmit.edu.au/~bevcimen/form.html > > maybe the internal server error is because mod_python isn't installed > assuming your using Apache as your web server Yeah, but it wouldn't work *at all* in that case, would it? ATM it seems to work as long as the textarea input has no spaces. From quetzalcotl at consultant.com Wed Apr 18 05:18:49 2007 From: quetzalcotl at consultant.com (Ingo Menger) Date: 18 Apr 2007 02:18:49 -0700 Subject: is laziness a programer's virtue? In-Reply-To: References: <1176757271.282365.319740@n76g2000hsh.googlegroups.com> <1176797558.403629.53140@b75g2000hsg.googlegroups.com> <1176823224.099381.4630@n59g2000hsh.googlegroups.com> Message-ID: <1176887929.405058.57960@y80g2000hsf.googlegroups.com> On 18 Apr., 01:54, Lew wrote: > Markus E Leypold > > >> Trying to correct Xah's behaviour is probably impossible. > Ingo Menger wrote: > > Perhaps somebody could ask the chinese government to put him in jail > > for "hurting international society" :) > > Y'know, even in jest, calling for an oppressive regime to suppress even > wrong-headed and self-serving garbage self-expression is immoral and horrible. You're right. I confess this joke was going too far. > Free speech, free press and free expression of ideas is not something to take > so lightly. I'm with you on this point. But, since the biggest crime in Xah Lee's opinion apparently is "harming" and "damaging" society through expression of ideas, it must be possible to judge him by his own standards. From grante at visi.com Tue Apr 24 12:56:45 2007 From: grante at visi.com (Grant Edwards) Date: Tue, 24 Apr 2007 16:56:45 -0000 Subject: Generate report containing pdf or ps figures? References: <132pnp6r4qg0lc2@corp.supernews.com> Message-ID: <132sdmde3vg6kf3@corp.supernews.com> On 2007-04-24, Steve Holden wrote: >>> I've looked at ReportLab's documentation, but although it >>> appears to be able to use bitmap images (e.g jpeg) it doesn't >>> appear to be able to use vector images (EPS/PDF/SVG). >>> >>> Is there a PDF generation library that can place EPS or >>> PDF figures on a page? >> . >> . >> . >> You're stuck. [...] > > In fairness to ReportLab I'd like to say that their *commercial* > products can do everything the OP asks for and more besides, but > unfortunately they are mostly targeted at the "enterprise" (read: big > money) market. This is just a smallish app for internal use by 1-2 people, so I probably can't justify spending much cash. I'll check on the ReportLab pricing. By the time I figure out how to bundle Ghostscript with py2exe, it will probably have been cheaper to pay for a copy of ReportLab. But it's usually easier to spend a week of engineering time that it is to spend $1000. -- Grant Edwards grante Yow! I am covered with at pure vegetable oil and I am visi.com writing a best seller! From soyouthinkimgonnalikethis at hotmail.com Sat Apr 7 20:53:12 2007 From: soyouthinkimgonnalikethis at hotmail.com (Eric Price) Date: Sat, 07 Apr 2007 19:53:12 -0500 Subject: Can't Get Email Interface Working In-Reply-To: Message-ID: >From: hlubenow >To: python-list at python.org >Subject: Re: Can't Get Email Interface Working >Date: Sun, 08 Apr 2007 01:59:53 +0200 > >You can use it just like that: > >----------------------------------- > >from simplemail import Email >Email( > from_address = "sender at domain.net", > to_address = "receiver at domain.net", > subject = "Subject", > message = "Text of the message" >).send() > That's easy enough ;) I ran it from the python interpreter and it returned "True". I presume that's a good sign ;) Thanks, Eric _________________________________________________________________ Need a break? Find your escape route with Live Search Maps. http://maps.live.com/?icid=hmtag3 From gagsl-py2 at yahoo.com.ar Thu Apr 12 06:42:13 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 12 Apr 2007 07:42:13 -0300 Subject: redirecting stdout to a file as well as screen References: <1176362072.527678.201150@l77g2000hsb.googlegroups.com> <1176368478.301318.35210@q75g2000hsh.googlegroups.com> <1176373423.576445.123220@y5g2000hsa.googlegroups.com> Message-ID: En Thu, 12 Apr 2007 07:23:43 -0300, SamG escribi?: >> >> > How could i make, from inside the program, to have the stdout and >> >> > stderr to be printed both to a file as well the terminal(as usual). >> >> >> class Tee(file): >> >> others = () >> >> >> def write(self, data): >> >> file.write(self, data) >> >> for f in others: >> >> f.write(data) >> >> > This is only creating an out.log file and all the stdout and stderr >> > are logged there. >> >> Sorry, `for f in others:` should read `for f in self.others:` >> > Does not make difference, does this work for you? Im working on linux. > But this code looks portable except for the file path :) Yes. And it's rather similar to your other example... Omit sys.stderr as Antoon Pardon suggested. -- Gabriel Genellina From Eric_Dexter at msn.com Sun Apr 15 09:53:21 2007 From: Eric_Dexter at msn.com (Eric_Dexter at msn.com) Date: 15 Apr 2007 06:53:21 -0700 Subject: Getting started with python In-Reply-To: <1176598011.463543.96990@q75g2000hsh.googlegroups.com> References: <1176598011.463543.96990@q75g2000hsh.googlegroups.com> Message-ID: <1176645201.901480.277030@d57g2000hsg.googlegroups.com> On Apr 14, 7:46 pm, "Eric" wrote: > Hello, after reading some of the book Programming Python it seems that > python is something I would like to delve deeper into. The only thing > is, I have no idea what I should try and write. So I was hoping that > someone here could help point me to a group/project that would be a > good starting place for a person with limited python knowledge, but > that is willing to learn whatever is necessary. I'm hoping that with a > goal I can start to learn python instead of just playing around with > it. Thanks. I have a little sub-project where I generate random numbers to a music file (a simpe ascii format that works in a grid) http://www.stormpages.com/edexter/csound.html or if you see some other part of it you would like to work on or expand.. https://sourceforge.net/projects/dex-tracker I haven't added the sub- project yet but I can upload it to some google space if you are intrested.. (uses wxwindows and python 2.5) From anton.vredegoor at gmail.com Thu Apr 19 12:13:13 2007 From: anton.vredegoor at gmail.com (Anton Vredegoor) Date: Thu, 19 Apr 2007 18:13:13 +0200 Subject: multirember&co In-Reply-To: References: <1176768854.720234.23320@w1g2000hsg.googlegroups.com> <1176790588.024371.119360@n76g2000hsh.googlegroups.com> <1176850352.999231.79260@n59g2000hsh.googlegroups.com> <1176921030.330467.76860@o5g2000hsb.googlegroups.com> <1176925857.535835.130010@b58g2000hsg.googlegroups.com> Message-ID: Anton Vredegoor wrote: > Anton Vredegoor wrote: >> attn.steven.kuo at gmail.com wrote: >> >>> Try it with >>> >>> def test(): >>> L = 'a', 1, 2, 'a' >>> it1, it2 = xsplitter(L, lambda x: x == 'a') >>> print it1.next() >>> print it2.next() >>> print it1.next() >>> print it2.next() >>> >>> >>> The last print statement raises StopIteration... >>> We, however, expected each iterator to contain >>> two elements (one yielding 'a' then 'a', and >>> the other yielding 1 then 2). >> Ouch! I never understood much about generators anyway. > > How about this one? No that can result in an infinite loop after yet another print it1.next() This one however ... from collections import deque class sentinel(object): pass class myiter(object): def __init__(self,seq): self.seq = seq self.index = -1 def __iter__(self): return self def next(self): self.index +=1 if self.index < len(self.seq): return self.seq[self.index] else: return sentinel def xsplitter(seq, pred): Q = deque(),deque() it = myiter(seq) def gen(p): for x in it: while Q[p]: yield Q[p].popleft() if x is sentinel: break if pred(x) == p: yield x else: Q[~p].append(x) for x in gen(p): yield x return gen(1),gen(0) def test(): L = 'a', 1, 2, 'a' it1, it2 = xsplitter(L, lambda x: x == 'a') print it1.next() print it2.next() print it1.next() print it2.next() if __name__=='__main__': test() A. From jeff at jmcneil.net Tue Apr 10 19:39:01 2007 From: jeff at jmcneil.net (Jeff McNeil) Date: Tue, 10 Apr 2007 19:39:01 -0400 Subject: XML-RPC SSL and client side certs? In-Reply-To: <1176241420.420028.276030@y5g2000hsa.googlegroups.com> References: <1176241420.420028.276030@y5g2000hsa.googlegroups.com> Message-ID: <82d28c40704101639m5ea9c1f0ja80a053b045f0b80@mail.gmail.com> I apologize for not giving you a Python specific answer, but for the XMLRPC services I've deployed, I front them with Apache and proxy back to localhost:8080. I do all of the encryption and authentication from within the Apache proper and rely on mod_proxy to forward validated requests on. I've settled on basic authentication, but I see no reason why you couldn't take advantage of mod_ssl. Thanks, hope that helps. Just another option, really. Jeff On 10 Apr 2007 14:43:40 -0700, Eli Criffield wrote: > > Does anyone have an example setup of a XML-RPC sever using client side > certs for authentication? > > And instead of having a list of certs allowed to connect, I'd like to > allow any cert signed by my CA. > > It doesn't seem like it would be to hard to do and I'll probably spend > some time setting it up here soon, but would be interested if anyone > else has already written a solution like this or has used one (in > python of course). > > Eli Criffield > > -- > http://mail.python.org/mailman/listinfo/python-list > From danb_83 at yahoo.com Sun Apr 15 21:19:00 2007 From: danb_83 at yahoo.com (Dan Bishop) Date: 15 Apr 2007 18:19:00 -0700 Subject: Python Feature Request: Allow changing base of member indices to 1 In-Reply-To: <1176678395.638748.174140@o5g2000hsb.googlegroups.com> References: <1176546465.632410.52630@w1g2000hsg.googlegroups.com> <1176579205.948684.171640@q75g2000hsh.googlegroups.com> <1176584444.335732.111740@n76g2000hsh.googlegroups.com> <1hwkok3.1kmipey1iv5ldzN%aleax@mac.com> <1176606776.016013.205170@p77g2000hsh.googlegroups.com> <1176678395.638748.174140@o5g2000hsb.googlegroups.com> Message-ID: <1176686340.575584.94970@o5g2000hsb.googlegroups.com> On Apr 15, 6:06 pm, "Beliavsky" wrote: > On Apr 14, 10:12 pm, "Paddy" wrote: > > > > > So the running count is: > > Ayes to the left: VB compatibility. > > Nays to the right: QuadIO, Perl, Dijkstra paper. > > > The nays have it! > > One-based indexing would also Python more compatible with Fortran, > Matlab/Octave/Scilab, and S (the language of S-Plus and R). It appears > that engineers, scientists, and statisticians, as opposed to > professional programmers, like 1-based indexing. An obvious argument > for 1-based indexing in the FORmula TRANslation programming language > is that formulas involving arrays in textbooks almost always use 1- > based indexing. I've seen plenty of examples of zero-based indexing in math textbooks. For example, the coefficients of polynomials and Fourier cosine series, both of which use a zero subscript for the constant term. From gagsl-py2 at yahoo.com.ar Sat Apr 7 22:28:30 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: 7 Apr 2007 19:28:30 -0700 Subject: How to control files such as windows update program? In-Reply-To: <1175997193.271155.144030@d57g2000hsg.googlegroups.com> References: <1175997193.271155.144030@d57g2000hsg.googlegroups.com> Message-ID: <1175999310.048693.288280@e65g2000hsc.googlegroups.com> soarnil wrote: > I hope i could write a program to execute a range of ".exe" files. > When there is a "Licensing Agreement", the program can choose > "Accept",then click "Next" until "Finish".Or maybe it could use some > function to finish this rather then really "click" the buttons. Some installers accept command line options to control how they behave, and sometimes you can run the installation completely unattended. If there are no choices, you could use pyWinAuto to "click" the buttons. -- Gabriel Genellina From gagsl-py2 at yahoo.com.ar Fri Apr 20 17:07:40 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 20 Apr 2007 18:07:40 -0300 Subject: When to clear a dictionary... References: <6sCdnXnrw_aAZbXbnZ2dnUVZ_sOknZ2d@comcast.com> Message-ID: En Fri, 20 Apr 2007 14:28:00 -0300, Larry Bates escribi?: > Bill Jackson wrote: >> What is the benefit of clearing a dictionary, when you can just reassign >> it as empty? > > If you have objects that point to the dictionary (something like a cache) > then you want to clear the existing dictionary instead of just assigning > it to empty. If nothing points to it, assigning it to empty is fast and > you can let garbage collection do the rest. For an actual comparision, see Alex Martelli posts a few days ago: http://mail.python.org/pipermail/python-list/2007-March/433027.html >>>>> a = {1:2,3:4} >>>>> b = {1:2:4:3} >>>>> a.clear() >>>>> a.update(b) >> >>>>> a = {1:2,3:4} >>>>> b = {1:2,4:3} >>>>> for key in b: >> ... a[key] = b[key] >> > Syntax error in the first example but if you fix that the first two are > equivalent (but I would suspect that the second would be faster for large > dictionaries). It's the other way; the first method contains a single Python function call and most of the work is done in C code; the second does the iteration in Python code and is about 4x slower. > python -m timeit -s "b=dict.fromkeys(range(10000));a={}" "a.update(b)" 100 loops, best of 3: 10.2 msec per loop > python -m timeit -s "b=dict.fromkeys(range(10000));a={}" "for key in b: > a[key]=b[key]" 10 loops, best of 3: 39.6 msec per loop -- Gabriel Genellina From piyali.de.bis at gmail.com Wed Apr 18 09:14:45 2007 From: piyali.de.bis at gmail.com (piyali biswas) Date: Wed, 18 Apr 2007 18:44:45 +0530 Subject: solved Message-ID: <75c5d9400704180614o29e697f0j6a2918d6383f55d8@mail.gmail.com> hi all, I solved the problem with the help of python cookbook+matplotlib I was getting the main error as * raise RuntimeError("'%s' is not a writable dir; you must set environment variable HOME to be * * a writable dir "%h)* Matplotlib needs the environment variable HOME to point to a writable directory.Thats why i did os.environ[ 'HOME' ] = 'C:/temp' and the cgi-script worked. For further questions about cgi+matplotlib/networkx please see http://www.scipy.org/Cookbook. Its very useful Thanks, Piyali Biswas -------------- next part -------------- An HTML attachment was scrubbed... URL: From sberub at gmail.com Fri Apr 27 20:56:17 2007 From: sberub at gmail.com (Simon Berube) Date: 27 Apr 2007 17:56:17 -0700 Subject: Memory addressing In-Reply-To: <1177717894.219673.141920@c35g2000hsg.googlegroups.com> References: <1177702902.156596.52510@n35g2000prd.googlegroups.com> <1177703803.179501.95300@n35g2000prd.googlegroups.com> <1177715277.592511.296990@h2g2000hsg.googlegroups.com> <1177717894.219673.141920@c35g2000hsg.googlegroups.com> Message-ID: <1177721777.703798.228850@n76g2000hsh.googlegroups.com> Well what I was looking for is more along the lines of if it was possible to assign an object at a fixed memory address like C. But most importantly I was expecting it to be a bad habbit in python and was simply wondering what was the accepted manner of doing so. I did know everything was passed by reference in Python but I was simply curious about the ability to just use *f1 = memory_address In order to create an object. The only use I saw for this was in the case of a string returning the memory location albeit from the replies I got that this would not really be desirable and necessary. I was really just trying to avoid developping bad habbits or depending on something that shouldnt be used commonly in the language. I think my question has been answered well so I would like to thank everyone for their input. Albeit a memory copy function would be fun to use but ultimately not very fit for such a high level language I suppose. Again, thank you everyone this forum is very helpful, Regards, On Apr 27, 7:51 pm, Gabriel Genellina wrote: > On 27 abr, 20:07, castiro... at gmail.com wrote: > > > That's what we need: a CopyMemory() routine. > > See the copy and pickle modules. > > -- > Gabriel Genellina From aleax at mac.com Sat Apr 28 17:34:35 2007 From: aleax at mac.com (Alex Martelli) Date: Sat, 28 Apr 2007 14:34:35 -0700 Subject: editing scripts on a mac References: Message-ID: <1hxaayb.1ckyktqpnll2xN%aleax@mac.com> Michael Bentley wrote: ... > highlighting for Python (and most everything else). But both Text > Edit and nano are dead easy for noobs. TextMate, a shareware program, is also widely appreciated -- it has pretty good support for many languages, including Python. Personally, I swear by VIM (the full downloaded version with GUI support and everything, see ) but unless you like the general approach of vi I guess you're more likely to swear AT it than BY it:-). Alex From steve at REMOVE.THIS.cybersource.com.au Fri Apr 20 22:16:44 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Sat, 21 Apr 2007 12:16:44 +1000 Subject: When are immutable tuples *essential*? Why can't you just use lists *everywhere* instead? References: <1177088796.622928.224890@d57g2000hsg.googlegroups.com> <1177089206.550423.288670@q75g2000hsh.googlegroups.com> <58sf33F2b1q8tU1@mid.individual.net> <1177103370.022138.110320@n59g2000hsh.googlegroups.com> <1177108656.291537.182560@o5g2000hsb.googlegroups.com> <1177109625.619171.121610@d57g2000hsg.googlegroups.com> Message-ID: On Fri, 20 Apr 2007 15:53:45 -0700, garrickp wrote: > Speaking of inessential but very useful things, I'm also a big fan of > the tuple swap... > a = 2 > b = 3 > (a, b) = (b, a) Since tuples are made by commas, not brackets, that can be written more cleanly as: a, b = b, a The only exception is the special case of an empty tuple, which can be written as (). > IMO, the biggest thing going for tuples is the syntactical sugar they > bring to Python. More important than the ability to use them as keys in dicts? -- Steven. From kay.schluehr at gmx.net Wed Apr 25 05:18:25 2007 From: kay.schluehr at gmx.net (Kay Schluehr) Date: 25 Apr 2007 02:18:25 -0700 Subject: Coding conventions for class names Message-ID: <1177492705.232244.312520@c18g2000prb.googlegroups.com> set, int, float, list, object,... Don't see any of the basic types following the capitalized word convention for classes covered by PEP 08. This does not hold only for __builtins__ in the strict sense but also for types defined in builtin modules like datetime. My question is: does anyone actually follow guidelines here and if yes which ones and are they resonable ( e.g. stable with regard to refactoring etc. )? From Alien8752 at gmail.com Tue Apr 17 22:34:23 2007 From: Alien8752 at gmail.com (nuny@bid.nes) Date: 17 Apr 2007 19:34:23 -0700 Subject: ??? POLICE AND CITY/UNIVERSITY OFFICIALS INCOMPETENCE LEADS TO 33 KILLED BY KOREAN-ALQAEDA TERRORIST ??? In-Reply-To: <1176819514.797706.124470@q75g2000hsh.googlegroups.com> References: <1176818165.135834.214220@y80g2000hsf.googlegroups.com> <1176819514.797706.124470@q75g2000hsh.googlegroups.com> Message-ID: <1176863663.082229.312570@y5g2000hsa.googlegroups.com> On Apr 17, 7:18 am, lemnit... at india.com wrote: > ...Bush has a knack for USING minorities for dirty jobs. > He used the mexican dog Gonzalez to serve his neocon agenda instead of > the american people. Um, Gonzalez is a Texan by birth. Let me guess again; you believe if only "we" could kick out all the "nonWhite and "nonChristians" the USA would be a better country? Fuck you and your "Brother John Birch" so very much. As for the rest of your screed; "So much bullshit, so little time". Mark L. Fergerson From josiah.carlson at sbcglobal.net Fri Apr 27 03:22:06 2007 From: josiah.carlson at sbcglobal.net (Josiah Carlson) Date: Fri, 27 Apr 2007 07:22:06 GMT Subject: regex question In-Reply-To: <1177655637.717863.93920@o40g2000prh.googlegroups.com> References: <1177655637.717863.93920@o40g2000prh.googlegroups.com> Message-ID: proctor wrote: > i have a regex: rx_test = re.compile('/x([^x])*x/') You probably want... rx_test = re.compile('/x([^x]*)x/') - Josiah From Martin.Drautzburg at web.de Mon Apr 23 02:14:32 2007 From: Martin.Drautzburg at web.de (Martin Drautzburg) Date: Mon, 23 Apr 2007 08:14:32 +0200 Subject: Dictionaries and dot notation References: <23087554.X5dcTmlj7P@beaureve.gmx.net> <462B6227.5070405@web.de> <5296241.Dh78hTc8ZZ@beaureve.gmx.net> <1hwzndv.1licthzy6aocnN%aleax@mac.com> Message-ID: <1724551.h8mdBJEZWL@beaureve.gmx.net> Alex Martelli wrote: > Martin Drautzburg wrote: > >> > mydata = data( ) >> > mydata.foo = 'foo' >> > mydata.bar = 'bar' >> > >> > print mydata.foo >> > print mydata.bar >> >> I am aware of all this. >> Okay let me rephrase my question: is there a way of using dot >> notation without having to create a class? > > Sure, all you need to create is an *INSTANCE* of a suitable type or > class. For example: > >>>> d = dict(foo=23, bar=45) >>>> m = new.module('for_martin') >>>> m.__dict__.update(d) >>>> m.foo > 23 >>>> m.bar > 45 >>>> > > A module may be appropriate, since it's little more than a "wrapper > around a dict to access items by dot notation":-). Thanks, I finally got it. Even your previous example actually does the trick. I did not notice that I can use a single class (or a module) for all my datastructures, because I can "plug in" new attributes into the instance without the class knowing about them. I was mistaken to believe that I had to know about attributes at the time of class creation. But your expample does not require that. Should have read this more carefully. From Martin.Drautzburg at web.de Sun Apr 22 12:33:24 2007 From: Martin.Drautzburg at web.de (Martin Drautzburg) Date: Sun, 22 Apr 2007 18:33:24 +0200 Subject: Dictionaries and dot notation References: <23087554.X5dcTmlj7P@beaureve.gmx.net> <462B6227.5070405@web.de> Message-ID: <5296241.Dh78hTc8ZZ@beaureve.gmx.net> > mydata = data( ) > mydata.foo = 'foo' > mydata.bar = 'bar' > > print mydata.foo > print mydata.bar I am aware of all this. Okay let me rephrase my question: is there a way of using dot notation without having to create a class? From ptmcg at austin.rr.com Fri Apr 13 11:41:31 2007 From: ptmcg at austin.rr.com (Paul McGuire) Date: 13 Apr 2007 08:41:31 -0700 Subject: Problem with algorithm In-Reply-To: References: <1176434160.047703.214600@q75g2000hsh.googlegroups.com> <1176434937.258002.162220@p77g2000hsh.googlegroups.com> <1176448576.047996.12930@d57g2000hsg.googlegroups.com> <1176473989.420067.190970@l77g2000hsb.googlegroups.com> Message-ID: <1176478891.573874.16050@y80g2000hsf.googlegroups.com> On Apr 13, 10:22 am, Michael Bentley wrote: > On Apr 13, 2007, at 9:19 AM, Paul McGuire wrote: > > > If you just expand the length to five million* or so, one of those > > strings will contain all the works of Shakespeare. > > Not likely, even with a tiny sampling of the works of Shakespeare: > > # :-) > > import string > import random > > def main(bardText, maxTries=5000000): > tries = 0 > while tries < maxTries: > tries += 1 > attempt = [] > for letter in bardText.lower(): > if random.choice( > string.lowercase[:26] > + string.punctuation > + ' ' > ) == letter: > attempt.append(letter) > else: > break > if len(attempt) >= 4: > print '%d: %s' % ( > tries, > ''.join(attempt) > ) > > if __name__ == "__main__": > main("Alas, poor Yorick!") 5000000 << infinity Keep tryin'! Also, the OP's technique was not doing random string permutations, but generating an exhaustive list of all possible sequences from aaa... to zzz... . So I think the works of Shakespeare are *bound* to be in there somewhere. For proof, here's an extract from my sample code from running this exhaustive program with length=14: ... ALASPOORYORICG ALASPOORYORICH ALASPOORYORICI ALASPOORYORICJ ALASPOORYORICK ALASPOORYORICL ALASPOORYORICM ALASPOORYORICN ALASPOORYORICO ... -- Paul :) (too late for April 1, unfortunately) From tinaweb at bestemselv.com Tue Apr 24 07:44:05 2007 From: tinaweb at bestemselv.com (Tina I) Date: Tue, 24 Apr 2007 13:44:05 +0200 Subject: Catching a specific IO error Message-ID: Hi group :) I have this standard line: export = open(self.exportFileName , 'w') 'exportFileName' is a full path given by the user. If the user gives an illegal path or filename the following exception is raised: "IOError: [Errno 2] No such file or directory: /some/path/file.txt" So at the moment I do this: try: export = open(self.exportFileName , 'w') export.write("Something") export.close() except IOError: # calling an error handling method. Now, this works but of course it catches every IOError, and I can not figure out how to restrict it to only catch the "[Errno 2]"? Thanks Tina From duncan.booth at invalid.invalid Fri Apr 27 10:37:53 2007 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 27 Apr 2007 14:37:53 GMT Subject: regex question References: <1177655637.717863.93920@o40g2000prh.googlegroups.com> <1177659238.159411.40640@c18g2000prb.googlegroups.com> <1177683018.566343.105620@c18g2000prb.googlegroups.com> Message-ID: proctor <12cc104 at gmail.com> wrote: > so my question remains, why doesn't the star quantifier seem to grab > all the data. isn't findall() intended to return all matches? i > would expect either 'abc' or 'a', 'b', 'c' or at least just > 'a' (because that would be the first match). why does it give only > one letter, and at that, the /last/ letter in the sequence?? > findall returns the matched groups. You get one group for each parenthesised sub-expression, and (the important bit) if a single parenthesised expression matches more than once the group only contains the last string which matched it. Putting a star after a subexpression means that subexpression can match zero or more times, but each time it only matches a single character which is why your findall only returned the last character it matched. You need to move the * inside the parentheses used to define the group, then the group will match only once but will include everything that it matched. Consider: >>> re.findall('(.)', 'abc') ['a', 'b', 'c'] >>> re.findall('(.)*', 'abc') ['c', ''] >>> re.findall('(.*)', 'abc') ['abc', ''] The first pattern finds a single character which findall manages to match 3 times. The second pattern finds a group with a single character zero or more times in the pattern, so the first time it matches each of a,b,c in turn and returns the c, and then next time around we get an empty string when group matched zero times. In the third pattern we are looking for a group with any number of characters in it. First time we get all of the string, then we get another empty match. From nagle at animats.com Tue Apr 24 13:18:30 2007 From: nagle at animats.com (John Nagle) Date: Tue, 24 Apr 2007 17:18:30 GMT Subject: Python un-plugging the Interpreter In-Reply-To: <1hx2dgy.zizz7ir95hlgN%aleax@mac.com> References: <1hwu415.1yyvbo61efn1uqN%aleax@mac.com> <1hx2dgy.zizz7ir95hlgN%aleax@mac.com> Message-ID: Alex Martelli wrote: > Jorgen Grahn wrote: > ... > >>>Perhaps the current wave of dual-core and quad-core CPUs in cheap >>>consumer products would change people's perceptions -- I wonder... > IronPython would appear to be coming along nicely and getting acceptance > in the Windows community, and I believe the underlying dotNet CLR does > do threads nicely; we'll see what develops on that front, I guess. Thus we now have a demonstration that Python implementations need not be as slow as CPython. And that Microsoft is beating open source on Python. Python as a language is in good shape. But the CPython implementation is holding back progress. What we need are better and faster implementations of the language we've got. PyPy, ShedSkin, and Jython all were steps in the right direction, but none had enough momentum to make it. Jython hasn't had a release since 2002, ShedSkin is basically one guy, and the EU pulled the plug on PyPy. Now what? John Nagle From bbxx789_05ss at yahoo.com Sat Apr 7 15:18:57 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: 7 Apr 2007 12:18:57 -0700 Subject: tuples, index method, Python's design In-Reply-To: References: <1175867771.114540.61810@n76g2000hsh.googlegroups.com> <1175884427.779950.267220@y80g2000hsf.googlegroups.com> <1175953520.316208.241490@o5g2000hsb.googlegroups.com> Message-ID: <1175973537.371754.78450@y66g2000hsf.googlegroups.com> On Apr 7, 8:27 am, Carsten Haese wrote: > On Sat, 2007-04-07 at 06:45 -0700, bearophileH... at lycos.com wrote: > > Carsten Haese: > > > The lack of convincing use cases is still a pertinent reason today. Note > > > that the original poster on this thread did not present a use case for > > > tuple.index, they were only asking out of curiosity. > > > If you have a use case for tuple.index, please show it to me, and I'll > > > show you what you should be using instead of a tuple. > > > Maybe we can add such methods to the PyPy tuples for some time, to > > experimentally see if they make the language worse :-) > > Adding useless features always makes a product worse. What's your use > case for tuple.index? > > -Carsten I'll trade you an index method for tuples for the whole complex number facility. From Bulkan at gmail.com Sun Apr 22 09:09:22 2007 From: Bulkan at gmail.com (placid) Date: 22 Apr 2007 06:09:22 -0700 Subject: python cgi problem with textarea In-Reply-To: <1177222084.696307.128620@n59g2000hsh.googlegroups.com> References: <1177222084.696307.128620@n59g2000hsh.googlegroups.com> Message-ID: <1177247362.014926.12500@n76g2000hsh.googlegroups.com> On Apr 22, 4:08 pm, Adrian Smith wrote: > This may be more a cgi thing than a Python one, but I'm trying to get > this page: > > http://adrian10.phpwebhosting.com/trial.html > > consisting basically of this: > >

> >

>

> > ...to print out the contents of the textarea with this cgi script: > > #!/usr/bin/python > import cgi > print "Content-type: text/html\n" > form = cgi.FieldStorage() > print form["essay"].value > > ...and I get an internal server error if I have any spaces in the > textarea, which is really going to limit its usefulness to me. Oddly, > it seems to work for a friend in the UK who's looked at it, but it > doesn't work for me here in Japan. i just tried it and its working. here it is http://yallara.cs.rmit.edu.au/~bevcimen/form.html maybe the internal server error is because mod_python isn't installed assuming your using Apache as your web server Cheers From slm_guzel at hotmail.com Tue Apr 3 14:41:59 2007 From: slm_guzel at hotmail.com (gslm) Date: 3 Apr 2007 11:41:59 -0700 Subject: doing standart window icons unvisible in python In-Reply-To: References: <1175549454.378661.93570@y66g2000hsf.googlegroups.com> Message-ID: <1175625719.902932.36840@l77g2000hsb.googlegroups.com> Only I want to print my application's view without these icons,ok. Thanks. From kenneth.m.mcdonald at sbcglobal.net Mon Apr 2 16:01:53 2007 From: kenneth.m.mcdonald at sbcglobal.net (Kenneth McDonald) Date: Mon, 02 Apr 2007 15:01:53 -0500 Subject: curses module Message-ID: <46116131.3010906@sbcglobal.net> I know that the curses module has a long-standing bug wherein cursor visibility can't be set. I'm looking at using the module for certain uses, and this isn't a problems (as long as I hide the cursor offscreen) as I would control visuals to provide a simulated cursor anyway. I'm wondering, though, if there are any other elements of the curses module I should be aware of before I commit to it, i.e. bugs that could cause serious difficulties at some point. This isn't criticism, I just know that the curses module is the sort of thing that probably isn't being maintained consistently, and I for one, have no idea how well all the new terms in common use maintain the sort of backwards compatibility python curses will need to do its job. Thanks, Ken From amaccormack at gmail.com Mon Apr 2 12:11:22 2007 From: amaccormack at gmail.com (amaccormack at gmail.com) Date: 2 Apr 2007 09:11:22 -0700 Subject: Parallel ping problems python puzzler In-Reply-To: <1175522608.589651.137580@n76g2000hsh.googlegroups.com> References: <1175509753.092714.281990@n76g2000hsh.googlegroups.com> <1175522608.589651.137580@n76g2000hsh.googlegroups.com> Message-ID: <1175530282.781862.147570@n76g2000hsh.googlegroups.com> On 2 Apr, 15:03, "Miki" wrote: > Hello, > > > def run(self): > > # -w 1 option topingmakes ittimeoutafter 1 second > > pingcmd="/bin/ping-c 2 -q -i 0.3 -w 1 %s >/dev/null" % ip > > Not sure, but "ip" should be "self.ip", this might cause theproblem. Sorry, that was my bad cutting-and-pasting to make a shorter example, it IS self.ip in the real code. The REAL code works fine parallel or serial as long as everything responds to the ping, but as soon as any devices do not respond, it hangs in the threaded version. From mwilson at the-wire.com Sat Apr 28 19:01:19 2007 From: mwilson at the-wire.com (Mel Wilson) Date: Sat, 28 Apr 2007 19:01:19 -0400 Subject: Numbers and truth values In-Reply-To: References: Message-ID: John Nagle wrote: > "True", "False", and "None" should be reserved words in Python. > "None" already is. The permissiveness makes it less painful to upgrade to new versions of Python. True and False only recently got assigned conventional values, but you can still import old modules without worrying whether they might violate the new rule; if True and False once meant something special to them, it will still mean the same thing. Meanwhile new code can follow the new conventions. Mel. From kar1107 at gmail.com Sat Apr 21 19:09:01 2007 From: kar1107 at gmail.com (Karthik Gurusamy) Date: 21 Apr 2007 16:09:01 -0700 Subject: Newbie question regarding string.split() In-Reply-To: <1177095062.826018.63590@n59g2000hsh.googlegroups.com> References: <1177095062.826018.63590@n59g2000hsh.googlegroups.com> Message-ID: <1177196941.250827.308050@n76g2000hsh.googlegroups.com> On Apr 20, 11:51 am, kevinliu23 wrote: > Hey guys, > > So I have a question regarding the split() function in the string > module. Let's say I have an string... > > input = "2b 3 4bx 5b 2c 4a 5a 6" > projectOptions = (input.replace(" ", "")).split('2') > print projectOptions > > ['', 'b34bx5b', 'c4a5a6'] > The confusion, as you can see from other posts, is because the behavior is different from default split(). Default split works on whitespace and we don't get leading/trailing empty list items. So just add input = input.strip('2') after the input assignment (BTW someone had pointed input is a reserved identifier). Note this solution will work for splitting on any sequence of chars..just strip them first. Note we still get empty elements in the middle of the string -- this probably we want to get in most cases. Karthik > My question is, why is the first element of projectOptions an empty > string? What can I do so that the first element is not an empty > string? but the 'b34bx5b' string as I expected? > > Thanks so much guys. :) From aahz at pythoncraft.com Fri Apr 27 16:42:24 2007 From: aahz at pythoncraft.com (Aahz) Date: 27 Apr 2007 13:42:24 -0700 Subject: editing scripts on a mac References: Message-ID: In article , Steve Holden wrote: > >Now, frankly, I don't think this answer is correct, since I know OS X is >a UNIX derivative, but I am loathe to involve a programming noob with vi >or something similar. So I wondered if one of the c.l.py mac users could >give brief instructions for firing up a visual text editor of some sort >and saving a file somewhere it can easily be accessed from a terminal >window (which I presume starts up in his home directory). What's wrong with IDLE? -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "...string iteration isn't about treating strings as sequences of strings, it's about treating strings as sequences of characters. The fact that characters are also strings is the reason we have problems, but characters are strings for other good reasons." --Aahz From apardon at forel.vub.ac.be Thu Apr 19 05:11:13 2007 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 19 Apr 2007 09:11:13 GMT Subject: Do other Python GUI toolkits require this? References: <462697A6.6010007@codebykevin.com> Message-ID: On 2007-04-19, Michael Bentley wrote: > > On Apr 18, 2007, at 5:11 PM, Kevin Walzer wrote: > >> James Stroud wrote: >> >>> This appears more or less unique to Objective C. It looks that with >>> PyObjC, you have to interact with the Objective C runtime to manage >>> memory. This is not required, thankfully, with any other GUI tookits >>> I've seen. >>> >>> I think the main difference is that PyObjC is not a GUI toolkit >>> per se, >>> but is simply a means to make the Objective C runtime (and hence >>> Cocoa) >>> available via a python layer. >>> >>> James >> >> That's kind of what I thought. Memory management? In Python? *shudder* >> >> I'm a Mac-only developer, and I keep telling myself I should drink the >> Mac-only Kool-aid of PyObjC. But Tk is burned into my brain, and >> anything else looks and feels weird to me. Tk is so flexible that it's >> fairly easy to tweak it to look Mac-like, and it's simpler to do that >> than learn a new tookit. > > PyObjC is pretty slick (and since Ronald hasn't made any commits in a > while I'm nearly certain it'll show up in the next official > distribution of the devtools). About the time you gave up on PyQt on > the Mac and switched over to Tkinter, I switched to PyObjC. The > learning curve is rather steep IMO, but worth it. Just a throw in remark, that you may ignore if you wish, but a steep learning curve means that the subject is easily familiarized and that the learning period is short. You seem to use it as if it is the opposite. -- Antoon Pardon From b.r.willems at gmail.com Fri Apr 6 11:07:17 2007 From: b.r.willems at gmail.com (Bart Willems) Date: Fri, 06 Apr 2007 11:07:17 -0400 Subject: Why NOT only one class per file? In-Reply-To: References: <1175721799.714907.52770@o5g2000hsb.googlegroups.com> Message-ID: Steven D'Aprano wrote: > On Wed, 04 Apr 2007 14:23:19 -0700, Chris Lasher wrote: > >> A friend of mine with a programming background in Java and Perl places >> each class in its own separate file in . I informed him that keeping >> all related classes together in a single file is more in the Python >> idiom than one file per class. He asked why, and frankly, his valid >> question has me flummoxed. > > > Hah! Writing one class per file is for wimps! When I program, I write one > *method* per file, then import them and build the class at runtime. > > I have a friend who writes one *line* per file, then pulls them all > together with exec(), but that's just being stupid. > > > I guess you're one of those sissies who uses EDLIN as an editor. REAL programmers use COPY CON: ... :) From phd at phd.pp.ru Wed Apr 11 11:36:27 2007 From: phd at phd.pp.ru (Oleg Broytmann) Date: Wed, 11 Apr 2007 19:36:27 +0400 Subject: SQLObject 0.7.5 Message-ID: <20070411153627.GB21003@phd.pp.ru> Hello! I'm pleased to announce the 0.7.5 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.5 News and changes: http://sqlobject.org/docs/News.html What's New ========== News since 0.7.4 ---------------- * Fixed a bug in DateValidator caused by datetime being a subclass of date. * Fixed test_deep_inheritance.py - setup classes in the correct order (required for Postgres 8.0+ which is strict about referential integrity). 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. -- http://mail.python.org/mailman/listinfo/python-announce-list Support the Python Software Foundation: http://www.python.org/psf/donations.html From ptmcg at austin.rr.com Wed Apr 18 18:34:40 2007 From: ptmcg at austin.rr.com (Paul McGuire) Date: 18 Apr 2007 15:34:40 -0700 Subject: comparison with None In-Reply-To: References: <3IqdnfRnCNWPC7vbnZ2dnUVZ_jqdnZ2d@rcn.net> Message-ID: <1176935680.404376.5260@y80g2000hsf.googlegroups.com> On Apr 18, 5:19 pm, Steven Howe wrote: > Alan G Isaac wrote: > > >>> None >= 0 > > False > > >>> None <= 0 > > True > > > Explanation appreciated. > > > Thanks, > > Alan Isaac > > I've read and found that 'None' comparisons is not always a good idea. > Better to: > from types import NoneType > > x = None > if type( x ) == NoneType: > # true > < code > > else: > # false; do something else. > < more code > > > Steven Howe None is a singleton - there is but one None and no other. The only comparisons that make sense with None are "is" or "is not". type(x) == NoneType is unnecessary, x is None is sufficient. >>> x = None >>> x is None True >>> y = None >>> x is y True >>> z = object() >>> z is None False >>> z is not None True >>> x is not None False >>> y is not None False -- Paul From see_below_no_spam at yahoo.es Sun Apr 15 13:42:13 2007 From: see_below_no_spam at yahoo.es (Javier Bezos) Date: Sun, 15 Apr 2007 19:42:13 +0200 Subject: Python Feature Request: Allow changing base of member indices to 1 References: <1176546465.632410.52630@w1g2000hsg.googlegroups.com> <1176579205.948684.171640@q75g2000hsh.googlegroups.com> Message-ID: > Here is a document giving good reasons for indexing to start at > zero, as in Python. > http://www.cs.utexas.edu/users/EWD/transcriptions/EWD08xx/EWD831.html > The author has done a bit: > http://en.wikipedia.org/wiki/Dijkstra Dijkstra's argument is obsolete, as it is based on how array length was computed many years ago -- if we have an array a = b..e, then the lenght of a is e-b (half open range). Good at low level programming. But a quarter of a century after we know concepts are much better than low level programming and explicit computations -- if we have an array a = b..e, then the length of a should be a.length() (or a.length(b,e)), and it is independent of arbitrary ranges, index bases, or even steps (eg, {-4, -2, 0, 2, 4}). Of course, the index base should be always the same _by default_ (individual lists could require another index base, and that's fine). Otherwise it would a mess, as you said. Javier ----------------------------- http://www.texytipografia.com From steve at holdenweb.com Tue Apr 24 10:37:45 2007 From: steve at holdenweb.com (Steve Holden) Date: Tue, 24 Apr 2007 10:37:45 -0400 Subject: getting scancodes In-Reply-To: <596hp5F2jf49qU1@mid.uni-berlin.de> References: <132r2hb2gltbf4d@corp.supernews.com> <596hp5F2jf49qU1@mid.uni-berlin.de> Message-ID: Diez B. Roggisch wrote: > andmarti at gmail.com wrote: > >> On Tue, Apr 24, 2007 at 04:40:11AM -0000, Grant Edwards wrote: >>> On 2007-04-24, andmarti at gmail.com wrote: >>> >>>> Anyone knows if its possible to get scan codes ??? >>> What hardware? What OS? >> Debian Sarge/Etch, i386.. >> >> :P > > Greeeeeaaaat. Now we only need to guess what scan code reader you use.... > > > I think he's talking about *keyboard* scan codes. Not barcodes. regards Steve -- Steve Holden +1 571 484 6266 +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 usenet-mail-0306.20.chr0n0ss at spamgourmet.com Mon Apr 2 08:32:24 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Mon, 02 Apr 2007 14:32:24 +0200 Subject: Question about text in Python References: <4610c366$0$15022$5a62ac22@per-qv1-newsreader-01.iinet.net.au> Message-ID: <57cbejF2cataiU1@mid.individual.net> Steve wrote: > What I want to add to the program is the abilty to rerun this > process (where the user enteres another line of text) until the > user has had enough and enters a blank line which would then end > the program. Homework? Regards, Bj?rn -- BOFH excuse #106: The electrician didn't know what the yellow cable was so he yanked the ethernet out. From bbxx789_05ss at yahoo.com Thu Apr 5 02:54:52 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: 4 Apr 2007 23:54:52 -0700 Subject: shelve error In-Reply-To: <1175746966.023613.178830@n76g2000hsh.googlegroups.com> References: <1175746456.995618.186190@e65g2000hsc.googlegroups.com> <1175746966.023613.178830@n76g2000hsh.googlegroups.com> Message-ID: <1175756092.643182.142420@n76g2000hsh.googlegroups.com> On Apr 4, 10:22 pm, mik3l3... at gmail.com wrote: > how did you generate aaa.txt? Ok, I got it to work by supplying a filename that didn't previously exist. Neither the book I am reading, "Beginning Python: From Novice to Professional" nor the book I am using as a reference, "Python in Nutshell", happens to mention that important fact. From robin at reportlab.com Wed Apr 4 09:58:49 2007 From: robin at reportlab.com (Robin Becker) Date: Wed, 04 Apr 2007 14:58:49 +0100 Subject: An error of matrix inversion using NumPy In-Reply-To: <1175692530.364381.77110@n59g2000hsh.googlegroups.com> References: <1175692530.364381.77110@n59g2000hsh.googlegroups.com> Message-ID: <4613AF19.4090501@chamonix.reportlab.co.uk> lancered wrote: > Hi dear all, .......... > matrices are correct. > > So, can you tell me what goes wrong? Is this a bug in > Numpy.linalg? How to deal with this situation? If you need, I can > post the matrix I used below, but it is so long,so not at the moment. ....... presumably the matrix KK is actually some kind of normal matrix obtained from the data. So you have say n variables and m observations the data matrix is than an n x m real valued thing say D then you want the inverse of something like D'D ie an n by n thing. Typically the data D is de-meaned and normalized by the column norms so that you end up with a fairly well scaled problem. A long time ago I used Numeric+python to do exactly this sort of calculation with excellent results and the matrices were as large or larger eg 100 x 100 and above. I don't think the underlying numeric routines have changed that much. If your matrix is symmetric then you should certainly be using Even if you can't post the matrix, perhaps you should indicate how you proceed from data to matrix. Another problem is that a large determinant is no guarantee of stability for the inversion. If the largest eigenvalue is 10**100 and the smallest 10**-200 I probably have an ill determined problem; surprisingly easy to achieve :( -- Robin Becker From gagsl-py2 at yahoo.com.ar Mon Apr 23 12:44:07 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 23 Apr 2007 13:44:07 -0300 Subject: Redirection problem References: <1177344655.365318.50940@q75g2000hsh.googlegroups.com> Message-ID: En Mon, 23 Apr 2007 13:10:55 -0300, CSUIDL PROGRAMMEr escribi?: > I am new to python. so be patient with me > > I am trying to redirect the output of os.popen command to a file. I > want to append to that file. but instead of appending. The file only > shows last command that was writtenn to it. > > > > filehandle= open("/root/yhpc-2.0/installer/yhpc-log" ,"a+"); > filehandle.write(" Command executed is " + cmd); > try: > pipe= os.popen('%s > /root/yhpc-2.0/installer/yhpc-log' %cmd ); > except : IOError; > filehandle.close(); There are two ways to redirect the output: - using the shell, with > and >> - using popen You are mixing both here. Your command line uses >xxx-log, thus efectively overwriting any previous content on the log file. You could do this: logfile = open("....", "a+) logfile.write("Command: %s\n" % cmd) pipe = os.popen(cmd) for line in pipe: logfile.write(line) pipe.close() logfile.close() Or try the subprocess module. -- Gabriel Genellina From steve at REMOVEME.cybersource.com.au Tue Apr 3 22:14:47 2007 From: steve at REMOVEME.cybersource.com.au (Steven D'Aprano) Date: Wed, 04 Apr 2007 12:14:47 +1000 Subject: how to remove multiple occurrences of a string within a list? References: <1175624433.206953.214290@n59g2000hsh.googlegroups.com> Message-ID: On Tue, 03 Apr 2007 11:20:33 -0700, bahoo wrote: > Hi, > > I have a list like ['0024', 'haha', '0024'] > and as output I want ['haha'] > > If I > myList.remove('0024') > > then only the first instance of '0024' is removed. There are a whole heap of ways of doing this. They all have in common the idea of doing something over and over again until you're finished. Here's one way, using a loop in a try...except block. try: while True: myList.remove('0024') # raises an exception when the target isn't in the list any more except ValueError: pass # we're done > It seems like regular expressions is the rescue, Since when did reg exes operate on lists? -- Steven D'Aprano From aleax at mac.com Sun Apr 29 21:41:33 2007 From: aleax at mac.com (Alex Martelli) Date: Sun, 29 Apr 2007 18:41:33 -0700 Subject: fastest way to find the intersection of n lists of sets References: <1177883328.835058.138990@p77g2000hsh.googlegroups.com> <1177889667.450984.88970@p77g2000hsh.googlegroups.com> Message-ID: <1hxcecb.1xtf5321bjwf0uN%aleax@mac.com> Prateek wrote: > > For the above example, it's worth sorting lists_of_sets by the > > length of the sets, and doing the short ones first. > > Thanks. I thought so - I'm doing just that using a simple Decorate- > Sort-Undecorate idiom. Use, instead, the DSU that is now build into Python: listofsets.sort(key=len) this will be faster (as well as more readable &c) than programming your own DSU, and is exactly the reason the key= parameter was added. I also suggest avoiding reduce in favor of a simple explicit loop. Alex From apardon at forel.vub.ac.be Tue Apr 10 03:45:05 2007 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 10 Apr 2007 07:45:05 GMT Subject: tuples, index method, Python's design References: <1175867771.114540.61810@n76g2000hsh.googlegroups.com> <1175884427.779950.267220@y80g2000hsf.googlegroups.com> <1175953520.316208.241490@o5g2000hsb.googlegroups.com> <7xzm5igbrb.fsf@ruckus.brouhaha.com> Message-ID: On 2007-04-08, Carsten Haese wrote: > On Sun, 2007-04-08 at 07:51 -0700, Paul Rubin wrote: >> Carsten Haese writes: >> > > Maybe we can add such methods to the PyPy tuples for some time, to >> > > experimentally see if they make the language worse :-) >> > >> > Adding useless features always makes a product worse. What's your use >> > case for tuple.index? >> >> Do you not see the gratuituous inconsistency between tuples and lists >> as a useless feature? What is the use case for keeping it? > > When a new feature is requested, the burden of proof is on the requester > to show that it has uses. I don't agree. Good or bad design is not dependant on what is implemented and what is not. > The use case for not having tuple.index is > that there are no use cases for having it. If that answer sounds absurd, > it is because your question is absurd. You mean that those who are against tuple.index won't find any use case convincing enough. -- Antoon Pardon From silverburgh.meryl at gmail.com Mon Apr 30 14:39:39 2007 From: silverburgh.meryl at gmail.com (silverburgh.meryl at gmail.com) Date: 30 Apr 2007 11:39:39 -0700 Subject: How to pass in argument to timeit.Timer In-Reply-To: <1177957491.046839.318270@o5g2000hsb.googlegroups.com> References: <1177786091.049008.278400@o5g2000hsb.googlegroups.com> <1177957491.046839.318270@o5g2000hsb.googlegroups.com> Message-ID: <1177958379.510543.35160@o5g2000hsb.googlegroups.com> On Apr 30, 1:24 pm, "silverburgh.me... at gmail.com" wrote: > On Apr 28, 3:37 pm, "Gabriel Genellina" > wrote: > > > > > En Sat, 28 Apr 2007 15:48:11 -0300, silverburgh.me... at gmail.com > > escribi?: > > > > I have a function in my python like this: > > > def callFunc(line, no): > > > # some code > > > > And I want to do a performance test like this: > > > for line in f: > > > for i in range(int(count)): > > > t1 = timeit.Timer("callFunc(line, i)","from __main__ > > > import callFunc") > > > r1 = t1.timeit(); > > > print r1; > > > > but when I run it, it can't recognize the parameter 'line' and 'i', > > > can you please tell me how to fix it? i get this error: > > > They go in the "setup" parameter, like this: > > > t1 = timeit.Timer("callFunc(line, i)","from __main__ import callFunc; > > line=%r; i=%d" % (line, i)) > > Thanks I try it: > > def stressTest(): > for line in f: > for i in range(int(count)): > print i; > t1 = timeit.Timer("callFunc(line, i)","from __main__ > import callFunc; line=%r; i=%d" % (line, i)) > r1 = t1.timeit(); > times.append(r1); > print r1; > > But it keeps calling callFunc() and it never returns from my loop. The > value of 'count' is 2. > > Thank you. > > > If it gets much longer, try this: > > > setup = """ > > from __main__ import callFunc > > line = %r > > i = %d""" % (line, i) > > stmt = "callFunc(line, i)" > > t1 = timeit.Timer(stmt, setup) > > > -- > > Gabriel Genellina > > > PS: Please leave out the final ; - this is Python, not C nor ... > > PS2: Perhaps the only place where I've used ; is with timeit. And even > > then you can avoid them as in the last example. I think I solve the problem by putting a number in timeit() function. thank you. From grahn+nntp at snipabacken.dyndns.org Fri Apr 13 08:32:58 2007 From: grahn+nntp at snipabacken.dyndns.org (Jorgen Grahn) Date: 13 Apr 2007 12:32:58 GMT Subject: which version libpcap References: <1176451078.244945.45290@y5g2000hsa.googlegroups.com> Message-ID: On 13 Apr 2007 00:57:58 -0700, eight02645999 at yahoo.com wrote: > hi > from the web, i found 2 kinds of wrappers for libpcap, one is > pylibpcap, the other is pcapy. may i know which is more popularly > used? thanks I use pcapy, based on looking for a decent one 2--3 years ago. Don't like it much, though. Maybe pylibpcap is newer than that. /Jorgen -- // Jorgen Grahn R'lyeh wgah'nagl fhtagn! From bhochstetler at gmail.com Wed Apr 11 11:51:27 2007 From: bhochstetler at gmail.com (bhochstetler at gmail.com) Date: 11 Apr 2007 08:51:27 -0700 Subject: troubles building python 2.5 on Windows XP x64 Windows Server 2003 sp1 Platform SDK In-Reply-To: <461412C9.8090609@v.loewis.de> References: <1175622506.730227.37060@p77g2000hsh.googlegroups.com> <461412C9.8090609@v.loewis.de> Message-ID: <1176306687.057275.174460@q75g2000hsh.googlegroups.com> On Apr 4, 5:04 pm, "Martin v. L?wis" wrote: > bhochstet... at gmail.com schrieb: > > > I am needing to buildpython2.5 on Windows XP x64 Windows Server 2003 > > sp1PlatformSDKand am not finding anything documented on the process > > to use. Has anyone had any success with this? > > I did - I built the official binaries with it. > > > If so has anyone > > documented it? The documentation that resides in pcbuild/readme.txt is > > not helpful at all. > > Did you try to follow it? If so, what precisely did you fail at? > > [in another message] > > > This doc has not been updated since the 64 bit compilers came out > > officially. > > That is not true. The documentation was last updated on 2006-07-14, > which is after an AMD-64SDKwas released. > > > It doesn't make a whole lot of sense of what steps you > > should follow to buildpython. I saw a link on the comp.lang.python > > that had the steps, but that link doesn't go anywhere now. I had to > > jump through some hoops to get it to build on VC 2005 64 bit, but that > > at least had an IDE to use > > If you use vsextcomp, you also have an IDE to do the build. This > is indeed how the official AMD-64 binaries forPython2.5 were > produced. > > Regards, > Martin I guess I am a little confused on the directions for the vsextcomp. I don't see an IDE for the vsextcomp. Do you know of any explicit directions on how to do this build? From slm_guzel at hotmail.com Tue Apr 3 14:16:16 2007 From: slm_guzel at hotmail.com (gslm) Date: 3 Apr 2007 11:16:16 -0700 Subject: print the screen shot in python In-Reply-To: <1175607746.643094.193320@q75g2000hsh.googlegroups.com> References: <1175549083.627721.315170@y80g2000hsf.googlegroups.com> <1175607746.643094.193320@q75g2000hsh.googlegroups.com> Message-ID: <1175624176.401359.137560@o5g2000hsb.googlegroups.com> Thanks, I use TKinter,os:Xp home,python25. I want to print all my application's view, except the close-minimize icons. From erikwickstrom at gmail.com Tue Apr 17 15:33:26 2007 From: erikwickstrom at gmail.com (erikcw) Date: 17 Apr 2007 12:33:26 -0700 Subject: Traceback when trying to run script from cron? In-Reply-To: References: <1176602160.043372.225190@q75g2000hsh.googlegroups.com> Message-ID: <1176838405.545383.10400@o5g2000hsb.googlegroups.com> On Apr 14, 10:50 pm, Dennis Lee Bieber wrote: > On 14 Apr 2007 18:56:00 -0700, "erikcw" > declaimed the following in comp.lang.python: > > > > > The cron command is python /home/lybp/public_html/wa/wa.py > > > Any idea why MySQLdb wouldn't like this? > > Does the cron service run with the same PYTHONPATH? Stuff in a > "print sys.path" (or a write to some file you can later examine) before > the deadly import, and compare direct invocation with the cron > invocation. > -- > 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/ You're right. Something is not right with my sys.path. cron: '/home/lybp/public_html/winneralert', '/usr/lib/python2.2', '/usr/lib/ python2.2/plat-linux2', '/usr/lib/python2.2/lib-tk', '/usr/lib/ python2.2/lib-dynload', '/usr/lib/python2.2/site-packages'] Traceback (most recent call last): File "/home/lybp/public_html/winneralert/wa.py", line 18, in ? import MySQLdb ImportError: No module named MySQLdb SHELL: # python wa.py ['/home/lybp/public_html/winneralert', '/usr/local/lib/python2.4/site- packages/setuptools-0.6c5-py2.4.egg', '/usr/local/lib/python2.4/site- packages/MySQL_python-1.2.2-py2.4-linux-i686.egg', '/usr/local/lib/ python24.zip', '/usr/local/lib/python2.4', '/usr/local/lib/python2.4/ plat-linux2', '/usr/local/lib/python2.4/lib-tk', '/usr/local/lib/ python2.4/lib-dynload', '/usr/local/lib/python2.4/site-packages'] +OK Hello there. Why isn't cron able to import the MySJL module? How do I make this work? (newbie) Thanks! Erik From rconradharris at gmail.com Wed Apr 11 19:37:35 2007 From: rconradharris at gmail.com (rconradharris at gmail.com) Date: 11 Apr 2007 16:37:35 -0700 Subject: Strange Behavior with Old-Style classes and implicit __contains__ Message-ID: <1176334655.677943.70030@q75g2000hsh.googlegroups.com> A co-worker of mine came across some interesting behavior in the Python interpreter today and I'm hoping someone more knowledgeable in Python internals can explain this to me. First, we create an instance of an Old-Style class without defining a __contains__ but instead define a __getitem__ method in which we raise KeyError. Next we repeatedly use the 'in' operator to test to see whether something, a string, an int, etc is an attribute of this new instance. Here's the strange part: The first test will return False as if the __getitem__ was never called. The next test will raise a KeyError as we'd expect. The test after that will again return False. This goes on ad infinitum. In Code: Python 2.5 (r25:51908, Jan 21 2007, 03:10:25) [GCC 3.4.6 20060404 (Red Hat 3.4.6-3)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> class Foo: ... def __getitem__(self, key): ... raise KeyError ... >>> foo = Foo() >>> "asdf" in foo False >>> "asdf" in foo Traceback (most recent call last): File "", line 1, in File "", line 3, in __getitem__ KeyError >>> "asdf" in foo False >>> "asdf" in foo Traceback (most recent call last): File "", line 1, in File "", line 3, in __getitem__ KeyError According to the language reference, if __contains__ isn't defined for Old-Style classes and __getitem__ is defined, __getitem__ will be called. So, how then can False ever be returned? And to make matters worse, I've set up a situation where Python will flat-out return incorrect results: Python 2.5 (r25:51908, Jan 21 2007, 03:10:25) [GCC 3.4.6 20060404 (Red Hat 3.4.6-3)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> class Foo: ... def __getitem__(self, key): ... raise KeyError ... >>> foo = Foo() >>> "asdf" in foo False >>> 1 in set([1,2,3]) <---- So the prior KeyError from another class is interacting and producing bad output Traceback (most recent call last): File "", line 1, in File "", line 3, in __getitem__ KeyError According to our cursory testing, this funny business doesn't happen with New-Style Classes or when using PyPy. If anyone can provide some insight into this, it would be greatly appreciated. Thanks, Rick Harris From kw at codebykevin.com Wed Apr 18 17:04:21 2007 From: kw at codebykevin.com (Kevin Walzer) Date: Wed, 18 Apr 2007 17:04:21 -0400 Subject: Future Python Gui? In-Reply-To: <1176929277.779449.270810@q75g2000hsh.googlegroups.com> References: <1176859699.906386.326720@b75g2000hsg.googlegroups.com> <1176863948.526051.186210@n76g2000hsh.googlegroups.com> <1176909848.455264.174730@e65g2000hsc.googlegroups.com> <1176929277.779449.270810@q75g2000hsh.googlegroups.com> Message-ID: <462687D5.4050907@codebykevin.com> >> I wouldn't mind using just Tkinter, despite it's primative look, >> except that it doesn't support more advanced widgets like "notebook". When Tile becomes part of the core Tk library, it should be accessible from Tkinter as well. Tile has a nice notebook widget. See http://tktable.sourceforge.net/tile/screenshots/windowsxp.html, http://tktable.sourceforge.net/tile/screenshots/macosx.html and http://tktable.sourceforge.net/tile/screenshots/unix.html. > I wouldn't mind seeing tkgrid and tkhtml added to the standard > library. But Tk is probably "good enough" for most simple > interfaces. I'm not sure what tkgrid is: isn't that the standard Tk "grid" algorithm? If so, it's already accessible from Tkinter. As for Tkhtml, it's undergoing *heavy* development: it's moving from a lightweight, basic HTML renderer into a full-featured browser widget with CSS support: see http://tkhtml.tcl.tk/ and http://tkhtml.tcl.tk/hv3.html and http://tkhtml.tcl.tk/screenshot1.gif. The drawbacks are that it's currently at an alpha stage, and while the hv3 browser based on Tkhtml 3 is very impressive, it's overkill for the simple display of HTML--and the API for constructing a simpler widget seems to be very complex. As well, because it's still alpha, no one has wrapped it for Tkinter as of yet. -- Kevin Walzer Code by Kevin http://www.codebykevin.com From bbxx789_05ss at yahoo.com Fri Apr 13 01:15:05 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: 12 Apr 2007 22:15:05 -0700 Subject: mac IDLE problems Message-ID: <1176441305.802719.105520@q75g2000hsh.googlegroups.com> Hi, In the IDLE, I can't get most shortcut keys that are listed next to the menu items to work. For instance, under the Format menu item only the shortcuts for "indent region" and "undent region" work. If I highlight some text and use Shift+3 to comment out the region I highlighted, the code is erased and I get the # symbol. When I use the option(alt key) and type a character, I get things like this: ?,?,?,? I looked under Options/Configure IDLE/Keys and tried the various built in key sets, and none seem to work. I also can't use my mouse to copy(or cut) and paste. When I highlight something and right click(in an attempt to bring up the context menu that has copy, cut, paste, etc.), the text that is highlighted is doubled when I right click, e.g.: some text becomes: some textsome text And, sometimes when I try to highlight a line, the line 7 lines below the cursor gets highlighted. intel mac, os 10.4.7, python 2.4.4 From robert.rawlins at thinkbluemedia.co.uk Wed Apr 25 06:58:57 2007 From: robert.rawlins at thinkbluemedia.co.uk (Robert Rawlins - Think Blue) Date: Wed, 25 Apr 2007 11:58:57 +0100 Subject: Now() Message-ID: <000301c78728$ba634ce0$2f29e6a0$@rawlins@thinkbluemedia.co.uk> Hello Guys, I'm using the following function 'str (now)' to place a date time stamp into a log file, which works fine, however it writes the stamp like this. 2007-04-25 11:06:53.873029 But I need to expel those extra decimal places as they're causing problems with the application that parses the log data, all I need is something like this: 2007-04-25 11:06:53 With time depicted to the nearest second, from my background in ColdFusion development we used to have a datetimeformat() function that I could use as DateTimeFormat(now(), "yyyy-mm-dd HH:mm:ss") Which would give the current time a mask. Any equivalent for this in python? Thanks, Rob -------------- next part -------------- An HTML attachment was scrubbed... URL: From jjcrump at myuw.net Thu Apr 12 12:24:05 2007 From: jjcrump at myuw.net (Jon Crump) Date: Thu, 12 Apr 2007 09:24:05 -0700 (PDT) Subject: python newbie beautifulSoup question In-Reply-To: <1176346264.708905.245820@e65g2000hsc.googlegroups.com> References: <1176346264.708905.245820@e65g2000hsc.googlegroups.com> Message-ID: Justin, Wow! I thought there might be a 'simple' way! thanks so much, you've given me a lot to chew on. Jon __________ J.J. Crump Dept. of History 353560 University of Washington Seattle, WA. 98195 On Wed, 11 Apr 2007, Justin Ezequiel wrote: > On Apr 12, 4:15 am, Jon Crump wrote: > >> Is it possible to feed findAll() a list of tags WITH attributes? > >>>> BeautifulSoup.__version__ > '3.0.3' >>>> s = '''\nboo\nhello\nboo\nhi\n''' >>>> soup = BeautifulSoup.BeautifulSoup(s) >>>> def func(tag): > ... if tag.name not in ('y', 'z'): return False > ... if tag.name=='y': return tag.get('a')=='foo' > ... return tag.get('a')=='foo' and tag.get('b')=='bar' > ... >>>> soup.findAll(func) > [hello, hi] >>>> def get_func(lst): > ... def func(tag): > ... for name, attrs in lst: > ... if tag.name==name: > ... for k, v in attrs.items(): > ... if tag.get(k, None)==v: continue > ... else: return False > ... else: return True > ... else: return False > ... return func > ... >>>> func2 = get_func([('y', {'a': 'foo'}), ('z', {'b': 'bar', 'a': 'foo'})]) >>>> soup.findAll(func2) > [hello, hi] >>>> > > > -- > http://mail.python.org/mailman/listinfo/python-list > From skip at pobox.com Tue Apr 10 12:17:22 2007 From: skip at pobox.com (skip at pobox.com) Date: Tue, 10 Apr 2007 11:17:22 -0500 Subject: Queue get timeout parameter question In-Reply-To: <1176187648.664744.69430@y80g2000hsf.googlegroups.com> References: <1176178232.836311.19390@p77g2000hsh.googlegroups.com> <7x1wisg8ru.fsf@ruckus.brouhaha.com> <1176187648.664744.69430@y80g2000hsf.googlegroups.com> Message-ID: <17947.47250.877559.568585@montanaro.dyndns.org> Godzilla> Ok... But I'm afraid no syncing is not an option for the Godzilla> device... Then you'll either need to use something like ntp or sync much more frequently so you don't yank the time by so much. Skip From stargaming at gmail.com Thu Apr 26 12:02:52 2007 From: stargaming at gmail.com (Stargaming) Date: Thu, 26 Apr 2007 18:02:52 +0200 Subject: SPE In-Reply-To: <1177602331.523239.54930@b40g2000prd.googlegroups.com> References: <1177602331.523239.54930@b40g2000prd.googlegroups.com> Message-ID: Glich schrieb: > Is SPE open source? I want to try to implement a windows compiler into > the GUI using py2exe. > > thanks! > > -Glich > Aye. The `Checkout Manual `_, `WebSVN `_ and `Submit a patch ` are likely to help you. Greetings, Stargaming From jstroud at mbi.ucla.edu Tue Apr 24 06:39:21 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Tue, 24 Apr 2007 10:39:21 GMT Subject: *** Watch BOMBSHELL video of Senator John Kerry admitting 911 was in INSIDE JOB ??? In-Reply-To: References: <1177387965.127809.175390@l77g2000hsb.googlegroups.com> Message-ID: Andy wrote: > On 23 Apr 2007 21:12:45 -0700, lemnitzer at india.com wrote: > >> http://www.911blogger.com/node/8053 >> >> Senator John Kerry was questioned concerning 9/11 during an appearance >> at Book People in Austin, Texas. Members of Austin 9/11 Truth Now >> asked Kerry about the officially unexplained collapse of WTC Building >> 7." >> >> Kerry responded: >> >> "I do know that that wall, I remember, was in danger and I think >> they made the decision based on the danger that it had in destroying >> other things-- that they did it in a controlled fashion." >> >> http://www.jonesreport.com/articles/220407_kerry_wtc7.html >> >> Thanks to the dozen or so people who submitted this as a blog entry :) >> >> "Mr. Kerry?!?" >> >> "Just a follow-up or two... >> >> WHAT THE HELL|?| Are you saying that building was wired that day? Or >> well in advance? 'Splain, please. >> >> Does your fellow Bonesman George Walker Bush appreciate you letting >> the cat out of the bag on this? Is that your cell phone I hear >> ringing? >> >> Why is your wife squirming like that? Stop it, Theresa! Stop it!" > > This is much more funny. > > http://www.youtube.com/watch?v=HCkYfYa8ePI&mode=related&search= Texas is a big state and that was only one part. Hook'em From kyosohma at gmail.com Wed Apr 4 09:57:46 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: 4 Apr 2007 06:57:46 -0700 Subject: Refactoring question In-Reply-To: <1175661692.837687.146350@q75g2000hsh.googlegroups.com> References: <1175661692.837687.146350@q75g2000hsh.googlegroups.com> Message-ID: <1175695066.405208.227670@w1g2000hsg.googlegroups.com> On Apr 3, 11:41 pm, "ginstrom" wrote: > > On Behalf Of Kevin Walzer > > What's the best way to do this? Can anyone point me in the > > right direction? How could, for instance, the top snippet be > > rewritten to separate the Tkinter parts from the generic stuff? > > I like to use the broadcaster/broker recipe athttp://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/81983 > > I added a few features (such as decorators for listener functions -- > see below sig). > There are other recipes out there, such as PyDispatcher. > > Basically, I have GUI events translated into broadcaster events (by > passing lambdas that call broadcaster.Broadcast() to the event > binders), which are received by controller functions/classes. > > Feedback (status/progress) is also communicated via broadcaster > events. > > Something I tried on my current project, which is going fairly well, > is first writing a command-line version, then writing a GUI version, > with the same controller back-end used in each case, and the > controller communicating progress/results via the same interface. This > approach has made me keep presentation and logic very loosely > coupled. > > So for instance, the view class would send request for processing, > which the controller gets. > The controller performs the requested action, sending broadcasts of > progress (note that the controller can start a worker thread for the > processing, but the broadcasts should be made on the GUI thread...) > > broadcaster.Broadcast( "progress", "start", (100, "Doing your > bidding now..." ) ) # number of items we will process > > # ... > broadcaster.Broadcast( "progress", "progress", (i, "Working on > item %i" % i ) ) # current item > # ... > > broadcaster.Broadcast( "progress", "end", (100, "Done!") ) > > Depending on who is showing the progress, this might go onto a status > bar, progress dialog, the console, a log file, and so on, or some > combination thereof -- the controller doesn't know or care. > > When the controller is finished, it asks the broker for a view, and > calls show results on the view > > view = broker.Request( "view" ) > view.ShowResults( results ) > > That could have been done equally with the broadcaster, but for some > reason I like the broker here (it makes the view "dumber"). > > Regards, > Ryan > > -- > Ryan Ginstrom > > ================== > # listener decorators > > def BrokerRequestHandler( title ): > """A decorator for broker listeners > > @param title: the title to provide > > The decorated function must take no arguments > (it can retrieve them using CurrentData()) > """ > > def decorator(func): > broker.Register( title, func ) > return func > return decorator > > def BroadcasterEventHandler( source, title ): > """A decorator for broadcaster event handlers > > @param source: the broadcast source > @param title: the title of the broadcast > > The decorated function must take no arguments > (it can retrieve them using CurrentData()) > """ > > def decorator(func): > broadcaster.Register( func, source, title ) > return func > return decorator > > # example ... > @BrokerRequestHandler( "meaning of life" ) > def getMeaningOfLife(): > return 42 > > ## A little more complicated for class methods. I stole this technique > from WCK > > # Lifted shamelessly from WCK (effbot)'s wckTkinter.bind > def EventHandler( source, title ): > """Dectorator for event-handling methods""" > > def decorator(func): > func.BroadcasterEvent = (source, title) > return func > return decorator > > class FrameController: > """Controller for the main frame window""" > > def __init__( self ): > > for key in dir(self): > method = getattr(self, key) > if hasattr(method, "BroadcasterEvent") and > callable(method): > source, title = method.BroadcasterEvent > broadcaster.Register( method, > source=source, > title=title ) > > @EventHandler( "event", "onExport" ) > def onExport( self ): > """Handles the onExport broadcast by exporting the database to > the requested format""" > > format = broadcaster.CurrentData() > # Perform export... I usually put all my GUI code into their own methods(s) and call those methods from the __init__(). I do the same with the logic (where applicable). This makes the code easier to manipulate and/or import. In wxPython, you can also use XRC to define most of the common elements of you GUI. I've found this method to be very helpful in keeping my code short and easy to read, for GUI code. Mike From tsuraan at gmail.com Sun Apr 1 11:45:54 2007 From: tsuraan at gmail.com (tsuraan) Date: Sun, 1 Apr 2007 10:45:54 -0500 Subject: zip files as nested modules? Message-ID: <84fb38e30704010845t13f6785ag270df1254c1a87db@mail.gmail.com> Supposing that I have a directory tree like so: a/ __init__.py b/ __init__.py c.py and b.py has some method (let's call it d) within it. I can, from python, do: from a.b.c import d d() And, that works. Now, suppose I want to have a zipped module under a, called b.zip. Is there any way that I can accomplish the same thing, but using the zip file as the inner module? My directory layout is then a/ __init__.py b.zip And b is a zipfile laid out like b/ __init__.py c.py I tried populating a's __init__ with this: import zipimport import os here = os.path.join(os.getcwd(), __path__[0]) zips = [f for f in os.listdir(here) if f.endswith('.zip')] zips = [os.path.join(here, z) for z in zips] for z in zips: print z mod = os.path.split(z)[-1][:-4] print mod globals()[mod] = zipimport.zipimporter(z).load_module(mod) All the zip modules appear (I actually have a few zips, but that shouldn't be important), but their contents do not seem to be accessible in any way. I could probably put import statements in all the __init__.py files to import everything in the level below, but I am under the impression that relative imports are frowned upon, and it seems pretty bug-prone anyhow. Any pointers on how to accomplish zip modules being nested within normal ones? From carsten at uniqsys.com Tue Apr 10 09:23:05 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Tue, 10 Apr 2007 09:23:05 -0400 Subject: setup() and C extensions In-Reply-To: <1176186934.996315.142040@w1g2000hsg.googlegroups.com> References: <1176184942.119878.230850@p77g2000hsh.googlegroups.com> <1176186934.996315.142040@w1g2000hsg.googlegroups.com> Message-ID: <1176211385.3430.25.camel@dot.uniqsys.com> On Mon, 2007-04-09 at 23:35 -0700, 7stud wrote: > 2) When returning None, why use the idiom: > > Py_INCREF(Py_None); > return Py_None; > > instead of: > > return Py_BuildValue(""); > As Gabriel said, the preferred idiom is faster and clearer. Sufficiently recent Pythons define the macro Py_RETURN_NONE for the preferred idiom. -Carsten From mail at timgolden.me.uk Tue Apr 17 08:08:20 2007 From: mail at timgolden.me.uk (Tim Golden) Date: Tue, 17 Apr 2007 13:08:20 +0100 Subject: sql to xml In-Reply-To: <1176804890.007875.286920@e65g2000hsc.googlegroups.com> References: <1176804890.007875.286920@e65g2000hsc.googlegroups.com> Message-ID: <4624B8B4.4010807@timgolden.me.uk> Ros wrote: > Hi, > > I wish to write xml file after validating data from mssql database. > I am using xml data mapping list and would use it for validating data. All right, I'm not going answer the question you're asking (a) because I'm not really sure what the question is and (b) because I'm not really an XML person. I will make two other suggestions which may or may not be of use: 1) Use MSSQL's builtin XML writing / reading capabilities. 2) Don't use XML if you don't need to. You don't say why you're using XML but it really isn't clear to me why you go to such extremes to check the min and max length of data coming out of a database. Perhaps this is just sample code and your real problem is more complex and must use XML, or perhaps there really is some compelling reason for using XML which escapes me here. (I'm only even posting this drivel to show willing since no-one's posted a response that I've seen). TJG From nagle at animats.com Sat Apr 21 02:01:01 2007 From: nagle at animats.com (John Nagle) Date: Fri, 20 Apr 2007 23:01:01 -0700 Subject: Unexpected exception from socket.getaddrinfo on Unicode URL Message-ID: Here's a strange little bug. "socket.getaddrinfo" blows up if given a bad domain name containing ".." in Unicode. The same string in ASCII produces the correct "gaierror" exception. Actually, this deserves a documentation mention. The "socket" module, given a Unicode string, calls the International Domain Name parser, "idna.py", which has a a whole error system of its own. The IDNA documentation says that "Furthermore, the socket module transparently converts Unicode host names to ACE, so that applications need not be concerned about converting host names themselves when they pass them to the socket module." However, that's not quite true; the IDNA rules say that syntax errors must be treated as errors, so you have to be prepared for IDNA exceptions. They are all "UnicodeError" exceptions. It's worth a mention in the documentation for "socket". John Nagle D:\>/python25/python.exe Python 2.5 (r25:51908, Sep 19 2006, 09:52:17) [MSC v.1310 32 bit (Intel)] on win 32 Type "help", "copyright", "credits" or "license" for more information. >>> ss = 'www.gallery84..com' >>> uss = unicode(ss) >>> import socket >>> socket.getaddrinfo(ss,"http") Traceback (most recent call last): File "", line 1, in socket.gaierror: (11001, 'getaddrinfo failed') >>> socket.getaddrinfo(uss,"http") Traceback (most recent call last): File "", line 1, in File "D:\python25\lib\encodings\idna.py", line 164, in encode result.append(ToASCII(label)) File "D:\python25\lib\encodings\idna.py", line 73, in ToASCII raise UnicodeError("label empty or too long") UnicodeError: label empty or too long >>> From jstroud at mbi.ucla.edu Fri Apr 27 01:23:33 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Thu, 26 Apr 2007 22:23:33 -0700 Subject: Command-line option equiv of PYTHONPATH In-Reply-To: <1177648804.947472.112830@s33g2000prh.googlegroups.com> References: <1177648804.947472.112830@s33g2000prh.googlegroups.com> Message-ID: Rajesh wrote: > Hi, > > The '-I' option adds the path to the list of directories that > contains modules that can be included in a script. I can use it as "#!/ > usr/bin/perl -I" thereby not asking the user of > the script to set the in their environment. > > Is there any equivalent command-line option to the python binary or a > command-line version of PYTHONPATH? > > Regards > Rajesh > Why not just modify sys.path within the actual script? James From Eric_Dexter at msn.com Mon Apr 9 06:35:01 2007 From: Eric_Dexter at msn.com (Eric_Dexter at msn.com) Date: 9 Apr 2007 03:35:01 -0700 Subject: pluie documentation in english In-Reply-To: References: <1176109628.413745.285120@n76g2000hsh.googlegroups.com> Message-ID: <1176114900.964184.46880@y80g2000hsf.googlegroups.com> On Apr 9, 4:25 am, Michel Claveau wrote: > Hi! > Bonjour ! > > Thanks very well for translation. > Merci beaucoup pour la traduction. > > I add a link on the index page of the site. > J'ai ajout? un lien vers le document, dans la page d'accueil. > > Site:http://www.ponx.org/ponx/guie.htm > > But... I hope complete the (french) doc in next days. > Mais... J'esp?re pouvoir compl?ter la documentation dans les jours qui > viennent. > > -- > @-salutations > > Michel Claveau I don't know if you will see this or not but I'll ask here. I am playing around with example21.py and I hit the quitter button and it doesn't quit. It appears that the python part is done running and it just leaves the html page up. windows explorer does give me a message that it is blocking content. It doesn't appear to print anything or give me an error in microsoft explorer.. I am using microsoft explorer 6.0 on a windows machine and python 2.5 From equation at techemail.com Mon Apr 2 23:41:33 2007 From: equation at techemail.com (equation) Date: 2 Apr 2007 20:41:33 -0700 Subject: *** TV report: all 15 British sailors confess to illegally entering Iranian Waters *** In-Reply-To: <1175527717.124222.129080@o5g2000hsb.googlegroups.com> References: <1175527717.124222.129080@o5g2000hsb.googlegroups.com> Message-ID: <1175571693.411551.258030@p15g2000hsd.googlegroups.com> Oh pleez, this is a tex / latex group ... do you want any equation typeset ? I know 911 was a big scam but you should found your own newsgroup. Everyone here is familiar with your message. now leave us alone to work on latex / tex. regards equation On Apr 2, 8:28 am, lemnit... at india.com wrote: > TV report: all 15 British sailors confess to illegally entering > Iranian Waters > > Here are the links: > > http://news.google.com/news?hl=en&ned=us&q=all+15&btnG=Search+Newshttp://www.canada.com/ottawacitizen/news/story.html?id=64454ab9-229c-... > > NOW COMPARE THAT WITH THE YANK MOTHER FUCKING PEDOPHILE BASTARDS AND > THE CORRUPT FBI BASTARDS COVERING UP FOR THEIR PEDOPHILE BOSSES: > > THEY COULD NOT GET CONFESSION WITHOUT TORTURE FOR 5 DAMN YEARS, BUT > IRAN GOT CONFESSIONS OUT UNDER TOUGHT QUESTIONING IN LESS THAN 5 > WEEKS. > > Top court rejects Guantanamo test > BBC News - 25 minutes ago > The US Supreme Court has said it will not rule on whether detainees > held at Guantanamo have the right to challenge their detention in US > federal courts. > > THE FACT IS THAT BUSH HAS MANAGED TO CORRUPT THE SUPREME COURT AND > FILL IT WITH CORRUPT JUDGES OR KNOWN HOW TO BLACKMAIL THEM. > > --- The Puke-istani Patsy of Bush, the foolish dictator, General > Parvez Musharraf who joined the TOTALLY FALSE war OF terror is used by > these yank bastards to copy their results or to experiment and test > their theories in the domain of establishing totalitarian system. He > tried to corrupt the supreme court of that country but the lawyers and > citizens came out in protest. HE HA S FAILED. WE ARE HAPPY COZ THIS IS > THE DEFEAT OF DICK FACE AND BUSH. HE IS THEIR PATSY. BUT WE ARE NOW > PROUD OF KIND ABDULLAH OF SAUDI ARABIA. HE WAS A PATSY BUT HAS BROKEN > OFF. > > This is a very clear analysis and I ask you to think about these > parallels. > > 911 was a heinous crime done by YANK BASTARDS who killed their own > people and blamed it on others with the help of their foolish patsies > in the press, aipac, europe and the middle east. Forced them into > FALSE GUILT about a crime that was not committed by any arabs but by > YANK MOTHERFUCKER PEDOPHILES themselves !!!!! > > Please reward the 911 workers, at many 911 truth sites such as > 911blogger.com simply by watching the videos and sending links via > email to friends. If you are shy to send, just make anonymous emails > at any of the email sites and send email links to your friends > anonymously. Send them to police chiefs, sherriffs, judges, city > councils, professors, teachers, lawyers, newspaper authors, editors > and the truth is spreading. 84% of americans now believe 911 was an > inside job. > > WE ARE SUCCEEDING BEYONG OUR WILDEST DREAMS COZ TRUTH IS ON OUR SIDE. > > THE ONLY THING TO BE AFRAID OF IS COWARDICE ITSELF. > > God bless ALL those working on 911 truth. From rohitsethidce at gmail.com Fri Apr 20 16:06:51 2007 From: rohitsethidce at gmail.com (rohit) Date: 20 Apr 2007 13:06:51 -0700 Subject: service for file monitoring Message-ID: <1177099611.498274.323180@y5g2000hsa.googlegroups.com> hi, i am designing a desktop search engine using python. i am having a query , is there a package available that contains functions for retrieving the files being edited , created,deleted in the file system. thanks From steve at holdenweb.com Fri Apr 6 07:41:30 2007 From: steve at holdenweb.com (Steve Holden) Date: Fri, 06 Apr 2007 07:41:30 -0400 Subject: About python Sybase module and the database manipulation! In-Reply-To: References: Message-ID: boyeestudio wrote: > I write a python program which can insert one record into the Sybase > databae at a time using the function "fetchone()",But I find it runs slowly. > So I want speed it up,But I don't know how to manipulate the database > more efficiently! Thread or any other methods can do it?? > Since fetchone() is for *retrieval* of data from a database and since you don't show us your code it's difficult to know what to suggest. If you let us have an example it will be easier to tell you why your code doesn't run fast enough. You may wish to look at executemany() if you have lots of insertions to make. 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 larry.bates at websafe.com Mon Apr 9 14:53:39 2007 From: larry.bates at websafe.com (Larry Bates) Date: Mon, 09 Apr 2007 13:53:39 -0500 Subject: Crypto Suggestion/Help In-Reply-To: References: Message-ID: <_PednXl2AN4sFofbnZ2dnUVZ_r3inZ2d@comcast.com> Jimmy E Touma wrote: > Hi all, > > I need some advise on doing the following. I have a Linux application > that allows users to access it via a code (password). At the end of the > day, I gather a log of activities of the users and zip the file and > would like to encrypt it so that the users can not access it or tamper > with it. Only manager should. If I use a private/public key for doing so > I have to store the private key on my computer. What is a good way to > encrypt a file and have the key well hidden on the same computer? If you > have any other way to do, like MD5 or similar, please let me know. > > > Thanks, > Jimmy Put the private key on a USB key and read it from there to create the logs. When you unplug the USB key, the private key is gone from the machine. -Larry From deets at nospam.web.de Thu Apr 26 08:49:05 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 26 Apr 2007 14:49:05 +0200 Subject: How does Jython compile python modules that can be used by the JVM? In-Reply-To: <1177584822.083670.123950@b40g2000prd.googlegroups.com> References: <1177584822.083670.123950@b40g2000prd.googlegroups.com> Message-ID: <59ble7F2gadl1U1@mid.uni-berlin.de> ChrisW schrieb: > Hi, > > I need a relatively technical answer to the above question - I've > looked through the Jython docs / FAQs and Googled it but to no > avail... if anyone can let me know I'd be most grateful, The jython mailing list is the better place to ask this. However, actually this compilation of jython isn't really happening. All that happens is that a java-proxy is created that delegates the calls to it's methods to an underlying jython-interpreter-based object. No bytecode beyond the proxy. diez From joel.granados at gmail.com Sat Apr 7 13:58:35 2007 From: joel.granados at gmail.com (Joel Granados) Date: Sat, 7 Apr 2007 12:58:35 -0500 Subject: Comments in ConfigParser module In-Reply-To: References: Message-ID: <7ad76b520704071058s3b926d6ao79b6f9bfa2ad225c@mail.gmail.com> On 4/6/07, James Stroud wrote: > > Joel Andres Granados wrote: > > Hi list: > > Any comment greatly appreciated.... > > Very clever. > -- > http://mail.python.org/mailman/listinfo/python-list > clever ??? Well I would expect that the ";" character to behave the same way that the "#", as they are both characters that come before a comment. But it doesn't. So I'm missing something here. Why is the different behavior clever? -- Joel Andr?s Granados Medell?n Colombia -- jgranad1 at eafit.edu.co joel.granados at ieee.org -------------- next part -------------- An HTML attachment was scrubbed... URL: From promagian at gmail.com Thu Apr 26 21:26:06 2007 From: promagian at gmail.com (bruce peng) Date: Fri, 27 Apr 2007 09:26:06 +0800 Subject: File not read to end References: <1177522730.327454.121120@s33g2000prh.googlegroups.com> Message-ID: "rb",,please wrote in message news:1177522730.327454.121120 at s33g2000prh.googlegroups.com... > Hi, > > I'm trying to write a simple log parsing program. I noticed that it > isn't reading my log file to the end. > > My log is around 200,000 lines but it is stopping at line 26,428. I > checked that line and there aren't any special characters. > > This is the file reading code segment that I'm using: > sysFile=open(sysFilename,'r') > lineCount = 0 > for line in sysFile: > lineCount +=1 > print str(lineCount) + " -- " + line > > I also stuck this same code bit into a test script and it was able to > parse the entire log without problem. Very quirky. > > This is my first foray from Perl to Python so I appreciate any help. > > Thanks in advance. > > --Andrew > From aleax at mac.com Sat Apr 28 16:47:47 2007 From: aleax at mac.com (Alex Martelli) Date: Sat, 28 Apr 2007 13:47:47 -0700 Subject: how can I put an Exception as the key of a hash table References: <1177786431.935154.89510@y5g2000hsa.googlegroups.com> Message-ID: <1hxa8r4.11b3bfx5zkc69N%aleax@mac.com> yinglcs at gmail.com wrote: > I want to keep track of the number of different exception happens in > my python program: > > ErrorHash = {} > > try: > > # come code ... > > except Exception, e: > print e > errcode = e > > if (ErrorHash.has_key(errcode)): > ErrorFailNo = ErrorHash[errcode] > > ErrorHash[errcode] = ErrorFailNo + 1 > > else: > ErrorHash[errcode] = 1 > > > But when i print out the ErrorHash like this: > > print ErrorHash > > i get an empty string. Can you please tell me how can I put an > Exception as the key of a hash table ? Or how can i dump out all the > content of the hashtable. I can't reproduce your problem (using simpler code of course, yours is wildly redundant and needlessly complicated, though it should be semantically equivalent): >>> errdic = {} >>> def f(whatever): ... try: ... exec(whatever, {}) ... except Exception, e: ... errdic[e] = 1 + errdic.get(e, 0) ... >>> f('(syntax err') >>> errdic {SyntaxError('unexpected EOF while parsing', ('', 1, 11, '(syntax err')): 1} >>> f('23/0') >>> errdic {SyntaxError('unexpected EOF while parsing', ('', 1, 11, '(syntax err')): 1, ZeroDivisionError('integer division or modulo by zero',): 1} >>> f('23/0') >>> errdic {SyntaxError('unexpected EOF while parsing', ('', 1, 11, '(syntax err')): 1, ZeroDivisionError('integer division or modulo by zero',): 1, ZeroDivisionError('integer division or modulo by zero',): 1} >>> As you can see, the only problem is that two occurrences of the same error ar kept distinct -- they're distinct instances of the same class without special hashing or comparison methods, and so are distinct when considered as keys into a dict. There are of course ways to "collapse" them (e.g, use (type(e), str(e)) as the dict key, or, many others), but at any rate this does not appear to have anything to do with the problem you report. Could you perhaps post a complete, self-sufficient short script or interactive interpreter session, such as the few lines I've just copied and pasted above, to help us understand your problem? (More generally, has pretty good advice about "how to ask questions the smart way"). Alex From tjreedy at udel.edu Wed Apr 18 22:38:30 2007 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 18 Apr 2007 22:38:30 -0400 Subject: What makes an iterator an iterator? References: <1hwr9pv.13v4ci6106qn0aN%aleax@mac.com> <1176936067.315082.17970@y80g2000hsf.googlegroups.com> Message-ID: An iterator is an object with a .__iter__ method that returns self and a .next method that either returns an object or raises StopIteration. One very good way to get an iterator from an iterable is for .__iter__ to be a generator function. When called, it returns an generator with .__iter__ and .next methods that work as specified. words = "Norwegian Blues have beautiful plumage!".split() print words prints ['Norwegian', 'Blues', 'have', 'beautiful', 'plumage!'] class Parrot(object): def __init__(self, words): self.words = words def __iter__(self): for word in words: yield word for word in Parrot(words): print word prints Norwegian Blues have beautiful plumage! One can also make an iterable an (self) iterator by correctly writing the two needed methods. class Parrot2(object): def __init__(self, words): self.words = words def __iter__(self): self.it = -1 return self def next(self): self.it += 1 try: return self.words[self.it] except IndexError: raise StopIteration for word in Parrot2(words): print word which prints the same 5 lines. However, when an object is its own iterator, it can only be one iterator at a time (here, pointing at one place in the word list), whereas the first method allows multiple iterators (here, possibly pointing to different places in the list. | Can you explain some of the details of why this code fails: [snip all examples of bad code that violate the iterator rule by improperly writing .next as a generator function] I think most people should learn how to write iterators correctly, as I gave examples of above, rather than worry about the details of how and why mis-written code fails with a particular version of a particular implementation. So I won't go down that road. Terry Jan Reedy From apardon at forel.vub.ac.be Mon Apr 30 03:05:38 2007 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 30 Apr 2007 07:05:38 GMT Subject: My python annoyances so far References: <1177541453.471959.120830@c18g2000prb.googlegroups.com> <1177599046.406827.5210@t38g2000prd.googlegroups.com> <4631d5be$0$2132$426a74cc@news.free.fr> <46326519$0$20759$426a74cc@news.free.fr> Message-ID: On 2007-04-27, Bruno Desthuilliers wrote: > Antoon Pardon a ?crit : >> On 2007-04-27, Bruno Desthuilliers wrote: >> >>>7stud a ?crit : >>> >>>>flifus at gmail.com wrote: >>>> >>>>>Annoyances: >>>>> >>>> >>>>Every language has annoyances. Python is no exception. >>> >>>Sure. But we may disagree on what are actually Python's annoyances !-) >> >> >> That is probably why the subject says: "my annoyances" >> > May I suggest that before finding something annyoing, one has to use it? Sure you may. But what do you mean by use? Are the first exetcices a newbee tries out already using or do you think these don't count? > When I first discovered Python - and before having any experience with > it - I thought that not having declarative static typing and access > restriction was kind of an annoyement. Real world experience made me > change my mind... That people may (probably) change their mind later doesn't make it any less annoying at the moment. The frustrations of the moment don't disappear just because the more experienced knows these will fade in the future. -- Antoon Pardon From martinskou at gmail.com Wed Apr 4 06:49:35 2007 From: martinskou at gmail.com (martinskou at gmail.com) Date: 4 Apr 2007 03:49:35 -0700 Subject: how to build a forum in Python? In-Reply-To: <1175672984.836097.21610@n76g2000hsh.googlegroups.com> References: <1175672984.836097.21610@n76g2000hsh.googlegroups.com> Message-ID: <1175683775.326928.64160@b75g2000hsg.googlegroups.com> There are several different web frameworks in which a forum can be implemented. Try to take a look at Django and Turbogear. You will need to put some time into learning the framework. But, if you want an easy "copy-paste" forum solution, I guess you will be better of with one of the PHP open source forums. /Martin From deets at nospam.web.de Mon Apr 30 05:20:23 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 30 Apr 2007 11:20:23 +0200 Subject: What's the life time of the variable defined in a class function? References: <1177924115.659293.185880@q75g2000hsh.googlegroups.com> Message-ID: <59lqmnF2lr5nkU1@mid.uni-berlin.de> ??????????????? wrote: > Please see the followed example: > class A: > def __init__(self): > pass > > class X: > def __init__(self): > n = 200 > if True: > j = 200 > m = j > k = A() > print m, j > > a = X() > # ?? what about the m, n and j? is it still alive? > del a > > -------------------------- > In C/C++, the life time of m,n and j was the nearest block. but > obviously, python doen't have this syntax, but I would like to know > that whether the life time of m, n, j is base on function range or > the object range. > > We can not access the m, n, and j from the outside of class X. Now I'm > writing a program base on the wxpython. In the __init__ function of > wx.Panel, I use normal varable(just like the m,n and j) created some > widgets. It could be show in the window. Does it indicated the life > time of varable m,n,j is base on the object range? Python has no variables. It has objects, which can be bound to names. Each binding to a name will increase a reference counter. Each unbinding will decrease it. so a = SomeObject() b = a del a will result in the SomeObject-instance still be alive. But when you add del b it will be garbage collected. Now in your example A() bound to k will not survive the exit of the method, as that means that k goes out of scope, and the object is bound to - the A-instance - gets its reference-counter decreased, resulting in it being freed. The wxwidgets example though is a different thing. If the panel stores a reference to the object, e.g. via a list (being part of a list or dict also increases the reference count), it will be kept around. Diez From gagsl-py2 at yahoo.com.ar Sat Apr 7 16:43:10 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: 7 Apr 2007 13:43:10 -0700 Subject: Convert xml symbol notation In-Reply-To: <46175AB6.8070602@v.loewis.de> References: <1175899141.354348.207530@q75g2000hsh.googlegroups.com> <1175923387.811717.279580@n76g2000hsh.googlegroups.com> <46175AB6.8070602@v.loewis.de> Message-ID: <1175978590.352314.230930@d57g2000hsg.googlegroups.com> Martin v. L?wis wrote: > >> I'm working on a script to download and parse a web page, and it > >> includes xml symbol notation, such as ' for the ' character. Does > > > > Try the htmlentitydefs module. > > That won't help: this is a character reference, not an entity reference. > htmlentitydefs only contains the definitions of entities. Ouch! Sorry. -- Gabriel Genellina From waylan at gmail.com Thu Apr 5 15:45:52 2007 From: waylan at gmail.com (waylan) Date: 5 Apr 2007 12:45:52 -0700 Subject: how to remove multiple occurrences of a string within a list? In-Reply-To: References: <1175624433.206953.214290@n59g2000hsh.googlegroups.com> <1175625098.269660.184790@o5g2000hsb.googlegroups.com> <1175627593.307674.11280@w1g2000hsg.googlegroups.com> <1175637133.938883.224570@q75g2000hsh.googlegroups.com> Message-ID: <1175802352.405276.150350@q75g2000hsh.googlegroups.com> On Apr 3, 6:05 pm, Steven Bethard wrote: > bahoo wrote: > > The larger problem is, I have a list of strings that I want to remove > > from another list of strings. > > If you don't care about the resulting order:: > > >>> items = ['foo', 'bar', 'baz', 'bar', 'foo', 'frobble'] > >>> to_remove = ['foo', 'bar'] > >>> set(items) - set(to_remove) > set(['frobble', 'baz']) I'm surprised no one has mentioned any of the methods of set. For instance: >>> set.difference.__doc__ 'Return the difference of two sets as a new set.\n\n(i.e. all elements that are in this set but not in the other.)' >>>set(items).difference(to_remove) set(['frobble', 'baz']) There are a few other cool methods of sets that come in handy for this sort of thing. If only order could be preserved. > > If you do care about the resulting order:: > > >>> to_remove = set(to_remove) > >>> [item for item in items if item not in to_remove] > ['baz', 'frobble'] > > STeVe From trial at ugyvitelszolgaltato.hu Mon Apr 16 11:50:01 2007 From: trial at ugyvitelszolgaltato.hu (Attila Szabo) Date: Mon, 16 Apr 2007 17:50:01 +0200 Subject: win32 register Message-ID: <20070416155001.GA55750@bsdman.ugyvitelszolgaltato.hu> Hi, I'm a unix programmer and I have minimal ideas, how things work under windows. I have a tkinter stuff, that has to accept data from explorer, I've done it via pipes, because I guess no drag'n'drop method exists... At program launch, it registers a context menu handler to png files, that sends the drag'n'drop info to the program via the pipes, it is working good under administrator privileges, but not with normal user... The pipe server runs in a separate thread in the tkinter program... At the end, it unregisters the menu handler... How can a make it work with a normal user ? I've registered the handler, but can't see in the menu under user... Can I register the handler under admin, and run the pipe server under user ? thanks very much Atti From Martin.Drautzburg at web.de Sun Apr 22 03:00:56 2007 From: Martin.Drautzburg at web.de (Martin Drautzburg) Date: Sun, 22 Apr 2007 09:00:56 +0200 Subject: sql to xml References: <1176804890.007875.286920@e65g2000hsc.googlegroups.com> Message-ID: <16585362.obHNqsFVGA@beaureve.gmx.net> Tim Golden wrote: > 2) Don't use XML if you don't need to. I would call this advice a "golden rule" the violation of which has caused serious pain in some of the projects I am working on. From slm_guzel at hotmail.com Tue Apr 3 16:50:36 2007 From: slm_guzel at hotmail.com (gslm) Date: 3 Apr 2007 13:50:36 -0700 Subject: print the screen shot in python In-Reply-To: <1175625518.189432.251020@b75g2000hsg.googlegroups.com> References: <1175549083.627721.315170@y80g2000hsf.googlegroups.com> <1175607746.643094.193320@q75g2000hsh.googlegroups.com> <1175624176.401359.137560@o5g2000hsb.googlegroups.com> <1175625518.189432.251020@b75g2000hsg.googlegroups.com> Message-ID: <1175633435.976636.52890@l77g2000hsb.googlegroups.com> On 3 Nisan, 21:38, kyoso... at gmail.com wrote: > On Apr 3, 1:16 pm, "gslm" wrote: > > > Thanks, > > I use TKinter,os:Xp home,python25. > > I want to print all my application's view, except the close-minimize > > icons. > > I don't know enough about Tkinter, but you can use the graphics module > according to this post that should take a screenshot: > > http://snippets.dzone.com/posts/show/398 > > You should also navigate through this series of posts on taking > screenshots using PIL and the win32 module:http://mail.python.org/pipermail/python-win32/2003-January/000714.html > > The following post has a short script using the os module to capture a > screenshot too:http://livingcode.blogspot.com/2006/03/screenshot-in-cocoa-python.html > > Hopefully this will give you some direction. Other than that, we'll > have to wait for a Tkinter guru. > > Mike Thanks again, I have used ImageGrab function according to a member of this group.But I have problems and I have just sent a question about them. If you look, I'll be very happy. From paul at boddie.org.uk Mon Apr 16 12:11:42 2007 From: paul at boddie.org.uk (Paul Boddie) Date: 16 Apr 2007 09:11:42 -0700 Subject: Python Feature Request: Add the "using" keyword which works like "with" in Visual Basic In-Reply-To: <1176547372.584539.89170@q75g2000hsh.googlegroups.com> References: <1176547372.584539.89170@q75g2000hsh.googlegroups.com> Message-ID: <1176739901.946900.132680@p77g2000hsh.googlegroups.com> samjnaa at gmail.com wrote: > Please check for sanity and approve for posting at python-dev. Technically, you can post it yourself to python-dev, but you'll just get bounced back here to discuss it with us. ;-) > In Visual Basic there is the keyword "with" which allows an object- > name to be declared as governing the following statements. For > example: > > with quitCommandButton > .enabled = true > .default = true > end with This is how the discussion started for the current "with" statement, although it ended up doing something somewhat different. [...] > Now I hear that the word "with" is being discussed for a different > purpose in Py 3 as a result of a PEP and I don't want to conflict with > that. The "with" keyword appears in 2.5 onwards. Paul From samfeltus at gmail.com Wed Apr 4 13:53:52 2007 From: samfeltus at gmail.com (SamFeltus) Date: 4 Apr 2007 10:53:52 -0700 Subject: SonomaSunshine Update Message-ID: <1175709232.416369.184210@b75g2000hsg.googlegroups.com> SonomaSunshine has been updated... It's a Python powered tool to generate and edit 21st Century Redneck Folk Art... http://samfeltus.com/as3/mardi_gras.html http://samfeltus.com/site_index.html From anton.vredegoor at gmail.com Fri Apr 20 13:56:26 2007 From: anton.vredegoor at gmail.com (Anton Vredegoor) Date: Fri, 20 Apr 2007 19:56:26 +0200 Subject: Expanding tkinter widgets to fill the window In-Reply-To: <1177085708.955388.119080@o5g2000hsb.googlegroups.com> References: <1177085708.955388.119080@o5g2000hsb.googlegroups.com> Message-ID: KDawg44 wrote: > I am writing a GUI front end in Python using Tkinter. I have > developed the GUI in a grid and specified the size of the window. The > widgets are centered into the middle of the window. I would like them > to fill the window. I tried using the sticky=E+W+N+S option on the > widgets themselves and the window itself. > > How can I get this? If at all possible post a short, self-contained, correct, example demonstrating your question. http://homepage1.nifty.com/algafield/sscce.html A. From bignose+hates-spam at benfinney.id.au Mon Apr 2 22:26:47 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Tue, 03 Apr 2007 12:26:47 +1000 Subject: Question about text in Python References: <4610c366$0$15022$5a62ac22@per-qv1-newsreader-01.iinet.net.au> <57cbejF2cataiU1@mid.individual.net> <4611af55$0$15038$5a62ac22@per-qv1-newsreader-01.iinet.net.au> Message-ID: <87wt0ugplk.fsf@benfinney.id.au> "Steve" writes: > Yes it is [a homework question]. > > Where else to ask for help but here. That's between you, your teacher, and your teaching institute's plagiarism guidelines. -- \ "I got a postcard from my best friend, it was a satellite | `\ picture of the entire Earth. On the back he wrote, 'Wish you | _o__) were here'." -- Steven Wright | Ben Finney From researchbase at gmail.com Wed Apr 11 14:12:40 2007 From: researchbase at gmail.com (krishnakant Mane) Date: Wed, 11 Apr 2007 23:42:40 +0530 Subject: how to pickle objects for database storage? Message-ID: hello, I have a strange but very interesting requirement? provided that a database can provide for an object data type like binary large object (blob), can I store a pickeled python object in it? I know oracle has blob and clob and believe that mysql/ postgre sql has some thing similar to store direct objects? if not then should a pickeled object wrapped inside a file and then stored in a database? regards. Krishnakant. From steven.bethard at gmail.com Sun Apr 22 16:06:19 2007 From: steven.bethard at gmail.com (Steven Bethard) Date: Sun, 22 Apr 2007 14:06:19 -0600 Subject: recursion depth problem In-Reply-To: <1177271382.859369.104790@q75g2000hsh.googlegroups.com> References: <1177267774.416169.276780@e65g2000hsc.googlegroups.com> <1177271382.859369.104790@q75g2000hsh.googlegroups.com> Message-ID: proctor wrote: > On Apr 22, 1:24 pm, Michael Bentley wrote: >> On Apr 22, 2007, at 1:49 PM, proctor wrote: >> >> >> >>> i have a small function which mimics binary counting. it runs fine as >>> long as the input is not too long, but if i give it input longer than >>> 8 characters it gives >>> RuntimeError: maximum recursion depth exceeded in cmp >>> i'm not too sure what i am doing improperly. is there really a lot of >>> recursion in this code? >>> ================== >>> import sys >>> def ch4(item, n=0): >>> if n < len(item): >>> if item[n] == '0': >>> item[n] = '1' >>> print ''.join(item) >>> ch4(item) >>> elif item[n] == '1': >>> item[n] = '0' >>> ch4(item, n+1) >>> ch4(list(sys.argv[1])) >>> ================== >> Yes. There really is *that* much recursion in that code. 502 levels >> with input length of 8 characters, 1013 with 9 characters, 2035 with >> 10 characters... There's a pattern there ;-) > > ok, thanks michael! > > is there a way to avoid it here? how could i write this better, (if > at all)? Google for permutation-like recipies: http://www.google.com/search?q=Python+permutations Use the code from the first hit:: >>> for x in xselections('01', 8): ... print ''.join(x) ... 00000000 00000001 00000010 ... 11111101 11111110 11111111 Explaining to your teacher why your code uses generators when you haven't been taught them yet is left as an exercise to the reader. ;-) STeVe From KDawg44 at gmail.com Tue Apr 10 15:30:14 2007 From: KDawg44 at gmail.com (KDawg44) Date: 10 Apr 2007 12:30:14 -0700 Subject: Parsing log in SQL DB to change IPs to hostnames In-Reply-To: <1176231258.626137.228220@d57g2000hsg.googlegroups.com> References: <1176219463.407804.315560@y80g2000hsf.googlegroups.com> <1176221494.813800.78580@y80g2000hsf.googlegroups.com> <1176231258.626137.228220@d57g2000hsg.googlegroups.com> Message-ID: <1176233414.710629.152760@q75g2000hsh.googlegroups.com> On Apr 10, 1:54 pm, "KDawg44" wrote: > On Apr 10, 11:11 am, "Kushal Kumaran" > wrote: > > > > > On Apr 10, 8:37 pm, "KDawg44" wrote: > > > > Hi, > > > > I am brand new to Python. In learning anything, I find it useful to > > > actually try to write a useful program to try to tackle an actual > > > problem. > > > > I have a syslog server and I would like to parse the syslog messages > > > and try to change any ips to resolved hostnames. Unfortunately, I am > > > not getting any matches on my regular expression. > > > > A message will look something like this: > > > Apr 10 2007 00:30:58 DEVICE : %DEVICEINFO: 1.1.1.1 Accessed URL > > > 10.10.10.10:/folder/folder/page.html > > > > I would like to change the message to have the hostnames, or even > > > better actually, have it appear as hostname-ip address. So a changed > > > message would look like: > > > > Apr 10 2007 00:30:58 DEVICE : %DEVICEINFO: pcname-1.1.1.1 Accessed > > > URLwww.asite.com-10.10.10.10:/folder/folder/page.html > > > > or some equivalent. > > > > Here is what i have so far. Please be kind as it is my first python > > > program.... :) > > > > #! /usr/bin/python > > > > import socket > > > import re > > > import string > > > import MySQLdb > > > > ipRegExC = r"\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}" > > > ipRegEx = re.compile(ipRegExC) > > > > try: > > > conn = MySQLdb.connect(host="REMOVED", user="REMOVED", > > > passwd="REMOVED", db="REMOVED") > > > > except MySQLdb.Error, e: > > > print "Error connecting to the database: %d - %s " % > > > (e.args[0], e.args[1]) > > > sys.exit(1) > > > > cursor = conn.cursor() > > > cursor.execute("SELECT msg, seq FROM REMOVED WHERE seq = 507702") > > > # one specific message so that it doesn't parse the whole DB during > > > testing... > > > while(1): > > > row = cursor.fetchone() > > > if row == None: > > > break > > > if ipRegEx.match(row[0]): > > > .... > > > > > > See the documentation of the re module for the difference between > > matching and searching. > > > -- > > Kushal > > Thank you very much. I think I have it figured out, except for an > error on the SQL statement: > > [----- BEGIN ERROR ---] > Traceback (most recent call last): > File "changeLogs.py", line 47, in ? > cursor.execute("""UPDATE logs SET msg = %s WHERE seq = %i""", > (newMsg,seqNum)) > File "/usr/lib/python2.4/site-packages/MySQLdb/cursors.py", line > 148, in execute > query = query % db.literal(args) > TypeError: int argument required > [----- END ERROR ---] > > Here is my code > > [----- BEGIN CODE ---] > #! /usr/bin/python > > import socket > import sys > import re > import string > import MySQLdb > > def resolveHost(ipAdds): > ipDict = {} > for ips in ipAdds: > try: > ipDict[ips] = socket.gethostbyaddr(ips)[0] > except: > ipDict[ips] = "Cannot resolve" > return ipDict > > ipRegExC = r"\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}" > ipRegEx = re.compile(ipRegExC) > > try: > conn = MySQLdb.connect(host="REMOVED", user="REMOVED", > passwd="REMOVED", db="REMOVED") > > except MySQLdb.Error, e: > print "Error connecting to the database: %d - %s " % > (e.args[0], e.args[1]) > sys.exit(1) > > cursor = conn.cursor() > cursor.execute("SELECT msg, seq FROM `logs` WHERE seq = 507702") > while(1): > row = cursor.fetchone() > ipAddresses = [] > resolvedDict = {} > if row == None: > break > if ipRegEx.search(row[0]): > seqNum = row[1] > ipAddresses = ipRegEx.findall(row[0]) > resolvedDict = resolveHost(ipAddresses) > newMsg = row[0] > for ip in resolvedDict.keys(): > newMsg = newMsg.replace(ip,ip + "-" + > resolvedDict[ip]) > cursor.execute("""UPDATE REMOVED SET msg = %s WHERE > seq = %i""", (newMsg,seqNum)) > > [----- END CODE ---] > > Thanks again! Also, i tried changing seqNum = row[1] to seqNum = int(row[1]) to cast it as an integer and I get the same error (because I think that pulling from a DB makes everything a string by default?) Thanks. From cam.ac.uk at mh391.invalid Mon Apr 16 21:47:21 2007 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Tue, 17 Apr 2007 02:47:21 +0100 Subject: list insertion question In-Reply-To: <1176771916.236282.206500@n59g2000hsh.googlegroups.com> References: <1176771916.236282.206500@n59g2000hsh.googlegroups.com> Message-ID: eight02645999 at yahoo.com wrote: > hi > i have a list (after reading from a file), say > data = [ 'a','b','c','d','a','b','e','d'] > > I wanted to insert a word after every 'a', and before every 'd'. so i > use enumerate this list: > for num,item in enumerate(data): > if "a" in item: > data.insert(num+1,"aword") > if "d" in item: > data.insert(num-1,"dword") #this fails > but the above only inserts after 'a' but not before 'd'. What am i > doing wrong? is there better way?thanks If you modify a list while you are iterating over it, you may get unexpected results (an infinite loop in this case for me). Also ("a" in item) will match "aword" since "a" is a component of it. I imagine you mean (item == "a"). Try this: output = [] for item in data: if item == "d": output.append("dword") output.append(item) if item == "a": output.append("aword") >>> output ['a', 'aword', 'b', 'c', 'dword', 'd', 'a', 'aword', 'b', 'e', 'dword', 'd'] -- Michael Hoffman From apardon at forel.vub.ac.be Tue Apr 10 05:48:41 2007 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 10 Apr 2007 09:48:41 GMT Subject: tuples, index method, Python's design References: <1175867771.114540.61810@n76g2000hsh.googlegroups.com> <1175884427.779950.267220@y80g2000hsf.googlegroups.com> <1175953520.316208.241490@o5g2000hsb.googlegroups.com> <7xzm5igbrb.fsf@ruckus.brouhaha.com> Message-ID: On 2007-04-10, Duncan Booth wrote: > Antoon Pardon wrote: > >>> When a new feature is requested, the burden of proof is on the requester >>> to show that it has uses. >> >> I don't agree. Good or bad design is not dependant on what is >> implemented and what is not. > > There is a cost to every new language feature: it has to be implemented, > documented, maintained, and above all learned by the users. Good design > involves, in part, not adding to these burdens except where there is a > benefit at least equal to the cost. So what is the easiest to learn: "All sequences have an index method" or "Such and so sequences have an index method and others don't" Which of the above is the easiest to document? Now with implementation and maintaining. If you would start with a class of sequence which classes like tuple and list would inherit from, then there also would be a single function to be implemented and maintained. It would just be usable in more types. >>> The use case for not having tuple.index is >>> that there are no use cases for having it. If that answer sounds absurd, >>> it is because your question is absurd. >> >> You mean that those who are against tuple.index won't find any use case >> convincing enough. >> > Why not try them? Pose a few useful cases where the existence of > tuple.index() would actually give a benefit and see what response you get. > > You would have to meet a few obvious conditions: the use case would need to > be one where a tuple was preferable to a list (the obvious one being where > you need to hash it), the tuple would have to be sufficiently long or the > calls to 'index' sufficiently frequent to make casting to a list so you can > call 'list(obj).index(...)' unattractive, and you actually need a reason to > be using 'index' rather than just the 'in' operator. If someone states: "Show me your use case for using tuple.index and I will show you how to avoid it." or words to that effect I think there is little use trying. Besides I have seen how such things evolve here before. Every use case that will be presented, will be rewritten in a way that doesn't need tuple.index and these rewritals will be used as an argument for not having tuple.index. If you need to hash it, you can simply subclass list and provide a hash with your class or you can simply use tuples and write an index function yourself. The same happened with the ternary operator. Every use case someone could come up with was rejected by rewriting the code without using a ternary operator. AFAICS the only reason the ternary operator finaly got introduced was because a python developer was bitten by an illusive bug, introduced by one of the idioms that was often used as a way to simulate a ternary operator. -- Antoon Pardon From http Sun Apr 15 21:05:17 2007 From: http (Paul Rubin) Date: 15 Apr 2007 18:05:17 -0700 Subject: yield, curry, mix-in, new.function, global, closure, .... what will work? References: <1176657848.944538.169780@p77g2000hsh.googlegroups.com> <7xy7ktmrzn.fsf@ruckus.brouhaha.com> <1176684145.537202.68090@p77g2000hsh.googlegroups.com> Message-ID: <7xbqhp6sdu.fsf@ruckus.brouhaha.com> ecir.hana at gmail.com writes: > On Apr 15, 8:07 pm, Paul Rubin wrote: > > That is total madness. Just use a normal object or dictionary with a lock. > > Please, can you elaborate further, I'm not sure if I understood. > Should I lock global variables i, j during the execution of run()? In > that case I have to apologize, I showed rather simplified version of > the actual problem I have - in fact changer() and run() will be a bit > more complex thus executing a bit longer and perhaps causing a dead-lock. Put both variables into one shared object with a lock (see the docs for threading.RLock()). Acquire the lock before modifying or reading the variables, and release it afterwards. That is the traditional way. Another way popular in Python is to have separate threads for changer and run, and have them communicate through Queue.Queue objects. In no case should you attempt to write a function that messes with another function's local variables. Local variables are called "local" for a reason ;-). Basically this stuff takes more understanding and getting used to than I can really convey in a newsgroup post. You might look at some Wikipedia articles or ASPN recipes about concurrent programming, or get the Python Cookbook. From s_broscious at comcast.net Thu Apr 12 17:29:01 2007 From: s_broscious at comcast.net (Scott) Date: Thu, 12 Apr 2007 17:29:01 -0400 Subject: Question About Creating Lists Message-ID: I'm sorry if most of my question's seem "petty", but as I've said before, I need to know the petty just because I need to know. This question is more along the lines of just having you guys either agree or disgree with me, and if disagreeing to give the reasoning behind it, to further my understanding of lists. Am I safe in assuming that if the list your building contains number's it will be written as follows: >>>my_list = [1, 2, 3, 4, 5] But the minute you throw in something that's not a number it has to be written as: >>>my_list = [1, 2, 3, 4, 'five'] >>> my_list [1, 2, 3, 4, 'five'] Unless five was defined, then it could be written as: >>>five = 5 >>>my_list = [1, 2, 3, 4, five] >>> my_list [1, 2, 3, 4, 5] Is this the correct way of thinking? Or am I, by thinking this is the case, crippling myself in my potential as a programmer From ejensen at visi.com Mon Apr 2 14:08:16 2007 From: ejensen at visi.com (Ed Jensen) Date: Mon, 02 Apr 2007 18:08:16 -0000 Subject: Problem with global variables References: <1311u48bqkehk24@corp.supernews.com> Message-ID: <1312hkgjcm39le2@corp.supernews.com> Ed Jensen wrote: > I'm having a vexing problem with global variables in Python. Thanks to everyone who replied. The peculiar way Python handles global variables in functions now makes sense to me. From datamonkey.ryan at gmail.com Thu Apr 19 22:58:35 2007 From: datamonkey.ryan at gmail.com (datamonkey.ryan at gmail.com) Date: 19 Apr 2007 19:58:35 -0700 Subject: List of Objects Message-ID: <1177037915.042476.153190@n76g2000hsh.googlegroups.com> Howdy, a (possibly) quick question for anyone willing to listen. I have a question regarding lists and Classes; I have a class called "gazelle" with several attributes (color, position, etc.) and I need to create a herd of them. I want to simulate motion of individual gazelles, but I don't want to have to go through and manually update the position for every gazelle (there could be upwards of 50). I was planning to create an array of these gazelle classes, and I was going to iterate through it to adjust the position of each gazelle. That's how I'd do it in C, anyway. However, Python doesn't support pointers and I'm not quite sure how to go about this. Any help you can provide would be greatly appreciated. Thanks a lot! -Ryan From steve at holdenweb.com Wed Apr 18 14:50:07 2007 From: steve at holdenweb.com (Steve Holden) Date: Wed, 18 Apr 2007 14:50:07 -0400 Subject: Help Understanding mx.ODBC Error In-Reply-To: <10063746.post@talk.nabble.com> References: <10063746.post@talk.nabble.com> Message-ID: Greg Corradini wrote: > Hello All, > A few weeks ago, I wrote two scripts using mx.ODBC on an Access DB. Among > other things, both scripts create new tables, perform a query and then > populate the tables with data in a dictionary that I've uploaded from > elsewhere. These scripts have run hundreds of times in the last few weeks > with no problems. > > But recently they continue to bail on the mycursor.execute('An SQL > Statement') after the table has been created. I get the following error > message: > Traceback (most recent call last): > File "C:\Documents and Settings\marv1shi\Desktop\Workspace\Existence > Script\DBF Checker\Access_SQL.py", line 35, in ? > curse.execute(sql) > ProgrammingError: ('07001', -3010, '[Microsoft][ODBC Microsoft Access > Driver] Too few parameters. Expected 4.', 4612) > > The real stinker, however, is that after it bails I can manually call > mycursor.execute('An SQL Statement'), then call my insert statement in the > Python Shell and it works fine. > > I just can't figure out how to reconcile this problem. Has anybody run into > this before? > > Thanks > Greg Corradini I suspect what's happening here is that you are presenting statements you have made up programmatically, and the values you are trying to insert include apostrophes that break the syntax of your SQL. However there isn't really enough evidence to decide unless you are prepared to show us the error traceback, possibly with a dump of the SQL statement you are actually trying to execute. I apologize in advance if you are using parameterized queries (as you should to avoid SQL injection vulnerabilities among other major problems) but this message is typical of Access when it sees words it can't parse. 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 duncan.booth at invalid.invalid Thu Apr 5 16:34:45 2007 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 5 Apr 2007 20:34:45 GMT Subject: RFC: Assignment as expression (pre-PEP) References: <1175802680.021987.39220@p77g2000hsh.googlegroups.com> Message-ID: Carsten Haese wrote: > If that's your only justification for this proposal, that's almost > certainly not enough to convince anybody of its necessity. Your code > example should be rewritten as a loop: > > match_actions = [(my_re1, action1), > (my_re2, action2), > ...] > > for my_re, action in match_actions: > if my_re.match(exp): > action(exp) > break > Depending on what his 'do something with temp' actually was, it may or may not be easy to rewrite it as a for loop. However, even if a for loop isn't an obvious replacement other solutions may be appropriate such as combining the regular expressions to a single regex with named groups and/or using the command pattern. If assignment was an expression that only addresses one problem with the sample code. It still leaves his code with excessive repetition and probably with an excessively long function that calls out to be refactored as a group of smaller methods. From claird at lairds.us Fri Apr 27 14:51:02 2007 From: claird at lairds.us (Cameron Laird) Date: Fri, 27 Apr 2007 18:51:02 +0000 Subject: : Re-ocurring Events References: <003101c7889c$ffabe6c0$ff03b440$@rawlins@thinkbluemedia.co.uk> Message-ID: In article , Robert Rawlins - Think Blue wrote: . . . >I've been thinking about the possibility of using a combination of xpath to >search the XML with some loops which change the date. As events won't ever . [much other detail] . . XPath's great, of course . Among XML devotees, the first bell that rings when someone is *transforming* XML, as you seem to need, is XSLT . I understand your problem poorly enough, and Python is rich enough, that perhaps the most appropriate solution involves any number of other technologies (XQuery? ...). From luismgz at gmail.com Fri Apr 20 13:13:26 2007 From: luismgz at gmail.com (=?iso-8859-1?q?Luis_M=2E_Gonz=E1lez?=) Date: 20 Apr 2007 10:13:26 -0700 Subject: When are immutable tuples *essential*? Why can't you just use lists *everywhere* instead? In-Reply-To: <1177088796.622928.224890@d57g2000hsg.googlegroups.com> References: <1177088796.622928.224890@d57g2000hsg.googlegroups.com> Message-ID: <1177089206.550423.288670@q75g2000hsh.googlegroups.com> On Apr 20, 2:06 pm, "seber... at spawar.navy.mil" wrote: > Please help me think of an example where immutable tuples are > essential. > > It seems that everywhere a tuple is used one could just as easily use > a list instead. > > chris I don't remember exactly where I read about it, but Guido said once that tuples are being kept mainly for historical reasons. This is what Python uses internally from the beginning and it's just an implementation detail that makes sense in some contexts. Although I guess you can ignore them and use only lists instead if you want.. luis From enleverlesX.XmcX at XmclaveauX.com Tue Apr 10 04:14:57 2007 From: enleverlesX.XmcX at XmclaveauX.com (Méta-MCI) Date: Tue, 10 Apr 2007 10:14:57 +0200 Subject: pluie documentation in english References: <1176109628.413745.285120@n76g2000hsh.googlegroups.com> <1176114900.964184.46880@y80g2000hsf.googlegroups.com> Message-ID: <461b479a$0$27407$ba4acef3@news.orange.fr> Bonjour ! Avec Internet-Explorer 6 : Dans Internet-explorer, par le menu, faire : Outils + Options_internet Aller sur le dernier onglet (Avanc?), et cocher : autoriser le contenu actif (d?sol? pour le fran?ais, mais mon anglais est vraiment trop mauvais). Et, merci pour l'info, ?a m'a permis d'ajouter un item ? la F.A.Q. @-salutations -- Michel Claveau From DustanGroups at gmail.com Thu Apr 26 08:31:21 2007 From: DustanGroups at gmail.com (Dustan) Date: 26 Apr 2007 05:31:21 -0700 Subject: conditional print statement ? In-Reply-To: References: <2c923$462fb3e0$d443bb3a$18429@news.speedlinq.nl> Message-ID: <1177590681.015153.67800@b40g2000prd.googlegroups.com> On Apr 26, 1:58 am, Antoon Pardon wrote: > On 2007-04-25, Stef Mientki wrote: > > > hello, > > > As part of a procedure I've a number sequences like this: > > > > > if Print_Info: print Datafile.readline() > > else: Datafile.readline() > > > > > Is there a more compressed way to write such a statement, > > especially I dislike the redundancy "Datafile.readline()". > > > thanks, > > Stef Mientki > > You could consider the following > > def Print(arg): > print arg > > def Noop(arg): > pass > or (untested): if Print_Info: def printOrNot(arg): print arg else: def printOrNot(arg): pass printOrNot(Datafile.readline()) > (Print if Print_Info else Noop) (Datafile.readline()) > > -- > Antoon Pardon From bruno.42.desthuilliers at wtf.websiteburo.oops.com Fri Apr 13 06:54:28 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Fri, 13 Apr 2007 12:54:28 +0200 Subject: Try problem In-Reply-To: <1176456312.752519.198130@e65g2000hsc.googlegroups.com> References: <1176455642.199343.136720@l77g2000hsb.googlegroups.com> <1176456312.752519.198130@e65g2000hsc.googlegroups.com> Message-ID: <461f60eb$0$641$426a74cc@news.free.fr> mik3l3374 at gmail.com a ?crit : > On Apr 13, 5:14 pm, "SamG" wrote: >> import sys >> try: >> s=1 >> if s==1: >> sys.exit(0) >> else: >> sys.exit(1) >> except SystemExit,s: >> if (s==0): >> print s >> else: >> print "Hello" >> >> How come i always end up getting the "Hello" printed on the screen as >> logically i should a '0' printed? > > > if you put a debug print statement, eg > > ... > except SystemExit,s: > print "s in exception " , s, type(s) > if (s==0): > .... > > you will notice 's' is an "instance". Not with Python 2.5.x (exceptions are now new-style classes too). > so when it reaches the if > (s==0), which you are comparing with a number, Actually, with an instance of class int. Everything in Python is an object. But the comparison will fail, indeed. From jstroud at mbi.ucla.edu Thu Apr 12 07:53:44 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Thu, 12 Apr 2007 04:53:44 -0700 Subject: parsing text in blocks and line too In-Reply-To: References: <1176370200.947603.314500@d57g2000hsg.googlegroups.com> Message-ID: A.T.Hofkamp wrote: > On 2007-04-12, flyzone at technologist.com wrote: >> Goodmorning people :) >> I have just started to learn this language and i have a logical >> problem. >> I need to write a program to parse various file of text. >> Here two sample: >> >> --------------- >> trial text bla bla bla bla error >> bla bla bla bla bla >> bla bla bla on more lines >> trial text bla bla bla bla warning bla >> bla bla more bla to be grouped with warning >> bla bla bla on more lines >> could be one two or ten lines also withouth the tab beginning >> again text >> text can contain also blank lines >> text no delimiters.... >> -------------- >> Apr 8 04:02:08 machine text on one line >> Apr 8 04:02:09 machine this is an error >> Apr 8 04:02:10 machine this is a warning >> -------------- > > I would first read groups of lines that belong together, then decide on each > group whether it is an error, warning, or whatever. > To preserve order in a group of lines, you can use lists. > > From your example you could first compute a list of lists, like > > [ [ "trial text bla bla bla bla error", > " bla bla bla bla bla", > " bla bla bla on more lines" ], > [ "trial text bla bla bla bla warning bla", > " bla bla more bla to be grouped with warning", > " bla bla bla on more lines", > " could be one two or ten lines also withouth the tab beginning" ], > [ "again text" ], > [ "text can contain also blank lines" ], > [ ], > [ "text no delimiters...." ] > ] > > Just above the "text no delimiters...." line I have added an empty line, and I > translated that to an empty group of lines (denoted with the empty list). > > By traversing the groups (ie over the outermost list), you can now decide for > each group what type of output it is, and act accordingly. > >> Hope someone could give me some tips. > > Sure, however, in general it is appreciated if you first show your own efforts > before asking the list for a solution. > > Albert If groups have 0 indent first line and other lines in the group are indented, group the lines blocks = [] block = [] for line in lines: if not line.startswith(' '): if block: blocks.append(block) block = [] block.append(line) if block: blocks.append(block) But if 0 indent doesn't start a new block, don't expect this to work, but that is what I infer from your limited sample. You can then look for warnings, etc., in the blocks--either in the loop to save memory or in the constructed blocks list. James From bjourne at gmail.com Sat Apr 14 13:46:10 2007 From: bjourne at gmail.com (=?ISO-8859-1?Q?BJ=F6rn_Lindqvist?=) Date: Sat, 14 Apr 2007 19:46:10 +0200 Subject: Python Feature Request: Add the "using" keyword which works like "with" in Visual Basic In-Reply-To: <1176560672.108264.44890@p77g2000hsh.googlegroups.com> References: <1176547372.584539.89170@q75g2000hsh.googlegroups.com> <1176560672.108264.44890@p77g2000hsh.googlegroups.com> Message-ID: <740c3aec0704141046x7bcb2ac0qb924a04440633124@mail.gmail.com> On 14 Apr 2007 07:24:32 -0700, jamadagni wrote: > > You already can emulate the using statement like this: > > You can emulate only assignments like this. How would you emulate > function calls, like the ones in my example? You can't, of course. But using the with statement: using self.q: .doit() becomes: with self.quit as q: q.doit() :) -- mvh Bj?rn From ocollioud at gmail.com Tue Apr 3 09:52:10 2007 From: ocollioud at gmail.com (olive) Date: 3 Apr 2007 06:52:10 -0700 Subject: XML DTD analysis, diffing ... In-Reply-To: <1175606848.838850.18150@w1g2000hsg.googlegroups.com> References: <1175603926.371027.69390@e65g2000hsc.googlegroups.com> <1175606848.838850.18150@w1g2000hsg.googlegroups.com> Message-ID: <1175608328.341381.97040@b75g2000hsg.googlegroups.com> Mike, I know all of these tools and I already suspected xmlproc as a good candidate. The problem is I can't download it for the moment since Lars website is blocked here at my work and PyXML is dead. Maybe there is an alternative download link ? Thank you for the Cookbook recipe anyway. Olivier. From nyamatongwe+thunder at gmail.com Mon Apr 9 18:16:27 2007 From: nyamatongwe+thunder at gmail.com (Neil Hodgson) Date: Mon, 09 Apr 2007 22:16:27 GMT Subject: Hosting Companies: Help for Python Users? In-Reply-To: References: Message-ID: <%WySh.11628$M.6973@news-server.bigpond.net.au> Steve Holden: > Dennis Lee Beiber: > > > Too many 3rd-party modules still aren't available in 2.5 > > versions for my tastes... > > This applies particularly (though not exclusively) to the Windows > platform, for various reasons -- the most common one is that Linux > developers frequently don't have a Windows machine available to help > them test their builds and ensure that distributions are available. > > I am trying to address this problem, initially by making hosted Windows > machines available for use as buildbots. I'd like to see this integrated in the Cheese Shop. I recently released a small extension class and provided a source distribution and a single binary for Python 2.5 on Windows. While I have the compilers needed for building back to 1.5, most people don't and even when you do it is complex to set up an environment for each version to compile successfully. It would be great if you could upload a source distribution and mark it as containing files that need compilation for each version - or a subset of versions if you know it requires particular features. Then the compilation is farmed out to machines set up for each Python version and when the compilation is finished, a status display shows the set that are available and which failed along with a link to see the compilation log. A unit test could be optionally included in an upload that would contribute to whether the build is marked good. Neil From martin at v.loewis.de Thu Apr 19 17:43:40 2007 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Thu, 19 Apr 2007 23:43:40 +0200 Subject: Better dict of dicts In-Reply-To: References: Message-ID: <4627E28C.1050406@v.loewis.de> Bill Jackson schrieb: > I have a dictionary of dictionaries where the keys are typically very > long tuples and repeated in each inner dictionary. What I don't understand here: you say the keys are tuples, yet later, you show that the keys are strings. Which one is it? > The dictionary > representation is nice because it handles sparseness well...and it is > nice to be able to look up values based on a string rather than a > number. However, since my keys are quite long, I worry that I am > wasting a lot of memory. I'm looking for better data structures. > > Here is an example: > >>>> a = {"string_1": {"string_2":1, > ... "string_3":5, > ... "string_4":10}, > ... "string_2": {"string_2":12, > ... "string_6":2, > ... "string_1":4}} > > So as my strings get longer and longer, it seems that the dictionary of > dictionary representation is less and less efficient. You seem to assume that every occurrence of "string_2" has separate memory. That may or may not be the case, depending on where the strings come from. For example, it may be that the keys are the very same strings: s1 = "string_1" s2 = "string_2" a[s1][s2] = 1 a[s2][s1] = 4 Then, the memory for the string would exist only once. > My thought was to subclass the dictionary structure.... > > keys = {"string_1":1, > "string_2":2, > "string_3":3, > "string_4":4, > "string_6":5} Instead of doing that, I would use a procedure called "interning". You may want to use the builtin intern function, or your can come up with your own interning: interns = {} def local_intern(s): return interns.setdefault(s, s) Then, instead of a[k1][k2] = value do a[local_intern(k1)][local_intern(k2)] = value then all strings occur only once as keys, as long as the interns dictionary isn't cleared. > Any ideas? HTH, Martin From aleax at mac.com Sat Apr 14 23:07:38 2007 From: aleax at mac.com (Alex Martelli) Date: Sat, 14 Apr 2007 20:07:38 -0700 Subject: Python Feature Request: Explicit variable declarations References: <1176546078.934340.253810@y5g2000hsa.googlegroups.com> <1176557734.456820.275780@p77g2000hsh.googlegroups.com> Message-ID: <1hwksmn.dnv0aw1jptdv6N%aleax@mac.com> Dennis Lee Bieber wrote: ... > In Python, the "variable" NAME does NOT define storage; unlike most > other classical languages where the "variable name" is a storage > address, and the value of the RHS is COPIED to that address. Python does > not do such copying. Names are references to the RHS object itself. Right, but that's just like today's most popular languages -- Java and C# -- with the one difference that in those languages "boxed" types (elementary numbers, in Java) have different semantics. > Languages with "variable declarations" are pre-allocating object > space that can only hold objects of that type (ignoring VB "variant"). Again, this is not true for the most popular languages, Java and C# -- in those cases, excepting boxed types, variable declarations are "pre-allocating" space for references, which can refer to any type derived from theirs (so, e.g., in Java, "Object x;" means x can refer to anything at all except a boxed type such as float). I think you're confusing two issues with languages' underlying models: boxes (C, Fortran, etc) vs tags (Java, Python, etc) for variables; and declarations vs not. APL uses boxes but no declarations, etc, etc: you can find all four variants!-) Alex From http Sun Apr 15 18:54:21 2007 From: http (Paul Rubin) Date: 15 Apr 2007 15:54:21 -0700 Subject: Making a tree out of a 2 column list References: <1176568327.669229.22910@b75g2000hsg.googlegroups.com> <1176677087.151276.223580@b75g2000hsg.googlegroups.com> Message-ID: <7x8xctuu3m.fsf@ruckus.brouhaha.com> bearophileHUGS at lycos.com writes: > > I guess this should make the program enter into a endless loop. But > > the data won't have such a redundancy, because it was taken from a > > philogenetic tree. > > But errors and bugs do happen, inside data too; so often it's better > to be on safe side if the safe code is fast enough. If you think the data may be wrong it's probably better to use a traditional graph algorithm to check it for cycles, than rely on some arbitrary recursion depth limit. From scott.daniels at acm.org Sat Apr 14 00:34:48 2007 From: scott.daniels at acm.org (Scott David Daniels) Date: Fri, 13 Apr 2007 21:34:48 -0700 Subject: Python in a strange land: IronPython and ASP.NET at the next PyGTA In-Reply-To: References: Message-ID: <462059E8.6060903@acm.org> Mike C. Fletcher wrote: > IronPython is a native implementation of Python on the Microsoft .NET > platform. The implementation is from Microsoft and the language is well > supported by the Visual Studio development environment which has always > been one of the Microsoft platform's strengths. Though Python is often > associated with the Free and Open Source communities, consultants and > developers frequently need to solve real-world problems using Python on > the .NET platform. IronPython makes using Python in these situations a > natural choice for the Python programmer. > > Our speaker for the evening is Myles Braithwaite, a local consultant and > developer. He is going to give us an idea of how developing a web > application using ASP.NET looks when using IronPython instead of C#, as > well as his impressions of the platform. > > As usual, we will hold the presentation at Linux Caffe, gathering for > introductions at 6:30 PM, with the formal presentation beginning at 7:00 > PM. We normally head out around 8:30 PM for beer, coffee and/or ice > cream. You can find directions and maps to Linux Caffe on the wiki: > > http://web.engcorp.com/pygta/wiki/NextMeeting > > Hope to see you all there, > Mike You might mention Toronto, Ontario, Canada in an announcement to a global mailing list. -- --Scott David Daniels scott.daniels at acm.org From steve at holdenweb.com Tue Apr 3 16:21:24 2007 From: steve at holdenweb.com (Steve Holden) Date: Tue, 03 Apr 2007 16:21:24 -0400 Subject: how to remove multiple occurrences of a string within a list? In-Reply-To: <1175627593.307674.11280@w1g2000hsg.googlegroups.com> References: <1175624433.206953.214290@n59g2000hsh.googlegroups.com> <1175625098.269660.184790@o5g2000hsb.googlegroups.com> <1175627593.307674.11280@w1g2000hsg.googlegroups.com> Message-ID: bahoo wrote: > On Apr 3, 2:31 pm, "Matimus" wrote: >> It depends on your application, but a 'set' might really be what you >> want, as opposed to a list. >> >>>>> s = set(["0024","haha","0024"]) >>>>> s >> set(["0024","haha"])>>> s.remove("0024") >>>>> s >> set(["haha"]) > > This sounds cool. > But is there a command I can convert the "set" back to a "list"? > That would be list(). So what you want is s = set(["0024","haha","0024"]) s.remove("0024") l = list(s) or something like it. It seems, a priori, unlikely that you only want to remove items with that specific value, Is this part of some larger 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 rNOSPAMon at flownet.com Sun Apr 22 12:36:57 2007 From: rNOSPAMon at flownet.com (Ron Garret) Date: Sun, 22 Apr 2007 09:36:57 -0700 Subject: Select weirdness References: <590s1nF2ibkeqU1@mid.individual.net> Message-ID: In article <590s1nF2ibkeqU1 at mid.individual.net>, Bjoern Schliessmann wrote: > > The only difference I can discern is that the browser send \r\n > > for end-of-line while telnet just sends \n. ... > > But I don't see why that should make any difference. > > Easy. If you only accept "\r\n" as EOL, you'll wait forever unless > you really receive it. But it's SELECT that is hanging. Select knows (or ought to know) nothing of end-of-line markers. Readline (when it is called) is doing the Right Thing, and my end-of-request test is (currently) reading a line less than 3 characters long. All that is working. The problem is that select is saying there is no input (and therefore hanging) when in fact there is input. rg From steven.bethard at gmail.com Fri Apr 13 16:14:39 2007 From: steven.bethard at gmail.com (Steven Bethard) Date: Fri, 13 Apr 2007 14:14:39 -0600 Subject: vocab question In-Reply-To: <461fe3d0$0$11935$426a74cc@news.free.fr> References: <461fe3d0$0$11935$426a74cc@news.free.fr> Message-ID: Bruno Desthuilliers wrote: > Alan G Isaac a ?crit : >> Pardon the vocab question; >> I'm not a computer science type. >> According to the Reference Manual, >> a class defintion has the structure:: >> >> classdef ::= "class" classname [inheritance] ":" suite >> >> What is the entire part before the suite called? > > A statement. In this case, a 'class' statement. Actually, the class statement includes the suite as well. As far as I know, there's no official term for the first four elements of a class statement. I'd probably call it the class statement header. STeVe From nagle at animats.com Mon Apr 23 16:08:15 2007 From: nagle at animats.com (John Nagle) Date: Mon, 23 Apr 2007 20:08:15 GMT Subject: Socket exceptions aren't in the standard exception hierarchy In-Reply-To: References: Message-ID: Steve Holden wrote: > John Nagle wrote: > >> Dennis Lee Bieber wrote: >> >>> On Sun, 22 Apr 2007 23:20:25 -0700, John Nagle >>> declaimed the following in comp.lang.python: >>> >>> >>>> 2. File "D:\Python24\lib\socket.py", line 295, in read >>>> data = self._sock.recv(recv_size) >>>> error: (10054, 'Connection reset by peer') >>>> >>> That looks like M$ Windows version of UNIX/Linux error number 54 >>> (pretty much all Windows socket errors are UNIX number+10000) >>> >>> Errors coming from Windows may not be mapped to specific Python >>> exceptions, but rather to some general error conditions. {hypothesis} As >>> such, the Windows errors may not match what UNIX/Linux report. >> >> >> Actually, that's not what's happening. The socket module is >> explicitly raising "socket.error" in C code. It's not an OSError or >> a WindowsError, although the text makes it look like one. >> >> The problem is not that socket errors aren't entirely portable. >> It's that they're not even in the Python exception hierarchy. >> See "http://docs.python.org/lib/module-exceptions.html". >> They have their own hierarchy, which starts at "socket.error". >> All built-in exceptions were supposed to be converted to the >> standard exception hierarchy back before Python 2.0, but these >> weren't. >> >> Either they should be under IOError, or there should be >> "NetworkError" under EnvironmentError, and they should be under >> that. "NetworkError", alongside IOError in the hierarchy, >> would be useful. All the things that go wrong in networking >> belong under there. Socket-level errors, SSL/TLS-level errors, >> and HTTP/FTP/etc. level errors all belong under NetworkError. >> >> This has to be fixed before PEP 352, when the exception >> hierarchy is enforced, or the socket exceptions won't even work >> right. >> > John: > > Where did you get this information? If true it would certainly need to > be logged as a bug, but under Windows on 2,4 I see > > >>> issubclass(socket.gaierror, Exception) > True > >>> > > and the same under Cygwin 2.5. I am presuming most other users will see > the same thing. > > regards > Steve Ah. "socket.error" is a subclass of "Exception", but not of "StandardError". issubclass(socket.error,StandardError) is False. John Nagle From NikitaTheSpider at gmail.com Sun Apr 22 11:56:38 2007 From: NikitaTheSpider at gmail.com (Nikita the Spider) Date: Sun, 22 Apr 2007 11:56:38 -0400 Subject: Python "robots.txt" parser broken since 2003 References: Message-ID: In article , John Nagle wrote: > This bug, "[ 813986 ] robotparser interactively prompts for username and > password", has been open since 2003. It killed a big batch job of ours > last night. > > Module "robotparser" naively uses "urlopen" to read "robots.txt" URLs. > If the server asks for basic authentication on that file, "robotparser" > prompts for the password on standard input. Which is rarely what you > want. You can demonstrate this with: > > import robotparser > url = 'http://mueblesmoraleda.com' # this site is password-protected. > parser = robotparser.RobotFileParser() > parser.set_url(url) > parser.read() # Prompts for password > > That's the tandard, although silly, "urllib" behavior. John, robotparser is (IMO) suboptimal in a few other ways, too. - It doesn't handle non-ASCII characters. (They're infrequent but when writing a spider which sees thousands of robots.txt files in a short time, "infrequent" can become "daily"). - It doesn't account for BOMs in robots.txt (which are rare). - It ignores any Expires header sent with the robots.txt - It handles some ambiguous return codes (e.g. 503) that it ought to pass up to the caller. I wrote my own parser to address these problems. It probably suffers from the same urllib hang that you've found (I have not encountered it myself) and I appreciate you posting a fix. Here's the code & documentation in case you're interested: http://NikitaTheSpider.com/python/rerp/ Cheers -- Philip http://NikitaTheSpider.com/ Whole-site HTML validation, link checking and more From aleax at mac.com Tue Apr 17 21:59:52 2007 From: aleax at mac.com (Alex Martelli) Date: Tue, 17 Apr 2007 18:59:52 -0700 Subject: python - dll access (ctypes or swig) References: Message-ID: <1hwq9na.98800513op6liN%aleax@mac.com> Larry Bates wrote: > recently learned that you can ship COM as either an .EXE or a .DLL (nobody > has yet let me know why). The "why" is pretty obvious -- you may want to be able to instantiate a COM object either in-process, or in its own separate process, depending on that object's nature. For example, a complete application that when running exposes COM objects to let other processes drive/script it will be an EXE file since it can also run independently. In general I'm no big fan of MS's design, but COM, despite its imperfections, was in fact seriously good (Don Box's "Essential COM", an excellent book, went just into enough depth to let a developer really appreciate that, IMHO). I'm using the past tense because MS has been trying to kill COM for a while now (but I notice that "Essential COM", while 10 years-old, is _still_ in stock at Amazon -- so, I guess that so far MS's attempts haven't _quite_ succeeded yet:-). Alex From john.davis.85 at gmail.com Mon Apr 30 18:16:58 2007 From: john.davis.85 at gmail.com (John Davis) Date: Mon, 30 Apr 2007 15:16:58 -0700 Subject: regular expression problem Message-ID: <61fdaffc0704301516m4eb3c92fp8a73c1c155dc014e@mail.gmail.com> Hi all, I have a large logged string "str". I would like to strip down "str" so that it contains only the lines that have "ERROR" in them. Could somebody give me and indication of how to do this? Thx John. ===== -------------- next part -------------- An HTML attachment was scrubbed... URL: From bbxx789_05ss at yahoo.com Tue Apr 3 17:28:04 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: 3 Apr 2007 14:28:04 -0700 Subject: Newbie - needs help In-Reply-To: <1175632937.838422.236850@y66g2000hsf.googlegroups.com> References: <1175632937.838422.236850@y66g2000hsf.googlegroups.com> Message-ID: <1175635684.420398.101540@n59g2000hsh.googlegroups.com> On Apr 3, 2:42 pm, "Anbeyon" wrote: > Hi > > I have not yet programmed in Python but am experienced in a number o > other languages. > > I'd like to start to use Python to develop cross platform applications > but havin kust started to investigate tols, libraries etc I feel a > little overwhelmed. > > I'm hoping someone might be able to point me in the right direction. > "Learning Python" can be purchased at amazon.com. Or, not as good: "Beginning Python: From Novice to Professional". If you get the second one, you'll need "Python in a Nutshell: A Desktop Quick Reference" to fill in all the gaps. From martin at v.loewis.de Sat Apr 14 06:56:40 2007 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sat, 14 Apr 2007 12:56:40 +0200 Subject: Python Feature Request: Explicit variable declarations In-Reply-To: <1176546078.934340.253810@y5g2000hsa.googlegroups.com> References: <1176546078.934340.253810@y5g2000hsa.googlegroups.com> Message-ID: <4620b369$0$6937$9b622d9e@news.freenet.de> samjnaa at gmail.com schrieb: > Hello. Please tell me whether this feature request is sane (and not > done before) for python so it can be posted to the python-dev mailing > list. I should say first that I am not a professional programmer with > too much technical knowledge. I believe it has been requested before, but I'm too lazy now to search for prior discussion. The request is sane, but is also incomplete: there is no syntax suggested for the actual declarations of local variables, and no discussion whether this is meant to apply to local variables only, or also to global variables and object attributes. I think there is a fairly low chance that such a request will be considered. It's a big change (implementation-wise, and documentation-wise), and likely controversial. So one would have to write a PEP first (see PEP 1 for details). Regards, Martin From anton.vredegoor at gmail.com Fri Apr 20 06:41:31 2007 From: anton.vredegoor at gmail.com (Anton Vredegoor) Date: Fri, 20 Apr 2007 12:41:31 +0200 Subject: multirember&co In-Reply-To: <1177025176.943890.252910@b75g2000hsg.googlegroups.com> References: <1176768854.720234.23320@w1g2000hsg.googlegroups.com> <1176790588.024371.119360@n76g2000hsh.googlegroups.com> <1176850352.999231.79260@n59g2000hsh.googlegroups.com> <1176921030.330467.76860@o5g2000hsb.googlegroups.com> <1176925857.535835.130010@b58g2000hsg.googlegroups.com> <1177010211.252779.83620@y5g2000hsa.googlegroups.com> <1177025176.943890.252910@b75g2000hsg.googlegroups.com> Message-ID: attn.steven.kuo at gmail.com wrote: > This one gets the order wrong. With > > def test(): > L = 1, 2, 3, 'a', 4, 'a', 5, 'a', 6, 'a' > it1, it2 = xsplitter(L, lambda x: x == 'a') > print it1.next() > print it2.next() > print it1.next() > print it2.next() > print it1.next() > print it2.next() > print it1.next() > print it2.next() > > 5 will appear before 4. Thanks. This one will give 4 first and it uses a normal iterator. from collections import deque def xsplitter(seq, pred): Q = deque(),deque() it = iter(seq) def gen(p): for x in it: if pred(x) == p: Q[p].append(x) while Q[p]: yield Q[p].popleft() else: Q[~p].append(x) for x in gen(p): yield x while Q[p]: yield Q[p].popleft() return gen(1),gen(0) def test(): # L = 1, 2, 3, 'a', 'a' # L = 'a', 1, 2, 'a' # L = 1, 'a', 3, 'a', 4, 5, 6, 'a' L = 1, 2, 3, 'a', 4, 'a', 5, 'a', 6, 'a' it1, it2 = xsplitter(L, lambda x: x == 'a') print it1.next() print it2.next() print it1.next() print it2.next() print it1.next() print it2.next() print it1.next() print it2.next() print it2.next() print it2.next() if __name__=='__main__': test() Because the function can be stopped and resumed anytime, it is possible that at the new point of execution the queue has changed. For example if in these lines from the code above: if pred(x) == p: Q[p].append(x) while Q[p]: yield Q[p].popleft() I would make the change: if pred(x) == p: while Q[p]: yield Q[p].popleft() yield x Then the output will be out of order ... I wonder if this function is OK now. A. From rschroev_nospam_ml at fastmail.fm Fri Apr 20 04:41:13 2007 From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven) Date: Fri, 20 Apr 2007 08:41:13 GMT Subject: Do other Python GUI toolkits require this? In-Reply-To: References: <462697A6.6010007@codebykevin.com> <1obf23tjhhpi8rotsuh0kde2ejf47p5k9l@4ax.com> Message-ID: Antoon Pardon schreef: > On 2007-04-19, Wayne Brehaut wrote: >> So the remark that " a steep learning curve means that the subject is >> easily familiarized and that the learning period is short" is >> completely incorrect on two points (i.e., all points that are >> relevant): first, steep always implies much to learn in a relatively >> short time (what else could the slope of a curve possibly mean >> "mathematicallY" or logically?); > > No it doesn't imply that at all. A learning curve doesn't show some > goal of a person who was given just so much time to familiarize himself > with some material. A learning curve shows the progres that is made > in familiarizing one self while studying. A steep curve means a > lot of actual learning in a short time. >> A learning curve is conventionally the graph of a function of >> "quantity to be learned" vs. time, > No it doesn't. A learning curve is the graph that somehow quantifies > what is actually learned vs time. Do you have any reference to back that up? As I understand it, a learning curve plots the learning effort vs. the progress made. A steep learning curve means you need to learn a lot in order to make a little progress. -- If I have been able to see further, it was only because I stood on the shoulders of giants. -- Isaac Newton Roel Schroeven From mail at microcorp.co.za Wed Apr 25 02:36:39 2007 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Wed, 25 Apr 2007 08:36:39 +0200 Subject: Would You Write Python Articles or Screencasts for Money? References: <462DCCE6.9060908@taupro.com> <462E0D93.3090705@holdenweb.com> Message-ID: <000a01c78706$4d2e9340$03000080@hendrik> "Steve Holden" wrote: > Jeff Rush wrote: > > There is discussion by the Python Software Foundation of offering cash > > bounties or perhaps periodic awards to the "best of" for magazine articles, > > video/screencast clips and such. > > > > If YOU would be swayed to get involved in producing content in exchange for > > cash, please speak up on the advocacy mailing list and also drop an email to > > Steve Holden , current champion of this idea and looking > > for encouragement. Ideas on how to evaluate contributions, how frequently to > > do this and critical thresholds of cash amounts necessary to induce YOUR > > participation are wanted. > > > Thanks for posting this, Jeff. I have already had a couple of replies. > Allow me to expand on my current thinking before this gets off-track. > > Lest people be lulled into thinking that the PSF is going into the > "articles for cash" business, let me say that isn't really the idea. I > don't really think we will necessarily improve the quality of > information about Python simply by throwing cash incentives at authors, > and I was more looking for a way to reward authors of excellence, as > judged by some subset of the Python community - this might have to be > the PSF membership given the impracticality of running a meaningful poll > with a larger set of voters. I get a bit confused here - when you say "articles" - what forum do you have in mind? I would suggest that paying for articles would make sense on a commisioned basis, if there were to be an identified "hole" in the documentation, or for some technique or recipe which is not well covered, and deserving of more exposure. > > So the intention is not so much to encourage people who wouldn't > otherwise write to start writing (desirable though this outcome might > be, I don't think cash incentives are the right way to achieve it) but > rather to reward *excellence* in Python writing and underline the fact > that standards are important. > > There are many other possibilities too. What about an award for "most > helpful responses on c.l.py" over some period? I think one of the > reasons people find Python so useful is its helpful community, and it > would be nice to see the tireless fielders of questions rewarded for > their community contribution. > This is a good idea - I sometimes marvel at the degree of effort that some of the answers to a question on this NG must cost the repliers. Another one would be to reward the most patient fellow... > However, these are only my ideas and I am open to any and all > suggestions from the broader Python community about how awards might be > used to provide incentives to improve the available information about > Python, and possibly even the software that's available in Python. I > have undertaken to make a proposal to the PSF Board for an incentive > scheme. So please let me have your ideas. Most bugs fixed in the month for the developers? (Watch them scrabbling for the easy ones - ) Most Patches reviewed and incorporated? Best recipe of the week/month/year? Best Existing Module - don't forget that there has been a lot of effort put in already into stuff like Twisted, Pyro, SPE, and many more - a lot of it excellent work provided by rugged individuals, just because they could... As somone else has already said : ...... is F******G awesome - and its all in python. Hey! how about starting with the best suggestion for spending the money... That should get the ball rolling. - Hendrik From nogradi at gmail.com Tue Apr 17 07:49:26 2007 From: nogradi at gmail.com (Daniel Nogradi) Date: Tue, 17 Apr 2007 13:49:26 +0200 Subject: Deleting or Empty a File In-Reply-To: <5159306219058249750@unknownmsgid> References: <5159306219058249750@unknownmsgid> Message-ID: <5f56302b0704170449l35c194afuf627f0e469bde10@mail.gmail.com> > I'm looking to clear those log files we were discussing earlier chaps, > > > What the best method to do this? Delete the file completely? Or just empty > its content? If you just want to delete the content of a file but keep it with 0 length you can do: f = open( 'myfile', 'w' ) # or open( 'myfile', 'wb' ) f.close( ) Since you mentioned log files, you might want to look at the logging module: http://docs.python.org/lib/module-logging.html HTH, Daniel From mccredie at gmail.com Tue Apr 3 14:31:38 2007 From: mccredie at gmail.com (Matimus) Date: 3 Apr 2007 11:31:38 -0700 Subject: how to remove multiple occurrences of a string within a list? In-Reply-To: <1175624433.206953.214290@n59g2000hsh.googlegroups.com> References: <1175624433.206953.214290@n59g2000hsh.googlegroups.com> Message-ID: <1175625098.269660.184790@o5g2000hsb.googlegroups.com> It depends on your application, but a 'set' might really be what you want, as opposed to a list. >>> s = set(["0024","haha","0024"]) >>> s set(["0024","haha"]) >>> s.remove("0024") >>> s set(["haha"]) From apardon at forel.vub.ac.be Thu Apr 19 08:01:28 2007 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 19 Apr 2007 12:01:28 GMT Subject: Do other Python GUI toolkits require this? References: <462697A6.6010007@codebykevin.com> <465B30B4-5BA0-459A-BE6F-1038874FA74B@jedimindworks.com> Message-ID: On 2007-04-19, Steve Holden wrote: > Michael Bentley wrote: >> On Apr 19, 2007, at 4:11 AM, Antoon Pardon wrote: >> >>> On 2007-04-19, Michael Bentley wrote: > [...] The >>>> learning curve is rather steep IMO, but worth it. >>> Just a throw in remark, that you may ignore if you wish, but a steep >>> learning curve means that the subject is easily familiarized and that >>> the learning period is short. >>> >>> You seem to use it as if it is the opposite. >> >> Mathematical absurdities aside, it's the common usage -- but perhaps >> you knew that. >> >> > Perhaps in Belgium they prefer climbing mountains over walking up and > down gentle hills? Or possibly they will simply pick any nit that is > carelessly left within range? If it is just a nit, why don't you ignore my remark as I suggested? Now suppose I give you a graph that shows you how different people are making progress. Would you prefer the rather flat curves instead of the steep curves because the latter gives you the idea of someone having to conquer huge obstacles or would you choose the steep curve because they show you someone is getting results fast? -- Antoon Pardon From kw at codebykevin.com Tue Apr 3 14:53:53 2007 From: kw at codebykevin.com (Kevin Walzer) Date: Tue, 03 Apr 2007 14:53:53 -0400 Subject: os.popen--which one to use? Message-ID: I'm confused by the number of variations on "popen" that Python offers. I'm using os.popen in my programs without difficulty. Is this wrong? Should I be using popen 2, popen3, etc.? I'm not clear on what the advantages of popen2, 3 etc. are: they seem a lot more complicated. -- Kevin Walzer Code by Kevin http://www.codebykevin.com From raims at dot.com Thu Apr 5 12:04:02 2007 From: raims at dot.com (Lawrence Oluyede) Date: Thu, 5 Apr 2007 18:04:02 +0200 Subject: Prevent Modification of Script? References: <1175735097.856840.177510@e65g2000hsc.googlegroups.com> <1175753207.779307.63260@n59g2000hsh.googlegroups.com> Message-ID: <1hw3zh2.1jox21b1g7l8e8N%raims@dot.com> wrote: > Just throw out the .py files and let it run on the .pyc's alone. Which are very easily decompilable. :-) -- Lawrence, oluyede.org - neropercaso.it "It is difficult to get a man to understand something when his salary depends on not understanding it" - Upton Sinclair From steve at holdenweb.com Thu Apr 5 15:36:14 2007 From: steve at holdenweb.com (Steve Holden) Date: Thu, 05 Apr 2007 15:36:14 -0400 Subject: Why NOT only one class per file? In-Reply-To: <46154b8c$0$14532$426a34cc@news.free.fr> References: <1175721799.714907.52770@o5g2000hsb.googlegroups.com> <46142acc$0$7532$426a34cc@news.free.fr> <4614b40e$0$26843$426a74cc@news.free.fr> <1175778276.603838.86500@l77g2000hsb.googlegroups.com> <2O9Rh.24647$uo3.24013@newssvr14.news.prodigy.net> <46154b8c$0$14532$426a34cc@news.free.fr> Message-ID: Bruno Desthuilliers wrote: > John Nagle a ?crit : >> Nate Finch wrote: [...] > >> Interestingly, PHP breaks this model; PHP programs are web pages. > > Err... Actually, "web pages" *are* text files. And FWIW, in most php > programs (at least the clean ones), the application logic is in separate > files, and the 'rendering' code (views, templates, call them what you > like) are seldom full html documents. And it's perfectly possible to write a PHP program that isn't a web page. It's just that PHP is such an awful language nobody chooses to do it. Perhaps I'm not being fair to PHP. It's just been pushed so far beyond its original design limits that it's screamingly uncomfortable to use. 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 holdenweb.com Wed Apr 11 15:09:17 2007 From: steve at holdenweb.com (Steve Holden) Date: Wed, 11 Apr 2007 15:09:17 -0400 Subject: MRO theory In-Reply-To: <1176317929.068559.263330@o5g2000hsb.googlegroups.com> References: <1176317929.068559.263330@o5g2000hsb.googlegroups.com> Message-ID: Clarence wrote: > I'm having problems creating classes because of "can't create a > consistent mro" problems. > > I noticed, in a test program, that if the base class list that I > pass to type.__new__ is sorted (using default keys, so presumably > sorting by the id's of the class objects), that the problem goes away. > > Now in this test, the id's (memory addresses) of the class objects > are presumably in the same order as the chronological order that > the classes were created in (since the program is simple and doesn't > delete any objects or make any temporaries). This may sound weird, > but I don't actually care what order the base classes appear in as > long as they're all there. > > This makes me wonder, since I can't say I understand the theory > (I read the paper referenced in typeobject.c source, my brain > didn't _quite_ melt) > behind mro creation, if it is the case that there cannot be a > consistency problem if each class in the base list was created > after all classes that precede it in the base list. > > Can any genius weigh in on this question? > Without wishing to lay claim to genius, I'd suggest that you don;'t write programs relying on multiple inheritance until you have a thorough understanding of its principles. The inability of the interpreter to create a consistent mro has nothing to do with the order in which the base classes were created or where they appear in memory. It's probably because you have introduced a circularity: you are trying to define something based on A, which is based on B, which is based on A or something similar. 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 Tue Apr 10 01:02:23 2007 From: aleax at mac.com (Alex Martelli) Date: Mon, 9 Apr 2007 22:02:23 -0700 Subject: ulimit on open sockets ? References: Message-ID: <1hwbp5h.1fnai9snzd1vpN%aleax@mac.com> Maxim Veksler wrote: > ValueError: filedescriptor out of range in select() > """ > > Should I be using a different version of select or something? Or select typically supports 1024 FDs at most (a design limit of the underlying operating system). You may want to try poll instead (epoll might be better but I doubt Python supports it yet). Alex From gagsl-py2 at yahoo.com.ar Thu Apr 26 18:07:06 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 26 Apr 2007 19:07:06 -0300 Subject: Dedicated CPU core for Python? References: <1177607759.916727.180950@t39g2000prd.googlegroups.com> <4630e90c$0$16272$88260bb3@free.teranews.com> Message-ID: En Thu, 26 Apr 2007 15:54:38 -0300, Joshua J. Kugler escribi?: > Are you talking about CPU affinity > (http://en.wikipedia.org/wiki/Processor_affinity) or an actual CPU that > can directory execute Python byte code? If the former, CPython only > uses one > CPU core right now because it's threads are all internal, and do not > spawn system threads (IIRC). Python threads are OS threads: http://docs.python.org/lib/module-thread.html "[The thread module] is supported on Windows, Linux, SGI IRIX, Solaris 2.x, as well as on systems that have a POSIX thread (a.k.a. ``pthread'') implementation." -- Gabriel Genellina From dillonco at comcast.net Thu Apr 19 20:38:06 2007 From: dillonco at comcast.net (DillonCo) Date: Thu, 19 Apr 2007 20:38:06 -0400 Subject: Better dict of dicts In-Reply-To: References: <4627E28C.1050406@v.loewis.de> Message-ID: <200704192038.06084.dillonco@comcast.net> On Thursday 19 April 2007, Bill Jackson wrote: > Martin v. L?wis wrote the following on 04/19/2007 02:43 PM: > > Bill Jackson schrieb: > >> I have a dictionary of dictionaries where the keys are typically very > >> long tuples and repeated in each inner dictionary. > > > > What I don't understand here: you say the keys are tuples, yet later, > > you show that the keys are strings. Which one is it? > > Sorry, I was just lazy. The keys will always be tuples...tuple of > strings, tuples of numbers, tuples of objects....simply tuples. That'll change things a bit because intern only works with strings. Of course, It's not so big a deal, but you will have to put together a class to implement interning. I wrote one for fun: class ITuple(tuple): _interns={} def __new__(cls, tup): if tup not in cls._interns: itup=tuple.__new__(cls, tup) cls._interns[tup]=itup return cls._interns[tup] def __init__(self, *args): #Prevent multiple calls to __init__ if hasattr(self, "_inited"): return tuple.__init__(self, *args) self._inited=True def __eq__(self, o): #If the other is an ITuple, self==o iff self is o if isinstance(o, ITuple): return self is o return tuple.__eq__(self, o) >>> t1=(1,2,3,4); t2=(1,2,3,4) >>> ti1=ITuple(t1); ti2=ITuple(t2) >>> print t1==t2, t1 is t2 True False >>> print ti1==ti2, ti1 is ti2 True True That seems to work. Something to note is that the call overhead of the __eq__ function is large enough that unless you have a slow comparing tuple, comparisons will be faster without it. Comparisons are fast if they are done internally; so between builtin objects or identical (" is ") objects. For an example, suppose you have: class TTT(object): def __eq__(self, o): return True a,b=TTT(),TTT() Then the follow comparisons are fast: (1,2,3)==(1,2,3) (1,2,3,a)==(1,2,3,a) (0,0,0,a)==(1,2,3,b) The following are slow: (1,2,3,a)==(1,2,3,b) Note that the only slow case is the one where a.__eq__(b) is called. However, a.__eq__(b) is assumed True is "a is b" is True. So chances are you'll want to comment out the __eq__ function. From hg at nospam.org Tue Apr 17 04:50:29 2007 From: hg at nospam.org (hg) Date: Tue, 17 Apr 2007 10:50:29 +0200 Subject: Syntax error References: <9w5Vh.8580$OT4.3503@newsfe19.lga> <58k89hF2hgicvU1@mid.uni-berlin.de> Message-ID: <706Vh.527552$Ju2.34696@newsfe16.lga> Diez B. Roggisch wrote: > hg wrote: > >> Hi, >> >> I've had this problem in the past and still cannot fully understand. >> >> I latelly passed my source code in Wing IDE wihch asked be to resolve >> tab/space/CRLF conflicts and I said yes (initially the code was >> developped under Linux ... and now all source got tabs replaced by spaces >> and all EOL when switched to Windows CR/LF) >> >> I sent a new release of the software, tested here first, to the customer >> who got a syntax error on a line which visibly did not have any error. >> >> retyping that line by and made the error jump around the file like crazy. >> >> I had the customer comment out the first two lines of the file: >> >> """ >> #!/bin/env python >> # -*- coding: iso-8859-15 -*- >> """ >> >> ... and the problem disappeared. >> >> I am at a loss. >> >> Any clue ? > > Without a stacktrace? It's spring, not crystal ball season. > > Diez Not worth showing really, it's a screen dump so can't put it here but: .... self.T_CARD_FOUND = 'PLEASE WAIT ...' ^ Syntax error hg From liupeng at 18mail.cn Wed Apr 11 21:41:30 2007 From: liupeng at 18mail.cn (liupeng) Date: Thu, 12 Apr 2007 09:41:30 +0800 Subject: python regular expression help In-Reply-To: <402459.62579.qm@web58905.mail.re1.yahoo.com> References: <402459.62579.qm@web58905.mail.re1.yahoo.com> Message-ID: <20070412014130.GA5046@pworld.org> pattern = re.compile(r'\w+\s*=\s*[0-9]*.[0-9]*\s*') lists = pattern.findall(s) print lists ['a=4 ', 'b=3.4 ', 'c=4.5'] On Wed, Apr 11, 2007 at 06:10:07PM -0700, Qilong Ren wrote: > Hi, everyone, > > I am extracting some information from a given string using python RE. The > string is ,for example, > s = 'a = 4 b =3.4 5.4 c = 4.5' > What I want is : > a = 4 > b = 3.4 5.4 > c = 4.5 > Right now I use : > pattern = re.compile(r'\w+\s*=\s*.*?\s+') > lists = pattern.findall(s) > It works for the string like 'a = 4 b = 3.4 c = 4.5', but does not work with > strings like 'a=4 b=3.4 5.4 c = 4.5' > > Any suggestion? > > Thanks,Qilong > > ??????????????????????????????????????????????????????????????????????????????? > Don't get soaked. Take a quick peak at the forecast > with theYahoo! Search weather shortcut. > -- > http://mail.python.org/mailman/listinfo/python-list -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 196 bytes Desc: Digital signature URL: From apt.shansen at gmail.com Tue Apr 3 02:51:07 2007 From: apt.shansen at gmail.com (Stephen Hansen) Date: Mon, 2 Apr 2007 23:51:07 -0700 Subject: python on mac os 10.4.x In-Reply-To: <1175576455.471249.58740@q75g2000hsh.googlegroups.com> References: <1175576455.471249.58740@q75g2000hsh.googlegroups.com> Message-ID: <7a9c25c20704022351qfac715ib538d38683d3f19@mail.gmail.com> Check out: http://www.pythonmac.org/packages/ for the latest version of Python, which will run the latest version of wxPython fine. (I'm using wxPython 2.8 on Python 2.4) On 2 Apr 2007 22:00:55 -0700, 7stud wrote: > > Hi, > > Python 2.3.5 comes pre-installed on mac os 10.4.7, and I've looked > around in /System/Library/Frameworks/Python.framework/ and under .../ > Versions/2.3/bin/, there is an exec file named 'idle'. I assume that > is the Python IDLE I've read about, but I can't figure out what I need > to do to use IDLE to edit a file. Any help would be appreciated. > > I know it's recommended to install the latest version of python, which > would then come with the IDLE, but I want to learn wxPython as well, > and from what I understand you need a "framework" build of python on a > Mac to use wxPython. And I don't have any idea how to install a > python framework build > > Thanks. > > -- > http://mail.python.org/mailman/listinfo/python-list > -- Stephen Hansen Development Advanced Prepress Technology shansen at advpubtech.com (818) 748-9282 -------------- next part -------------- An HTML attachment was scrubbed... URL: From sjdevnull at yahoo.com Thu Apr 12 00:13:06 2007 From: sjdevnull at yahoo.com (sjdevnull at yahoo.com) Date: 11 Apr 2007 21:13:06 -0700 Subject: pop() clarification In-Reply-To: <1176338113.035908.52880@b75g2000hsg.googlegroups.com> References: <1176318615.056436.47430@y5g2000hsa.googlegroups.com> <1176338113.035908.52880@b75g2000hsg.googlegroups.com> Message-ID: <1176351186.707318.81720@e65g2000hsc.googlegroups.com> Carl Banks wrote: > On Apr 11, 3:10 pm, "7stud" wrote: > > On Apr 11, 10:44 am, "Scott" wrote: > > > > > > > > > As said before I'm new to programming, and I need in depth explaination to > > > understand everything the way I want to know it, call it a personality quirk > > > ;p. > > > > > With pop() you remove the last element of a list and return its value: > > > > > Now I know list is a bad name, but for the sake of arguement lets assume its > > > not a built in sequence> > > > > > >>>list = ['this', 'is', 'an', 'example'] > > > >>>list.pop() > > > 'example' > > > >>>list > > > > > ['this', 'is', 'an'] > > > > > I understand all that. What I don't understand is why all the documentation > > > I see says, "When removing a specific element from a list using pop() it > > > must be in this format: list.pop([i]). > > > At first I took that to mean that list.pop(i) would return some type of > > > error, but it doesn't. > > > > It's understandable that the definition of pop() is confusing in that > > way. It looks like the argument should be a list. As others have > > said, that is not what the brackets mean when the documents show the > > formal definition of a function. > > I wonder if the documentation could take advantage of Python 3000 > annotation syntax. So > > pop([x]) > > would be replaced in the docs by > > pop(x: OPTIONAL) > > Just a thought, probably not a good one. The brackets are so > pervasive that it's probably better to just let newbies be confused > for a little bit. Especially since [] are used for optional arguments in many non-Python contexts, so sticking with [] helps those coming from a background that uses them in such a manner. From Kamy.Iltcheva at gmail.com Sun Apr 22 08:23:14 2007 From: Kamy.Iltcheva at gmail.com (Kamy.Iltcheva at gmail.com) Date: 22 Apr 2007 05:23:14 -0700 Subject: Access to file dropped on .exe/.app icon In-Reply-To: <1177238512.066413.41660@n59g2000hsh.googlegroups.com> References: <1177238512.066413.41660@n59g2000hsh.googlegroups.com> Message-ID: <1177244594.194873.228330@p77g2000hsh.googlegroups.com> On Apr 22, 1:41 pm, Martin wrote: > If i create an app using py2exe/py2app is there then a way on windows/ > mac to get access to a file dragged and dropped on to the .exe/.app > icon? > > Martin Windows: import sys print sys.argv[1:] From len-l at telus.net Sun Apr 1 17:58:57 2007 From: len-l at telus.net (Lenard Lindstrom) Date: Sun, 01 Apr 2007 21:58:57 GMT Subject: Using Simple MAPI with MS Outlook 2007 In-Reply-To: <1175380241.373052.267110@b75g2000hsg.googlegroups.com> References: <1175380241.373052.267110@b75g2000hsg.googlegroups.com> Message-ID: tomer.ha at gmail.com wrote: > Hi there, > > I'd like to send emails from a Python program using Simple MAPI. I've > tried this code: http://mail.python.org/pipermail/python-list/2004-December/298066.html > and it works well with Outlook Express 6 and Thunderbird 1.5, but it > doens't work at all with Microsoft Outlook 2007. I keep getting this > message: "WindowsError: MAPI error 2". > > I don't want to use Extended MAPI because it doesn't support > thunderbird not OE. Therefore, Simple MAPI is the only option for me. > > So, what did I miss here? > > From - Sun Error code 2 error translates to: "MAPI_E_FAILURE One or more unspecified errors occurred. No message was sent. " , rather vague. I haven't used Simple MAPI with Outlook, but did a quick google search. I found that there is a security feature that may effect access to Outlook. I have included a few links on the chance that this is the cause of the problem. Outlook Email Security Update: http://www.slipstick.com/outlook/esecup.htm Outlook security block & Simple MAPI: http://help.lockergnome.com/office/Outlook-security-block-Simple-Mapi-ftopict946357.html Customize programmatic settings in Outlook 2007: http://technet2.microsoft.com/Office/en-us/library/8a611f92-e197-4dd3-9417-5ed513891af11033.mspx?mfr=true The google search also uncovered a memory issues with Simple MAPI and Outlook: http://blogs.msdn.com/stephen_griffin/archive/2006/11/03/the-intentional-memory-leak.aspx Hope this helps, Lenard Lindstrom From nagle at animats.com Sat Apr 21 19:06:20 2007 From: nagle at animats.com (John Nagle) Date: Sat, 21 Apr 2007 16:06:20 -0700 Subject: Easy make money! In-Reply-To: <1177190013.974042.231630@d57g2000hsg.googlegroups.com> References: <1177188351.751842.169370@d57g2000hsg.googlegroups.com> <1177190013.974042.231630@d57g2000hsg.googlegroups.com> Message-ID: Dustan wrote: > On Apr 21, 3:45 pm, GPcapital wrote: > >>Lately I've been surfing trought some web pages and got this one >>www.gpcapitalgroup.com. It looks quite interesting, it may be a great >>chance to invest. > > >>>>advertisement.delete() I couldn't resist. I ran that through SiteTruth, our automatic website legitimacy checker (written in Python, of course). http://www.sitetruth.com/cgi-bin/ratingdetails.cgi?url=www.gpcapitalgroup.com Not found in Open Directory. Not found in US business database. No address found on site. No usable SSL certificate. Rating: "Site ownership unknown or questionable." Any questions? John Nagle From steve at REMOVE.THIS.cybersource.com.au Thu Apr 19 10:22:09 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Fri, 20 Apr 2007 00:22:09 +1000 Subject: comparison with None References: <_JAVh.1700$jR5.897@trnddc08> <462709FB.9020607@gmail.com> Message-ID: On Thu, 19 Apr 2007 08:18:30 -0400, Steve Holden wrote: >> Which is why I suggested using the explicit type(x) == types.NoneType as >> opposed to >> x is None >> >> > This seems to go entirely against the spirit of the language. It's about > as sensible as writing > > (3 > 4) == True Please! For extra certainty, you should write that as: ((int(3) > int(4)) == True) == True Explicit is better than sensible, yes? *wink* -- Steven. From harlinseritt at yahoo.com Sun Apr 29 12:34:13 2007 From: harlinseritt at yahoo.com (Harlin Seritt) Date: 29 Apr 2007 09:34:13 -0700 Subject: Python ODBC Message-ID: <1177864453.282136.233030@n59g2000hsh.googlegroups.com> Is there a Python odbc module that will work on Linux? I have a jdbc connection to a DB2 server. I am looking hopefully for an open source solution and not a commercial one. Thanks, Harlin From mensanator at aol.com Tue Apr 17 14:59:03 2007 From: mensanator at aol.com (mensanator at aol.com) Date: 17 Apr 2007 11:59:03 -0700 Subject: The smallest and largest values of numeric types In-Reply-To: References: Message-ID: <1176836343.114315.81820@y80g2000hsf.googlegroups.com> On Apr 17, 11:37 am, t... at finland.com wrote: > Thank you for your answers. Seems like the limits of numeric values > aren't considered as important in Python as in C ;) Sure, they're important, we just don't want to notice them. That's why conversion to longs is automatic, so that number size limits don't cause problems and your problems are solved rather than throw exceptions or produce invalid results. From nico-NoSp at m-tekNico.net.invalid Thu Apr 26 13:09:40 2007 From: nico-NoSp at m-tekNico.net.invalid (Nicola Larosa) Date: Thu, 26 Apr 2007 19:09:40 +0200 Subject: [PyCon Uno Italy] Call For Papers Message-ID: <4630dcca@extreme.x-privat.org> PyCon Uno: Python first Italian conference about Python. Call for Papers =============== Important dedalines ------------------- * April 30, 2007 Submission of paper and tutorial abstracts. * May 5, 2007 Papers and tutorials admission notification. * June 9, 2007 Submission of paper and tutorial final versions. What is PyCon Uno? ------------------ PyCon Uno is the first Italian conference about the Python programming language. It will be held in __Florence on June 9 and 10, 2007__. The conference aims to help spreading the Python language, and better expose professional developers, students, businesses and interested people. The conference official language is the Italian one. Papers ------ The conference is made up of two parallel tracks: *tutorial* and *advanced*. * The *tutorial* track talks will mainly deal with introductory matters related to Python technologies and libraries; * The *advanced* track will deal with more advanced matters, both from a technical point of view and regarding development methodologies, use cases (for example, Python for businesses) and management; Here is a tentative and incomplete list of relevant matters: * huge and/or distributed Python applications * scientific and numeric applications * integration with other languages and environenments, RPC and services * web development and frameworks * desktop and GUI toolkit programming * Python as a system language (scripting, COM etc.) * Python and databases * Python as an instructional language Papers will be evaluated according to content, relevance to the Python community, writing style and quality. Each talk will last at most 60 minutes, which comprise setup and teardown time. How to submit a talk proposal ----------------------------- Send talk proposals to the call-for-papers AT pycon.it email address, with "[TALK] Talk title" as subject, and the abstract in the mail body. What to send when, and how to send it ------------------------------------- Please only send papers that have been explicitly accepted by the organization. Send them before the conference starting date. Papers must be your own original production: any paper containing materials copyrighted by others will not be accepted. Papers have to be written in the Italian language. Papers may be submitted in text, HTML (one file), Postscript or PDF format, or any other standard format that may be opened and printed on many systems. To submit a paper, proceed as follows: 1. create a tar/bz2/zip/gz file containing the paper, any supplementary files (like images), and a README file with your name, email and any further information; 2. send an email to call-for-papers AT pycon.it , attaching the above mentioned file. Additional information ---------------------- For any question, please contact us at info AT pycon.it . Conference organizers --------------------- * Giovanni Bajo (Develer SRL) * Marco Beri (Link I.T.) * Antonio Cavedoni (Bunker) * Enrico Franchi (Sviluppatore Indipendente) * Alan Franzoni (Sviluppatore Indipendente) * Nicola Larosa (Space SPA) * Alex Martelli (Google Inc.) * Stefano Masini (Pragma2000) * Carlo Miron (Visiant Galyleo) * David Mugnai (Space SPA) * Lawrence Oluyede (Sviluppatore Indipendente) * Manlio Perillo (Sviluppatore Indipendente) * Fabio Pliger (Sia Verona SRL) * Giovanni Porcari (Softwell SaS) * Michele Simionato (StatPro Plc) * Daniele Varrazzo (Develer SRL) * Maurizio Volonghi * Valentino Volonghi (Sviluppatore Indipendente) * Simone Zinanni (Develer SRL) -- Nicola Larosa - http://www.tekNico.net/ From deets at nospam.web.de Sun Apr 22 14:00:50 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sun, 22 Apr 2007 20:00:50 +0200 Subject: Convert from/to struct_time In-Reply-To: References: Message-ID: <591m6lF2hodehU1@mid.uni-berlin.de> Florian Lindner schrieb: > Hello, > I have a struct_time and a datetime object and need compare them. Is there > any function that converts either of these two to another? datetime.datetime(*time.localtime()[:6]) Diez From maric at aristote.info Thu Apr 12 11:20:13 2007 From: maric at aristote.info (Maric Michaud) Date: Thu, 12 Apr 2007 17:20:13 +0200 Subject: reading from sys.stdin In-Reply-To: <1176387908.406115.270630@w1g2000hsg.googlegroups.com> References: <1176366058.261031.111870@p77g2000hsh.googlegroups.com> <1176387908.406115.270630@w1g2000hsg.googlegroups.com> Message-ID: <200704121720.14631.maric@aristote.info> Le jeudi 12 avril 2007 16:25, Matimus a ?crit?: > # Then you check to see if your file is interactive > if f.isatty(): > ? ? # This is unbuffered, and will iterate the same as f > ? ? f = iter(raw_input(),"") This should be f = iter(raw_input,"") and this will end in a EOFError and stop on blank line. So you need a wrapper like : >>> def stdin_iterator() : ... while(True) : ... try : yield raw_input() ... except EOFError : return ... >>> f = stdin_iterator() Do you really need to iterate on the file this way instead of using the straightforward readline method ? >>> import sys >>> l=sys.stdin.readline() >>> while(l) : ... print l, ... l=sys.stdin.readline() -- _____________ Maric Michaud _____________ Aristote - www.aristote.info 3 place des tapis 69004 Lyon Tel: +33 4 26 88 00 97 Mobile: +33 6 32 77 00 21 From aisaac at american.edu Wed Apr 18 22:46:18 2007 From: aisaac at american.edu (Alan Isaac) Date: Thu, 19 Apr 2007 02:46:18 GMT Subject: comparison with None Message-ID: <_JAVh.1700$jR5.897@trnddc08> "Terry Reedy" wrote in message news:mailman.6686.1176934558.32031.python-list at python.org... > Should be in the reference manual section on comparisons. Only to this extent: http://www.python.org/doc/2.4/ref/comparisons.html objects of different types always compare unequal, and are ordered consistently but arbitrarily. (This unusual definition of comparison was used to simplify the definition of operations like sorting and the in and not in operators. In the future, the comparison rules for objects of different types are likely to change.) ... Most other types compare unequal unless they are the same object; the choice whether one object is considered smaller or larger than another one is made arbitrarily but consistently within one execution of a program. This does not provide a direct answer to "why" None comparisons. (As far as I can tell, None is less than any object.) However, Gary Herron's explanation makes sense: this provides a stable sort when None is involved, and meets the criterion that objects of different types must always compare unequal. However this would also be true if None always compared greater than any object, and the current behavior does not seem to be guaranteed. Is that about right? Cheers, Alan Isaac From maric at aristote.info Thu Apr 12 08:46:12 2007 From: maric at aristote.info (Maric Michaud) Date: Thu, 12 Apr 2007 14:46:12 +0200 Subject: reading from sys.stdin In-Reply-To: <586984F2g0ejiU1@mid.uni-berlin.de> References: <1176366058.261031.111870@p77g2000hsh.googlegroups.com> <586984F2g0ejiU1@mid.uni-berlin.de> Message-ID: <200704121446.14303.maric@aristote.info> Le jeudi 12 avril 2007 10:34, Diez B. Roggisch a ?crit?: > I presume this is an OS thing. The first lines aren't communicated to > the process until either the file is closed - C-d - or the buffer the OS > puts before the stream is filled. You can switch to unbuffered behviour > somehow, google for it. Termios should be in your query. I don't know if this a python or OS thing, but I know that iterating over a file is not like applying successive call to readline method. You should try to use readline instead. The following work exactly the same on windows and Linux (python2.4) : >>> f=open('txt') >>> l=f.readline() >>> while(l) : ... print l, ... print "rest : " + f.read() ... l=f.readline() ... foo rest : bar baz works as expected, while : >>> f=open('txt') >>> for l in f : ... print l, ... print "rest : " + f.read() ... foo rest : bar rest : baz rest : doesn't, it seems that file iteratiion itself use a buffer. In python 2.5, you just can't do this : Python 2.5 (release25-maint, Dec 9 2006, 14:35:53) [GCC 4.1.2 20061115 (prerelease) (Debian 4.1.1-20)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> f=open('txt') >>> for l in f : ... print l, ... print "rest : " + f.read() ... foo Traceback (most recent call last): File "", line 3, in ValueError: Mixing iteration and read methods would lose data -- _____________ Maric Michaud _____________ Aristote - www.aristote.info 3 place des tapis 69004 Lyon Tel: +33 4 26 88 00 97 Mobile: +33 6 32 77 00 21 From paddy3118 at googlemail.com Fri Apr 27 01:59:26 2007 From: paddy3118 at googlemail.com (Paddy) Date: 26 Apr 2007 22:59:26 -0700 Subject: webbrowser.open works in IDLE and cmd shell but not from cygwin prompt In-Reply-To: <1177646975.285805.106920@b40g2000prd.googlegroups.com> References: <1177646975.285805.106920@b40g2000prd.googlegroups.com> Message-ID: <1177653566.133454.79330@t39g2000prd.googlegroups.com> On Apr 27, 5:09 am, Gregory Bloom wrote: > I'm running Python 2.5 under Windows. If I fire up IDLE and enter: > > >>> import webbrowser > >>> url = 'http://www.python.org' > >>> webbrowser.open_new(url) > > it works like a champ, opening the page in Firefox. Same thing goes > from a Windows cmd shell: it works as advertised. > > But if I open a cygwin bash shell and try the same thing from a python > prompt, I get: > > >>> import webbrowser > >>> url = 'http://www.python.org' > >>> webbrowser.open_new(url) > > Traceback (most recent call last): > File "", line 1, in > File "C:\Python25\lib\webbrowser.py", line 60, in open_new > return open(url, 1) > File "C:\Python25\lib\webbrowser.py", line 55, in open > if browser.open(url, new, autoraise): > File "C:\Python25\lib\webbrowser.py", line 185, in open > p = subprocess.Popen(cmdline, close_fds=True, preexec_fn=setsid) > File "C:\Python25\lib\subprocess.py", line 551, in __init__ > raise ValueError("close_fds is not supported on Windows " > ValueError: close_fds is not supported on Windows platforms > > What's up with that? And, more to the point, how can I use webbrowser > from scripts launched under cygwin? I have X and kde for cygwin installed. If i use startxwin to start an xterm, without starting kde, and do the above in cygwins python version 2.4.3 i have to wait around 3 minutes then up pops konqueror at the requested page. - Paddy. From mangabasi at gmail.com Tue Apr 3 18:45:39 2007 From: mangabasi at gmail.com (Mangabasi) Date: 3 Apr 2007 15:45:39 -0700 Subject: Calling Fortran from Python Message-ID: <1175640339.648190.207530@y66g2000hsf.googlegroups.com> Howdy, I have been trying to call the following Fortran function from Python (using Windows XP, Compaq Fortran and Python 2.4). I tried F2Py, Pyfort and calldll with no success. I think I came very close with calldll. Here is a short summary Fortran code: SUBROUTINE SAMPLE(IERR1,IERR2,AIN,AOUT) C C SIMPLE SAMPLE OF A DLL C !DEC$ATTRIBUTES DLLEXPORT :: SAMPLE !DEC$ATTRIBUTES ALIAS:'SAMPLE' :: SAMPLE INTEGER,INTENT(OUT) :: IERR1,IERR2 REAL*8,INTENT(IN) :: AIN(*) REAL*8,INTENT(OUT) :: AOUT(*) C C *** SET MAXIMUM EXPECTED ELEMENTS OF ARRAY AIN AND AOUT C PARAMETER (MAXNVIN=101,MAXNVOUT=200) C C *** SET ERROR INDICATORS TO ZERO C IERR1=0 IERR2=0 C C *** GET NUMBER OF INPUT VALUES C NVIN=AIN(1) C *** IF NUMBER EXCEEDS MAXIMUM EXPECTED SET ERRORS AND RETURN IF(NVIN .GT. MAXNVIN) THEN IERR1=1 IERR2=1 RETURN ENDIF C C *** SET NUMBER OF OUTPUT VALUES C NVOUT=2*NVIN C *** IF NUMBER EXCEEDS MAXIMUM EXPECTED SET ERRORS AND RETURN IF(NVOUT .GT. MAXNVOUT) THEN IERR1=1 IERR2=2 RETURN ENDIF C C *** INITIALIZE AOUT INDEX C JOUT=0 C C *** COMPUTE TWO OUTPUT VALUES FOR EACH INPUT VALUE C DO I=1,NVIN JOUT=JOUT+1 AOUT(JOUT)=2.*AIN(I+1) JOUT=JOUT+1 AOUT(JOUT)=3.*AIN(I+1) END DO RETURN END compiled it to a dll and called this dll from another Fortran program with success, so this tells me that dll is OK. This is how I tried to call it from python 2.4 import calldll handle = calldll.load_library('c:/sample_dll.dll') addr = calldll.get_proc_address(handle, 'SAMPLE') #so far so good, I got a handle and address e1 = 0 e2 = 0 ain = [2, 3, 4] aout = [ ] calldll.call_foreign_function(addr, 'hhll', 'l',(e1, e2,ain,aout)) Traceback (most recent call last): File "", line 1, in ? TypeError: an integer is required Has anyone provide a similar example with Pyfort, F2Py or calldll? Thanks in advance. From deets at nospam.web.de Sun Apr 29 08:14:15 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sun, 29 Apr 2007 14:14:15 +0200 Subject: Could zipfile module process the zip data in memory? In-Reply-To: <1177847479.803195.12820@c35g2000hsg.googlegroups.com> References: <1177845313.798239.71580@o5g2000hsb.googlegroups.com> <1177847479.803195.12820@c35g2000hsg.googlegroups.com> Message-ID: <59jggvF2l55aoU1@mid.uni-berlin.de> ??????????????? schrieb: > On Apr 29, 7:37 pm, "Daniel Nogradi" wrote: >>> I made a C/S network program, the client receive the zip file from the >>> server, and read the data into a variable. how could I process the >>> zipfile directly without saving it into file. >>> In the document of the zipfile module, I note that it mentions the >>> file-like object? what does it mean? >>> class ZipFile( file[, mode[, compression[, allowZip64]]]) >>> Open a ZIP file, where file can be either a path to a file (a >>> string) or a file-like object. >> Yes it is possible to process the content of the zipfile without >> saving every file: >> >> [untested] >> >> from zipfile import ZipFile >> from StringIO import StringIO >> >> zipp = ZipFile( this_is_the_zip_file_from_your_server, 'r' ) >> for name in zipp.namelist( ): >> content = zipp.read( name ) >> s = StringIO( ) >> s.write( content ) >> # now the file 'name' is in 's' (in memory) >> # you can process it further >> # ............ >> s.close( ) >> zipp.close( ) >> >> HTH, >> Daniel > Thanks! > Maybe my poor english makes you confusion:-). The client receive the > zip file data from the server, and keep these data as a variable, not > as a file in harddisk. such as "zipFileData", but the first argument > of the "ZipFile" is filename. I would like to let the ZipFile() open > the file from "zipFileData" directly but not file in harddisk > > zipp = ZipFile( this_is_the_zip_file_from_your_server, 'r' ) > ^ I don't have this file, all its data > is in a variable. You can use cStringIO for that as well. Read the module docs for it. Diez From malkarouri at gmail.com Wed Apr 11 11:21:43 2007 From: malkarouri at gmail.com (malkarouri at gmail.com) Date: 11 Apr 2007 08:21:43 -0700 Subject: run function in separate process In-Reply-To: <1176302047.122464.156680@o5g2000hsb.googlegroups.com> References: <1176301427.183706.321920@n76g2000hsh.googlegroups.com> <1176302047.122464.156680@o5g2000hsb.googlegroups.com> Message-ID: <1176304903.497577.224880@q75g2000hsh.googlegroups.com> Thanks Mike for you answer. I will use the occasion to add some comments on the links and on my approach. I am programming in Python 2.5, mainly to avoid the bug that memory arenas were never freed before. The program is working on both Mac OS X (intel) and Linux, so I prefer portable approaches. On Apr 11, 3:34 pm, kyoso... at gmail.com wrote: [...] > I found a post on a similar topic that looks like it may give you some > ideas: > > http://mail.python.org/pipermail/python-list/2004-October/285400.html I see the comment about using mmap as valuable. I tried to use that using numpy.memmap but I wasn't successful. I don't remember why at the moment. The other tricks are problem-dependent, and my case is not like them (I believe). > http://www.artima.com/forums/flat.jsp?forum=106&thread=174099 Good ideas. I hope that python will grow a replacable gc one day. I think that pypy already has a choice at the moment. > http://www.nabble.com/memory-manage-in-python-fu-t3386442.html > http://www.thescripts.com/forum/thread620226.html Bingo! This thread actually reaches more or less the same conclusion. In fact, Alex Martelli describes the exact pattern in http://mail.python.org/pipermail/python-list/2007-March/431910.html I probably got the idea from a previous thread by him or somebody else. It should be much earlier than March, though, as my program was working since last year. So, let's say the function I have written is an implementation of Alex's architectural pattern. Probably makes it easier to get in the cookbook:) Regards, Muhammad From mwilson at the-wire.com Sat Apr 14 11:37:59 2007 From: mwilson at the-wire.com (Mel Wilson) Date: Sat, 14 Apr 2007 11:37:59 -0400 Subject: Python Feature Request: Add the "using" keyword which works like "with" in Visual Basic In-Reply-To: <1176547372.584539.89170@q75g2000hsh.googlegroups.com> References: <1176547372.584539.89170@q75g2000hsh.googlegroups.com> Message-ID: samjnaa at gmail.com wrote: > In Visual Basic there is the keyword "with" which allows an object- > name to be declared as governing the following statements. For > example: > > with quitCommandButton > .enabled = true > .default = true > end with > > This is syntactic sugar for: > > quitCommandButton.enabled=true > quitCommandButton.default=true > > This can be very useful especially in GUI programming when we have to > type the same object name in line-after-line. q = quitCommandButton q.enabled = true q.default = true Mel. From steve at holdenweb.com Wed Apr 4 15:37:22 2007 From: steve at holdenweb.com (Steve Holden) Date: Wed, 04 Apr 2007 15:37:22 -0400 Subject: Requirements For A Visualization Software System For 2010 In-Reply-To: <1175714617.095757.162510@y80g2000hsf.googlegroups.com> References: <1175628186.459945.290750@d57g2000hsg.googlegroups.com> <1175714617.095757.162510@y80g2000hsf.googlegroups.com> Message-ID: galathaea wrote: > On Apr 3, 12:23 pm, "Xah Lee" wrote: > [top posting for clarity] > [and then redundantly quoting the whole article to which comments referred]. Come on, people - remember netiquette? Please trim out material that's not relevant to your reply. 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 zafere at gmail.com Fri Apr 27 05:24:12 2007 From: zafere at gmail.com (ozan SARI) Date: Fri, 27 Apr 2007 12:24:12 +0300 Subject: How can I save command prompt screen Message-ID: <8843bd8a0704270224t57b7f295wf09b0a3ae1866224@mail.gmail.com> Hi , I run a python acript with os.system('script.py') I want save command prompt screen in a text file (everything ) how can I do this? Thanks for your help Ozan -------------- next part -------------- An HTML attachment was scrubbed... URL: From apardon at forel.vub.ac.be Fri Apr 13 03:32:20 2007 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 13 Apr 2007 07:32:20 GMT Subject: tuples, index method, Python's design References: <1175953520.316208.241490@o5g2000hsb.googlegroups.com> <7xzm5igbrb.fsf@ruckus.brouhaha.com> <1176200361.260546.280510@n76g2000hsh.googlegroups.com> <740c3aec0704100824m132c45fbi5c4c3ec0c0fa3a67@mail.gmail.com> Message-ID: On 2007-04-12, Carsten Haese wrote: > On Thu, 2007-04-12 at 14:10 +0000, Antoon Pardon wrote: >> People are always defending duck-typing in this news group and now python >> has chosen to choose the option that makes duck-typing more difficult. > > Au contraire! The "inconsistent" behavior of "in" is precisely what > duck-typing is all about: Making the operator behave in a way that makes > sense in its context. No it isn't. Ducktyping is about similar objects using a similar interface to invoke similar behaviour and getting similar result. So that if you write a function you don't concern yourself with the type of the arguments but depend on the similar behaviour. Suppose someone writes a function that acts on a sequence. The algorithm used depending on the following invariant. i = s.index(e) => s[i] = e Then this algorithm is no longer guaranteed to work with strings. On the other hand I subclass list and add a sub method to check for the argument being a sublist of the object. Now I write a function that depends on this functionality. But although strings have the functionality I can't use them as argument because the functionality is invoked in a different way. > Nobody seems to be complaining about "+" behaving > "inconsistently" depending on whether you're adding numbers or > sequences. You are wrong. I already mentioned problems with it. The problem is that there are structures that are numbers and sequences at the same time. So I have a choice. Either I overload the "+" to get an addition or to get a concatanation. In the first case I can't trust my structure to work with functions that expect a general sequence because they may depend on the fact that "+" concatenates. In the other case I can't trust my structure to work with numbers because they may depend on the fact that "+" behaves like an addition. -- Antoon Pardon From larry.bates at websafe.com Mon Apr 2 13:19:21 2007 From: larry.bates at websafe.com (Larry Bates) Date: Mon, 02 Apr 2007 12:19:21 -0500 Subject: Python Based API In-Reply-To: <1175441871.933442.152630@p77g2000hsh.googlegroups.com> References: <1175441871.933442.152630@p77g2000hsh.googlegroups.com> Message-ID: Dean.Brotzel at gmail.com wrote: > Hi, > > I work on a project that is built entirely using python and Tkinter. > We are at the point where we would like to give access to our > functionality to others via some sort of API. People who would use > our API develop in all kinds of languages from C/C++ to Pascal. > > Ideas that come to mind that allow us to build such an API are: > > 1) Require others to imbed the python interpreter via the c API to be > able to utilize our functionality. > 2) Build an XML RPC interface around our code. > 3) Rewrite our code base in C/C++, which should make it accessible to > all modern languages. > > I'm looking for more and potentially better ideas that will allow us > to offer an API to our customers without having to throw away or redo > a lot of the python code that we have already written. > > Thanks in advance, > Dean > You don't say what your operating system is, so I'll give an answer in case it is Windows: I went through something similar recently and decided that writing a COM wrapper around my Python API was the best answer (and it turned out to be pretty easy). I was easily able to call from VB, Delphi and Python COM. I haven't tried C/C++ yet, but expect no problems. I think COM is now the way to go (unless you do .NET). -Larry From hg at nospam.org Tue Apr 17 04:16:23 2007 From: hg at nospam.org (hg) Date: Tue, 17 Apr 2007 10:16:23 +0200 Subject: Syntax error Message-ID: <9w5Vh.8580$OT4.3503@newsfe19.lga> Hi, I've had this problem in the past and still cannot fully understand. I latelly passed my source code in Wing IDE wihch asked be to resolve tab/space/CRLF conflicts and I said yes (initially the code was developped under Linux ... and now all source got tabs replaced by spaces and all EOL when switched to Windows CR/LF) I sent a new release of the software, tested here first, to the customer who got a syntax error on a line which visibly did not have any error. retyping that line by and made the error jump around the file like crazy. I had the customer comment out the first two lines of the file: """ #!/bin/env python # -*- coding: iso-8859-15 -*- """ ... and the problem disappeared. I am at a loss. Any clue ? Thanks hg From jorgen.maillist at gmail.com Tue Apr 17 05:44:03 2007 From: jorgen.maillist at gmail.com (Jorgen Bodde) Date: Tue, 17 Apr 2007 11:44:03 +0200 Subject: Import From SubFolder In-Reply-To: <6786614291591918997@unknownmsgid> References: <6786614291591918997@unknownmsgid> Message-ID: <11e49df10704170244v76f55addwbde0ff930d019dd6@mail.gmail.com> >From what I know, if you place a __init__.py file in the folder that will become your subfolder, you can make it a module subfolder. Like; d:\src\app\submodule\__init__.py (can be empty file) Then in d:\src\app\main.py simply do; import submodule # use your new module like submodule.somefunction() - Jorgen From PlankensteinC at stle.sci Sat Apr 7 13:55:26 2007 From: PlankensteinC at stle.sci (Dr. V I Plankenstein) Date: Sat, 7 Apr 2007 12:55:26 -0500 Subject: Dr Jeff King, A Jewish MIT Engineer is the LEAD SPEAKER on 911 truth, no Islamics involved http://video.google.com/videoplay?docid=1822764959599063248 References: <1175713650.228538.165920@p77g2000hsh.googlegroups.com> <5oWdnfYyjuySzonbnZ2dnUVZ_oSnnZ2d@comcast.com> <1175877597.303013.297780@w1g2000hsg.googlegroups.com> <1175877828.372962.323450@d57g2000hsg.googlegroups.com> Message-ID: wrote in message news:1175877828.372962.323450 at d57g2000hsg.googlegroups.com... > See the video with your own EYEBALLS, that is if you have some courage > and shame left: > > http://video.google.com/videoplay?docid=1822764959599063248 OK - I watched the video and I think it is a ridiculous position. They claim that they can see puffs of smoke from squibs and charges ? That is stupid. Clearly, it is an air blast from a bellows effect of an entire floor of a building being slapped flat by many many tons of force. Then they are trying to figure out how office products could become pulverized. Stupid. Obviously, all that energy must be going somewhere. This is fucking idiotic to think that the Gov blew up WTC - pure fucking idiocy. Look at some actual footage of a controlled demo and you can see the charges firing. In WTC there is dust clouds, but no flashes of light from charges, which would have been practically impossible to disguise. The notion that the smoke came from an explosive blast is utterly ridiculous. Really, completely stupid and contemptible to even say such a thing. The whole idea is false, and idiotic. From jim.hefferon at gmail.com Sun Apr 22 10:40:22 2007 From: jim.hefferon at gmail.com (Jim) Date: 22 Apr 2007 07:40:22 -0700 Subject: python cgi problem with textarea In-Reply-To: <1177222084.696307.128620@n59g2000hsh.googlegroups.com> References: <1177222084.696307.128620@n59g2000hsh.googlegroups.com> Message-ID: <1177252822.099111.66410@e65g2000hsc.googlegroups.com> On Apr 22, 2:08 am, Adrian Smith wrote: > ...and I get an internal server error if I have any spaces in the > textarea, And what error appears in the server error log? From stefan.behnel-n05pAM at web.de Thu Apr 26 10:08:03 2007 From: stefan.behnel-n05pAM at web.de (Stefan Behnel) Date: Thu, 26 Apr 2007 16:08:03 +0200 Subject: Parsing HTML/XML documents In-Reply-To: References: Message-ID: <4630B243.3070501@web.de> pabloski at giochinternet.com wrote: > I need to parse real world HTML/XML documents and I found two nice python > solution: BeautifulSoup and Tidy. There's also lxml, in case you want a real XML tool. http://codespeak.net/lxml/ http://codespeak.net/lxml/dev/parsing.html#parsers > However I found pyXPCOM that is a wrapper for Gecko. So I was thinking > Gecko surely handles bad html in a more consistent and error-proof way > than BS and Tidy. > > I'm interested in using Mozilla DOM from inside a Python script, however > I'm a bit confused about how can I use pyXPCOM to accomplish this job. I've never used it, but I doubt Gecko would yield substantially better results than any of the three above. You're dealing with broken data here, so it just depends on your input which one of them wins. Stefan From reder at ieee.org Fri Apr 13 02:49:15 2007 From: reder at ieee.org (Leonard J. Reder) Date: Fri, 13 Apr 2007 06:49:15 GMT Subject: Python and JMS? Message-ID: Hello, I would like to write some Python to monitor a JMS middleware software bus. JMS being Java Messaging Service. Can anyone recommend a Python wrapper to JMS for this? My goal is to listen for XML being transfered over a JMS implementation. All the applications so far are in Java. Thanks for any replies? Len -- =================================== Leonard J. Reder Home office email : reder at ieee.org Lab email : reder at jpl.nasa.gov Lab web page : http://reder.jpl.nasa.gov =================================== From bruno.42.desthuilliers at wtf.websiteburo.oops.com Thu Apr 12 04:52:16 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Thu, 12 Apr 2007 10:52:16 +0200 Subject: reaching hidden methods + casting In-Reply-To: <1176362298.986221.280520@n59g2000hsh.googlegroups.com> References: <1176362298.986221.280520@n59g2000hsh.googlegroups.com> Message-ID: <461df2d5$0$22345$426a34cc@news.free.fr> per9000 a ?crit : > Hi, > can I reach a hidden method when doing ugly inheritance in python? > >>>> class A: > ... def spin(self, n): print "A", n > ... >>>> class B: > ... def spin(self, m): print "B", m > ... >>>> class C(A,B): > ... def spin(self, k): print "C", k > ... >>>> myC = C() >>>> dir(myC) > ['__doc__', '__module__', 'spin'] > > In f.x. the C-family of languages I guess something like this would > call B.spin: > ((B)myC).spin("Lancelot"); // almost forgot the ';' B.spin(myC, "lancelot") In Python, the syntax: some_instance.some_method(param) is syntactic sugar for SomeClass.some_method(some_instance, param) (assuming isinstance(some_instance, SomeClass) == True) > Please correct me I am wrong (which I likely am) but as I understand > it this example calls the constructor of int instead of casting it, > right? >>>> leet = int('1337') >>>> leet > 1337 There's nothing like "casting" in Python - it would be meaningless in a dynamically typed language. The above example does not "cast" a string to an int, it creates an int - you have two distinct objects, whereas with casting you have two representations of the same object. > Or should I have thought about getting unique names before I > implemented the ugly inheritance graph? This is a design question, and we don't have enough context to answer it. From kyosohma at gmail.com Tue Apr 3 12:23:26 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: 3 Apr 2007 09:23:26 -0700 Subject: Stack experiment In-Reply-To: References: <5QuQh.152$9L1.108@read3.inet.fi> Message-ID: <1175617406.269202.301490@l77g2000hsb.googlegroups.com> On Apr 3, 11:17 am, Steve Holden wrote: > t... at finland.com wrote: > > Hi! Im new to Python and doing exercise found from internet. It is > > supposed to evaluate expression given with postfix operator using > > Stack() class. > > > class Stack: > > def __init__(self): > > self.items = [] > > > def push(self, item): > > self.items.append(item) > > > def pop(self): > > return self.items.pop() > > > def isEmpty(self): > > return (self.items == []) > > > def evaluatePostfix(expr): > > import re > > tokenList = re.split(" ([^0-9])", expr) > > If you add a print statement here I think you will find that the > tokenisation here isn't really what you want: > > >>> expr = "56 47 + 2 *" > >>> re.split(" ([^0-9])", expr) > ['56 47', '+', ' 2', '*', ''] > > > > > stack = Stack() > > for token in tokenList: > > if token == '' or token == ' ': > > continue > > if token == '+': > > sum = stack.pop() + stack.pop() > > stack.push(sum) > > elif token == '*': > > product = stack.pop() * stack.pop() > > stack.push(product) > > else: > > stack.push(int(token)) > > return stack.pop() > > > print evaluatePostfix("56 47 + 2 *") > > > Errormsg: > > Traceback (most recent call last): > > File "C:\*\postfix1.py", line 31, in > > print evaluatePostfix("56 47 + 2 *") > > File "C:\*\postfix1.py", line 28, in evaluatePostfix > > stack.push(int(token)) > > ValueError: invalid literal for int() with base 10: '56 47' > > > How can I avoid the error and get desired result? > > I'd try using > > tokenList = split(expr) > > instead - this has the added benefit of removing the spaces, so you can > simplify your code by removing the case that handles empty tokens and > sapaces, I suspect. > > 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 Steve, How do you do "tokenList = split(expr)"? There is no builtin called "split". Mike From gregcorradini at gmail.com Wed Apr 11 16:01:47 2007 From: gregcorradini at gmail.com (Greg Corradini) Date: Wed, 11 Apr 2007 13:01:47 -0700 (PDT) Subject: Creating Unique Dictionary Variables from List In-Reply-To: <461d27d5$0$3630$426a74cc@news.free.fr> References: <9943321.post@talk.nabble.com> <461d27d5$0$3630$426a74cc@news.free.fr> Message-ID: <9947284.post@talk.nabble.com> Bruno, Your help is much appreciated. I will give this a try tomorrow morning and get back on how it works. Bruno Desthuilliers wrote: > > Greg Corradini a ?crit : >> Hello All, >> I'm attempting to create multiple dictionaries at once, each with unique >> variable names. The number of dictionaries i need to create depends on >> the >> length of a list, which was returned from a previous function. >> The pseudo code for this problem would be: >> >> returnedlist = [x,y,z] >> count = 0 >> for i in returnedlist: >> if count < len(returnedlist): >> # then create a dictionary (beginning with variable dic) for each >> i >> with a unique name such that >> # my unique name would be dic + count >> >> Any ideas about this? > > Yes : use a dict to store your dicts: > > returnedlist = [x,y,z] > dicts = dict() > for num, item in enumerate(returnedlist): > dicts['dict%s' % num] = dict() > -- > http://mail.python.org/mailman/listinfo/python-list > > -- View this message in context: http://www.nabble.com/Creating-Unique-Dictionary-Variables-from-List-tf3560643.html#a9947284 Sent from the Python - python-list mailing list archive at Nabble.com. From tjreedy at udel.edu Wed Apr 4 00:36:36 2007 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 4 Apr 2007 00:36:36 -0400 Subject: NumPy 1.0.2 References: Message-ID: "Travis E. Oliphant" wrote in message news:euumtt$4p4$1 at sea.gmane.org... | | We are pleased to announce the release of NumPy 1.0.2 For those curious like me, the summary news at SourceForge is " The latest release is a mostly bug-fix release with a few optimizations and enhancements." The actual release notes with more details are at http://sourceforge.net/project/shownotes.php?group_id=1369&release_id=498427 From 12cc104 at gmail.com Sun Apr 22 17:08:31 2007 From: 12cc104 at gmail.com (proctor) Date: 22 Apr 2007 14:08:31 -0700 Subject: recursion depth problem In-Reply-To: <1177275314.846022.249000@e65g2000hsc.googlegroups.com> References: <1177267774.416169.276780@e65g2000hsc.googlegroups.com> <1177275314.846022.249000@e65g2000hsc.googlegroups.com> Message-ID: <1177276111.720137.315710@b75g2000hsg.googlegroups.com> On Apr 22, 2:55 pm, half.ital... at gmail.com wrote: > On Apr 22, 11:49 am, proctor <12cc... at gmail.com> wrote: > > > > > hello, > > > i have a small function which mimics binary counting. it runs fine as > > long as the input is not too long, but if i give it input longer than > > 8 characters it gives > > > RuntimeError: maximum recursion depth exceeded in cmp > > > i'm not too sure what i am doing improperly. is there really a lot of > > recursion in this code? > > > ================== > > > import sys > > > def ch4(item, n=0): > > if n < len(item): > > if item[n] == '0': > > item[n] = '1' > > print ''.join(item) > > ch4(item) > > elif item[n] == '1': > > item[n] = '0' > > ch4(item, n+1) > > > ch4(list(sys.argv[1])) > > > ================== > > > this function expects input in the form of a string of zeros, like > > this: > > > python test-bin.py 00000000 > > > and is expected to output a list of permutations like this: > > > $ python test-bin.py 0000 > > 1000 > > 0100 > > 1100 > > 0010 > > 1010 > > 0110 > > 1110 > > 0001 > > 1001 > > 0101 > > 1101 > > 0011 > > 1011 > > 0111 > > 1111 > > > thanks for all help! > > > sincerely, > > proctor > > If you just want to make it work as is....check > > sys.setrecursionlimit() > > ~Sean very nice. thanks sean. so is the structure of my original code unrescuable? i cannot rearrange it to bypass the recursion? proctor. From soyouthinkimgonnalikethis at hotmail.com Sat Apr 7 14:42:38 2007 From: soyouthinkimgonnalikethis at hotmail.com (Eric Price) Date: Sat, 07 Apr 2007 13:42:38 -0500 Subject: Can't Get Email Interface Working In-Reply-To: <2oRRh.19305$PL.16388@newsread4.news.pas.earthlink.net> Message-ID: > Complain to the providers of the server? Or find out what the host >name is for the outgoing SMTPd connection, and use it directly. Complaining isn't going to help. How do I determine the outgoing smtpd connection and how do I use it directly? TIA, Eric _________________________________________________________________ Exercise your brain! Try Flexicon. http://games.msn.com/en/flexicon/default.htm?icid=flexicon_hmemailtaglineapril07 From dietmar at schwertberger.de Fri Apr 27 19:04:48 2007 From: dietmar at schwertberger.de (Dietmar Schwertberger) Date: Sat, 28 Apr 2007 00:04:48 +0100 Subject: what python technology for my app? References: <4631dc06$0$15457$426a74cc@news.free.fr> <4631fbc2$0$641$426a74cc@news.free.fr> Message-ID: In article , Robert Rawlins - Think Blue wrote: > Haha, no Troll, just a shameless plug for my life's one true love ;-) Strange enough to live that love on the wrong newsgroup... Until now all indications are: Troll Anyway, given the original poster's description I would be /very/ surprised that CF would be the right answer. On the other hand, you're writing that CF would deliver all kinds of PDFs, statistical charts etc. As I'm working on similar applications, I would be very interested to hear about how to approach such requirements in any language/environment. Please outline a solution to e.g.: - 1000 data files / lots - per data file / lot: - some meta information like: date/time, equipment, temperature, ... - 5000 data sets / parts for each data set / part: - 5 meta data entries / flags (16 bit int each) - 1000 data entries each (floating point value + 16 bits of flags) Example query/report requirement: - select 800 of the data files acc. to the meta information ?(e.g. date/time range) - select all data sets within the 800 files where the meta data matches some bit masks - calculate statistical data like min/avg/median/max, percentiles etc. per data file for the selected data sets - create a time series plot of these statistical results Regards, Dietmar From kyosohma at gmail.com Mon Apr 2 11:48:49 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: 2 Apr 2007 08:48:49 -0700 Subject: wx textctrl font style In-Reply-To: References: Message-ID: <1175528929.407888.98350@y80g2000hsf.googlegroups.com> On Mar 31, 3:13 am, Pom wrote: > 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 !!! You could experiment with the "Rich Text" style of the text control (see the wxPython Demo). You might also mess with refactoring your code a little and doing a FOR loop. # untested code!!! fonts = [tmpnewfont, tmpnewfont2, tmpnewfont3] count = 0 tmppos = self.txtInfo.GetInsertionPoint() self.txtInfo.write(str(csr[count])+'\n') for i in range(3): tmppos2 = self.txtInfo.GetInsertionPoint() self.txtInfo.SetStyle(tmppos, tmppos2, wx.TextAttr("BLUE", wx.NullColour, fonts[count])) tmppos = tmppos2 count += 1 self.txtInfo.write(str(csr[count])+'\n') I also noticed a FancyText widget. I've used the HtmlWindow widget for an About screen before and I thought it was pretty cool if you know HTML. You might also try dropping an email to the wxPython Users Group at http://wxpython.org/maillist.php Hope this helps! Mike From jakub.stolarski at gmail.com Fri Apr 13 12:37:55 2007 From: jakub.stolarski at gmail.com (Jakub Stolarski) Date: 13 Apr 2007 09:37:55 -0700 Subject: function/method assigment In-Reply-To: <1176480852.643836.121930@p77g2000hsh.googlegroups.com> References: <1176480852.643836.121930@p77g2000hsh.googlegroups.com> Message-ID: <1176482275.733000.308790@n76g2000hsh.googlegroups.com> On Apr 13, 6:14 pm, viscr... at gmail.com wrote: > I have a confusion when I do some practice, the code and output are as > following, > > >>> def fun(): > > print 'In fun()....' > > >>> testfun = fun() > In fun().... > >>> print testfun > None > >>> testfun2 = fun > >>> print testfun2 > > > >>> print testfun2() > > In fun().... > None > > > > what is 'testfun'? Why it is 'None'? And print testfun2(), what is the > meaning of 'None'? > > Thanks! Your 'fun' is the sam as: def fun(): print 'In fun()....' return None So testfun = fun() First prints message and then assign None to testfun. From robert.rawlins at thinkbluemedia.co.uk Sat Apr 21 03:45:03 2007 From: robert.rawlins at thinkbluemedia.co.uk (Robert Rawlins - Think Blue) Date: Sat, 21 Apr 2007 08:45:03 +0100 Subject: Schedule Task Message-ID: <001001c783e8$f953f9b0$ebfbed10$@rawlins@thinkbluemedia.co.uk> Hello Guys, I've got a method in my app that I want to run every 20 minutes that the application it running, what's the best way of achieving this? At the moment I'm using this kind of method. import sched import time, sys scheduler = sched.scheduler(time.time, time.sleep) scheduler.enter(1.0, 0, sys.stdout.write, ("one\n",)) scheduler.run() Now when the function runs after 20 minutes I just have it schedule itself to run again in 20 minutes time, which seems to work for me quite nicely, it just seems a little 'hacky' to keep the task reoccurring like that. Is there any other method? I've spent some time on Google but couldn't really find anything. Not sure if it makes any difference but I'm running Linux. Thanks, Rob -------------- next part -------------- An HTML attachment was scrubbed... URL: From gregturn at mindspring.com Thu Apr 5 11:23:32 2007 From: gregturn at mindspring.com (Goldfish) Date: 5 Apr 2007 08:23:32 -0700 Subject: Python and Java In-Reply-To: References: Message-ID: <1175786612.615941.136760@q75g2000hsh.googlegroups.com> On Apr 5, 7:18 am, Steve Holden wrote: > Sreelatha G wrote: > > Hi > > > I am new to python .I need your help in solving my problem. > > Is there any way to call python files in a java file .How is it possible? > Your other option is to utilize a system exec call, and try and trap the results. From vgupta at neatreceipts.com Wed Apr 11 23:20:11 2007 From: vgupta at neatreceipts.com (Vipin Gupta) Date: Wed, 11 Apr 2007 23:20:11 -0400 Subject: please post an example of python being embedded in c# Message-ID: <45E36921B695A14FA56A34F29424A1EC446B33@Apollo.neatreceipts.local> Hello guys, Newbie here. I wish to study an example where python is being embedded in C#. I have gone through Python for .NET intro website, but I think a simple example can help me visualize stuff better. All help is deeply appreciated. Thanks Vipin -------------- next part -------------- An HTML attachment was scrubbed... URL: -------------- next part -------------- A non-text attachment was scrubbed... Name: image001.gif Type: image/gif Size: 862 bytes Desc: image001.gif URL: From bj_666 at gmx.net Sun Apr 15 06:00:13 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Sun, 15 Apr 2007 12:00:13 +0200 Subject: Python editor/IDE on Linux? References: <1176575715.649316.130430@n76g2000hsh.googlegroups.com> Message-ID: In , Dotan Cohen wrote: > Has anyone any experience with Python in Kate or Kdevelop? I'm using Kate/KWrite quite often. Syntax highlighting and an auto indention for Python are standard features. The only "extra" I'm using is the word completion plug-in to spare myself too much typing and limit typing errors in long names. Along with the editor there's always a terminal with IPython running to test and explore my own code and libraries. Ciao, Marc 'BlackJack' Rintsch From python-url at phaseit.net Fri Apr 20 15:14:56 2007 From: python-url at phaseit.net (Cameron Laird) Date: Fri, 20 Apr 2007 19:14:56 +0000 Subject: Python-URL! - weekly Python news and links (Apr 18) Message-ID: QOTW: "I can't say enough about Python and agile programming. Piecing together small, well-documented, well-tested pieces of software makes solving big problems easier." - Shannon Behrens of Foxmarks; May DDJ http://www.ddj.com/dept/architect/198800578 "Automatic type inference may be sufficient to get good performance." - "I think it's more Pythonic to just profile a program to learn about actual types.." - interchange between John Nagle and Mark Dufour "Riverbank Computing is pleased to announce the release of PyQt v4.2 available from http://www.riverbankcomputing.co.uk/pyqt/." Alex Martelli correctly identifies that COM and *Essential COM* have many virtues: http://groups.google.com/group/comp.lang.python/msg/2875962cba85ed65 Carsten Haese speculates entertainingly on cooperation between Python and, let's say, Delphi: http://groups.google.com/group/comp.lang.python/browse_thread/thread/fd035ebb44c822a/ Precision's a virtue. Python pays off biggest for those who distinguish between, "I need an iterator" and "I need something that works in a 'for'" or "this is a method" and "this is a callable attribute", at the same time as it remains friendly to those who operate at a more elementary level. Notice the slickly self-sorting dictionary skeleton: http://groups.google.com/group/comp.lang.python/browse_thread/thread/d60f1a5ac38d8af3/ ======================================================================== 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, Planet Python indexes much of the universe of Pybloggers. http://www.planetpython.org/ 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/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 should get through. To receive a new issue of this posting in e-mail each Monday morning (approximately), ask 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 Marko.Cain.23 at gmail.com Sun Apr 15 17:24:31 2007 From: Marko.Cain.23 at gmail.com (Marko.Cain.23 at gmail.com) Date: 15 Apr 2007 14:24:31 -0700 Subject: how to strip the domain name in python? In-Reply-To: References: <1176526155.679721.159870@l77g2000hsb.googlegroups.com> <1176564977.498635.171600@n59g2000hsh.googlegroups.com> <1176654669.737355.78300@y5g2000hsa.googlegroups.com> Message-ID: <1176672270.932679.283230@d57g2000hsg.googlegroups.com> On Apr 15, 11:57 am, Marc 'BlackJack' Rintsch wrote: > In <1176654669.737355.78... at y5g2000hsa.googlegroups.com>, Marko.Cain.23 > wrote: > > > > > On Apr 14, 10:36 am, Marko.Cain... at gmail.com wrote: > >> On Apr 14, 12:02 am, Michael Bentley > >> wrote: > > >> > On Apr 13, 2007, at 11:49 PM, Marko.Cain... at gmail.com wrote: > > >> > > Hi, > > >> > > I have a list of url names like this, and I am trying to strip out the > >> > > domain name using the following code: > > >> > >http://www.cnn.com > >> > >www.yahoo.com > >> > >http://www.ebay.co.uk > > >> > > pattern = re.compile("http:\\\\(.*)\.(.*)", re.S) > >> > > match = re.findall(pattern, line) > > >> > > if (match): > >> > > s1, s2 = match[0] > > >> > > print s2 > > >> > > but none of the site matched, can you please tell me what am i > >> > > missing? > > >> > change re.compile("http:\\\\(.*)\.(.*)", re.S) to re.compile("http:\/ > >> > \/(.*)\.(.*)", re.S) > > >> Thanks. I try this: > > >> but when the 'line' ishttp://www.cnn.com, I get 's2' com, > >> but i want 'cnn.com' (everything after the first '.'), how can I do > >> that? > > >> pattern = re.compile("http:\/\/(.*)\.(.*)", re.S) > > >> match = re.findall(pattern, line) > > >> if (match): > > >> s1, s2 = match[0] > > >> print s2 > > > Can anyone please help me with my problem? I still can't solve it. > > > Basically, I want to strip out the text after the first '.' in url > > address: > > >http://www.cnn.com-> cnn.com > > from urlparse import urlsplit > > def get_domain(url): > net_location = urlsplit(url)[1] > return '.'.join(net_location.rsplit('.', 2)[-2:]) > > def main(): > print get_domain('http://www.cnn.com') > > Ciao, > Marc 'BlackJack' Rintsch Thanks for your help. But if the input string is "http://www.ebay.co.uk/", I only get "co.uk" how can I change it so that it works for both www.ebay.co.uk and www.cnn.com? From aleax at mac.com Tue Apr 17 00:54:37 2007 From: aleax at mac.com (Alex Martelli) Date: Mon, 16 Apr 2007 21:54:37 -0700 Subject: How to better pickle an extension type References: <1176736722.383507.37810@n59g2000hsh.googlegroups.com> Message-ID: <1hwonh3.ksfurdiqstcpN%aleax@mac.com> dgdev wrote: > I would like to pickle an extension type (written in pyrex). I have > it working thus far by defining three methods: > > class C: > # for pickling > __getstate__(self): > ... # make 'state_obj' > return state_obj > > __reduce__(self): > return C,(args,to,__init__),me.__getstate__() > > # for unpickling > __setstate__(self,state_obj): > self.x=state_obj.x > ... > > > This gets the class pickling and unpickling. > > However, I'd like to not specify arguments for __init__ (as I do now > in __reduce__), and so not have __init__ invoked during unpickling. > > I would like to have the pickling machinery somehow create an > uninitialized object, and then call its __setstate__, where I can re- > create it from 'state_obj'. > > Is there a kosher way to do so, that is without me having to have a > special mode in the constructor for when the object is being created > by the unpickler? I don't understand why you have a problem -- __init__ is NOT called by default upon loading an object w/__setstate__. Witness: >>> class C(object): ... def __init__(self, *a): print 'init', a ... def __getstate__(self): print 'gs'; return {} ... def __setstate__(self, *a): print 'ss', a ... >>> c = C() init () >>> s = cPickle.dumps(c, 2) gs >>> s '\x80\x02c__main__\nC\nq\x01)\x81q\x02}b.' >>> z = cPickle.loads(s) ss ({},) Perhaps you're not using protocol 2? You should be... Alex From bernhard.voigt at gmail.com Fri Apr 13 09:22:30 2007 From: bernhard.voigt at gmail.com (bernhard.voigt at gmail.com) Date: 13 Apr 2007 06:22:30 -0700 Subject: Getting Stack Trace on segfault In-Reply-To: <87fy767hxz.fsf@pobox.com> References: <87fy767hxz.fsf@pobox.com> Message-ID: <1176470550.790217.52310@w1g2000hsg.googlegroups.com> GDB would could work. Here's how I use it to track down problems in a C ++ program controlled by python. $ gdb python GDB starts up, now at the gdb prompt, set the program args (gdb) set arg testscript.py (gdb) run ... program running until crash (gdb) where gives you the backtrace if you compiled you're module code with debug options Cheers! Bernhard On Apr 11, 10:51 pm, j... at pobox.com (John J. Lee) wrote: > James Stroud writes: > > Hello All, > > > The built-in mac osx vecLib is segfaulting in some cases--A very fun > > fact to find out the hard way over two nights of work. I also spent an > > embarrassing amount of time figuring out just where. Although I'm in > > quite a self-congratulatory mood right now, in the future, I feel like > > I could save a lot of time by coercing the interpreter to spew forth > > method calls to stderr. Is this possible? > > > I would hope to produce something hauntingly reminiscent of > > > [] my_function > > [my_function] another_function > > [my_function -> another_function] yet_a_deeper_function > > [...] > > I remember David Beazley (of SWIG fame) wrote something called WAD > that claimed to turn segfaults into Python exceptions (hence > tracebacks). IIRC it was Linux-specific, and I have no idea how it > worked. I guess it could be ported to Windows with SEH, but no idea > about OS X. > > John From apardon at forel.vub.ac.be Fri Apr 20 03:21:21 2007 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 20 Apr 2007 07:21:21 GMT Subject: Do other Python GUI toolkits require this? References: <462697A6.6010007@codebykevin.com> <465B30B4-5BA0-459A-BE6F-1038874FA74B@jedimindworks.com> Message-ID: On 2007-04-19, Steve Holden wrote: > Antoon Pardon wrote: >> On 2007-04-19, Steve Holden wrote: >>> Michael Bentley wrote: >>>> On Apr 19, 2007, at 4:11 AM, Antoon Pardon wrote: >>>> >>>>> On 2007-04-19, Michael Bentley wrote: >>> [...] The >>>>>> learning curve is rather steep IMO, but worth it. >>>>> Just a throw in remark, that you may ignore if you wish, but a steep >>>>> learning curve means that the subject is easily familiarized and that >>>>> the learning period is short. >>>>> >>>>> You seem to use it as if it is the opposite. >>>> Mathematical absurdities aside, it's the common usage -- but perhaps >>>> you knew that. >>>> >>>> >>> Perhaps in Belgium they prefer climbing mountains over walking up and >>> down gentle hills? Or possibly they will simply pick any nit that is >>> carelessly left within range? >> >> If it is just a nit, why don't you ignore my remark as I suggested? >> > Because I suffer from the quixotic urge to help stamp out obsessive > compulsive behavior on c.l.py? This is self-defeating, of course, since > it makes me appear obsessive compulsive in my own right ... > >> Now suppose I give you a graph that shows you how different people >> are making progress. Would you prefer the rather flat curves instead >> of the steep curves because the latter gives you the idea of someone >> having to conquer huge obstacles or would you choose the steep curve >> because they show you someone is getting results fast? >> > Suppose I should you a hill you have to climb? Would you rather don > mountain boots and crampons to climb 3,000 feet up a vertical cliff or > would you rather amble up, say, Ben Lomond with the other tourists? So if you have the choice between a steep or a shalow income curve you will prefer the shalow curve because a steep curve makes you think about verticale clifs and such? The analogy with a walk is just silly because curves are not like walks. Nobody will say something like: I won't invest in that company because it has a steep profit curve or the reverse: I'll invest in this company because it has an easy looking downhill going profit curve. > Clearly you have no wish to bow before common usage. be careful this > doesn't put you in a universe with only one inhabitant. We all have to > get along. Indeed I have no wish to bow before common usage. I prefer to think about things and dare to speak out when they don't seem to make sense. Just repeating common usage propagates a lot of nonsense. From ghirai at ghirai.com Mon Apr 2 18:35:49 2007 From: ghirai at ghirai.com (Ghirai) Date: Tue, 3 Apr 2007 01:35:49 +0300 Subject: p2p chat framework Message-ID: <1869609874.20070403013549@ghirai.com> Hello python-list, Are there any p2p chat/filetransfer frameworks/examples floating around? If not, can someone give me some rough directions towards writing my own? Thanks. -- Best regards, Ghirai. From enleverlesX.XmcX at XmclaveauX.com Sat Apr 28 17:09:54 2007 From: enleverlesX.XmcX at XmclaveauX.com (Méta-MCI) Date: Sat, 28 Apr 2007 23:09:54 +0200 Subject: python and activeX control References: <1177792357.047096.18480@q75g2000hsh.googlegroups.com> Message-ID: <4633b838$0$27395$ba4acef3@news.orange.fr> Bonsoir ! Flagrant d?lit de manque de confiance dans les newsgroups fran?ais en vue... Ha ! Ha ! Ha ! Bonne chance avec les US... From steve at holdenweb.com Thu Apr 19 07:37:45 2007 From: steve at holdenweb.com (Steve Holden) Date: Thu, 19 Apr 2007 07:37:45 -0400 Subject: What makes an iterator an iterator? In-Reply-To: <1176961515.450458.189530@p77g2000hsh.googlegroups.com> References: <1hwr9pv.13v4ci6106qn0aN%aleax@mac.com> <1176936067.315082.17970@y80g2000hsf.googlegroups.com> <1hws6rd.u0a6hd78fhhpN%aleax@mac.com> <1176961515.450458.189530@p77g2000hsh.googlegroups.com> Message-ID: 7stud wrote: > Hi, > > Thanks for the responses. > >> 7stud wrote: >>> Can you explain some of the details of why this code fails: >> --- >> class Parrot(object): >> def __iter__(self): >> return self >> def __init__(self): >> self.next = self.next().next >> def next(self): >> for word in "Norwegian Blue's have beautiful >> plumage!".split(): >> yield word >> >> P = Parrot() >> for word in P: >> print word >> ------ > > On Apr 18, 8:45 pm, a... at mac.com (Alex Martelli) wrote: >> ...a loop like "for x in y:" binds an unnamed temporary >> variable (say _t) to iter(y) and then repeatedly calls _t.next() [or to >> be pedantic type(_t).next(t)] until that raises StopIteration. > > > Aiiii. Isn't this the crux: > >> repeatedly calls....[type(_t).next(t)] > > As far as I can tell, if the call was actually _t.next(), the code I > asked about would work. However, the name look up for 'next' when you > call: > [snip wild goose chase that appears to miss the main point]. It's nothing to do with the name lookup. Alex mentioned that to remind us that the magic "double-under" names are looked up on the type rather than the instance, so messing around with instances won't change the behavior. [This is not true of "old-style" or "classic" classes, which we should be eschewing in preparation for their disappearance]. You have to understand the iterator protocol, which is how the language interacts with objects whose contents it iterates over (for example in for loops). When you iterate over an object X then the *interpreter*, under the hood, initializes the loop by calling iter(X) and stashing the result away as, let's say, _t. Every time a new value is needed in the iteration _t.next() is called to produce it. We can see this if we open a file: >>> f = open("travel.txt") >>> f.__iter__() >>> f.next() 'Virgin Flight booking extension 33024 Louise reference 1VV75R\r\n' >>> Calling the file's .next() method produces the next line in the file. The point is that a function with "yield" expressions in it, when called, returns a generator object. So if an instance's next() method contains yield statements then repeated calls to it give you an (endless) sequence of generator objects. Here's a simple object class that adheres to the iterator protocol: >>> class myI(object): ... def __init__(self, lim): ... self.lim = lim ... self.current = 0 ... def __iter__(self): ... return self ... def next(self): ... self.current += 1 ... if self.current > self.lim: ... raise StopIteration ... return self.current # NOT yield! ... >>> myi = myI(5) >>> for i in myi: ... print i ... 1 2 3 4 5 >>> I hope this helps. You appear to be forming a rather over-complex model of the way Python behaves. Think "simple" - Python tries to be as simple as it can to achieve its objectives. 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 gandalf at designaproduct.biz Wed Apr 11 14:20:50 2007 From: gandalf at designaproduct.biz (Laszlo Nagy) Date: Wed, 11 Apr 2007 20:20:50 +0200 Subject: how to pickle objects for database storage? In-Reply-To: References: Message-ID: <461D2702.4000902@designaproduct.biz> krishnakant Mane ?rta: > hello, > I have a strange but very interesting requirement? > provided that a database can provide for an object data type like > binary large object (blob), can I store a pickeled python object in > it? > Why not? > I know oracle has blob and clob and believe that mysql/ postgre sql > has some thing similar to store direct objects? > Yes, although PostgreSQL's large object interface is quite different. In Pg, a large object is more likely a file object that you can read/write, and it has limited support. The Python DB API does not define large object functions, and that is only the top of the iceberg.... If you do not want to store very big objects and if you really want something that is similar to blob fields found in other databases, then I recommend that you use the 'text' type and base64encode the pickled data. (AFAIK in PostgreSQL, the 'text' type can store 4GB of data, but you will run into problems if you try to store real binary data in it with SQL sentences...) > if not then should a pickeled object wrapped inside a file and then stored in a database? > Sorry, I do not understand this question. :-) Laszlo From gagsl-py2 at yahoo.com.ar Sat Apr 7 01:26:25 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: 6 Apr 2007 22:26:25 -0700 Subject: Custom Python Runtime In-Reply-To: <2NudnVn5jsm2QIvbnZ2dnUVZ_vqpnZ2d@comcast.com> References: <2NudnVn5jsm2QIvbnZ2dnUVZ_vqpnZ2d@comcast.com> Message-ID: <1175923585.832974.296660@l77g2000hsb.googlegroups.com> Jack wrote: > Since the full installation of Python (from either the standard installer or > ActiveState installer) is too big for my intended use, I'd like to build a > custom distribution of Python for Windows platform, omitting some lib files, > such as audio, tk, printing, testing units, etc. > > Is there a way to customize the Windows build? In my case, there is no need > to build an installer. The best way is to have everything in a directory, as > long as I know where to find Python and Python knows where to find the > necessary libs. Any online docs describing this? Thanks! Perhaps the easiest way is start with the standard distribution and just delete whatever you don't want. I think that the Unicode tables are rather big and could be omited if you don't need them. -- Gabriel Genellina From steve at REMOVE.THIS.cybersource.com.au Sun Apr 15 00:14:09 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Sun, 15 Apr 2007 14:14:09 +1000 Subject: Python Feature Request: Allow changing base of member indices to 1 References: <1176546465.632410.52630@w1g2000hsg.googlegroups.com> <4620b47b$0$14410$9b622d9e@news.freenet.de> <1176557999.665663.299740@y80g2000hsf.googlegroups.com> <1176559643.450533.296850@n59g2000hsh.googlegroups.com> <1176608086.323323.154260@d57g2000hsg.googlegroups.com> Message-ID: On Sat, 14 Apr 2007 20:34:46 -0700, Dan Bishop wrote: > On Apr 14, 10:55 am, Dennis Lee Bieber wrote: > >> The FORTRAN family had started as 1-based (F95, and Ada, now allow >> for each array to have its own "base" => x : array (-10..10) of float). >> Pascal, I forget... > > Pascal allows arbitrary array bases. It's where Ada got the idea. It does? Since when? When I was being taught Pascal at University (20 years ago...) Pascal always started indices at 1. We used to joke you could tell musicians who were trained as C programmers from those who were Pascal programmers because they did sound checks "Testing, 0 1 2". -- Steven. From sgeiger at ncee.net Sun Apr 1 20:27:21 2007 From: sgeiger at ncee.net (Shane Geiger) Date: Sun, 01 Apr 2007 19:27:21 -0500 Subject: Measureing memory used by a subprocess In-Reply-To: References: Message-ID: <46104DE9.1070104@ncee.net> Getting the pid: http://timgolden.me.uk/python/wmi_cookbook.html 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 () Andrew McLean wrote: > I want to script the benchmarking of some compression algorithms on a > Windows box. The algorithms are all embodied in command line > executables, such as gzip and bzip2. I would like to measure three things: > > 1. size of compressed file > 2. elapsed time (clock or preferably CPU) > 3. memory used > > The first is straightforward, as is measuring elapsed clock time. But > how would I get the CPU time used by a sub-process or the memory used? > > I'm guessing that the Windows Performance Counters may be relevant, see > the recipe > > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/303339 > > But I don't see any obvious way to get the process id of the spawned > subprocess. > > - Andrew > -- 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 http Sat Apr 7 17:56:23 2007 From: http (Paul Rubin) Date: 07 Apr 2007 14:56:23 -0700 Subject: itertools, functools, file enhancement ideas References: <7xveg7rhc7.fsf_-_@ruckus.brouhaha.com> Message-ID: <7xd52fu9vc.fsf@ruckus.brouhaha.com> Paul Rubin writes: > # loop through all the files crunching all lines in each one > for line in (ichain(file_lines(x) for x in all_filenames)): > crunch(x) supposed to say crunch(line) of course. From quetzalcotl at consultant.com Tue Apr 17 11:20:24 2007 From: quetzalcotl at consultant.com (Ingo Menger) Date: 17 Apr 2007 08:20:24 -0700 Subject: is laziness a programer's virtue? In-Reply-To: References: <1176757271.282365.319740@n76g2000hsh.googlegroups.com> <1176797558.403629.53140@b75g2000hsg.googlegroups.com> Message-ID: <1176823224.099381.4630@n59g2000hsh.googlegroups.com> On 17 Apr., 12:33, Markus E Leypold wrote: > What makes Xah a troll is neither off-topic posts nor being > incoherent -- its the attitude. He's broadcasting his drivel to a > number of groups not with the intention to discuss (he hardly ever > answers to answers to his posts), but solely with the intention to > inform the world at large about his own magnificient thoughts. This hits the nail on the head. Perhaps one could understand this behaviour on cultural grounds. In chinese culture it may be not uncommon to write something that merely sounds like great wisdom and it is nevertheless appreciated because it's a piece of calligraphic art. > Trying to correct Xah's behaviour is probably impossible. Perhaps somebody could ask the chinese government to put him in jail for "hurting international society" :) From nagle at animats.com Sat Apr 21 15:22:06 2007 From: nagle at animats.com (John Nagle) Date: Sat, 21 Apr 2007 19:22:06 GMT Subject: Unexpected exception from socket.getaddrinfo on Unicode URL In-Reply-To: References: Message-ID: Steve Holden wrote: > John Nagle wrote: > >> Here's a strange little bug. "socket.getaddrinfo" blows up >> if given a bad domain name containing ".." in Unicode. The >> same string in ASCII produces the correct "gaierror" exception. >> >> Actually, this deserves a documentation mention. The "socket" >> module, >> given a Unicode string, calls the International Domain Name parser, >> "idna.py", which has a a whole error system of its own. The IDNA >> documentation says that "Furthermore, the socket module transparently >> converts Unicode host names to ACE, so that applications need not be >> concerned about converting host names themselves when they pass them >> to the socket module." >> However, that's not quite true; the IDNA rules say that syntax errors >> must >> be treated as errors, so you have to be prepared for IDNA exceptions. >> They are all "UnicodeError" exceptions. >> >> It's worth a mention in the documentation for "socket". >> >> John Nagle >> >> D:\>/python25/python.exe >> Python 2.5 (r25:51908, Sep 19 2006, 09:52:17) [MSC v.1310 32 bit >> (Intel)] on win >> 32 >> Type "help", "copyright", "credits" or "license" for more information. >> >>> ss = 'www.gallery84..com' >> >>> uss = unicode(ss) >> >>> import socket >> >>> socket.getaddrinfo(ss,"http") >> Traceback (most recent call last): >> File "", line 1, in >> socket.gaierror: (11001, 'getaddrinfo failed') >> >>> socket.getaddrinfo(uss,"http") >> Traceback (most recent call last): >> File "", line 1, in >> File "D:\python25\lib\encodings\idna.py", line 164, in encode >> result.append(ToASCII(label)) >> File "D:\python25\lib\encodings\idna.py", line 73, in ToASCII >> raise UnicodeError("label empty or too long") >> UnicodeError: label empty or too long >> >>> >> > I took a look at the documentation but couldn't see where to add what, > given that the documentation for socket already says: > > """All errors raise exceptions. The normal exceptions for invalid > argument types and out-of-memory conditions can be raised; errors > related to socket or address semantics raise the error socket.error. > """. > > Do we really need to specifically mention Unicode errors? It says "errors related to socket or address semantics raise the error 'socket.error'", so, yes. The error really has nothing to do with Unicode; it's that a different parser is used when a domain name is in Unicode. It really shouldn't be a "Unicode error" at all. When Python goes to Unicode by default, this is likely to break some existing code. Python's IDNA support is good, but not entirely invisible. The socket module documentation should mention IDNA support. It's not clear, for example, when you call "getnameinfo()", whether you get back the name in Unicode or in Punycode. John Nagle From qilong_ren at yahoo.com Thu Apr 12 03:44:47 2007 From: qilong_ren at yahoo.com (Qilong Ren) Date: Thu, 12 Apr 2007 00:44:47 -0700 (PDT) Subject: python regular expression help Message-ID: <46581.515.qm@web58907.mail.re1.yahoo.com> Hi, Yeah, a little bit tricky. Actually it is part of some Fortran input file. Thanks for suggestion! It helps a lot! Thanks,Qilong ----- Original Message ---- From: Gabriel Genellina To: python-list at python.org Sent: Wednesday, April 11, 2007 9:50:00 PM Subject: Re: python regular expression help En Wed, 11 Apr 2007 23:14:01 -0300, Qilong Ren escribi?: > Thanks for reply. That actually is not what I want. Strings I am dealing > with may look like this: > s = 'a = 4.5 b = 'h' 'd' c = 4.5 3.5' > What I want is > a = 4.5 > b = 'h' 'd' > c = 4.5 3.5 That's a bit tricky. You have LHS = RHS where RHS includes all the following text *except* the very next word before the following = (which is the LHS of the next expression). Or something like that :) py> import re py> s = "a = 4.5 b = 'h' 'd' c = 4.5 3.5" py> r = re.compile(r"\w+\s*=\s*.*?(?=\w+\s*=|$)") py> for item in r.findall(s): ... print item ... a = 4.5 b = 'h' 'd' c = 4.5 3.5 -- Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list ____________________________________________________________________________________ Don't pick lemons. See all the new 2007 cars at Yahoo! Autos. http://autos.yahoo.com/new_cars.html -------------- next part -------------- An HTML attachment was scrubbed... URL: From kyosohma at gmail.com Mon Apr 16 12:22:16 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: 16 Apr 2007 09:22:16 -0700 Subject: Lame wrapper for Python In-Reply-To: <1176739463.129242.77490@o5g2000hsb.googlegroups.com> References: <1176739463.129242.77490@o5g2000hsb.googlegroups.com> Message-ID: <1176740536.897549.193080@y5g2000hsa.googlegroups.com> On Apr 16, 11:04 am, "Harlin Seritt" wrote: > Is there any type of lame_enc.dll wrapper for Python that's available? > > Thanks, > > Harlin Seritt If you are talking about the LAME codec, then you might be able to use py-lame: http://sourceforge.net/project/showfiles.php?group_id=290&release_id=122796 And here's a post that looks like it may be related: http://mail.python.org/pipermail/tutor/2004-January/027379.html Mike From email at christoph-haas.de Fri Apr 13 15:11:02 2007 From: email at christoph-haas.de (Christoph Haas) Date: Fri, 13 Apr 2007 21:11:02 +0200 Subject: Python editor/IDE on Linux? In-Reply-To: References: Message-ID: <20070413191102.GB3907@aldi.workaround.org> On Fri, Apr 13, 2007 at 11:20:23AM -0700, Jack wrote: > I wonder what everybody uses for Python editor/IDE on Linux? > I use PyScripter on Windows, which is very good. Not sure if > there's something handy like that on Linux. I need to do some > development work on Linux and the distro I am using is Xubuntu. We should do a weekly poll. :) Seriously - this question is coming up very frequently and everybody has their preference. Large list: http://wiki.python.org/moin/IntegratedDevelopmentEnvironments My (current) favorite: pida (exists as a ready package on Debian as derivates like Xubuntu) pida because it embeds the 'vim' editor which I love and adds useful features without really getting in my way. And it's the only IDE I found that supports bazaar-ng (bzr) repositories. Christoph From http Sat Apr 7 17:44:30 2007 From: http (Paul Rubin) Date: 07 Apr 2007 14:44:30 -0700 Subject: block scope? References: <7xr6qwal50.fsf@ruckus.brouhaha.com> <7xtzvseqzo.fsf@ruckus.brouhaha.com> <1hw72cg.115yokgarr9enN%aleax@mac.com> Message-ID: <7xr6qvrha9.fsf@ruckus.brouhaha.com> aleax at mac.com (Alex Martelli) writes: > Thus the following example does not compile: > class Test { > public static void main(String[] args) { > int i; > for (int i = 0; i < 10; i++) I'm ok with this; at the minimum, I think such nesting should produce a warning message. From nospam at invalid.com Wed Apr 4 00:39:32 2007 From: nospam at invalid.com (Jack) Date: Tue, 3 Apr 2007 21:39:32 -0700 Subject: Where to find pywin32/win32all for Python 1.5.2? References: <1175656089.023440.286290@q75g2000hsh.googlegroups.com> Message-ID: Thanks Jay. When I searched the net, I also found mentioning of win32all-125.exe but I couldn't find a download link. Does anyone still have it in the HD? "jay graves" wrote in message news:1175656089.023440.286290 at q75g2000hsh.googlegroups.com... > On Apr 3, 7:52 pm, "Jack" wrote: >> I searched around but could not find win32all source or binaries for >> earlier >> versions of Python. Don't ask me why but I have to use Python 1.5.2 in >> this >> project :) The sourceforget page only has latest versions. ActiveState >> does >> not even have 1.5.2 for download. Is it still available somewhere? >> Thanks! > > I looked through my stash of old versions but I couldn't find it. > > I believe the filename you are looking for is 'win32all-128.exe' and > Google has some references to it but the download links don't respond. > > Someone else has it stashed somewhere, hopefully having the filename > will help. > > ... > Jay Graves > From roman.yakovenko at gmail.com Thu Apr 19 04:48:37 2007 From: roman.yakovenko at gmail.com (Roman Yakovenko) Date: Thu, 19 Apr 2007 11:48:37 +0300 Subject: Boost.Python create extra functions not in wrapped object In-Reply-To: References: <1176968256.066230.238940@n59g2000hsh.googlegroups.com> <7465b6170704190119o266a8f1du31f80a4cbaa8abea@mail.gmail.com> Message-ID: <7465b6170704190148y2206313aoe60b685ff9b15a4a@mail.gmail.com> On 4/19/07, Stou Sandalski wrote: > > Thanks for the reply, > > That is what I am doing now, the problem is that I need the code to be > in C/C++ inside the wrapper. I am creating a lot of these objects and > each time I am iterating over ~1.4 million points... and in python > it's quite slow.... which is unpleasant especially since it's such a > trivial operation. My calculation's in NumPy take seconds, and to > create an object for visualization I have to wait 2 minutes. =( You can define function that first argument is a reference to the instance of your class. Then you can register it as usual function. For example: http://language-binding.net/pyplusplus/documentation/functions/transformation/built_in/input_c_buffer.html take a look on generated source code( at the bottom of the page ) Thanks again, > > Stou > > On 4/19/07, Roman Yakovenko wrote: > > On 19 Apr 2007 00:37:36 -0700, Stou Sandalski > > wrote: > > > Hi, > > > > > > I have a python library created by wrapping the C++ library using > > > Boost.Python, the problem is that the wrappers are not very > > > pythonic.... so I want to add some methods that do not exist in the C+ > > > + implementation, that would create a better Python interface. > > > > > > For example to initialize the data in an object in the library one > > > must iterate through every point, setting a value for each > > > individually. That's the way it works in C++ but in python it would > > > be nice to instead just have one call that can receive a numpy array > > > or a tuple. I want to add a call like: setData(array) to the python > > > object, a call that does not exist in the C++ implementation and then > > > in the C++ wrappers actually use setData to iterate through the array > > > and set the values using the normal C++ method, say setValue(index, > > > value). > > > > > > Something along the lines of this (initData is not in the constructor > > > on purpose) C++ object: > > > > > > class Foo > > > { > > > public: > > > void initData(int size) > > > { > > > data = new float[size]; > > > }; // Create the data array > > > void setValue(int index, float value) // Set given value > > > { > > > data[index] = value; > > > } > > > private: > > > float *data; > > > }; > > > > > > > > > In python however I want to do this: > > > > > > obj = foo() > > > ar = array([1,2,3,4,5], dtype=float) > > > > > > foo.setData(ar) > > > > > > Or even better: > > > > > > ar = array([1,2,3,4,5], dtype=float) > > > obj = foo(ar) > > > > > > And have it somehow call initData() and setValue() iteration inside > > > the C++ code of the wrapper. I've only used SWIG and don't really > > > know much about Boost, I am not even sure how to label what I am > > > trying to do. > > > > > > Can this be done with Boost, without changing the C++ library? > > > > Take a look on next link: > > > http://boost.org/libs/python/doc/tutorial/doc/html/python/techniques.html#python.extending_wrapped_objects_in_python > > > > > Regards, > > > > > > Stou > > > > > > -- > > > http://mail.python.org/mailman/listinfo/python-list > > > > > > > > > > > -- > > Roman Yakovenko > > C++ Python language binding > > http://www.language-binding.net/ > -- Roman Yakovenko C++ Python language binding http://www.language-binding.net/ -------------- next part -------------- An HTML attachment was scrubbed... URL: From S.Mientki-nospam at mailbox.kun.nl Sat Apr 28 03:09:56 2007 From: S.Mientki-nospam at mailbox.kun.nl (Stef Mientki) Date: Sat, 28 Apr 2007 09:09:56 +0200 Subject: Portable SciPy v0.1 released In-Reply-To: <1177714703.751242.61090@e65g2000hsc.googlegroups.com> References: <2418d$463275ce$d443bb3a$25239@news.speedlinq.nl> <1177714703.751242.61090@e65g2000hsc.googlegroups.com> Message-ID: Beliavsky wrote: > On Apr 27, 6:17 pm, Stef Mientki > wrote: >> Portable SciPy, is an easy installer of SciPy for M$ windows users. > > If you have an announcement for Windows users, I suggest that you not > needlessly turn them off by abbreviating Microsoft as M$ . You don't > like Windows, but many of us Windows users don't like the anti-Windows > snobs. There is nothing wrong with making money by selling software. > Of course I've totally no objection with earning money in a fair way. But do hard drug dealers earn their money in a fair way ? The European Committee has taken several measures over the past 10 years, to make the competition in the software market more fair, but AFAIK there is only one country that succeeded in this goal. So if politician can't achieve the goal, wanted by almost all their residents, I feel it as my duty to make people aware of this faulty situation, whenever I can. But let us use this list for more constructive tasks, after all, Python might be an important step on the road to a more fair competition. cheers, Stef Mientki From peterbe at gmail.com Sun Apr 1 13:06:34 2007 From: peterbe at gmail.com (Peter Bengtsson) Date: 1 Apr 2007 10:06:34 -0700 Subject: Pickling a class with a __getattr__ In-Reply-To: References: <1175445521.216223.130470@y80g2000hsf.googlegroups.com> Message-ID: <1175447194.572579.317180@o5g2000hsb.googlegroups.com> On Apr 1, 5:48 pm, Peter Otten <__pete... at web.de> wrote: > Peter Bengtsson wrote: > > Hi, I'm trying to pickle an object instance of a class that is like a > > dict but with a __getattr__ and I'm getting pickling errors. > > This is what happens when I'm trying to be clever: > > >>>> import cPickle as pickle > >>>> class Dict(dict): > > ... def __getattr__(self, key): > > ... return self.__getitem__(key) > > ... > >>>> friend = Dict(name='Zahid', age=40) > >>>> friend > > {'age': 40, 'name': 'Zahid'} > >>>> friend.name > > 'Zahid' > >>>> v=pickle.dumps(friend) > > Traceback (most recent call last): > > File "", line 1, in ? > > File "/usr/lib/python2.4/copy_reg.py", line 73, in _reduce_ex > > getstate = self.__getstate__ > > File "", line 3, in __getattr__ > > KeyError: '__getstate__' > > > Why can't I pickle the slightly more featurefull class there called > > 'Dict'? > > Because you allow your __getattr__() implementation to raise the wrong kind > of exception. > > >>> from cPickle import dumps, loads > >>> class Dict(dict): > > ... def __getattr__(self, key): > ... try: > ... return self[key] > ... except KeyError: > ... raise AttributeError > ...>>> friend = Dict(name="Zaphod", age=42) > >>> v = dumps(friend) > >>> p = loads(v) > >>> p > > {'age': 42, 'name': 'Zaphod'} > > Peter Thanks! That did the trick. I also noticed that I could define __getstate__ and __setstate__ (needed for protocol 2) but your solution works much better. From gagsl-py2 at yahoo.com.ar Thu Apr 12 06:30:44 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 12 Apr 2007 07:30:44 -0300 Subject: Calling private base methods References: <11e49df10704120147x5d5df991r93d2b266a67e64ea@mail.gmail.com> Message-ID: En Thu, 12 Apr 2007 05:47:57 -0300, Jorgen Bodde escribi?: > Now that I am really diving into Python, I encounter a lot of things > that us newbies find difficult to get right. I thought I understood > how super() worked, but with 'private' members it does not seem to > work. For example; Someone already told you what happens here. But aren't *private* methods supposed to be private? That is, not called from outside the class. > Is it possible to call a private base method? I come from a C++ > background, and I liked this construction as my base class has helper > methods so that I do not have to duplicate code. It's been a while since I do any serious work in C++, but AFAIK you *can't* call a private method from another class (even from a derived one) unless you use "friend". Maybe you want a "protected" method - by convention, in Python they're written as _name (single underscore). -- Gabriel Genellina From mail at timgolden.me.uk Wed Apr 25 03:44:21 2007 From: mail at timgolden.me.uk (Tim Golden) Date: Wed, 25 Apr 2007 08:44:21 +0100 Subject: MS SQL Server Extension? In-Reply-To: References: Message-ID: <462F06D5.2050209@timgolden.me.uk> Jack wrote: > Hi all, in my next project, my Python code needs to talk to an MS SQL > 2000 Server. Internet search gives me http://pymssql.sourceforge.net/ > I wonder what module(s) people are using. My code runs on a Linux > box so the module has to build on Linux. Any hints/pointers are welcome. There are several modules around which will cover this. One of these days I'll take the post I'm about to write and stick it on a Wiki or something because I seem to write it about once every six months :) In no particular order: adodbapi - recently resurrected from moribundity (if that's a word); search the list archives because I can't remember who's working on it. + Win32 only (afaik) + Covers all sorts of things as well as MSSQL + Allows for passthrough authentication - Used to have some slight flakiness in it. Bloke who's taken over maintenance says he's patched and simplified things. Haven't tried it since. pymssql - http://pymssql.sf.net + Win32 & Linux (via FreeTDS) - Doesn't allow passthrough authentication - Has some issues with Unicode pyodbc - http://pyodbc.sf.net (a recent runner) + Win32 & Linux (via whatever *nix ODBC package) + Apparently more actively maintained than pymssql + (Is currently the favoured front-runner among the sqlalchemy devs) - Lacks .nextset (in case that's important to you) Other contenders: mxODBC - Commercial License but a very strong and long-standing candidate. Lacks .nextset support. Works on *nix via iODBC etc. Object Craft MSSQL - Worked well for me for years but they seemed to have abandoned it of late. Still there. Still works. But no binaries beyond Python 2.3. (I did try to recompile using MingW but couldn't get it to work). Works on *nix via FreeTDS. TJG From pyguido at hotmail.fr Fri Apr 13 04:11:22 2007 From: pyguido at hotmail.fr (pierre-yves guido) Date: Fri, 13 Apr 2007 10:11:22 +0200 Subject: HELP PARAMETERS IN SQL QUERY Message-ID: hello, I'm doing a training course and I'm a newbie in Python. My problem : I have a form, and when I click, I make an update. But all the parameters are all required to make the update. So I'd like to put in my code something like [optional]... My code (simplyfied) : prg.ev_ind_update(wf_pk_ev_ind=wf_pk_ev_ind,wf_fonction=wf_fonction,wf_nom=wf_nom) and so, when I put nothing in wf_nom, it put me that error :"the parameter wf_nom...was omitted from the request...". But sometimes, wf_nom is not required ! Thanks for your help _________________________________________________________________ D?couvrez le Blog heroic Fantaisy d'Eragon! http://eragon-heroic-fantasy.spaces.live.com/ From thorsten at thorstenkampe.de Sun Apr 1 11:14:09 2007 From: thorsten at thorstenkampe.de (Thorsten Kampe) Date: Sun, 1 Apr 2007 16:14:09 +0100 Subject: I18n issue with optik References: Message-ID: Just an addition : when I insert this statement... print _('THIS SOFTWARE COMES WITHOUT WARRANTY, LIABILITY OR SUPPORT!') into this skript, the line is printed out. So if my Skript can output the localised text but Optparse can't it should be an optparse bug, right?! Thorsten From trevis.crane at gmail.com Fri Apr 20 14:02:37 2007 From: trevis.crane at gmail.com (orangeDinosaur) Date: 20 Apr 2007 11:02:37 -0700 Subject: matplotlib basic question In-Reply-To: References: <1177016327.543985.34500@o5g2000hsb.googlegroups.com> Message-ID: <1177092157.763869.77600@o5g2000hsb.googlegroups.com> OK, I'll go with the enthought installation. This seems to be the path of least resistance. For those of you who have been in my position, is there a reason NOT to go with the enthought installation and do things piecemeal instead? thanks, trevis On Apr 20, 11:36 am, Pete Forman wrote: > orangeDinosaur writes: > > > [...] But now, the figure window is completely unresponsive -- I > > can't even close it without getting the "your program is not > > repsonding" business. What am I missing? This behavior so far > > seems pretty unintuitive. > > The best way out of this is to use IPython. It also needs a backend > which remains responsive, WxAgg works but Tk did not last time I > tried. IPython 0.8.1 is a release candidate which fixes some Windows > issues in 0.8.0. If you want a stable package that has all the parts > present out of the box then look at Enthought. > -- > Pete Forman -./\.- Disclaimer: This post is originated > WesternGeco -./\.- by myself and does not represent > pete.for... at westerngeco.com -./\.- the opinion of Schlumberger orhttp://petef.port5.com -./\.- WesternGeco. From mail at timgolden.me.uk Wed Apr 18 03:56:26 2007 From: mail at timgolden.me.uk (Tim Golden) Date: Wed, 18 Apr 2007 08:56:26 +0100 Subject: Screen Control in WinXP and Linux In-Reply-To: <1176847598.832345.220270@b75g2000hsg.googlegroups.com> References: <1176847598.832345.220270@b75g2000hsg.googlegroups.com> Message-ID: <4625CF2A.30602@timgolden.me.uk> peter wrote: > I've been wrestling on and off with this problem for over a year now, > without success. Basically, I am looking for a simple set of screen > and keyboard manipulation commands that will run identically under > Linux and Windows. Nothing fancy - just clear the screen, print a > string at an arbitrary xy position and detect a keystroke. I've > googled around this newsgroup and elsewhere, and come across various > suggestions (and even posted my own partial solutions), but still > haven't come up with an elegant solution. OK, a bit of info from the Windows side of things. Here are several existing modules which offer the kind of thing you're after in different ways. Don't bother with the ANSI thing; it's a dead end under Windows. http://newcenturycomputers.net/projects/wconio.html http://effbot.org/zone/console-index.htm http://adamv.com/dev/python/curses/ I've used the first two for relatively trivial things, the third not at all. The third is interesting, obviously, because curses is readily available on Linux (indeed comes as part of Python, I think). So that might be a quick win. Alternatively, and depending on your needs, there are a few UI addons for pygame: http://www.pygame.org/projects/9 Might not be what you're after from your original description, but better too much information than too little. Obviously, unless the curses stuff fits your needs, you might need to write a wrapper module doing a bit of conditional importing or platform-sniffing, but that's not beyond the wit of man. TJG From stefan.behnel-n05pAM at web.de Sat Apr 14 06:53:50 2007 From: stefan.behnel-n05pAM at web.de (Stefan Behnel) Date: Sat, 14 Apr 2007 12:53:50 +0200 Subject: XML/encoding/prolog/python hell... In-Reply-To: <1175103659.463125.39370@y66g2000hsf.googlegroups.com> References: <1175103659.463125.39370@y66g2000hsf.googlegroups.com> Message-ID: <4620B2BE.5050602@web.de> fscked schrieb: > 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. UTF-8 encoding is the default. No need for a prologue here. ET 1.3 will have an xml_declaration keyword argument for write() that will allow you to write the declaration even if unnecessary. lxml already has it now (and is ET compatible, so your code should just straight work). http://codespeak.net/lxml > 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: > > > > pl_h="No Data" name="Lounge" address="here" phone="555-5555" > country="US" city="LA"/> > pl_h="No Data" name="MyHouse" address="there" phone="555-5556" > country="US" city="New York"/> > This should help you to get namespaces working: http://effbot.org/zone/element.htm#xml-namespaces Hope it helps, Stefan From see_signature at nospam.nowire.org Tue Apr 24 18:27:45 2007 From: see_signature at nospam.nowire.org (=?ISO-8859-1?Q?Thomas_Kr=FCger?=) Date: Wed, 25 Apr 2007 00:27:45 +0200 Subject: os.system('tar -c * | tar -C dst') ##Any other suggestions... In-Reply-To: <1177448277.150142.146130@c18g2000prb.googlegroups.com> References: <1177448277.150142.146130@c18g2000prb.googlegroups.com> Message-ID: list.repository at gmail.com: > Any suggestions on a different approach or fix? Check your commandline! The second command is wrong, -C is not valid as the only option, a command is missing. If you just want to archive files in a tarball try: "tar -c * > dst.tar" or take a look at Python's tarfile lib. Thomas -- sinature: http://nospam.nowire.org/signature_usenet.png From gigs at hi.t-com.hr Thu Apr 5 13:23:11 2007 From: gigs at hi.t-com.hr (gigs) Date: Thu, 5 Apr 2007 19:23:11 +0200 Subject: tkinter canvas Message-ID: I have made drawing area and few butons. How can I make when i click my fill button that later when i click on oval oval gets filled with chousen color? From scott.daniels at acm.org Thu Apr 12 00:33:54 2007 From: scott.daniels at acm.org (Scott David Daniels) Date: Wed, 11 Apr 2007 21:33:54 -0700 Subject: Strange Behavior with Old-Style classes and implicit __contains__ In-Reply-To: References: <1176334655.677943.70030@q75g2000hsh.googlegroups.com> Message-ID: <131rdk3oosbccbf@corp.supernews.com> Steven D'Aprano wrote: > On Wed, 11 Apr 2007 16:37:35 -0700, rconradharris wrote: > ... > Here are the results under Python 2.5: > >>>> tester(10) > Checking index 0... > Checking index 0... > Checking index 0... > Checking index 0... > Checking index 0... > [False, 'KeyError', False, 'KeyError', False, > 'KeyError', False, 'KeyError', False, 'KeyError'] > > > And here are the results under Python 2.4.3: > >>>> tester(10) [works] > > Looks like a bug to me. No problem with 2.5.1c1 here. --Scott David Daniels scott.daniels at acm.org From maheh_saied at yahoo.com Thu Apr 26 01:58:14 2007 From: maheh_saied at yahoo.com (mahdieh saeed) Date: Wed, 25 Apr 2007 22:58:14 -0700 (PDT) Subject: python loop performance Message-ID: <695102.7521.qm@web50304.mail.re2.yahoo.com> I use python and berkeley db for my application.(use bsddb3) Use freebsd operating system. My question is about loop that I use for my application.I use loop like this for fetch information. info=cur.get(key,DB_SET) while info: info=cur.next() If this loop fetch 10000 records taking alot of time .(about 6 seconds). I use this loop with out any operation .Does any one have idea for imporove performance. regrards, saeed --------------------------------- Ahhh...imagining that irresistible "new car" smell? Check outnew cars at Yahoo! Autos. -------------- next part -------------- An HTML attachment was scrubbed... URL: From mangabasi at gmail.com Wed Apr 4 16:23:24 2007 From: mangabasi at gmail.com (Mangabasi) Date: 4 Apr 2007 13:23:24 -0700 Subject: Calling Fortran from Python In-Reply-To: References: <1175640339.648190.207530@y66g2000hsf.googlegroups.com> <1175685841.847487.173440@w1g2000hsg.googlegroups.com> Message-ID: <1175718204.410453.29510@q75g2000hsh.googlegroups.com> On Apr 4, 12:22 pm, Robert Kern wrote: > Mangabasi wrote: > > Robert, > > > Thanks for your prompt response. I think I got a lot closer but no > > cigar yet. > > > This is the output > > > C:\fortrandll>f2py -c -m sample sample.pyf sample.for > > numpy_info: > > FOUND: > > define_macros = [('NUMERIC_VERSION', '"\\"24.2\\""')] > > include_dirs = ['C:\\Python24\\include'] > > > running build > > running config_fc > > running build_src > > building extension "sample" sources > > creating c:\docume~1\fb\locals~1\temp\tmpcosvgv > > creating c:\docume~1\fb\locals~1\temp\tmpcosvgv\src > > f2py: sample.pyf > > Reading fortran codes... > > Reading file 'sample.pyf' > > Post-processing... > > Block: sample > > Block: sample > > Post-processing (stage 2)... > > Building modules... > > Building module "sample"... > > Constructing wrapper function "sample"... > > ierr1,ierr2,aout = sample(ain) > > Wrote C/API module "sample" to file "c:\docume~1\fb > > \locals~1\temp\tmpcos > > vgv\src/samplemodule.c" > > adding 'c:\docume~1\fb\locals~1\temp\tmpcosvgv\src\fortranobject.c' > > to sources > > . > > adding 'c:\docume~1\fb\locals~1\temp\tmpcosvgv\src' to include_dirs. > > copying C:\python24\lib\site-packages\f2py2e\src\fortranobject.c -> c: > > \docume~1\ > > fb\locals~1\temp\tmpcosvgv\src > > copying C:\python24\lib\site-packages\f2py2e\src\fortranobject.h -> c: > > \docume~1\ > > fb\locals~1\temp\tmpcosvgv\src > > running build_ext > > No module named msvccompiler in scipy_distutils, trying from > > distutils.. > > error: The .NET Framework SDK needs to be installed before building > > extensions f > > or Python. > > > I think I have a problem with distutils' msvccompiler.py. It may be > > the MacroExpander in distutils guessing the visual studio path > > incorrectly or something related to the registry keys. Is there a way > > to specify the C compiler path to f2py so that it does not rely on the > > distutils? Or maybe I am totally off base here, I don't know. > > What C and Fortran compilers are you trying to use? You can look at f2py's help > for flags that you can use to help control where the compilers get picked up, > but you can't avoid distutils. > > -- > 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- Hide quoted text - > > - Show quoted text - I am using Visual Studio 6.0 and Compaq Visual Fortran 6.6. From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Sat Apr 14 17:01:51 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Sat, 14 Apr 2007 23:01:51 +0200 Subject: Python Feature Request: Add the "using" keyword which works like "with" in Visual Basic References: <1176547372.584539.89170@q75g2000hsh.googlegroups.com> <58buojF2e7nifU1@mid.individual.net> <1176557659.625615.138080@d57g2000hsg.googlegroups.com> Message-ID: <58ctpvF2gtuo3U1@mid.individual.net> jamadagni wrote: > Bjoern Schliessmann wrote: >> In more complex modules, when you are >> looking for, e. g., self.myVar and anotherObject.myVar, >> this "using" statement decreases readability and maintainability >> (in full text searching). IMHO. > > Why? Just search for self and you turn up using self. Just scan > down (the block) and you get myVar. Similarly for > anotherObject.myVar. It seems to me that the biggest module you've ever written has less than 100 lines. > Of course, you lose the possibility of just searching for > self.myVar -- something lost, something gained, IMHO. So, the gain is the loss of something different? If you say so. IMHO, the ability to find something quickly weighs much stronger than needing to write 5 characters more. After all, working on the code doesn't mean writing new stuff all the time, but modifying and extending the existing code. A few characters more can enhance readability vastly. IMHO. Regards, Bj?rn -- BOFH excuse #261: The Usenet news is out of date From collinstocks at gmail.com Thu Apr 5 16:02:52 2007 From: collinstocks at gmail.com (Collin Stocks) Date: Thu, 5 Apr 2007 16:02:52 -0400 Subject: Can we make a local variable in a function as global variable??? In-Reply-To: References: <1175764774.260576.286420@y66g2000hsf.googlegroups.com> <4c0048df0704051130k23b282av778059aa2fd64eb4@mail.gmail.com> Message-ID: <4c0048df0704051302t5170d104n2e1fa6cba1b838ee@mail.gmail.com> Then name it something else. I tend to chose "this" because it is a meaningless name that would not tend to be used for anything else. I would have used "self", except that that tends to be used inside classes. My inspiration for coming up with this is to make modules a little more like classes. I suppose you wouldn't like me to post my own (somewhat buggy) module that allows you to import modules as new type classes? On 4/5/07, Steve Holden wrote: > > Collin Stocks wrote: > > As for me, I find this problem annoying, but easy to solve. My solution > is: > > > > >>> this=__import__(__name__) > > > > To set global variable spam to 4, I say: > > > > >>> this.spam=4 > > > > This always works, and is much more convenient than: > > > > >>> global spam > > >>> spam=4 > > > > and then worry about local variables also named spam. > > > That's truly horrible. And what if you have a local variable called > "this"? > > 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 > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From larry.bates at websafe.com Thu Apr 5 14:27:52 2007 From: larry.bates at websafe.com (Larry Bates) Date: Thu, 05 Apr 2007 13:27:52 -0500 Subject: Looping issues In-Reply-To: <1175796069.501575.157410@w1g2000hsg.googlegroups.com> References: <1175796069.501575.157410@w1g2000hsg.googlegroups.com> Message-ID: <7dWdnYepWOY6oojbnZ2dnUVZ_ompnZ2d@comcast.com> brochu121 at gmail.com wrote: > What I am trying to do is compare two files to each other. > > If the 2nd file contains the same line the first file contains, I want > to print it. I wrote up the following code: > > > > correct_settings = open("C:\Python25\Scripts\Output > \correct_settings.txt","r") > current_settings = open("C:\Python25\Scripts\Output\output.txt","r") > > for line in correct_settings: > for val in current_settings: > if val == line: > print line + " found." > > > correct_settings.close() > current_settings.close() > > > For some reason this only looks at the first line of the > correct_settings.txt file. Any ideas as to how i can loop through each > line of the correct_settings file instead of just looking at the first? > If the files aren't terribly large (not tested): correct_lines=open(r"C:\Python25\Scripts\Output" \ "\correct_settings.txt", "r").readlines() current_lines=open(r"C:\Python25\Scripts\Output\output.txt", "r").readlines() for line in current_settings: if line in correct_lines: print line + " found" This does what you asked for but somehow I don't think it is what you want. I would suggest that you take a look at difflib. Somththing along the lines of: import difflib correct_lines=open(r"C:\Python25\Scripts\Output" \ "\correct_settings.txt", "r").readlines() current_lines=open(r"C:\Python25\Scripts\Output\output.txt", "r").readlines() delta=difflib.unified_diff(correct_lines, current_lines) diffs=''.join(delta) print diffs Will show you the lines that are different and some lines around it for context. -Larry From martin at v.loewis.de Sun Apr 29 05:51:49 2007 From: martin at v.loewis.de (=?ISO-8859-2?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sun, 29 Apr 2007 11:51:49 +0200 Subject: Asynchronous XML-RPC client library? In-Reply-To: References: Message-ID: <46346ab6$0$18128$9b622d9e@news.freenet.de> Jarek Zgoda schrieb: > Is there anything like that? Googling yields many articles on async > servers, but virtually nothing on clients. I have to talk to remote in > an environment that does not allow threads... My recommendation would be to use xmlrpclib, and combine it with the async framework that you currently use. Regards, Martin From bdesth.quelquechose at free.quelquepart.fr Wed Apr 11 15:03:20 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Wed, 11 Apr 2007 21:03:20 +0200 Subject: Creating Unique Dictionary Variables from List In-Reply-To: References: Message-ID: <461d27d5$0$3630$426a74cc@news.free.fr> Greg Corradini a ?crit : > Hello All, > I'm attempting to create multiple dictionaries at once, each with unique > variable names. The number of dictionaries i need to create depends on the > length of a list, which was returned from a previous function. > The pseudo code for this problem would be: > > returnedlist = [x,y,z] > count = 0 > for i in returnedlist: > if count < len(returnedlist): > # then create a dictionary (beginning with variable dic) for each i > with a unique name such that > # my unique name would be dic + count > > Any ideas about this? Yes : use a dict to store your dicts: returnedlist = [x,y,z] dicts = dict() for num, item in enumerate(returnedlist): dicts['dict%s' % num] = dict() From jkirwan at easystreet.com Wed Apr 25 00:17:16 2007 From: jkirwan at easystreet.com (Jonathan Kirwan) Date: Wed, 25 Apr 2007 04:17:16 GMT Subject: Video: Professor of Physics Phd at Cal Tech says: 911 Inside Job References: <1177467203.719625.93920@u32g2000prd.googlegroups.com> Message-ID: On Wed, 25 Apr 2007 15:33:45 +1200, Gib Bogle wrote: >When did the University of Iowa (Iowhere?) become CalTech. "Grabbe earned his PhD from Caltech in 1978. He is a graduate of Caltech, but has no current academic appointment there." So I read, anyway. Jon From surekap at gmail.com Sun Apr 22 06:50:45 2007 From: surekap at gmail.com (Prateek) Date: 22 Apr 2007 03:50:45 -0700 Subject: Support for new items in set type In-Reply-To: <1hwxx1e.1un7urc1de872aN%aleax@mac.com> References: <1177211624.069474.3960@y5g2000hsa.googlegroups.com> <1hwxx1e.1un7urc1de872aN%aleax@mac.com> Message-ID: <1177239045.216195.245580@e65g2000hsc.googlegroups.com> > > 2) Maintaining a copy wastes memory > > 3) I don't have a good solution if I delete items from the set > > (calculating the difference will return an empty set but I need to > > actually delete stuff). > > (3) is easy -- the difference originalset-finalset is the set of things > you have to delete. Now why didn't I think of that? > > Does anyone have any ideas? > > Your problem is really a thinly disguised version of one of the most > ancient and venerable ones in data processing -- the "master file / > transaction file" problem. With sets (which are built as hash tables) > you have very powerful weapons for this fray (it used to be, many years > ago, that sorting and "in-step processing of sorted files" was the only > feasible approach to such problems), but you still have to wield them > properly. > > In your shoes, I would write a class whose instances hold three sets: > -- the "master set" is what you originally read from the file > -- the "added set" is the set of things you've added since then > -- the "deleted set" is the set of things you've deleted since them > > You can implement a set-like interface; for example, your .add method > will need to remove the item from the deleted set (if it was there), > then add it to the added set (if it wasn't already in the master set); > and so on, for each and every method you actually desire (including no > doubt __contains__ for membership testing). E.g., with suitably obvious > names for the three sets, we could have...: > > class cleverset(object): > ... > def __contains__(self, item): > if item in self.deleted: return False > elif item in self.added: return True > else: return item in self.master > > When the time comes to save back to disk, you'll perform deletions and > additions based on self.deleted and self.added, of course. Ok. This class sounds like a good idea. I'll try it. > I'm not addressing the issue of how to best represent such sets on disk > because it's not obvious to me what operations you need to perform on > the on-disk representation -- for example, deletions can be very costly > unless you can afford to simply set a "logically deleted" flag on > deleted items; but, depending on how often you delete stuff, that will > eventually degrade performance due to fragmentation, and maintaining the > indexing (if you need one) can be a bear. I actually don't have very many transactions I need to perform on disk. Once I've loaded these sets, I normally use the contains operation and union/intersection/difference operations. I can definitely use a tombstone on the record to mark it as logically deleted. The problem right now is that I don't need indexing within sets (I either load the whole set or don't bother at all) - I'm only indexing the entire file (one entry in the index per tablespace). So even if I use tombstones, I'll have to still go through all the tablespace to find the tombstoned files. Alternatively, I could write the deleted data at the end of the tablespace and mark it with the tombstone (since I don't care about space so much) and when I load the data, I can eliminate the tombstoned entries. I'm give that a try and report my performance results on this thread - I absolutely love that I can make this important a change in one or two days using Python! > Normally, I would use a good relational database (which has no doubt > already solved on my behalf all of these issues) for purpose of > persistent storage of such data -- usually sqlite for reasonably small > amounts of data, PostgreSQL if I need enormous scalability and other > "enterprise" features, but I hear other people are happy with many other > engines for relational DBs, such as Oracle (used to be superb if you > could afford full-time specialized db admins), IBM's DB2, SAP's database > (now opensourced), Firebird, even MySQL (I've never, but NEVER, had any > good experience with the latter, but I guess maybe it's only me, as > otherwise it could hardly be so popular). The main point here is that a > relational DB's tables _should_ be already very well optimized for > storing "sets", since those table ARE exactly nothing but sets of tuples > (and a 1-item tuple is a tuple for all that:-). Thanks Alex, but we're actually implementing a (non-relational) database engine. This particular file is one of many files (which are all kept in sync by the engine) I need to persist (some files use other methods - including pickling - for persistence). I've already solved most of our other problems and according to hotshot, this is one of the next hurdles (this commit is responsible for 8% of the total CPU time @ 3000 items and 3 files). If you're interested, you can check it out at http://www.brainwavelive.com or email me. Prateek From S.Mientki-nospam at mailbox.kun.nl Thu Apr 12 15:56:56 2007 From: S.Mientki-nospam at mailbox.kun.nl (Stef Mientki) Date: Thu, 12 Apr 2007 21:56:56 +0200 Subject: [ANN] mlabwrap-1.0final In-Reply-To: References: Message-ID: Alexander Schmolck wrote: > I'm pleased to finally announce mlabwrap-1.0: > > Project website > --------------- > > > > Description > ----------- > > Mlabwrap-1.0 is a high-level python to matlab(tm) bridge that makes calling > matlab functions from python almost as convenient as using a normal python > library. It is available under a very liberal license (BSD/MIT) and should > work on all major platforms and (non-ancient) python and matlab versions and > either numpy or Numeric (Numeric support will be dropped in the future). > Probably quit a large and nice job, to embed MatLab in Python. But, I've the idea I'm missing something ... ... coming from MatLab, a few months ago I tried Python, ... and at the moment I've decided to move completely from MatLab to Python. All new programs will be written in Python and the old programs will be translated. Is my decision wrong ? What can do MatLab, that can't be done in Python (SciPy) ? (Ok I accept there's no SimuLink/PowerSim). Both environments can create any program you like. If MatLab is your standard / favorite why not stick to MatLab ? Please enlighten me. cheers, Stef Mientki From larry.bates at websafe.com Thu Apr 26 11:16:45 2007 From: larry.bates at websafe.com (Larry Bates) Date: Thu, 26 Apr 2007 10:16:45 -0500 Subject: Python keywords In-Reply-To: <1177599386.204340.65680@r35g2000prh.googlegroups.com> References: <1177599386.204340.65680@r35g2000prh.googlegroups.com> Message-ID: <4630C25D.9010309@websafe.com> gtb wrote: > Have done some searching but have not found a place where I can look > up python keywords. I was looking at a script that contained the > following line: > > assert self.getResponseCode() in (200, 304, 302) > > I can infer the usage here but previously I had thought that "in" was > only used with '"for". I looked thru 'the Python Reference Manual and > found "in" is a keyword but in skimming thru I found it only with > "for". The reference manual seems good but seems not to be setup for > searching. Or maybe I just missed something. > > Thanks, > > gtb > http://docs.python.org/ref/keywords.html in keyword is a general one and can be used for many objects. x in 'xyz' y in ['a','b','c','y','z''] z in ('a','b','c','y','z'] key in {'key1':1, 'key2': 2} The in you see with a for isn't associated with the for loop but rather the sequence you are iterating over for i in range(10): -Larry From gagsl-py2 at yahoo.com.ar Sun Apr 22 10:23:35 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sun, 22 Apr 2007 11:23:35 -0300 Subject: serializable object references References: <1242622.P0zHLAfcMH@beaureve.gmx.net> Message-ID: En Sun, 22 Apr 2007 08:07:27 -0300, Martin Drautzburg escribi?: > Is it possible to convert an object into a string that identifies the > object in a way, so it can later be looked up by this string. > Technically this should be possible, because things like > > <__main__.Foo instance at 0xb7cfb6ac> > > say everything about an object. But how can I look up the real object, > when I only have this string? > > I know such a thing can be achieved with a dictionary that holds > reference-object pairs. Is there another way? Without further information, this would be the way. What do you want to achieve? Maybe you are looking for the pickle module. -- Gabriel Genellina From deets at nospam.web.de Mon Apr 23 05:55:08 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 23 Apr 2007 11:55:08 +0200 Subject: Two syntax questions (newbie) References: <1177316126.432039.232300@o5g2000hsb.googlegroups.com> <1177320268.228495.186590@y5g2000hsa.googlegroups.com> Message-ID: <593e3sF2iscqaU1@mid.uni-berlin.de> > This is already better. Is it possible to define function composition > as an operator and have something like (list at reversed@sorted)(items) > or (list*reversed*sorted)(items) ? Not on functions, but on classes/instances. So something like this might work for you (untested): class FunctionComposer(object): def __init__(self, f=None): if f is None: f = lambda x: x self._f = f def __call__(self, *args, **kwargs): return self._f(*args, **kwargs) def __mul__(self, other): def combined(*args, **kwargs): return other(self._f(*args, **kwargs)) return FunctionComposer(combined) fc = FunctionComposer Then you can write (fc() * list * reversed * sorted)(items) Diez From paddy3118 at googlemail.com Tue Apr 17 14:59:15 2007 From: paddy3118 at googlemail.com (Paddy) Date: 17 Apr 2007 11:59:15 -0700 Subject: Compare regular expressions In-Reply-To: <58je5lF2hg4r3U2@mid.uni-berlin.de> References: <1176753723.382697.268430@y80g2000hsf.googlegroups.com> <58je5lF2hg4r3U2@mid.uni-berlin.de> Message-ID: <1176836355.261501.94400@l77g2000hsb.googlegroups.com> On Apr 17, 9:17 am, "Diez B. Roggisch" wrote: > Paddy schrieb: > > > > > On Apr 16, 10:50 am, Thomas Dybdahl Ahle wrote: > >> Hi, I'm writing a program with a large data stream to which modules can > >> connect using regular expressions. > > >> Now I'd like to not have to test all expressions every time I get a line, > >> as most of the time, one of them having a match means none of the others > >> can have so. > > >> But ofcource there are also cases where a regular expression can > >> "contain" another expression, like in: > >> "^strange line (\w+) and (\w+)$" and "^strange line (\w+) (?:.*?)$" in > >> which case I'd like to first test the seccond and only if it mathces test > >> the seccond. > > >> Do anybody know if such a test is possible? > >> if exp0.contains(exp1): ... > > > you could OR all the individual RE's test them all at once then find > > out which matched. > > > big_re = "|".join( r"(?P<__match_%i__>%s)" % (i, r) > > for i,r in enumerate(regexps) ) > > > now if one of the regexps matches then the corresponding named > > group should have a non-empty string value. > > This doesn't answer the question if two of the sub-expressions matched. > > Diez Or three, or four... If the frequencies of occurence are right and the OP wants all, then he could use the above to get any then follow up with a search for all the rest to the right of the matching regexp portion to get any more. But thats complex. Better to just do individual matches in a loop I'd think. - Paddy. From jstroud at mbi.ucla.edu Thu Apr 12 17:03:14 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Thu, 12 Apr 2007 14:03:14 -0700 Subject: Need help with the get() method of a Text entry In-Reply-To: References: <1176409717.585710.184960@y80g2000hsf.googlegroups.com> Message-ID: James Stroud wrote: > Chad wrote: > >> I have a simple little program that brings up asks the user to enter a >> note, then is supposed to place that note into a text file when the >> user hits the submit button. However, when the user hits the submit >> button, absolutely nothing happens. IDLE doesn't give an error >> message and the note is not entered into the text file. For >> troubleshooting puposes, I wanted to see if IDLE would at least print >> the user's input; it doesn't do that either. Can someone please help >> me? >> >> Here is the code: >> >> from Tkinter import * >> >> class Application(Frame): >> """ GUI application that creates a story based on user input. """ >> def __init__(self, master): >> """ Initialize Frame. """ >> Frame.__init__(self, master) >> self.grid() >> self.create_widgets() >> >> def create_widgets(self): >> """ Create widgets to get note information. """ >> # create instruction label and text entry for notes >> Label(self, >> text = "Notes" >> ).grid(row = 0, column = 0, columnspan = 2 ) >> >> >> self.notes_ent = Text(self, width = 75, height = 10, wrap = >> WORD) >> self.notes_ent.grid(row = 2, column = 0 ,columnspan = 7, >> rowspan = 3, sticky = W) >> create submit button >> text1 = StringVar(self) >> text1 = self.notes_ent.get(1.0, END) >> self.notes_ent.config(state=NORMAL) >> Button(self, >> text = "Add Note", >> command = self.add_note(text1) >> ).grid(row = 1, column = 0, sticky = W) >> >> >> >> >> def add_note(self, text1): >> print text1 >> text_file = open("write_it.txt", "a+") >> text_file.write(text1) >> >> >> >> >> >> >> >> >> root = Tk() >> root.title("Mad Lib") >> app = Application(root) >> root.mainloop() >> > > On second look, it seems you have deeper problems, some of which are: > > > text1 = StringVar(self) > > text1 = self.notes_ent.get(1.0, END) > > You obviously added the second because the first will never work. Get > rid of both lines. Even if you intended the second, it immediately > nullifies the first. Instead of my previous suggestions, do this: > > 1. delete both "text1 =" lines > 2. change "command = self.add_note(text1)" to > "command = self.add_note" > 3. change "def add_note(self, text1):" to > "def add_note(self):" > 4. delete "print text1" > 5. change "text_file.write(text1)" to > "text_file.notes_ent.get(1.0, END) > > James > Or rather 5. change "text_file.write(text1)" to "text_file.write(self.notes_ent.get(1.0, END))" From CRhode at LacusVeris.com Sat Apr 14 10:04:45 2007 From: CRhode at LacusVeris.com (Chuck Rhode) Date: Sat, 14 Apr 2007 09:04:45 -0500 Subject: nonstandard XML character entities? References: <7xfy73ae08.fsf@ruckus.brouhaha.com> <46207e75$0$5795$9b622d9e@news.freenet.de> Message-ID: Martin v. L?wis wrote this on Sat, 14 Apr 2007 09:10:44 +0200. My reply is below. > Paul Rubin: >> I'm new to xml mongering so forgive me if there's an obvious >> well-known answer to this. It's not real obvious from the library >> documentation I've looked at so far. Basically I have to munch of >> a bunch of xml files which contain character entities like ú >> which are apparently nonstandard. -snip- > In ElementTree, the XMLTreeBuilder has an attribute entity which is > a dictionary used to map entity names in entity references to their > definitions. Whether you can make the parser download the DTD > itself, I don't know. What he said.... Try this on your piano: : import xml.etree.ElementTree # or elementtree.ElementTree prior to 2.5 : ElementTree = xml.etree.ElementTree : import htmlentitydefs : class XmlFile(ElementTree.ElementTree): : def __init__(self, file=None, tag='global', **extra): : ElementTree.ElementTree.__init__(self) : parser = ElementTree.XMLTreeBuilder( : target=ElementTree.TreeBuilder(Element)) : parser.entity = htmlentitydefs.entitydefs : self.parse(source=file, parser=parser) : return It looks goofy as can be, but it works for me. -- .. Chuck Rhode, Sheboygan, WI, USA .. Weather: http://LacusVeris.com/WX .. 32? ? Wind Calm From bj_666 at gmx.net Thu Apr 26 03:06:53 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Thu, 26 Apr 2007 09:06:53 +0200 Subject: If Dict Contains a particular key References: <1177436682.3441.15.camel@dot.uniqsys.com> <1177565430.992904.149450@n35g2000prd.googlegroups.com> Message-ID: In <1177565430.992904.149450 at n35g2000prd.googlegroups.com>, mensanator at aol.com wrote: > On Apr 24, 1:41 pm, Steven Bethard wrote: >> Steven Howe wrote: >> >> > or try: >> > thedict = { 'a': 1, 'b':2, 'c':3 } >> > if 'a' in thedict.keys(): >> > print thedict['a'] >> >> Better yet, just: >> >> if 'a' in thedict: >> ... >> >> There's no need for the call to keys(). > > Why not > > if thedict.has_key('a'): > pass > elde: > pass Additional to the speed argument, the ``in`` operator works with more types, like lists, sets and "iterables". And if someone implements a "container" class with membership testing, it is more likely he writes a `__contains__()` method than a `has_key()` method. Ciao, Marc 'BlackJack' Rintsch From mangabasi at gmail.com Thu Apr 5 09:05:47 2007 From: mangabasi at gmail.com (Mangabasi) Date: 5 Apr 2007 06:05:47 -0700 Subject: Calling Fortran from Python In-Reply-To: References: <1175640339.648190.207530@y66g2000hsf.googlegroups.com> <1175685841.847487.173440@w1g2000hsg.googlegroups.com> <1175718204.410453.29510@q75g2000hsh.googlegroups.com> <1175726427.114890.7990@y80g2000hsf.googlegroups.com> <1175729338.287712.305870@e65g2000hsc.googlegroups.com> Message-ID: <1175778347.934706.62470@w1g2000hsg.googlegroups.com> On Apr 4, 10:10 pm, Lenard Lindstrom wrote: > Mangabasi wrote: > > On Apr 4, 5:48 pm, Robert Kern wrote: > >> Mangabasi wrote: > >>> Would Python 2.5 work with Visual Studio 6.6? > >> No. > > >> -- > >> 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 > > > I will try the GCC then. It is a shame that I could not get calldll > > to work. It was very simple to use. I think I am making a mistake > > with the argument types but not sure. > > > Thanks for your help, it is greatly appreciated. > > Did you try ctypes? > > >>> from ctypes import * > >>> sample=cdll.sample.sample_ > >>> sample.restype=None > >>> sample.argtypes=[POINTER(c_int), POINTER(c_int), POINTER(c_double), > POINTER(c_double)] > >>> e1 = c_int(0) > >>> e2 = c_int(0) > >>> ain = (c_double*3)(2.0, 3.0, 4.0) > >>> aout = (c_double*4)() > >>> sample(e1, e2, ain, aout) > >>> aout[:] > [6.0, 9.0, 8.0, 12.0] > >>> e1.value > 0 > >>> e2.value > 0 > > I compile the SAMPLE example with mingw g77 3.4.5: > > g77 -shared -o sample.dll sample.for > > I had to take out the "INTENT(OUT)"s because g77 didn't like them. And > "SAMPLE" became "sample_" in the dll. Also note that argument passing to > Fortran subroutines is strictly pass-by-reference. Thus the ain pointer. > > Lenard Lindstrom- Hide quoted text - > > - Show quoted text - Lenard, Now I tried it as you suggested. I did not install G77 yet. I tried it with the dll I already had. Something interesting happened: >>> from ctypes import * >>> sample=cdll.sample_dll.SAMPLE >>> sample.restype=None >>> sample.argtypes=[POINTER(c_int), POINTER(c_int), POINTER(c_double), POINTER(c_double)] >>> sample.argtypes=[POINTER(c_int), POINTER(c_int), POINTER(c_double), POINTER(c_double)] >>> e1 = c_int(-10) >>> e2 = c_int(-10) >>> ain = (c_double*3)(2.0, 3.0, 4.0) >>> ain = (c_double*3)(2.0, 3.0, 4.0) >>> aout = (c_double*4)() >>> aout = (c_double*4)() >>> sample(e1, e2, ain, aout) Traceback (most recent call last): File "", line 1, in ? ValueError: Procedure called with not enough arguments (16 bytes missing) or wrong calling convention >>> aout[:] [6.0, 9.0, 8.0, 12.0] I got an error message and the expected answer! Any guesses? From jeba.ride at gmail.com Tue Apr 17 07:52:19 2007 From: jeba.ride at gmail.com (Clement) Date: 17 Apr 2007 04:52:19 -0700 Subject: Help on Shelve.... Message-ID: <1176810739.765433.47470@n59g2000hsh.googlegroups.com> Can i use Shelve for storing large amount of data around 6GB.. Is it stable...? if any problems come, can i retrive the document.. Plzzzzz tell the suggestions. By clement From robert.kern at gmail.com Wed Apr 18 19:05:55 2007 From: robert.kern at gmail.com (Robert Kern) Date: Wed, 18 Apr 2007 18:05:55 -0500 Subject: comparison with None In-Reply-To: <4626996E.1090200@gmail.com> References: <3IqdnfRnCNWPC7vbnZ2dnUVZ_jqdnZ2d@rcn.net> <4626996E.1090200@gmail.com> Message-ID: Steven Howe wrote: > Alan G Isaac wrote: >> >>> None >= 0 >> False >> >>> None <= 0 >> True >> >> Explanation appreciated. >> >> Thanks, >> Alan Isaac >> > I've read and found that 'None' comparisons is not always a good idea. > Better to: > from types import NoneType > > x = None > if type( x ) == NoneType: > # true > < code > > else: > # false; do something else. > < more code > The recommended idiom is to test for "x is None". -- 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 larry.bates at websafe.com Thu Apr 12 09:58:30 2007 From: larry.bates at websafe.com (Larry Bates) Date: Thu, 12 Apr 2007 08:58:30 -0500 Subject: Creating an EXE for XLRD + WIN32COM + wxWidgets application - Help request In-Reply-To: <1176331416.703642.242690@y5g2000hsa.googlegroups.com> References: <1176331416.703642.242690@y5g2000hsa.googlegroups.com> Message-ID: <461E3B06.5020809@websafe.com> BrendanC wrote: > I've started learninhg Python and have developed a small Python app > that imports Excel data into an Access mdb/jet database. This > application has dependencies on the following: > > XLRD - http://cheeseshop.python.org/pypi/xlrd/0.5.2 - (to read Excel > files) > Python windows extensions - http://starship.python.net/crew/mhammond/win32/ > - to use ADO > wxPython GUI toolkit - http://www.wxpython.org/ - for the GUI > interface > > Ideally I'd like to create a standalone app that I can deliver to a > client who can will run this on a Windows system that has Access > installed. (Python will not be installed on this system). > > I'm planning to use P2YEXE for the build - however I'm not sure if it > is possible to include all the required components for this in a > package. I imagine there may be a few 'gotchas' with this. > > Any suggestions on how to do this and are there some additional issues > I might run into? > > Thx in advance > > BrendanC > I can tell you that I've used py2exe to build quite a number of apps that depended on many different pieces. I have not experience with XLRD but the other pieces you use work just fine. Check on www.py2exe.org for docs an wiki. There is also a newsgroup at gmane.comp.python.py2exe that you can submit questions to if you like. I know that it is monitored by Mark Hammond, Thomas Heller, and other users of py2exe that can help you. -Larry From jeremyfee at gmail.com Wed Apr 18 20:35:43 2007 From: jeremyfee at gmail.com (jeremyfee at gmail.com) Date: 18 Apr 2007 17:35:43 -0700 Subject: Spawn/Exec with asterisk in argument Message-ID: <1176942943.090705.281320@l77g2000hsb.googlegroups.com> The spawn* and exec* functions appear to escape asterisks, I'm guessing all shell characters too, before the spawn/exec'ed process sees them. Is there a way around this? Not sure if this is a bug or a "feature". user$ touch test.txt user$ ls -l * -rw-r--r-- 1 user user 0 Apr 18 18:30 test.txt user$ ls -l \* ls: *: No such file or directory user$ python Python 2.3.5 (#1, Aug 12 2006, 00:08:11) [GCC 4.0.1 (Apple Computer, Inc. build 5363)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> import os >>> os.system("ls -l *") -rw-r--r-- 1 user user 0 Apr 18 18:30 test.txt 0 >>> os.spawnvp(os.P_WAIT, "ls", ("ls", "-l", "*")) ls: *: No such file or directory 1 From samjnaa at gmail.com Sat Apr 14 06:21:18 2007 From: samjnaa at gmail.com (samjnaa at gmail.com) Date: 14 Apr 2007 03:21:18 -0700 Subject: Python Feature Request: Explicit variable declarations Message-ID: <1176546078.934340.253810@y5g2000hsa.googlegroups.com> Hello. Please tell me whether this feature request is sane (and not done before) for python so it can be posted to the python-dev mailing list. I should say first that I am not a professional programmer with too much technical knowledge. I would like to have something like the "option explicit" statement in Visual Basic which turns on C-like checking for declaration of variables. This is highly helpful for people who are coming from C/C+ +, for people who are learning programming using Python, and even professionals, since this helps prevent typo errors like: sunlognitude = sunlongitude + 180.0 where the user has inadvertantly typed "g" before "n" and will later wonder why his application is not working as expected. From rdh at new.rr.com Mon Apr 16 12:21:53 2007 From: rdh at new.rr.com (DataSmash) Date: 16 Apr 2007 09:21:53 -0700 Subject: moving multiple directories Message-ID: <1176740512.975411.158380@p77g2000hsh.googlegroups.com> Hi, I need to organize thousands of directories full of files. I want to move these directories into other subdirectories. For example, all the directories that start with 01, move to a directory named "one", all directories that start with 02, move to a directory name "two", and so on.... I can't seem to find any easy way to do this. Looks like shutil.move only lets you move if the subdirectory DOES NOT exist, so after the first directory moves, the script blows up on the second move. I guess you could use shutil.copy or shutil.copytree but then you have to delete as well. Much longer process when you have hundreds of gigabytes of data. Thanks for your help! R.D. From http Fri Apr 13 01:58:50 2007 From: http (Paul Rubin) Date: 12 Apr 2007 22:58:50 -0700 Subject: Problem with algorithm References: <1176434160.047703.214600@q75g2000hsh.googlegroups.com> <1176434937.258002.162220@p77g2000hsh.googlegroups.com> <461f1831$0$6621$c30e37c6@lon-reader.news.telstra.net> Message-ID: <7xwt0gke79.fsf@ruckus.brouhaha.com> Charles Sanders writes: > Forgive any silly mistakes I have made (I've been teaching > myself python for about 1 week) but there is a moderately > well known algorithm for this that extends to arbitrary > lengths of both the list of alternatives and the length > of the required output, and avoids deeply nested loops. s = "abcd" def a(n): if n==0: yield '' return for c in s: for r in a(n-1): yield c+r print list(a(3)) From gilcneth at earthlink.net Fri Apr 13 10:21:15 2007 From: gilcneth at earthlink.net (Chris Nethery) Date: Fri, 13 Apr 2007 14:21:15 GMT Subject: Using python to delta-load files into a central DB References: Message-ID: Gabriel, I think that would work well. Also, thank you for suggesting the use of filecmp. I have never used this module, but it looks like a much better solution than what I had been doing previously--using os.stat and performing a DB lookup in order to verify that the filename and timestamp existed in a 'file update' table. Also, if the only limitation to difflib is that both files reside in memory, I should be fine. The largest of all of these files is just over 200k, which should be fine. If memory serves me right, I can't use more than 4MB, so I should be fine. And, if I spawn separate processes for generating the delta files, I should be able to speed things up even more. Thanks again for your help! Best Regards, Christopher Nethery "Gabriel Genellina" wrote in message news:mailman.6444.1176436788.32031.python-list at python.org... > En Thu, 12 Apr 2007 23:51:22 -0300, Chris Nethery > escribi?: > >> Yes, they are tab-delimited text files that will change very little >> throughout the day. >> But, this is messy, antiquated 80s junk, nonetheless. > > Ugh... > >> Rows are designated either by a row type or they contain a comment. Each >> row type has an identity value, but the 'comment' rows do not. The >> comment >> rows, however, are logically associated with the last occurring row type. >> When I generate my bulk insert file, I add the identity of the last >> occurring row type to the comment rows, and generate and populate an >> additional identity column in order to retain the order of the comments. >> Generally rows will either be added or changed, but sometimes rows will >> be >> removed. Typically, only 1-5 new rows will be added to a file in a given >> day, but users sometimes make manual corrections/deletions to older rows >> and >> sometimes certain column values are recalculated. > > http://tgolden.sc.sabren.com/python/win32_how_do_i/watch_directory_for_changes.html > > You could keep a copy of all files - let's say, as they were yesterday. > When you want to process the changes, iterate over all files and see if > they are newer than your copy. You could use the filecmp module: > http://docs.python.org/lib/module-filecmp.html > For each modified file: load it, and process the comments adding the > associated row type and the identity. Just do the same with the > "yesterday" file. (I assume they're not so big that you can keep both in > memory). You have then two lists of lines; then, use the functions in > module difflib to detect the changed lines; based on those results, > generate your database inserts/deletes/updates. > > This way you will not process the unchanged files, and inside each file, > you will ignore unchanged lines. At least in principle it should be faster > than redoing all from scratch each time... > >> Did I mention that the header contains another implied hierarchy? >> Fortunately, I can just ignore it and strip it off. > > good - I imagine it's enough work as it is now... > > -- > Gabriel Genellina > From bbxx789_05ss at yahoo.com Thu Apr 19 17:39:48 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: 19 Apr 2007 14:39:48 -0700 Subject: What makes an iterator an iterator? In-Reply-To: <1177017151.900443.71450@o5g2000hsb.googlegroups.com> References: <1hwr9pv.13v4ci6106qn0aN%aleax@mac.com> <1176936067.315082.17970@y80g2000hsf.googlegroups.com> <1hws6rd.u0a6hd78fhhpN%aleax@mac.com> <1176961515.450458.189530@p77g2000hsh.googlegroups.com> <1177017151.900443.71450@o5g2000hsb.googlegroups.com> Message-ID: <1177018788.309583.124350@n76g2000hsh.googlegroups.com> On Apr 19, 3:12 pm, 7stud wrote: > On Apr 19, 5:37 am, Steve Holden wrote: > > > > > It's nothing to do with the name lookup. Alex mentioned that to remind > > us that the magic "double-under" names are looked up on the type rather > > than the instance... > > P.next() > > vs. > > type(P).next() > > Where is the "double-under" name? The following example looks up next() in the instance not the class: class Parrot(object): def __init__(self): self.next = lambda: "hello" def __iter__(self): return self def next(self): yield "goodbye" raise StopIteration p = Parrot() _t = iter(p) print _t.next() -----output: ---- hello From robin at reportlab.com Wed Apr 4 11:49:03 2007 From: robin at reportlab.com (Robin Becker) Date: Wed, 04 Apr 2007 16:49:03 +0100 Subject: An error of matrix inversion using NumPy In-Reply-To: <1175698343.919351.9710@o5g2000hsb.googlegroups.com> References: <1175692530.364381.77110@n59g2000hsh.googlegroups.com> <1175698343.919351.9710@o5g2000hsb.googlegroups.com> Message-ID: <4613C8EF.30502@chamonix.reportlab.co.uk> lancered wrote: > Here is the eigenvalues of KK I obtained: > > >>> linalg.eigvals(KK) > array([ 1.11748411e+05, 3.67154458e+04, 3.41580846e+04, > 2.75272440e+04, 2.09790868e+04, 1.86242332e+04, > 8.68628325e+03, 6.66127732e+03, 6.15547187e+03, > 4.68626197e+03, 3.17838339e+03, 2.84888045e+03, > 1.88279736e+03, 1.32427574e+03, 1.04946287e+03, > 5.79303171e+02, 3.83111876e+02, 4.93826556e-12, > 1.50263232e-12]) > > You are right. The ratio of max/min eigenvalues is 7.4368432669e+016 > Maybe this exceed the of precision of my machine? > > Is there any tricks for me to be able to deal with this matrix > correctly with > NumPy? > ....... You have to be very careful with a set of eigenvalues like the above. The implication is that you have a rank deficiency of two ie either you have to small a number of observations or there's something fishy about the model (two of the data matrix columns can be written as linear combinations of the others or two of the columns are structurally zero). If you really believe the data to be good then normalize to unit column length first ie try using [d(1)/||d(1)||.....d(n)/||d(n)||] and see if the eigenvalues are still zero (this will only be of benefit if the data is vastly different in scale). I often got bad results, but that was mostly bad programming and or measuring the voltage of the earth wire by mistake :). Some problems naturally have a zero at the origin. -- Robin Becker From 12cc104 at gmail.com Mon Apr 23 00:20:42 2007 From: 12cc104 at gmail.com (proctor) Date: 22 Apr 2007 21:20:42 -0700 Subject: recursion depth problem In-Reply-To: <1hwzkey.19hmuyn1tebhe7N%aleax@mac.com> References: <1177267774.416169.276780@e65g2000hsc.googlegroups.com> <1177271382.859369.104790@q75g2000hsh.googlegroups.com> <1177278499.378120.246560@o5g2000hsb.googlegroups.com> <1hwzkey.19hmuyn1tebhe7N%aleax@mac.com> Message-ID: <1177302042.418360.84620@n76g2000hsh.googlegroups.com> On Apr 22, 8:23 pm, a... at mac.com (Alex Martelli) wrote: > Steven Bethard wrote: > > ... > > > > > >>>>> import sys > > >>>>> def ch4(item, n=0): > > >>>>> if n < len(item): > > >>>>> if item[n] == '0': > > >>>>> item[n] = '1' > > >>>>> print ''.join(item) > > >>>>> ch4(item) > > >>>>> elif item[n] == '1': > > >>>>> item[n] = '0' > > >>>>> ch4(item, n+1) > > >>>>> ch4(list(sys.argv[1])) > ... > > > for interest sake: is my method unredeemable? > > > Let's just say that I don't currently see an obvious way of redeeming > > it. ;-) > > Change the outer if into a while, and the recursive calls into proper > assignments to n. They're both tail-recursive calls, so this won't > change the semantics, as it happens. > > Alex really helpful! thank you very much! proctor. From gagsl-py2 at yahoo.com.ar Sat Apr 7 01:23:07 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: 6 Apr 2007 22:23:07 -0700 Subject: Convert xml symbol notation In-Reply-To: <1175899141.354348.207530@q75g2000hsh.googlegroups.com> References: <1175899141.354348.207530@q75g2000hsh.googlegroups.com> Message-ID: <1175923387.811717.279580@n76g2000hsh.googlegroups.com> dumbkiwi wrote: > I'm working on a script to download and parse a web page, and it > includes xml symbol notation, such as ' for the ' character. Does > anyone know of a pre-existing python script/lib to convert the xml > notation back to the actual symbol it represents? Try the htmlentitydefs module. -- Gabriel Genellina From kbk at shore.net Thu Apr 19 00:23:05 2007 From: kbk at shore.net (Kurt B. Kaiser) Date: Thu, 19 Apr 2007 00:23:05 -0400 (EDT) Subject: Weekly Python Patch/Bug Summary Message-ID: <200704190423.l3J4N5t2029975@bayview.thirdcreek.com> Patch / Bug Summary ___________________ Patches : 357 open ( +8) / 3745 closed ( +8) / 4102 total (+16) Bugs : 958 open (+19) / 6657 closed ( +9) / 7615 total (+28) RFE : 251 open ( +2) / 280 closed ( +2) / 531 total ( +4) New / Reopened Patches ______________________ Help with Python codebase (2007-04-11) CLOSED http://python.org/sf/1698723 opened by Munawar Update to Macintosh library documentation (2007-04-11) http://python.org/sf/1698768 opened by Kevin Walzer ZipFile.printdir fix (2.5) (2007-04-11) http://python.org/sf/1698915 opened by Alan McIntyre ZipFile.printdir fix (2.6) (2007-04-11) http://python.org/sf/1698917 opened by Alan McIntyre Bastion and rexec message out-of-date (2007-04-12) http://python.org/sf/1698951 opened by Gabriel Genellina getstate/setstate for incremental codecs (2007-04-12) CLOSED http://python.org/sf/1698994 opened by Walter D?rwald replacing char* with const char* in sysmodule.c/.h (2007-04-12) http://python.org/sf/1699259 opened by sebastinas Armin's method cache optimization updated for Python 2.6 (2007-04-13) http://python.org/sf/1700288 opened by Kevin Jacobs VC6 build patch for trunk (2007-04-14) http://python.org/sf/1700463 opened by Hirokazu Yamamoto stack size of python_d.exe on VC6 (2007-04-14) http://python.org/sf/1700467 opened by Hirokazu Yamamoto link_objects in setup.cfg crashes build (2007-04-18) http://python.org/sf/1703178 opened by Markus Schatten silenced a compiler warning (2007-04-18) http://python.org/sf/1703268 opened by Alexander Belopolsky missing declaration in readline.c (2007-04-18) http://python.org/sf/1703270 opened by Alexander Belopolsky bug fix: ctypes truncates 64-bit pointers (2007-04-18) http://python.org/sf/1703286 opened by Alexander Belopolsky fixes non ansi c declarations in libffi (2007-04-18) http://python.org/sf/1703300 opened by Alexander Belopolsky Refactor test_frozen.py to use unittest. (2007-04-18) http://python.org/sf/1703379 opened by Jerry Seutter Patches Closed ______________ Fix test_urllib on Windows buildbots (2007-04-07) http://python.org/sf/1695862 closed by zseil Don't block on Queue get/put when time is moved back (2007-03-29) http://python.org/sf/1690578 closed by loewis struct.pack() on 64bit architectures (2004-03-30) http://python.org/sf/925932 closed by zseil bug# 1607041: Condition.wait timeout fails on clock change (2006-12-01) http://python.org/sf/1607149 closed by loewis Add IllegalStateError (2007-03-21) http://python.org/sf/1685642 closed by gvanrossum Help with Python codebase (2007-04-11) http://python.org/sf/1698723 closed by gbrandl getstate/setstate for incremental codecs (2007-04-12) http://python.org/sf/1698994 closed by doerwalter Change *args from a tuple to list (2006-05-31) http://python.org/sf/1498441 closed by collinwinter New / Reopened Bugs ___________________ README is referencing obsolete? http://starship.python.net (2007-04-09) http://python.org/sf/1696740 opened by Jiri Navratil package.pth file name not used as described. (2007-04-09) http://python.org/sf/1697169 opened by cfk winreg module for cygwin? (2007-04-09) http://python.org/sf/1697175 opened by Zooko O'Whielacronx Property with -> annotation triggers assert (2007-04-09) http://python.org/sf/1697248 opened by Guido van Rossum types.InstanceType is missing but used by pydoc (2007-04-10) http://python.org/sf/1697782 reopened by gbrandl types.InstanceType is missing but used by pydoc (2007-04-10) http://python.org/sf/1697782 opened by Christian Heimes __getslice__ still used in built-in types (2007-04-10) http://python.org/sf/1697820 opened by Torsten Bronger Segfaults on memory error (2007-04-10) http://python.org/sf/1697916 reopened by gbrandl Segfaults on memory error (2007-04-10) http://python.org/sf/1697916 opened by STINNER Victor msgfmt cannot cope with BOM (2007-04-10) http://python.org/sf/1697943 opened by Christoph Zwerschke xml.etree document element.tag (2007-04-11) http://python.org/sf/1698167 opened by paul rubin wrong % of params for format string in ZipFile.printdir() (2007-04-11) http://python.org/sf/1698398 opened by Szabolcs Berecz dtdparser discards last line (2007-04-11) CLOSED http://python.org/sf/1698944 opened by L. Peter Deutsch shlex fails to parse strings correctly (2007-04-12) http://python.org/sf/1699594 opened by Collin Winter pickle example contains errors (2007-04-13) http://python.org/sf/1699759 opened by Mark Edgington locale.getlocale() output fails as setlocale() input (2007-04-13) http://python.org/sf/1699853 opened by Bernhard Reiter import and capital letters (2007-04-13) http://python.org/sf/1700132 opened by omsynge pydoc.help samples sys.stdout and sys.stdin at import time (2007-04-13) http://python.org/sf/1700304 opened by James Lingard ctypes Fundamental data types (2007-04-14) http://python.org/sf/1700455 opened by hg6980 Carbon.Scrap.PutScrapFlavor (2007-04-14) http://python.org/sf/1700507 opened by dingus9 PCbuild8/pcbuild.sln is missing "_socket" sub-project (2007-04-14) http://python.org/sf/1700865 opened by Raghuram Devarakonda questionable results from IDLE, Windows, & several built-in (2007-04-15) http://python.org/sf/1700912 opened by bavantgarde314 symbol conflict for 'readahead' (2007-04-15) http://python.org/sf/1701192 opened by ajrh svnversion_init assertion failed (2007-04-15) CLOSED http://python.org/sf/1701207 opened by ajrh utf-16 codec problems with multiple file append (2007-04-16) http://python.org/sf/1701389 opened by Iceberg Luo Segfault in c_char_p of ctypes (2007-04-16) http://python.org/sf/1701409 opened by sebastien Martini documentation bug in profile module (2007-04-16) CLOSED http://python.org/sf/1701449 opened by Keith Briggs Feature request: Comparing regexps (2007-04-16) http://python.org/sf/1701452 opened by Thomas Dybdahl Ahle Turtle isn't thread-safe (crashes) (2007-04-17) http://python.org/sf/1702036 opened by lomm distutils sdist does not exclude SVN/CVS files on Windows (2007-04-18) http://python.org/sf/1702551 opened by Guy Dalberto Incorrect example for add_password() (2007-04-18) http://python.org/sf/1703110 opened by Bob Kline Bugs Closed ___________ logging.handlers.SocketHandler.makeSocket() blocks app (2007-04-07) http://python.org/sf/1695948 closed by vsajip asyncore DoS vulnerability (2007-03-21) http://python.org/sf/1685000 closed by josiahcarlson compiler package needs better documentation. (2000-11-27) http://python.org/sf/223616 closed by facundobatista types.InstanceType is missing but used by pydoc (2007-04-10) http://python.org/sf/1697782 closed by gbrandl Segfaults on memory error (2007-04-10) http://python.org/sf/1697916 closed by haypo dead link in tkinter documentation (2007-03-11) http://python.org/sf/1678710 closed by fdrake Condition.wait timeout fails when system clock changes (2006-12-01) http://python.org/sf/1607041 closed by rhettinger dtdparser discards last line (2007-04-12) http://python.org/sf/1698944 closed by loewis svnversion_init assertion failed (2007-04-15) http://python.org/sf/1701207 closed by nnorwitz documentation bug in profile module (2007-04-16) http://python.org/sf/1701449 closed by quiver New / Reopened RFE __________________ audioop module - request to add a note (2007-04-15) http://python.org/sf/1700821 opened by ncryptor Prevent textwrap from breaking words at hyphens (2007-04-17) http://python.org/sf/1702681 opened by Matt Kraai RFE Closed __________ make slices pickable (2005-04-28) http://python.org/sf/1191699 closed by rhettinger 'str'.translate(None) => identity translation (2005-04-30) http://python.org/sf/1193128 closed by rhettinger From steve at holdenweb.com Sun Apr 15 20:42:00 2007 From: steve at holdenweb.com (Steve Holden) Date: Sun, 15 Apr 2007 20:42:00 -0400 Subject: how to strip the domain name in python? In-Reply-To: <1176672270.932679.283230@d57g2000hsg.googlegroups.com> References: <1176526155.679721.159870@l77g2000hsb.googlegroups.com> <1176564977.498635.171600@n59g2000hsh.googlegroups.com> <1176654669.737355.78300@y5g2000hsa.googlegroups.com> <1176672270.932679.283230@d57g2000hsg.googlegroups.com> Message-ID: Marko.Cain.23 at gmail.com wrote: > On Apr 15, 11:57 am, Marc 'BlackJack' Rintsch wrote: >> In <1176654669.737355.78... at y5g2000hsa.googlegroups.com>, Marko.Cain.23 >> wrote: >> >> >> >>> On Apr 14, 10:36 am, Marko.Cain... at gmail.com wrote: >>>> On Apr 14, 12:02 am, Michael Bentley >>>> wrote: >>>>> On Apr 13, 2007, at 11:49 PM, Marko.Cain... at gmail.com wrote: >>>>>> Hi, >>>>>> I have a list of url names like this, and I am trying to strip out the >>>>>> domain name using the following code: >>>>>> http://www.cnn.com >>>>>> www.yahoo.com >>>>>> http://www.ebay.co.uk >>>>>> pattern = re.compile("http:\\\\(.*)\.(.*)", re.S) >>>>>> match = re.findall(pattern, line) >>>>>> if (match): >>>>>> s1, s2 = match[0] >>>>>> print s2 >>>>>> but none of the site matched, can you please tell me what am i >>>>>> missing? >>>>> change re.compile("http:\\\\(.*)\.(.*)", re.S) to re.compile("http:\/ >>>>> \/(.*)\.(.*)", re.S) >>>> Thanks. I try this: >>>> but when the 'line' ishttp://www.cnn.com, I get 's2' com, >>>> but i want 'cnn.com' (everything after the first '.'), how can I do >>>> that? >>>> pattern = re.compile("http:\/\/(.*)\.(.*)", re.S) >>>> match = re.findall(pattern, line) >>>> if (match): >>>> s1, s2 = match[0] >>>> print s2 >>> Can anyone please help me with my problem? I still can't solve it. >>> Basically, I want to strip out the text after the first '.' in url >>> address: >>> http://www.cnn.com-> cnn.com >> from urlparse import urlsplit >> >> def get_domain(url): >> net_location = urlsplit(url)[1] >> return '.'.join(net_location.rsplit('.', 2)[-2:]) >> >> def main(): >> print get_domain('http://www.cnn.com') >> >> Ciao, >> Marc 'BlackJack' Rintsch > > Thanks for your help. > > But if the input string is "http://www.ebay.co.uk/", I only get > "co.uk" > > how can I change it so that it works for both www.ebay.co.uk and www.cnn.com? > >>> def get_domain(url): ... net_location = urlsplit(url)[1] ... return net_location.split(".", 1)[1] ... >>> print get_domain('http://www.cnn.com') cnn.com >>> print get_domain('http://www.ebay.co.uk') ebay.co.uk >>> 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 Thu Apr 26 23:27:38 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: 26 Apr 2007 20:27:38 -0700 Subject: My python annoyances so far In-Reply-To: References: <1177541453.471959.120830@c18g2000prb.googlegroups.com> <1177599046.406827.5210@t38g2000prd.googlegroups.com> Message-ID: <1177644458.458027.53090@r3g2000prh.googlegroups.com> On Apr 26, 9:08 am, Michael Hoffman wrote: > 7stud wrote: > > fli... at gmail.com wrote: > >> Annoyances: > > > Every language has annoyances. Python is no exception. Post away. > > Anyone that is offended can go drink a Guinness. > > I find Guinness annoying. > -- > Michael Hoffman lol. From andmarti at gmail.com Tue Apr 24 07:43:19 2007 From: andmarti at gmail.com (andmarti at gmail.com) Date: Tue, 24 Apr 2007 11:43:19 +0000 Subject: getting scancodes In-Reply-To: <-4udnQQIc_KaiLPbnZ2dneKdnZydnZ2d@comcast.com> References: <132r2hb2gltbf4d@corp.supernews.com> <596hp5F2jf49qU1@mid.uni-berlin.de> <-4udnQQIc_KaiLPbnZ2dneKdnZydnZ2d@comcast.com> Message-ID: <20070424114319.GA29641@lacordilleraandina.com.ar> On Tue, Apr 24, 2007 at 09:32:29AM -0500, Larry Bates wrote: > Diez B. Roggisch wrote: > > andmarti at gmail.com wrote: > > > >> On Tue, Apr 24, 2007 at 04:40:11AM -0000, Grant Edwards wrote: > >>> On 2007-04-24, andmarti at gmail.com wrote: > >>> > >>>> Anyone knows if its possible to get scan codes ??? > >>> What hardware? What OS? > >> Debian Sarge/Etch, i386.. > >> > >> :P > > > > Greeeeeaaaat. Now we only need to guess what scan code reader you use.... > > > > > > > I believe he his referring to keyboard scancodes not a scanner. > > -Larry Both Larry and Steve are right. ;) Anyone knows how to? Any clue? Thanks Andr?s M. From robert.rawlins at thinkbluemedia.co.uk Mon Apr 16 06:15:02 2007 From: robert.rawlins at thinkbluemedia.co.uk (Robert Rawlins - Think Blue) Date: Mon, 16 Apr 2007 11:15:02 +0100 Subject: Signal Handlers Message-ID: <014501c78010$18e102a0$4aa307e0$@rawlins@thinkbluemedia.co.uk> Hello Guys, Thanks again for all the help you've given me this past week, things are moving briskly and my class library is building nicely and seems to be working well :-D Now, I'm working with an API for another piece of software today, and the API documentation details the signals that are broadcast upon particular events, which I need to listen for and then handle. Here is an example: void RemoteDeviceFound(string address, uint32 class, int16 rssi) This signal will be send every time an inquiry result has been found by the service daemon. In general they only appear during a device discovery. Now, how do I listen for this signal? I've seen a couple of examples where by they import the signal module, and then to signal.signal(RemoteDeviceFound, myFunctionToCall) but the python documentation seemed to think that this would be limited to 2 arguments, when I've obviously got 3 of them. Perhaps I've got my wires crossed, if it's really that simple then great. However, where about in my application should I declare that signal listener? Thanks, Rob -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at REMOVE.THIS.cybersource.com.au Sun Apr 22 02:14:33 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Sun, 22 Apr 2007 16:14:33 +1000 Subject: Can __init__ not return an object? References: Message-ID: On Sat, 21 Apr 2007 22:36:42 -0400, Steven W. Orr wrote: > When I go to create an object I want to be able to decide whether the > object is valid or not in __init__, and if not, I want the constructor to > return something other than an object, (like maybe None). None is an object, like everything else in Python. __init__ is not a constructor, it is an initializer -- by the time __init__ is called, the instance is already constructed. __init__ is expected to return None. >>> class Foo(object): ... def __init__(self): ... return 2 ... >>> f = Foo() __main__:1: RuntimeWarning: __init__() should return None > I seem to be > having problems. At the end of __init__ I say (something like) > > if self.something < minvalue: > del self > return None > > and it doesn't work. del self doesn't really do anything useful there, except unbind the name "self" from the instance. "return None" is redundant, because all functions and methods will automatically return None if you don't specify differently. > I first tried just the return None, then I got crafty > and tried the del self. Is what I'm trying to do possible in the > constructor or do I have to check after I return? Or would raising an > exception in the constructor be appropriate? Yes, absolutely raise an exception. -- Steven. From aleax at mac.com Sun Apr 15 23:16:57 2007 From: aleax at mac.com (Alex Martelli) Date: Sun, 15 Apr 2007 20:16:57 -0700 Subject: pyparsing Catch-22 References: <1176686782.270354.164630@l77g2000hsb.googlegroups.com> <1176692031.142326.134710@y80g2000hsf.googlegroups.com> Message-ID: <1hwmo7x.lydgndjr9awfN%aleax@mac.com> 7stud wrote: > 1) Even though the download at sourceforge said the file name was: > > pyparsing-1.4.6.tar.gz > > it was downloaded to my Desktop as: > > pyparsing-1.4.6.tar > > Did os x 10.4.7 automatically unzip it for me? .gz means the file was > compressed with gzip, but I didn't have to do any unzipping. You probably have Safari, the browser, set up to do that upon download (but not set up to also untar the tarfile) -- I believe that those are its default settings. Still, Safari's just an application, even though Apple reasonably chooses to bundle it into the OS; you might use Firefox, Opera, Camino, or any other browser, and the issue of what that given browser does upon download (and how to change those settings) will be different each time. It's not really a question at OS level, rather it depends on each specific browser. Alex From gagsl-py2 at yahoo.com.ar Wed Apr 11 15:01:39 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 11 Apr 2007 16:01:39 -0300 Subject: Universal Feed Parser issue References: <1176227922.910993.36910@y80g2000hsf.googlegroups.com> <1176267073.787216.80170@n76g2000hsh.googlegroups.com> <1176311235.792366.296010@b75g2000hsg.googlegroups.com> Message-ID: En Wed, 11 Apr 2007 14:07:15 -0300, i3dmaster escribi?: > Hmm... well I don't know if I made my question clear then or you might > have misread it?... Anyway, the namespace handling wasn't the issue > of this question. feedparser handles it as expected but only when > there is a text value associated with it. Look at the rdf file you > will see the prism:issn element has a text value but in my case, the > foo:timezone element DOES NOT have a text value but a Attribute or > maybe attributes... What it looks like is feedparser simply ignores > all the attributes when parsing it. This behavior wasn't seen from > other xml parsers though. Oh, sorry! I thought you were complaining about the namespace. You're out of luck with this parser - see my own reply on January for a similar issue: http://mail.python.org/pipermail/python-list/2007-January/422237.html -- Gabriel Genellina From draghuram at gmail.com Thu Apr 12 10:47:18 2007 From: draghuram at gmail.com (draghuram at gmail.com) Date: 12 Apr 2007 07:47:18 -0700 Subject: reading from sys.stdin In-Reply-To: <1176387908.406115.270630@w1g2000hsg.googlegroups.com> References: <1176366058.261031.111870@p77g2000hsh.googlegroups.com> <1176387908.406115.270630@w1g2000hsg.googlegroups.com> Message-ID: <1176389238.366186.105760@d57g2000hsg.googlegroups.com> On Apr 12, 10:25 am, "Matimus" wrote: > * well, not ALL, it will read in chunks. But, I think they are 4096 > Byte chunks by default. If you are referring to the read ahead buffer size, it is 8192 bytes. Raghu. From larry.bates at websafe.com Mon Apr 9 17:45:46 2007 From: larry.bates at websafe.com (Larry Bates) Date: Mon, 09 Apr 2007 16:45:46 -0500 Subject: recursively archiving files In-Reply-To: <1176154692.532747.85720@l77g2000hsb.googlegroups.com> References: <1176154692.532747.85720@l77g2000hsb.googlegroups.com> Message-ID: bahoo wrote: > Hi, > > Can I use python to recursively compress files under subdirectories > with a certain format such as "ABC_XXX_XXX.dat" into a .gz or .zip > file? I used to do it with "tar" on unix, but I don't like to put > commands into a single line, as it is often more prone to error. > > Thanks > bahoo > Use os.walk to talk your branch of directories. Use glob.glob to find only those files that match your mask. Use zipfile or tarfile module (depending on if you want .gz or .zip compressed file) to add each file to the compressed file. -Larry From samjnaa at gmail.com Sat Apr 14 23:50:08 2007 From: samjnaa at gmail.com (jamadagni) Date: 14 Apr 2007 20:50:08 -0700 Subject: Python Feature Request: Explicit variable declarations In-Reply-To: <4620b369$0$6937$9b622d9e@news.freenet.de> References: <1176546078.934340.253810@y5g2000hsa.googlegroups.com> <4620b369$0$6937$9b622d9e@news.freenet.de> Message-ID: <1176609008.400374.146560@n59g2000hsh.googlegroups.com> On Apr 14, 3:56 pm, "Martin v. L?wis" wrote: > for prior discussion. The request is sane, but is also incomplete: there > is no syntax suggested for the actual declarations of local variables, > and no discussion whether this is meant to apply to local variables > only, or also to global variables and object attributes. I suggest that the C syntax be followed: int a, b, c a = "foo" should raise a TypeError But as has been pointed out in the intervening messages which are slightly OT, the line int a, b, c should mean: "a, b and c are meant to be labels of integer objects so don't allow them to be labels of other kinds of objects without redeclaration", and NOT the following: "create three memory spaces for integers with labels a, b and c" as it would be in C. This ensures that Python's behaviour of: >>> a = 2 >>> b = a >>> a is b True continues even after int a, b. If the C meaning were taken, a is b would never be True. I do not see why this cannot be applicable to global variables also. When explicit type declarations is enabled, no label can be used implicitly for an object unless it has been declared that that label is meant for that kind of object. If that label is reassigned to an object of a different type, a TypeError should be raised. If a label that has not been declared is used for an object, a VariableNotDeclaredError should be raised. This can be used for object attributes also. When a programmer creates a class, he would be expected to type-declare the members. This also means that function arguments and return values should be type-declared: def bool printNameAndAge ( str name, int age ) : _print name _print age _return True This option should be set for each source file. Otherwise it will raise errors in modules which were written without type declaration (and maybe in modules written in C too ??). I realize this may be a big thing to include in a language which has been traditionally dynamically-typed, but it can ease transitions to lower-level languages like C, especially since one of the most important uses of Python is learning programming. It is also useful to pure Python programmers as said above for error-catching. From steve at REMOVE.THIS.cybersource.com.au Fri Apr 13 06:44:47 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Fri, 13 Apr 2007 20:44:47 +1000 Subject: Lists and Tuples and Much More References: <1176418911.743940.251300@l77g2000hsb.googlegroups.com> Message-ID: On Thu, 12 Apr 2007 16:01:51 -0700, bearophileHUGS wrote: >> [1, 2, 3, 4, 5, 6, [7, 9, 8, 10]] > > Such sorting may be impossible in Python 3.0 (comparing the order of > lists with integers may be seen as meaningless. Otherwise you can see > single numbers as lists of len=1, like another language does). And such sorting may be impossible in ten billion years when the sun explodes, but is it really necessary to confuse a newbie who is having problems with basic concepts with what "may" happen in some future version of Python? It would be one thing if sorting such lists was depreciated, but it isn't, so I think as far as the Original Poster is concerned, that's just muddying the water. -- Steven. From bbxx789_05ss at yahoo.com Thu Apr 12 05:02:41 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: 12 Apr 2007 02:02:41 -0700 Subject: Newbie help with array handling In-Reply-To: <1176364734.439383.252930@o5g2000hsb.googlegroups.com> References: <1176364734.439383.252930@o5g2000hsb.googlegroups.com> Message-ID: <1176368561.245625.251270@y5g2000hsa.googlegroups.com> loial wrote: > I am new to python and am converting an awk script to python > > I need to store some data in an array/table of some form > > keyvalue1, value1, value2, value3 > keyvalue2, value1,value2, value3 > keyvalue3, value1,value2,value3 > etc > > I will later need to sort in keyvalue order and also need to be able > to check if a key already exists > > It is not clear how to do this in python. All the examples I see have > just a key and a single value Any python type can be a value for a key/value pair. See if this helps: mydict = { "zkeyvalue1":[1, "red", 2.5], "akeyvalue2":[1.5, "black", 30] } key = "keyvalue50" if key in mydict: print "found it" else: print "invalid key" lst = sorted(mydict) print lst for key in lst: print mydict[key], From carsten at uniqsys.com Mon Apr 30 20:41:12 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Mon, 30 Apr 2007 20:41:12 -0400 Subject: [Q] module name available in 'from ... import ...' statement In-Reply-To: <1177975194.782804.155070@n76g2000hsh.googlegroups.com> References: <1177975194.782804.155070@n76g2000hsh.googlegroups.com> Message-ID: <1177980072.3362.6.camel@localhost.localdomain> On Mon, 2007-04-30 at 16:19 -0700, kwatch wrote: > [...] > The goal what I want to do is to create a module by 'new' module > and specify that module name in 'from ...' statement. > > ---------------------------------------- > # create a module > import new > foo = new.module('foo') > foo.pi = 3.14159 > foo.x2 = lambda x: 2*x > # specify it in 'from' statement > from foo import pi, x2 # ImportError: No module named foo > ---------------------------------------- Not that this can't be done, but why do you think you have to create this 'foo' module on the fly? What is the actual problem you're trying to solve? -Carsten From R.Brodie at rl.ac.uk Tue Apr 3 12:14:44 2007 From: R.Brodie at rl.ac.uk (Richard Brodie) Date: Tue, 3 Apr 2007 17:14:44 +0100 Subject: Stack experiment References: <5QuQh.152$9L1.108@read3.inet.fi> <1175616703.386553.147830@w1g2000hsg.googlegroups.com> Message-ID: wrote in message >There may be something wrong with the "re" code in your example, >but I don't know enough about that to help in that area. There is a stray leading space in it. From youngha.yoon at gmail.com Fri Apr 13 22:31:57 2007 From: youngha.yoon at gmail.com (Youngha Yoon) Date: Sat, 14 Apr 2007 04:31:57 +0200 Subject: deepcopy for object insertion Message-ID: Hello! I wrote next code. I intended to insert class object to Pool list. ========================================== import random,copy class Particle: Dimension = 2 CurrentPosition = {} def __init__(self, dimension): self.Dimension = dimension for i in range(self.Dimension): value = random.uniform(0.,1.) self.CurrentPosition[i] = value class Group: Pool = [] def __init__(self, size, dimension): for i in range(size): particle = Particle(dimension) print 'particle generated' print particle.CurrentPosition self.Pool.append(copy.deepcopy(particle)) print '\n total Pool' group = Group(3, 2) for i in group.Pool: print i.CurrentPosition ============================================== But the result is like follow. It always synchronized with final insertion. What do you think is the problem ? ======================================= $ python test3.py particle generated {0: 0.70968382903877392, 1: 0.8019162560229226} particle generated {0: 0.76791838585848948, 1: 0.91689882120031052} particle generated {0: 0.32582853916678456, 1: 0.72166384931732286} total Pool {0: 0.32582853916678456, 1: 0.72166384931732286} {0: 0.32582853916678456, 1: 0.72166384931732286} {0: 0.32582853916678456, 1: 0.72166384931732286} ============================================== Thank you in advance ! -------------- next part -------------- An HTML attachment was scrubbed... URL: From sjmachin at lexicon.net Sun Apr 29 22:58:57 2007 From: sjmachin at lexicon.net (John Machin) Date: Mon, 30 Apr 2007 12:58:57 +1000 Subject: Counting In-Reply-To: References: <1177873864.502180.283390@u30g2000hsc.googlegroups.com> <1177877775.780666.222080@p77g2000hsh.googlegroups.com> Message-ID: <46355B71.70803@lexicon.net> On 30/04/2007 7:17 AM, James Stroud wrote: > rockmode at gmail.com wrote: >> That's a short, abridged version of my code :) But, what I want is to >> count total# of keywords per line and print 'em. Rather than >> printing : >> >> The word 'and' belongs in line num: 1 >> The word 'del' belongs in line num: 1 >> The word 'from' belongs in line num: 1 >> >> I want to print " Line #1 has 3 keywords" >> >> ;) >> > > > I think it would be obvious how to write this: > > > for i,line in enumerate(linelist): > line = line.split() > for k in line: > if keyword.iskeyword(k): > c = line.count(k) > total += line.count(k) > print "Line #%d has %d keywords." % (i+1, c) > break > > print "Total keyords are: %d" % total I would have thought so too. But the above is ... let's just say it's not quite right. If there are 3 different keywords (as in the OP's example), the above code prints 3 times for the same line. Here's a straight-forward natural way to do it: total = 0 for i, line in enumerate(linelist): c = 0 line = line.split() for k in line: if keyword.iskeyword(k): c += 1 # Alternatively, replace above 5 lines by # c = sum(keyword.iskeyword(k) for k in line.split()) # or the equivalent using map(), depending on taste etc :-) total += c print "Line #%d has %d keywords." % (i+1, c) print "Total number of keywords is", total ====== Perhaps someone should point out to the OP that using str.split as a tokeniser is somewhat deficient: 1. comments and string literals could make the counts somewhat unreliable: "# if not use mung(), will break while frobotzing later in code" 2. "else:" 3. "if not(0 <= n < maxn):" HTH, John From steve at holdenweb.com Wed Apr 18 14:52:02 2007 From: steve at holdenweb.com (Steve Holden) Date: Wed, 18 Apr 2007 14:52:02 -0400 Subject: Iterate through a dictionary of lists one "line" at a time In-Reply-To: <1176921542.567121.248820@b58g2000hsg.googlegroups.com> References: <1176921542.567121.248820@b58g2000hsg.googlegroups.com> Message-ID: wswilson wrote: > Here is my code: > > listing = {'id': ['a', 'b', 'c'], 'name': ['Joe', 'Jane', 'Bob']} > > I need to output: > > id name > a Joe > b Jane > c Bob > > I could do: > > print 'id', 'name' > for id, name in zip(listing['id'], listing['name']): print id, name > > but that only works if there are two entries in the dictionary, id and > name, and I know what they are. My problem is I don't know how many of > these entries there will be. Thanks for any help you can give! > >>> listing = {'id': ['a', 'b', 'c'], 'name': ['Joe', 'Jane', 'Bob']} >>> for (id, name) in zip(listing['id'], listing['name']): ... print id, name ... a Joe b Jane c Bob >>> 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 martin at v.loewis.de Sat Apr 14 07:02:33 2007 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sat, 14 Apr 2007 13:02:33 +0200 Subject: Python Feature Request: (?) Group all file-directory-related stdlib functions in one place In-Reply-To: <1176546615.450418.268090@y5g2000hsa.googlegroups.com> References: <1176546615.450418.268090@y5g2000hsa.googlegroups.com> Message-ID: <4620b4c9$0$14410$9b622d9e@news.freenet.de> > Currently file-directory-related functionality in the Python standard > library is scattered among various modules such as shutil, os, > dircache etc. So I request that the functions be gathered and > consolidated at one place. Some may need renaming to avoid conflicts > or for clarification. > Please see PEP 355. Regards, Martin From aisaac at american.edu Sat Apr 28 14:58:30 2007 From: aisaac at american.edu (Alan Isaac) Date: Sat, 28 Apr 2007 18:58:30 GMT Subject: relative import broken? Message-ID: Are relative imports broken in 2.5? Directory ``temp`` contains:: __init__.py test1.py test2.py File contents: __init__.py and test2.py are empty test1.py contains a single line:: from . import test2 Python 2.5.1 under Win2000, cmd line execution, produces as output:: Traceback (most recent call last): File "F:\temp\test1.py", line 1, in from . import test2 ValueError: Attempted relative import in non-package Why? Thanks, Alan Isaac From jstroud at mbi.ucla.edu Mon Apr 30 06:22:52 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Mon, 30 Apr 2007 03:22:52 -0700 Subject: regexp match string with word1 and not word2 In-Reply-To: <1177920984.247487.54620@c35g2000hsg.googlegroups.com> References: <1177920984.247487.54620@c35g2000hsg.googlegroups.com> Message-ID: Flyzone wrote: > Hello, > i have again problem with regexp :-P > I need to match all lines that contain one word but not contain > another. > Like to do "grep one | grep -v two:" > The syntax of the string is: > (any printable char)two:(any printable char)one(any printable char) > Example: > Apr 30 00:00:09 v890neg0 two: [ID 702911 daemon.one] findings: > blablabla > > I tried with: > .*[^t][^w][^o].*one.* > but is not working, the string is always match and in other tries > using "less logic" i get always some different match :-( > > P.S: i can't have more re.search, so i just need ONE regexp > The P.S: suggests homework, but this can't be homework because python regex won't do this, so your teacher gets an F if its homework. You require a negative look-behind assertion of variable length--not possible in python regex. You will have to use something else--or maybe you don't understand the homework problem. James From fperez.net at gmail.com Wed Apr 11 01:18:46 2007 From: fperez.net at gmail.com (Fernando Perez) Date: Tue, 10 Apr 2007 23:18:46 -0600 Subject: [ANN] IPython 0.8.0 is out Message-ID: Hi all, The IPython team is happy to release version 0.8.0, with a lot of new enhancements, as well as many bug fixes. We hope you all enjoy it, and please report any problems as usual. WHAT is IPython? ---------------- 1. An interactive shell superior to Python's default. IPython has many features for object introspection, system shell access, and its own special command system for adding functionality when working interactively. 2. An embeddable, ready to use interpreter for your own programs. IPython can be started with a single call from inside another program, providing access to the current namespace. 3. A flexible framework which can be used as the base environment for other systems with Python as the underlying language. 4. A shell for interactive usage of threaded graphical toolkits. IPython has support for interactive, non-blocking control of GTK, Qt and WX applications via special threading flags. The normal Python shell can only do this for Tkinter applications. Where to get it --------------- IPython's homepage is at: http://ipython.scipy.org and downloads are at: http://ipython.scipy.org/dist We've provided: - Source download (.tar.gz) - A Python Egg (http://peak.telecommunity.com/DevCenter/PythonEggs). - A python 2.4 RPM. - A native win32 installer. The egg is 'light', as it doesn't include documentation and other ancillary data. If you want a full ipython installation, use the source tarball or your distribution's favorite system. We note that IPython is now officially part of most major Linux and BSD distributions, so packages for this version should be coming soon, as the respective maintainers have the time to follow their packaging procedures. Many thanks to the distribution packagers for their work, which helps users get IPython more conveniently. Thanks to all the users who contributed bug reports, ideas and especially patches. The ChangeLog has hopefully detailed acknowledgements, but please let us know if we've accidentally ommitted giving you due credit. Many thanks to Enthought for their continued hosting support for IPython. Release notes ------------- As always, the full ChangeLog is at http://ipython.scipy.org/ChangeLog. The highlights of this release follow. Also see the "What's New" page at http://ipython.scipy.org/moin/WhatsNew * Support for KeyboardInterrupt (Ctrl-C) when running in multithreaded mode with GUI support. This had been a long-requested feature that we had never quite been able to implement correctly. Many thanks to Tomer Filiba's for his ctypes-based trick: http://sebulba.wikispaces.com/recipe+thread2, which we used (any implementation mistakes are our own and not his fault). Users of Python 2.4 should note that they need to install ctypes separately to access this feature; ctypes is part of Python 2.5 already. * Fully syntax-highlighted tracebacks and debugger listings. IPython used to color tracebacks, but only certain elements; now the source is actually highlighted by the same engine that handles '??' source listings, both in tracebacks and during interactive debugging. * Improved the ipipe system: http://ipython.scipy.org/moin/UsingIPipe, including a new WX-based graphical browser. * Much improved unicode support. There may still be bugs remaining, but a number of known-incorrect cases have been fixed. * Make the execution of 'from pylab import *' when -pylab is given be otional. A new flag (which can be set in your ipythonrc file), pylab_import_all controls this behavior, the default is True for backwards compatibility. * Extensions for perforce support via a new magic (%p4) and custom command completers. * Improved support for (X)Emacs under win32. * Several small fixes and improvements to the interactive demo module. * Add \N for the actual prompt number, without any coloring, as an escape for customized prompt definitions. This lets users write their own custom prompts with arbitrary coloring schemes. * Many more bugfixes and small features everywhere (the ChangeLog linked above has the gory details). API changes: * genutils.clock() now returns user+system time. The new clocku/clocks functions return respectively user and system time only. Enjoy, and as usual please report any problems. The IPython team. From sjmachin at lexicon.net Sun Apr 29 07:34:20 2007 From: sjmachin at lexicon.net (John Machin) Date: 29 Apr 2007 04:34:20 -0700 Subject: Could zipfile module process the zip data in memory? In-Reply-To: <1177845313.798239.71580@o5g2000hsb.googlegroups.com> References: <1177845313.798239.71580@o5g2000hsb.googlegroups.com> Message-ID: <1177846460.767627.101520@o5g2000hsb.googlegroups.com> On Apr 29, 9:15 pm, ??????????????? wrote: > I made a C/S network program, the client receive the zip file from the > server, and read the data into a variable. how could I process the > zipfile directly without saving it into file. > In the document of the zipfile module, I note that it mentions the > file-like object? what does it mean? > > class ZipFile( file[, mode[, compression[, allowZip64]]]) > Open a ZIP file, where file can be either a path to a file (a > string) or a file-like object. > A file-like object is an object that is not a file object, but behaves like a file object. Instead of keeping the data on disk, it will use Python objects (e.g. str or maybe array.array) or malloc its own memory. Have a look at the StringIO module (pure Python) and the similar but faster cStringIO module. Regards, John From tcrane at REMOVETHISuiuc.edu Mon Apr 30 13:49:56 2007 From: tcrane at REMOVETHISuiuc.edu (T. Crane) Date: Mon, 30 Apr 2007 17:49:56 GMT Subject: re-importing modules Message-ID: <8%pZh.18192$Kd3.76@newssvr27.news.prodigy.net> Hi, When troubleshooting code that's saved in a text file, I often find that I want to make a change to it, re-save it, then reimport it. However, just typing import myTestCode doesn't always seem to import the newer version. Is it supposed to? I find that right now I often have to close my iPython window, then reopen it and import my recently modified code. I know this can't be the best way to do this, but I don't know what is. any suggestions/help welcome and appreciated, trevis From soyouthinkimgonnalikethis at hotmail.com Sat Apr 7 09:29:27 2007 From: soyouthinkimgonnalikethis at hotmail.com (Eric Price) Date: Sat, 07 Apr 2007 08:29:27 -0500 Subject: Can't Get Email Interface Working Message-ID: Hi; I'm writing a script that includes an email function. So I went to the cookbook and dug up this, and tweaked it just a bit to make it easier to get it to work, but it throws an error: >>>def createMail(sender, recipient, subject, html, text): ... import MimeWriter, mimetools, cStringIO ... out = cStringIO.StringIO() ... # txtin = cStringIO.StringIO(msg) ... writer = MimeWriter.MimeWriter(out) ... writer.addheader("From", sender) ... writer.addheader("To", recipient) ... writer.addheader("Subject", subject) ... writer.addheader("MIME-Version", "1.0") ... writer.startmultipartbody("alternative") ... writer.flushheaders() ... subpart = writer.nextpart() ... subpart.addheader("Content-Transfer-Encoding", "quoted-printable") ... pout = subpart.startbody("text/plain", [("charset", 'us-ascii')]) ... mimetools.encode(txtin, pout, 'quoted-printable') ... txtin.close() ... subpart = writer.nextpart() ... subpart.addheader("Content-Transfer-Encoding", "quoted-printable") ... pout = subpart.startbody("text/html", [("charset", 'us-ascii')]) ... mimetools.encode(htmlin, pout, 'quoted-printable') ... htmlin.close() ... writer.lastpart() ... msg = "test" ... out.close() ... return msg ... >>># --------------------------------------------------------------- ... def sendMail(sender, recipient, subject, html, text): ... import smtplib ... message = createMail(sender, recipient, subject, html, text) ... server = smtplib.SMTP("localhost") ... server.sendmail(sender, recipient, message) ... server.quit() ... >>>if __name__=="__main__": ... sendMail("root at mail.example.com", "joe at yahoo.com", "Web Stie(s) Down!!!", "", "text") ... Traceback (most recent call last): File "", line 2, in ? File "", line 4, in sendMail File "", line 10, in createMail File "/usr/local/lib/python2.4/MimeWriter.py", line 153, in startmultipartbody self._boundary = boundary or mimetools.choose_boundary() File "/usr/local/lib/python2.4/mimetools.py", line 130, in choose_boundary hostid = socket.gethostbyname(socket.gethostname()) socket.gaierror: (8, 'hostname nor servname provided, or not known') >>> Now, I can send email from my server no problem. In fact, I have my script working already...but with a shell script instead of this python code. Please advise. TIA, Eric _________________________________________________________________ Get a FREE Web site, company branded e-mail and more from Microsoft Office Live! http://clk.atdmt.com/MRT/go/mcrssaub0050001411mrt/direct/01/ From bbxx789_05ss at yahoo.com Thu Apr 12 20:02:26 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: 12 Apr 2007 17:02:26 -0700 Subject: Lists and Tuples and Much More In-Reply-To: References: Message-ID: <1176422546.385731.172910@d57g2000hsg.googlegroups.com> > Yes. Tuples are immutable - once created, they can't change. Just to explain that statement a little better. If you do this: t = (1, 2, ["red", "white"]) t[2].append("purple") print t #(1, 2, ['red', 'white', 'purple']) It sure looks like t changed, and therefore t is NOT immutable--and the whole "tuples are immutable" mantra is a lie. However, the list itself isn't actually stored inside t. What's stored inside t is python's internal id for the list. So suppose python gave the list the internal id: 10008. The tuple really looks like this: t = (1, 2, <10008>) And no matter what you do to the list: append() to it, sort() it, etc., the list's id remains the same. In that sense, the tuple is immutable because the id stored in the tuple never changes. In actuality, the numbers 1 and 2 aren't stored in the list either-- python has internal id's for them too, so the tuple actually looks like this: t = (<56687>, <93413>, <10008>) | | | | | | | | | V V V 1 2 ["red", "white", "purple"] Because of that structure, you can create situations like this: >>> lst = ["red", "white"] >>> t1 = (1, 2, lst) >>> t2 = (15, 16, lst) >>> print t1 (1, 2, ['red', 'white']) >>> print t2 (15, 16, ['red', 'white']) >>> lst.append("purple") >>> print lst ['red', 'white', 'purple'] >>> print t1 (1, 2, ['red', 'white', 'purple']) >>> print t2 (15, 16, ['red', 'white', 'purple']) >>> lst, t1, and t2 all refer to the same list, so when you change the list, they all "see" that change. In other words, the names lst, t1[2], and t2[2] all were assigned the same python id for the original list ["red", "white"]. Since all those names refer to the same list, any of those names can be used to change the list. From kw at codebykevin.com Wed Apr 11 11:00:42 2007 From: kw at codebykevin.com (Kevin Walzer) Date: Wed, 11 Apr 2007 11:00:42 -0400 Subject: Seeking list of Python applications on OS X Message-ID: Hello, I am seeking to update this wiki page, which lists Mac OS X applications using Python in a significant way: http://wiki.python.org/moin/MacPython/MacSoftwareUsingPython This query is directed at developers of cross-platform Python applications who provide full support for the Mac. By "full support," I mean that you have Mac-specific builds of your application, deployed in a Mac-specific manner (wrapped with py2app or bundlebuilder into a standalone application with its own icon, for drag-and-drop installation), and that the application run natively in the Mac Aqua environment (no X11). This query focuses mainly on desktop applications developed with one of the major cross-platform toolkits (Tkinter, wxPython, PyQt; Gtk does not run natively on the Mac). Please post to c.l.p. with your replies and I will add the appropriate response to the wiki. Thanks. -- Kevin Walzer Code by Kevin http://www.codebykevin.com From larry.bates at websafe.com Fri Apr 20 18:05:18 2007 From: larry.bates at websafe.com (Larry Bates) Date: Fri, 20 Apr 2007 17:05:18 -0500 Subject: When to clear a dictionary... In-Reply-To: References: <6sCdnXnrw_aAZbXbnZ2dnUVZ_sOknZ2d@comcast.com> Message-ID: Gabriel Genellina wrote: > En Fri, 20 Apr 2007 14:28:00 -0300, Larry Bates > escribi?: > >> Bill Jackson wrote: >>> What is the benefit of clearing a dictionary, when you can just reassign >>> it as empty? >> >> If you have objects that point to the dictionary (something like a cache) >> then you want to clear the existing dictionary instead of just assigning >> it to empty. If nothing points to it, assigning it to empty is fast and >> you can let garbage collection do the rest. > > For an actual comparision, see Alex Martelli posts a few days ago: > http://mail.python.org/pipermail/python-list/2007-March/433027.html > >>>>>> a = {1:2,3:4} >>>>>> b = {1:2:4:3} >>>>>> a.clear() >>>>>> a.update(b) >>> >>>>>> a = {1:2,3:4} >>>>>> b = {1:2,4:3} >>>>>> for key in b: >>> ... a[key] = b[key] >>> > >> Syntax error in the first example but if you fix that the first two are >> equivalent (but I would suspect that the second would be faster for large >> dictionaries). > > It's the other way; the first method contains a single Python function > call and most of the work is done in C code; the second does the > iteration in Python code and is about 4x slower. > >> python -m timeit -s "b=dict.fromkeys(range(10000));a={}" "a.update(b)" > 100 loops, best of 3: 10.2 msec per loop > >> python -m timeit -s "b=dict.fromkeys(range(10000));a={}" "for key in >> b: a[key]=b[key]" > 10 loops, best of 3: 39.6 msec per loop > > --Gabriel Genellina That is what I meant to say, thanks for catching the error. -Larry From surekap at gmail.com Sun Apr 22 22:29:07 2007 From: surekap at gmail.com (Prateek) Date: 22 Apr 2007 19:29:07 -0700 Subject: Python and Javascript equivalence In-Reply-To: References: Message-ID: <1177295347.006598.168930@n59g2000hsh.googlegroups.com> Try creating a dict with sequential numeric keys. If you already have a list called my_list, you can do: com_array = dict(zip(range(len(my_list)), my_list)) This works when you want to convert Python objects to Javascript using JSON. It may work for you. -Prateek From bdesth.quelquechose at free.quelquepart.fr Wed Apr 11 18:24:12 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Thu, 12 Apr 2007 00:24:12 +0200 Subject: Shebang or Hashbang for modules or not? In-Reply-To: <1176308951.932721.197630@y80g2000hsf.googlegroups.com> References: <1176308951.932721.197630@y80g2000hsf.googlegroups.com> Message-ID: <461d56e9$0$27586$426a74cc@news.free.fr> Chris Lasher a ?crit : > Should a Python module not intended to be executed have shebang/ > hashbang (e.g., "#!/usr/bin/env python") or not? The shebang is only useful for files that you want to make directly executable on a *n*x system. They are useless on Windows, and not technically required to use the file as a main program -ie: you can always run it like this: $ /path/to/python filename.py > I'm used to having a > shebang in every .py file An encoding declaration might be more useful IMHO !-) From andrew.veitch at yahoo.co.uk Fri Apr 20 04:55:11 2007 From: andrew.veitch at yahoo.co.uk (Andrew Veitch) Date: Fri, 20 Apr 2007 09:55:11 +0100 (BST) Subject: Domain Keys in Python Message-ID: <979299.95854.qm@web27101.mail.ukl.yahoo.com> I am trying to implement Domain Keys (http://domainkeys.sourceforge.net/) in Python. In Perl I would just use Crypt:RSA which has a sign method with an armour option which generates exactly what I want but I can't find a way of doing this in Python. I tried this: from M2Crypto import RSA key = RSA.load_key('rsa.private') msg='Hello world' print key.sign(msg) But the output isn't quite right because there isn't an armour option - I verified this by reading the source. I'm not even sure if M2Crypto is the right library to be using or is it just that I need to use something else for the final step? Thanks in advance Andrew From phd at phd.pp.ru Wed Apr 11 11:36:27 2007 From: phd at phd.pp.ru (Oleg Broytmann) Date: Wed, 11 Apr 2007 19:36:27 +0400 Subject: SQLObject 0.7.5 Message-ID: <20070411153627.GB21003@phd.pp.ru> Hello! I'm pleased to announce the 0.7.5 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.5 News and changes: http://sqlobject.org/docs/News.html What's New ========== News since 0.7.4 ---------------- * Fixed a bug in DateValidator caused by datetime being a subclass of date. * Fixed test_deep_inheritance.py - setup classes in the correct order (required for Postgres 8.0+ which is strict about referential integrity). 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 steve at REMOVE.THIS.cybersource.com.au Fri Apr 20 22:13:23 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Sat, 21 Apr 2007 12:13:23 +1000 Subject: Significance of "start" parameter to string method "endswith" References: <1177016236.700474.16170@n59g2000hsh.googlegroups.com> <1177107716.353954.223460@p77g2000hsh.googlegroups.com> Message-ID: On Fri, 20 Apr 2007 15:21:56 -0700, John Machin wrote: > On Apr 20, 9:12 am, Steven D'Aprano > wrote: >> On Thu, 19 Apr 2007 13:57:16 -0700, Boris Dusek wrote: >> >> > what is the use-case of parameter "start" in string's "endswith" >> >> > method? >> >> >> def foo(function,instance,param): >> >> if function(instance,param,2,4): >> >> return True >> >> else: return False >> >> >> The function must work whether you pass it >> >> foo(str.endswith,"blaahh","ahh"), or >> >> foo(str.startswith,"blaahh","aah"). This is a really bad example, but >> >> it gets the point across that similar functions must have similar >> >> parameters in order to be Pythonic. >> >> > Thanks for explanation, this point makes sense. And I agree that I can >> > hardly imagine any use of both parameters :-). >> >> No, sorry, it doesn't make sense because not all string methods take the >> same arguments! See, for instance, ''.translate() and ''.lower(). >> >> The best reason for giving string methods and functions start and end >> parameters is to avoid copying potentially large lumps of text. Here's a >> silly example. Instead of doing this: >> >> while text: >> p = text.find('parrot') >> buffer = text[:p] >> text = text[p:] >> do_something_with(buffer) >> >> You can do this: >> >> p = 0 >> while text: >> p = text.find('parrot', p) >> do_something_with(buffer, p) >> >> which avoids copying text unnecessarily. > > ... but increases the care and attention required when coding: There are always trade-offs. > > (1) "while text"? "while 1" is a more obvious way of stress-testing > your CPU fan :-) but perhaps you meant "while p >= 0". No, I meant exactly what I said. You might notice that text becomes smaller after each iteration: text = text[p:] Eventually text becomes the empty string and the while loop is exited cleanly. "while p >= 0" would be an alternative, but you still need to copy chars into a buffer, and you still need to shrink the text or else you'll just keep getting the same p over and over again. > (2) 4s/buffer/text/ Yes, a silly typo caused by copy-and-paste-without-proof-reading. -- Steven. From kw at codebykevin.com Mon Apr 23 09:55:04 2007 From: kw at codebykevin.com (Kevin Walzer) Date: Mon, 23 Apr 2007 09:55:04 -0400 Subject: Do other Python GUI toolkits require this? In-Reply-To: References: <462697A6.6010007@codebykevin.com> <57C90994-391D-4350-A2F2-29C1590A3335@jedimindworks.com> Message-ID: <462CBAB8.3050107@codebykevin.com> Michael Bentley wrote: > OK. In order to kill the-thread-that-would-not-die(tm), I think I know > what I must do. I'll print a correction: > > On Apr 19, 2007, at 2:22 AM, Michael Bentley wrote: >> ... I switched to PyObjC. The >> learning curve is rather steep IMO, but worth it. One thing I think >> I should mention though is that if you move to PyObjC -- do some >> projects in Objective C first. Otherwise your brain will implode. > > Should be changed to: > > .. I switched to PyObjC. The > learning-effort curve is rather steep IMO, but worth it. One thing I think > I should mention though is that if you move to PyObjC -- do some > projects in Objective C first. Otherwise your brain will implode. > > Hope this helps, > Michael ;-) > I had originally thought that learning PyObjC might preclude me from having to learn Objective-C, but that seems not to be the case. I have previously found the same to be true with PyQt and wxPython--not knowing the toolkits as they are implemented in C++ is a serious handicap. I've even found this to be the case with Tkinter: understanding the Tcl implementation of Tk (which I do, because I am also a Tcl developer) is a huge advantage. Am I wrong to conclude that, if you want to do GUI programming in Python, then some level of proficiency with another language is not just recommended, but almost required? This is the case at least in my experience. When I first started learning Python a couple of years ago, I spun my wheels with it for months, because I couldn't figure out where to get started with GUI programming. Finally I set Python aside and took up Tcl/Tk for awhile--its simplicity in building GUI's is more beginner-friendly. (No "there's more than one way to do it"--there's only one way to do it, and that's Tk.) Now, coming back to Python with the Tk model of GUI development burned in my brain, I appreciate the breadth of functions that Python supports--but I still find myself "dropping down into Tcl" (!) to assemble elements of my GUI's--either to write a Python wrapper, or figure out how to implement something in pure Python. I understand the argument for Python having lots of bindings to different GUI toolkits. If you are already proficient with a GUI toolkit in a compiled language (Gtk, wxWidgets, Cocoa, Qt) then presumably switching to Python will speed up your development--learning Python is easy if you already know C++, for instance, and usually the Python bindings are just a "thin wrapper" over the compiled bits. But if you come to Python from the other direction--you're a relative beginner and you want to learn GUI programming without the complexities of compiled languages--then it's a lot harder to get started, ironically. Even Tkinter is a challenge for someone who doesn't know Tcl. The basics are easy enough--buttons, menus, labels, images--but doing anything sophisticated, such as trees, column views, drag-and-drop, and so on, requires extensions that may or may not be implemented in Python. -- Kevin Walzer Code by Kevin http://www.codebykevin.com From apardon at forel.vub.ac.be Fri Apr 20 05:31:13 2007 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 20 Apr 2007 09:31:13 GMT Subject: Do other Python GUI toolkits require this? References: <462697A6.6010007@codebykevin.com> <1177014799.004875.262060@y80g2000hsf.googlegroups.com> Message-ID: On 2007-04-20, Steve Holden wrote: > Antoon Pardon wrote: >> On 2007-04-19, sjdevnull at yahoo.com wrote: >>> On Apr 19, 6:54 am, Antoon Pardon wrote: >>>> I don't know how you come to the conclusion that it is a mathematical >>>> absurdity but consider this: If you find that common usage propagates >>>> something that is incorrect, should we just shrug it off or should we >>>> attemp a correction? >>> a) In English, "learning curve" is not restricted to a mathematical >>> plot--Webster's also defines it as "the course of progress made in >>> learning something". In that context, adding the adjective steep >>> ("extremely or excessively high...STEEP implies such sharpness of >>> pitch that ascent or descent is very difficult") makes sense. >> >> How much sense does it really make? Suppose we would talk about >> an income curve. Would you not prefer a steep curve over a shalow >> one? What about a productivity curve? It is all about the progress >> made in something. >> >> So how much sense does it make that a steep curve in earnings and >> productivity is good but a steep curve in learning is bad? >> > Just as much sense as that a motor car is great for driving around in > but bad for being run over by. Context is everything. Do *all* steep > curves have to be good or all bad? What the hell happened to common sense? You are just grabbing for straws. Sure context is everything. But you don't make a case that the context makes a difference here. Are you suggesting progres in productivity is good but progres in learning is bad? Just asserting how something can make a difference withouth arguing how in the particular case it actucally makes a difference is just a divertion tactic without real merrit. -- Antoon Pardon From steve at holdenweb.com Thu Apr 26 07:55:54 2007 From: steve at holdenweb.com (Steve Holden) Date: Thu, 26 Apr 2007 07:55:54 -0400 Subject: PIL and font colour. In-Reply-To: <46306E11.30338.1CA2026C@python.hope.cz> References: <1177441923.378487.210310@r3g2000prh.googlegroups.com> <46306E11.30338.1CA2026C@python.hope.cz> Message-ID: python at hope.cz wrote: > Steve > Thank you for your reply. > > Is there a way how to find out a complementary colour for an area where I will write the text, so > that the text will be seen clearly?Is there a routine in PIL or in Python somewhere? > Thank you for help > > Lad. > I see that you had an answer to this question on the PIL list, so I will merely note that it's difficult if the background color turns out close to mid-gray, or if it's very variable. In general this is a hard problem. Are you sure it wouldn't be easier to just put a colored strip behind the text and in front of the image? regards Steve -- Steve Holden +1 571 484 6266 +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 apardon at forel.vub.ac.be Thu Apr 12 03:12:55 2007 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 12 Apr 2007 07:12:55 GMT Subject: tuples, index method, Python's design References: <1175867771.114540.61810@n76g2000hsh.googlegroups.com> <1175884427.779950.267220@y80g2000hsf.googlegroups.com> <1175953520.316208.241490@o5g2000hsb.googlegroups.com> <7xzm5igbrb.fsf@ruckus.brouhaha.com> <1176200361.260546.280510@n76g2000hsh.googlegroups.com> <1176214831.3430.49.camel@dot.uniqsys.com> Message-ID: On 2007-04-11, Steven D'Aprano wrote: > > So how about it? All you people who desperately want tuples to grow an > index method -- will any of you donate your time to write and maintain the > code? But as far as I understood the code is already there; the code for list.index being usable almost as it is. It doesn't seem to be a question of where to put valuable resource. AFAIU it is simply a question of do the developers want it or not. -- Antoon Pardon From wegwerp at gmail.com Mon Apr 30 14:02:19 2007 From: wegwerp at gmail.com (Bas) Date: 30 Apr 2007 11:02:19 -0700 Subject: Is it possible to merge xrange and slice? Message-ID: <1177956139.320184.50590@n76g2000hsh.googlegroups.com> Hi, stupid question, but would it be possible to somehow merge xrange (which is supposed to replace range in py3k) and slice? Both have very similar start, stop and step arguments and both are lightweight objects to indicate a range. But you can't do a[xrange(10,20)] and 'for i in slice(10,20)'. The only difference is see is some behavior with infinities (e.g. object[3:] gives a slice(3,maxint) inside _getitem_ , but I think this should not be a large problem (xrange(0,infinity) could just yield a generator that never stops). Which problems am I overlooking that prevent this? Cheers, Bas From blackjay at x.cn Wed Apr 18 05:31:44 2007 From: blackjay at x.cn (blackjay at x.cn) Date: 18 Apr 2007 02:31:44 -0700 Subject: How? Movable yet? Click here to join! Message-ID: <1176888704.840256.283380@d57g2000hsg.googlegroups.com> How? Movable yet? Click here to join! AsiaFriendFinder http://www.9fy.cn/love/friends/ From andre.ditador9999 at gmail.com Sat Apr 14 14:37:28 2007 From: andre.ditador9999 at gmail.com (Andre P.S Duarte) Date: 14 Apr 2007 11:37:28 -0700 Subject: Really badly structured Python Books. Message-ID: <1176575848.526066.254520@y80g2000hsf.googlegroups.com> I started reading the beginning Python book. It is intended for people who are starting out in the Python world. But it is really complicated, because he tries to explain, then after a bad explanation he puts out a bad example. I really recommend NOT reading the book. For it will make you want not to continue in Python. This is just me letting the air out of my lungs. No need to reply this is just a recommendation. Txs for the opportunity . From aleax at mac.com Sat Apr 28 14:31:36 2007 From: aleax at mac.com (Alex Martelli) Date: Sat, 28 Apr 2007 11:31:36 -0700 Subject: Memory addressing References: <1177702902.156596.52510@n35g2000prd.googlegroups.com> <1177703803.179501.95300@n35g2000prd.googlegroups.com> <1177715277.592511.296990@h2g2000hsg.googlegroups.com> Message-ID: <1hxa2g4.1kd9hw1168ztj9N%aleax@mac.com> Steven D'Aprano wrote: > On Fri, 27 Apr 2007 16:07:57 -0700, castironpi wrote: > > > That's what we need: a CopyMemory() routine. > > What we _really_ need are Poke() and Peek() routines. You can easily write them with ctypes (it's part of the standard library now, too) -- at least on systems where you can easily access the C runtime library as a dynamic library, such as Windows, Linux, and MacOSX, but I imagine it wouldn't be that much harder on others (I haven't really looked in depth at the lowest-level functionality offered by ctype, as the higher-level stuff is plenty sufficient to get a lot of core dumps:-). Alex From tom at finland.com Tue Apr 17 12:37:00 2007 From: tom at finland.com (tom at finland.com) Date: Tue, 17 Apr 2007 16:37:00 GMT Subject: The smallest and largest values of numeric types In-Reply-To: References: Message-ID: Thank you for your answers. Seems like the limits of numeric values aren't considered as important in Python as in C ;) From gagsl-py2 at yahoo.com.ar Thu Apr 26 18:26:34 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 26 Apr 2007 19:26:34 -0300 Subject: Python CGI and Browser timeout References: <1177624109.532664.105840@t39g2000prd.googlegroups.com> Message-ID: En Thu, 26 Apr 2007 18:48:29 -0300, escribi?: > I am creating a simple cgi script which needs to retrieve and process > a huge number of records from the database (more than 11,000) and > write the results to a file on disk and display some results when > processing is complete. > > However, nothing needs to be displayed while the processing is on. I > was facing browser timeout issue due to the time it takes to process > these records. > > In order to work around this problem, I started printing empty strings > (i.e. print "") so that the browser does not timeout. > > Is there a better solution to avoid browser timeouts? You could spawn another process or thread, reporting the progress somewhere. Then redirect to another page showing the progress (and auto-reloading itself each few seconds). When it detects that processing is complete, redirect to another page showing the final results. -- Gabriel Genellina From howe.steven at gmail.com Fri Apr 27 11:15:15 2007 From: howe.steven at gmail.com (Steven Howe) Date: Fri, 27 Apr 2007 08:15:15 -0700 Subject: getting rid of EOL character ? In-Reply-To: <268cc$4631f634$83aef404$27224@news1.tudelft.nl> References: <268cc$4631f634$83aef404$27224@news1.tudelft.nl> Message-ID: <46321383.3090608@gmail.com> stef wrote: > hello, > > In the previous language I used, > when reading a line by readline, the EOL character was removed. > > Now I'm reading a text-file with CR+LF at the end of each line, > Datafile = open(filename,'r') > line = Datafile.readline() > > now this gives an extra empty line > print line > > and what I expect that should be correct, remove CR+LF, > gives me one character too much removed > print line[,-2] > > while this gives what I need ??? > print line[,-1] > > Is it correct that the 2 characters CR+LF are converted to 1 character ? > Is there a more automatic way to remove the EOL from the string ? > > thanks, > Stef Mientki > >>> abcd = 'abcdedff . \n' >>> abcd 'abcdedff . \n' >>> print abcd abcdedff . >>>* from string import strip* >>> print abcd.strip() abcdedff . >>> a = abcd.strip() >>> a 'abcdedff .' >>> sph -------------- next part -------------- An HTML attachment was scrubbed... URL: From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Fri Apr 27 16:39:25 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Fri, 27 Apr 2007 22:39:25 +0200 Subject: My newbie annoyances so far References: <1177688082.758043.133920@r30g2000prh.googlegroups.com> Message-ID: <59f5btF2k70baU2@mid.individual.net> Dennis Lee Bieber wrote: > And I'll probably ignore those expressions whenever I do get > around to 2.5+... That syntax, in my mind, just... stinks... > > HP RPL made more sense: b if c [else d] end Please explain. HP RPL: b if c [else d] end Python: b if c else d What's the "more sense" here? Regards, Bj?rn -- BOFH excuse #21: POSIX compliance problem From Eric_Dexter at msn.com Mon Apr 9 05:07:08 2007 From: Eric_Dexter at msn.com (Eric_Dexter at msn.com) Date: 9 Apr 2007 02:07:08 -0700 Subject: pluie documentation in english Message-ID: <1176109628.413745.285120@n76g2000hsh.googlegroups.com> I have converted the pluie documentation from french to english in a pdf. There may be some errors due to translation of the commands themselves that I have not fixed yet. I am still playing around with the library to see if it is of any use so there may be more documentation to come.. http://groups.google.com/group/dexrow-software-and-programming-group/files?upload=1 http://www.stormpages.com/edexter/csound.html From nate.finch at gmail.com Sat Apr 7 20:42:58 2007 From: nate.finch at gmail.com (Nate Finch) Date: 7 Apr 2007 17:42:58 -0700 Subject: Not understanding absolute_import In-Reply-To: <1175776410.788058.309080@w1g2000hsg.googlegroups.com> References: <1175776410.788058.309080@w1g2000hsg.googlegroups.com> Message-ID: <1175992978.756288.17030@w1g2000hsg.googlegroups.com> On Apr 5, 8:33 am, "Nate Finch" wrote: > I've been trying to use fromabsolute_importand it's giving me a hell > of a headache. I can't figure out what it's *supposed* to do, or > maybe rather, it doesn't seem to be doing what I *think* it's supposed > to be doing. No one? Is this too simple a question, or is it just that no one is using this? -Nate From irstas at gmail.com Mon Apr 2 15:51:02 2007 From: irstas at gmail.com (irstas at gmail.com) Date: 2 Apr 2007 12:51:02 -0700 Subject: RSS feed parser In-Reply-To: References: <1175531874.535702.212510@n76g2000hsh.googlegroups.com> Message-ID: <1175543462.493944.51110@b75g2000hsg.googlegroups.com> On Apr 2, 10:20 pm, Florian Lindner wrote: > Some of the question I have but found answered nowhere: > > I have a feedparser object that was created from a string. How can I trigger > a update (from a new string) but the feedparser should treat the new string > like the same feed (thus setting feed.updated etc.). Hmm. Do you mean that the feed object should stay the same? Like the difference between "a = [1,2,3]; a = [1,2,3]+[4]" and "a = [1,2,3]; a.append(4)"? I glanced at the parse function in the source code and it looks like it's not directly possible. You could modify it so that the "result" dictionary is optionally given as an argument, so when updating you'd do: feedparser.parse(string, oldFeed). You'd also have to clear the oldFeed object before update. But you might also be able to solve the problem by using an additional layer of indirection. Instead of passing around the "feed" object, you'd pass around a proxy object like this: class Empty: pass proxy = Empty() proxy.feed = feedparser.parse(string) storeProxyForLaterUse(proxy) proxy.feed = feedparser.parse(string2) useStoredProxy() #this would use the updated feed through the proxy Then just use proxy.feed.updated everywhere instead of directly feed.updated. A smarter proxy would automatically translate proxy.updated into proxy.feed.updated so usage would stay as simple as without the proxy. Doing this is quite easy in Python (search for __getattr__ examples). From larry.bates at websafe.com Tue Apr 10 11:33:59 2007 From: larry.bates at websafe.com (Larry Bates) Date: Tue, 10 Apr 2007 10:33:59 -0500 Subject: convert html entities into real chars In-Reply-To: References: Message-ID: <461BAE67.2070901@websafe.com> Laszlo Nagy wrote: > > Hi, > > I would like to have a function that can convert '>' into '>', > '&' into '&' etc. I could not find how to do it easily (I have a > code snippet for the opposite). > Thanks, > > Laszlo > You can use htmlentitydefs module to help with this. import htmlentitydefs chr(htmlentitydefs.name2codepoint['gt']) and (to go the other way) htmlentitydefs.codepoint2name[ord('>')] -Larry From aleax at mac.com Mon Apr 16 10:51:19 2007 From: aleax at mac.com (Alex Martelli) Date: Mon, 16 Apr 2007 07:51:19 -0700 Subject: newbie question: how to read back the dictionary from a file? References: <1176717819.937015.9890@y80g2000hsf.googlegroups.com> Message-ID: <1hwnjnq.1ym3g381lfcvvhN%aleax@mac.com> lancered wrote: > Hi Dear all, > > I have some data here in the form of a dictionary, called "vdic". Then > I write them to a data file "f" using the write function as > f.write(str(vdic)). The keys of this dictionary are integers and > values are float numbers. Something like this: > > { 1: 0.00951486513347, 2: 0.0388123556019, ... ...} > > Now, I want to read these data back in another function. Of course, I > could parse the string little by little, e.g, first read a "{", then > loop read a int, then read a ":", then a float etc etc... Since it is > written out with standard python builtin functions, I guess there may > be some more direct method than this, say a function in some modules? > Could someone give me a hint? Others have suggested better ways of writing the file out. However, it's possible to recover the data from the string form you've written, via the eval builtin function -- with all sorts of caveats (won't be as fast as other approaches, enormous security risk if anybody could have tampered with the file, etc). To mitigate the security risks a little, try eval(thestr, dict(__builtins__={})) or more advanced approaches such as discussed at , etc. Alex From S.Mientki-nospam at mailbox.kun.nl Wed Apr 4 17:39:29 2007 From: S.Mientki-nospam at mailbox.kun.nl (Stef Mientki) Date: Wed, 04 Apr 2007 23:39:29 +0200 Subject: Requirements For A Visualization Software System For 2010 In-Reply-To: <1175628186.459945.290750@d57g2000hsg.googlegroups.com> References: <1175628186.459945.290750@d57g2000hsg.googlegroups.com> Message-ID: <1ece7$46141acf$d443bb3a$27660@news.speedlinq.nl> Xah Lee wrote: > REQUIREMENTS FOR A VISUALIZATION SOFTWARE SYSTEM FOR 2010 > > Xah Lee, 2007-03-16 > > In this essay, i give a list of requirements that i think is necessary > for a software system for creating scientific visualization for the > next decade (2007-2017). > > (for a HTML version with images, please see > http://xahlee.org/3d/viz.html ) > Very nice overview, of what IS and what SHOULD BE. And I'm very surprised that there's still so little open source software, in the form a graphical calculator for simple and interactive (2D, 3D, timeseries) math. As I stepped from MatLab to Python a couple of months ago, I still had hopes such a graphical visualization tool existed in Python :-( -- cheers, Stef Mientki http://pic.flappie.nl From rNOSPAMon at flownet.com Fri Apr 13 19:25:39 2007 From: rNOSPAMon at flownet.com (Ron Garret) Date: Fri, 13 Apr 2007 16:25:39 -0700 Subject: BaseHTTPServer and Apache Message-ID: I have a fairly large web app written in Python as a CGI fairly elaborate CGI. All of the requests go through a single CGI script which does authentication and session management and then dispatches to one of a number of handlers that generate the various pages. There is one page that is a performance bottleneck (because it is accessed automatically once a second by an XMLHTTPRequest, but that's another story). I have fixed this by re-implementing that page using a BaseHTTPServer. So I can fix my problem by redirecting the XMLHTTPRequest to a URL that is served by this BaseHTTPServer. The problem is that this server can't run on port 80 because Apache has to be there to serve everything else, and having a Python process serving a publicly accessible TCP port makes me a little queasy. Does anyone know of a straightforward way to get Apache to "forward" requests to a given path to another HTTP server running on a different port? Also, is anyone out there using BaseHTTPServer in an industrial setting? What has been your experience with it? And how do you make it fit in to your overall architecture? Thanks! rg From per9000 at gmail.com Thu Apr 12 08:00:26 2007 From: per9000 at gmail.com (per9000) Date: 12 Apr 2007 05:00:26 -0700 Subject: reaching hidden methods + casting In-Reply-To: References: <1176362298.986221.280520@n59g2000hsh.googlegroups.com> Message-ID: <1176379226.942564.5030@e65g2000hsc.googlegroups.com> On 12 Apr, 09:42, "Gabriel Genellina" wrote: > > > > > In f.x. the C-family of languages I guess something like this would > > call B.spin: > > ((B)myC).spin("Lancelot"); // almost forgot the ';' > > Try this in Python: > B.spin(myC, "Lancelot") > > > > Thanks, that was exactly the insight i needed. /Per -- Per Erik Strandberg blog: http://www.pererikstrandberg.se/blog/ From subscriber123 at gmail.com Thu Apr 5 13:53:01 2007 From: subscriber123 at gmail.com (Subscriber123) Date: Thu, 5 Apr 2007 13:53:01 -0400 Subject: Prevent Modification of Script? In-Reply-To: <1175735097.856840.177510@e65g2000hsc.googlegroups.com> References: <1175735097.856840.177510@e65g2000hsc.googlegroups.com> Message-ID: <4c0048df0704051053s57b6f795ub75d66bac95c00e3@mail.gmail.com> If you are *really* worried about the database being attacked and edited, encrypt it by private key: require that the user set a password and use that password every time that s/he accesses the database. I am afraid that you cannot really prevent the database from being deleted completely, but you can stop it from being edited such that it actually contains readable information. I am repeating what someone else has already said, but how likely is it that someone will attack your program specifically with malware? The very worst that can happen is that someone replaces your application completely, and there is no way to prevent this. There are probably much better things to replace than your program (such as OS files that are run during startup). Perhaps now would be a good time for me to begin my rant about how security has all been gone about the wrong way within computers (network security is just fine, with the exception of WEP). Part I: the problem Firstly, it is possible to bypass all security in Windows (I only talk about windows because I have not used any other OS enough to know the security flaws, not because they are any better). This is because Windows runs on top of the bios, which runs on top of the hardware. Making calls to the bios or the hardware directly therefore bypasses Windows, and allows you to do anything that Windows might prevent you from doing (this is all theoretical, by the way). I have actually managed to log into other users of whom I do not know the password in Windows 98. It is quite simple, in fact I discovered it by accident. If that user was logged in last, and shut down the computer, you (1) start up the computer, (2) type in a few bogus passwords in the login screen and try to login with them, and (3) clear the password field, and press login. You will login as that previous user. Part II: what is wrong with this The OS should not be inhibiting users or programs from doing things. These things can be done anyway by bypassing it. This is a security flaw that can be fixed (and will be in a computer that I am in the process of designing: don't expect it to be on the market any time soon). Current security is like security written in javascript (client side). The browser checks a form against source code which is available to the user to see if the password is correct, and then goes to a page, the URL of which is also available to the user in the source code. My planned security is more like security written in php (server side). The browser submits the form, and the server checks it against a database, choosing the location which the browser goes to based on that. The location to which the browser is sent was not previously available to the user in the source code. It was safely hidden away in a remote database for which the user had no access. Part III: the solution Since I will be including the solution in my design for a computer, I can only vaguely explain it. When programs run, they will be given a password. When the program tries to connect to a piece of hardware, they must securely pass the password to that hardware. The hardware then decides what rights the program has to it based on the location of the password in a database. The OS will inhibit nothing. The hardware will inhibit everything. Not even the OS nor the hardware has access to the contents of the database: They can only compare passwords against it, just like anything else. -------------- next part -------------- An HTML attachment was scrubbed... URL: From http Sun Apr 8 22:05:49 2007 From: http (Paul Rubin) Date: 08 Apr 2007 19:05:49 -0700 Subject: tuples, index method, Python's design References: <1175867771.114540.61810@n76g2000hsh.googlegroups.com> <1175884427.779950.267220@y80g2000hsf.googlegroups.com> <1175953520.316208.241490@o5g2000hsb.googlegroups.com> <7xzm5igbrb.fsf@ruckus.brouhaha.com> <7x8xd2iq53.fsf@ruckus.brouhaha.com> Message-ID: <7xwt0mcneq.fsf@ruckus.brouhaha.com> Steven D'Aprano writes: > I think the problem is that Python developers are split between those who > see tuples as immutable lists, and those who see them as records/structs. I think the construction def f(*a): ... shows that the "immutable list" interpretation is firmly ensconced in the language. From ramashish.lists at gmail.com Fri Apr 20 04:21:55 2007 From: ramashish.lists at gmail.com (Ramashish Baranwal) Date: 20 Apr 2007 01:21:55 -0700 Subject: How to upgrade python from 2.3 to 2.4 In-Reply-To: <1177016635.483952.27450@y5g2000hsa.googlegroups.com> References: <1177016635.483952.27450@y5g2000hsa.googlegroups.com> Message-ID: <1177057315.585286.178620@n76g2000hsh.googlegroups.com> On Apr 20, 2:03 am, "ying... at gmail.com" wrote: > Hi, > > Red hat 4 comes with python 2.3, and I am trying to upgrade to python > 2.4. So I download and compile the source of python2.4. > > But as I run it I get the following error, can you please tell me how > to fix it? > > # /root/src/Python-2.4.4/python ./nov/scripts/stressTestServlet.py ./ > nov/scripts/stressTestInputFile 10 127.0.0.1 > Traceback (most recent call last): > File "./nov/scripts/stressTestServlet.py", line 6, in ? > import time > ImportError: No module named time The best way to do it will be to use your operating system package manager. If you have yum (a package manager for red hat distributions) installed, it might be as simple as- # yum update python HTH Ram From steve at holdenweb.com Thu Apr 5 15:32:20 2007 From: steve at holdenweb.com (Steve Holden) Date: Thu, 05 Apr 2007 15:32:20 -0400 Subject: Trouble w/ 'create table' sql on mx.ODBC In-Reply-To: <9860747.post@talk.nabble.com> References: <9860747.post@talk.nabble.com> Message-ID: Greg Corradini wrote: > Hello, > Lately I've been using the mx.ODBC module to query Access (mdb) tables. For > the life of me, I can't get the 'create table' sql command to work. I use > this command in Oracle and I've seen other mx.ODBC users weave into their > scripts for Access. But I still can't get this simple test run below to work > (ignore the geoprocessor object for ArcGIS): > > #Import Python Standard Library Modules > import win32com.client, sys, os, string, copy, glob > import mx.ODBC.Windows as odbc > > # Create the Geoprocessor Object > gp = win32com.client.Dispatch("esriGeoprocessing.GpDispatch.1") > gp.overwriteoutput = 1 > > # Variables > tempspace = "C:\Documents and Settings\corr1gre\Desktop\Workspace\DBFs & > Shapefiles\TEST.mdb" > workspace = string.replace(tempspace,"\\","/") > > #Conection to Access > driv = 'DRIVER={Microsoft Access Driver (*.mdb)};DBQ='+workspace > conn = odbc.DriverConnect(driv) > curse = conn.cursor() > > #Upload Tbl 1 as a List of Tuples > curse.execute('SELECT TISCODE,EXISTSIN,STATUS,NOTES from Mower_I') > x = curse.fetchall() > > #Create New Table > curse.execute('Create table TEST (TISCODE Integer)') > curse.close() > conn.close() > del gp So what happens? Do you see a traceback, or does the program complete without any apparent change to the database? It might be because Access doesn't automatically commit DDL changes like some other databases do. Try adding a conn.commit() before your conn.close(). 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 steven.bethard at gmail.com Fri Apr 13 12:49:21 2007 From: steven.bethard at gmail.com (Steven Bethard) Date: Fri, 13 Apr 2007 10:49:21 -0600 Subject: Class Dependancy Injection In-Reply-To: References: <15088.0762412728$1176479941@news.gmane.org> Message-ID: Robert Rawlins - Think Blue wrote: > For instance, in my application I have a configuration bean which > contains all the applications configuration information. Now in one of > other classes I need access to those configuration settings. What I > would have done in my ColdFusion/JAVA type applications is create an > instance of the configuration bean, and then pass that in as an > argument to the constructor for my other class, then have the other > class set that as a ?self? variable. Then from within my class I can > access the configuration details like self.config.getName() and it > would return the name of the application. > > How is this best handled in python, can I still inject dependencies as > a constructor argument like that? If so then is there anything in > particular I need to watch out for that may cause me trouble? I would tend to create a config module, rather define a singleton object that gets passed to every constructor. My configuration loader code would look something like:: import config for name, value in get_config_values(): setattr(config, name, value) And my code that used the configuration settings would look like:: import config ... foo(config.bar, config.baz) ... I don't like the idea of adding another argument to every constructor for application-global configuration information. If it's really application-global, then use Python's built-in application-global objects: modules. STeVe From steven.bethard at gmail.com Sun Apr 15 09:14:19 2007 From: steven.bethard at gmail.com (Steven Bethard) Date: Sun, 15 Apr 2007 07:14:19 -0600 Subject: proposed PEP: iterator splicing In-Reply-To: <7xirbyi5d7.fsf_-_@ruckus.brouhaha.com> References: <7xirbyi5d7.fsf_-_@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > The boilerplate > > def some_gen(): > ... > for x in some_other_gen(): > yield x > ... > > is so common (including the case where some_other_gen is the same as > some_gen, i.e. it's a recursive call) that I find myself wanting > a more direct way to express it: > > def some_gen(): > ... > yield *some_other_gen() > > comes to mind. Less clutter, and avoids yet another temp variable > polluting the namespace. > > Thoughts? This has been brought up before and there was mixed support: http://www.python.org/dev/summary/2006-01-16_2006-01-31/#yielding-from-a-sub-generator My guess is that the only way it has any chance is if someone takes the time to implement it and posts a full-fledged PEP to python-dev. STeVe From carsten at uniqsys.com Fri Apr 20 10:54:52 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Fri, 20 Apr 2007 10:54:52 -0400 Subject: Byte-Array to String In-Reply-To: <000901c78351$56abae70$04030b50$@rawlins@thinkbluemedia.co.uk> References: <000f01c7828f$8b8ce770$a2a6b650$@rawlins@thinkbluemedia.co.uk> <46278FF4.9070505@gmail.com> <004d01c78329$1e5f7a60$5b1e6f20$@rawlins@thinkbluemedia.co.uk> <1177074008.3412.12.camel@dot.uniqsys.com> <000901c78351$56abae70$04030b50$@rawlins@thinkbluemedia.co.uk> Message-ID: <1177080892.3412.33.camel@dot.uniqsys.com> On Fri, 2007-04-20 at 14:39 +0100, Robert Rawlins - Think Blue wrote: > Thanks for that Carsten, > > I've given that a go and I still get similar results to what I've seen in the past whereby it prints a couple of elements I would expect to see but other which I'm not sure about, and what seems to be ALOT of blank characters. > > 6e > 555 5 5 5 en j 5 %OBEX Object Push ? > > That's what your suggestion returns to me, I'm using the API to scan a Bluetooth device for services, one of which is OBEX Object Push, but the rest of that output is apparent junk. > > Unfortunately the API doesn?t really give any suggestions at all, take a look here http://bluez.cvs.sourceforge.net/*checkout*/bluez/utils/hcid/dbus-api.txt if you look down under the 'adapter' section, I'm running the method called GetRemoteServiceRecord() which returns the byte array but there really isn?t any suggestion as to how you extract the information from what's returned. It says that it returns the binary stream of an SDP database. I seems that the writer of the API documentation assumed that you'd only ask for such a thing if you already know what to do with it. Directly below the GetRemoteServiceRecord method is the description of a method called GetRemoteServiceRecordAsXML. Maybe that'll give you a more readable result? > > I have no idea if we're barking up the right tree here or if we're going about this the wrong way. That depends entirely on what you want to achieve in the end, which I don't think you told us. You asked how to convert a (dbus) byte array into a string. We told you, but the result isn't as helpful as you hoped. Maybe the following analogy will illustrate the futility of this process. You: I need to get onto the roof of my house. How do I do that? Us: Use a ladder. You: Um, okay... Alright, thanks, I've climbed onto the roof of my house, but I still can't reach the moon. How do I do that? In other words, the more information you give us about what you are actually trying to achieve, the more helpful the advice we can give you. Good luck, Carsten. From Eric_Dexter at msn.com Wed Apr 18 04:42:48 2007 From: Eric_Dexter at msn.com (Eric_Dexter at msn.com) Date: 18 Apr 2007 01:42:48 -0700 Subject: Getting started with python In-Reply-To: <1176868817.675179.231110@q75g2000hsh.googlegroups.com> References: <1176598011.463543.96990@q75g2000hsh.googlegroups.com> <1176868817.675179.231110@q75g2000hsh.googlegroups.com> Message-ID: <1176885768.162090.89320@o5g2000hsb.googlegroups.com> On Apr 17, 11:00 pm, Basilisk96 wrote: > On Apr 14, 8:46 pm, "Eric" wrote: > > > Hello, after reading some of the book Programming Python it seems that > > python is something I would like to delve deeper into. The only thing > > is, I have no idea what I should try and write. So I was hoping that > > someone here could help point me to a group/project that would be a > > good starting place for a person with limited python knowledge, but > > that is willing to learn whatever is necessary. I'm hoping that with a > > goal I can start to learn python instead of just playing around with > > it. Thanks. > > Eric, > > You will certainly appreciate how concise and easy Python is. > I am also relatively new to Python (started about a year ago), and I'd > rather not go back to any other language! Why would I want to torment > my not-so-quick typing fingers?? :) I'm a self-learner. I learn by > reading, by example, and by doing. > > Here is a list of suggestions. Start with simple things, grow > confident, and move on to more interesting stuff as you progress: > > At the Python command line, type "import this" to see the basic ideas > behind Python development. It begins with "Beautiful is better than > ugly." - a nice thought. > > 1. First of all, read the publication "How to Think Like a Computer > Scientist: Learning with Python" by Allen B. Downey et al. I have > found this little gem to be very, very useful when I first got > interested in Python and thought to myself, "how do I go about > learning this, where do I start??". Highly recommended. I read it > from start to finish in a couple of days and started making useful > scripts right after that. The author actually implements a simple > card game toward the end of the book, using all the knowledge from the > previous chapters. The text is available at:http://www.ibiblio.org/obp/thinkCSpy/ > > 2. Play with Python from the command line first, using PyShell, > PyCrust, or any of its other siblings that come with the wxPython > package (a GUI toolkit - see #8 below). You will find the code > completion feature and the syntax helper quite useful. > > 3. Tinker around with the builtin modules. There's a lot of built-in > functionality in Python right out of the box. Try the "os" and "sys" > modules to experiment with filesystem handling. Try reading and > writing text files, as this is quite a common task with a variety of > applications. Try the "struct" module for binary file processing. Try > the "urllib" and "urllib2" modules for loading and processing Web > pages... I could go on, but you get the idea. > > 4. If you have a text processing background, dip your hand in regular > expressions with the "re" module. Maybe you have a need for extracting > some statistical data from a financial report, and this might be one > way to do it. > > 5. If you have a mathematical background, download and install the > NumPy or SciPy package and do some wild matrix math! > > 6. I have recently tinkered with the Pymedia package, perhaps you want > to try it later on. It is a nice tool for dealing with audio - for > recording, encoding, decoding, spectrum analysis, etc. In just a few > hours, I came up with a nice voice-activated MP3 sound recorder > application. > > 7. If you feel brave and want to work with Windows COM client/server > stuff (assuming Windows is your platform), get the PythonWin package, > also known as "win32com" and try to read/write Excel, Word files, > etc., or whatever > > 8. Last but certainly not least, once you feel comfortable with basic > Python, try GUI development. Several gui toolkits are out there. > wxPython is a good one to start with, though you may find some others > to your liking. > > 9. If you have previous programming experience, try taking an > application you've developed before and port it to Python. See how > much your code base shrinks compared to its C++ or Java counterpart :) > But really, do it just to understand Python on a deeper level. Instead > of thinking in the old way, try to think in the Pythonic way. A nice > example of this is iteration. Where an iteration counter variable is > required in most other languages, Python inherently supports iteration > in sequence objects like lists, strings, and dictionary keys; so the > syntax is simpler in most cases. > > -Basilisk96 I choose python with a goal in mind the language was not important.. Python is fantastic for input and output.. Once in a while I get stuck and to be honest if I had a little more cash I would be putting a small project on rent a coder that said tracker software where the notes are defined in collums are great for practicing input output, I can always do that myself but if there is a interest (or if a intresting idea presents itself because small projects can be linked) then I am game... good luck to all of you and happy learning From steve at holdenweb.com Mon Apr 2 10:23:26 2007 From: steve at holdenweb.com (Steve Holden) Date: Mon, 02 Apr 2007 10:23:26 -0400 Subject: socket read timeout In-Reply-To: <000401c77471$5ee152a0$03000080@hendrik> References: <17930.25631.86693.827473@montanaro.dyndns.org><000e01c771d2$2f3dd240$03000080@hendrik> <000401c77471$5ee152a0$03000080@hendrik> Message-ID: Hendrik van Rooyen wrote: > "Steve Holden" > > >> 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? >>> >> Yes. But you have to use non-blocking calls in your application to use >> them as full-duplex in your code. > > This seems to bear out the scenario I have described elsewhere in this > thread - I think its caused by the file handlers, but I don't _know_ it. > >>> I know Ethernet isn't. >>> >> Don't know much, then, do you? ;-) > > No not really - I easily get confused by such things as collisions... > > : - ) Right, but collisions are *so* twentieth-century, aren't they. With a properly-implemented switched infrastructure Ethernet interfaces can transmit and receive at the same time. 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 Mon Apr 30 23:54:50 2007 From: steve at REMOVEME.cybersource.com.au (Steven D'Aprano) Date: Tue, 01 May 2007 13:54:50 +1000 Subject: if __name__ == 'main': & passing an arg to a class object References: <1177708104.277756.245360@t38g2000prd.googlegroups.com> Message-ID: On Sun, 29 Apr 2007 07:32:44 -0400, Bart Willems wrote: > gtb wrote: >> appear at the end of many examples I see. Is this to cause a .class >> file to be generated? > This might be obvious, but no one else mentioned it: the Python > interpreter cannot execute code that it hasn't compiled yet, which is > why the "if __name__ ..." code is always at the end of the module - to > guarantee that the entire file is scanned first. Nonsense. Here's my "test.py": %%%%% x = 42 if __name__ == "__main__": print "x has value", x x = 23 print "now x has value", x %%%%% It works just as you would expect: $ python test.py x has value 42 now x has value 23 And when you import it: >>> import test now x has value 42 There is nothing, absolutely nothing, magic about the idiom if __name__ == "__main__". It is just an if block, like any other if block. If you still aren't convinced, try this one: %%%%% x = 42 if __name__ == "__main__": print "x has value", x print "y has value", y y = 43 %%%%% -- Steven D'Aprano From duncan.booth at invalid.invalid Sat Apr 14 12:45:18 2007 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 14 Apr 2007 16:45:18 GMT Subject: Python Feature Request: Add the "using" keyword which works like "with" in Visual Basic References: <1176547372.584539.89170@q75g2000hsh.googlegroups.com> <1176557293.861585.290070@b75g2000hsg.googlegroups.com> Message-ID: "jamadagni" wrote: >> If you are going to reference self.quit a lot of times then it makes >> sense to also assign it to a local variable and then you already get >> even fewer characters (239): > > But you realize readability decreases considerably. > Not as much as it would with your 'using' statement. Using a local alias for an expression lets you use appropriate mnemonic abbreviations for multiple expressions with. Nested 'using' statements means you have to look back through the code to try to work out which is in scope at each level. From nun at example.com Fri Apr 27 13:23:47 2007 From: nun at example.com (Mitja Trampus) Date: Fri, 27 Apr 2007 19:23:47 +0200 Subject: Correct behavior? In-Reply-To: <1177635228.144366.74600@o40g2000prh.googlegroups.com> References: <1177634055.017575.236810@t39g2000prd.googlegroups.com> <1177635228.144366.74600@o40g2000prh.googlegroups.com> Message-ID: DanBishop04 at gmail.com wrote: > On Apr 26, 8:34 pm, asker wrote: >> But:>>> print "%15.2f" % a+b >> >> Traceback (most recent call last): >> File "", line 1, in >> TypeError: cannot concatenate 'str' and 'float' objects >> >> Is this correct for Python to issue this error? > > The % operator has higher precedence than +. Thus, "%15.2f" % a+b == > ("%15.2f" % a)+b, an illegal str+float addition. Just as a warning: If you're not expecting this behavior, you can get a pretty nasty surprise if the adddition in question is str+str and the operation becomes legal (but semantically different): s1 = "Captain " s2 = "Bertorelli" print "Ah, %s! Welcome to my humble cafe..." % s1+s2 --> "Ah, Captain ! Welcome to my humble cafe...Bertorelli" Of course this can (and should) be avoided using "...%s%s..." % (s1,s2), but I know it has bitten me once. From steven.bethard at gmail.com Thu Apr 12 10:28:04 2007 From: steven.bethard at gmail.com (Steven Bethard) Date: Thu, 12 Apr 2007 08:28:04 -0600 Subject: Code Explaination: Spelling correction code In-Reply-To: <1176381680.678201.233880@b75g2000hsg.googlegroups.com> References: <1176345676.300560.78020@n59g2000hsh.googlegroups.com> <_tqdnfpprqGxOoDbnZ2dnUVZ_uTinZ2d@comcast.com> <1176381680.678201.233880@b75g2000hsg.googlegroups.com> Message-ID: Drew wrote: > On Apr 11, 11:27 pm, Steven Bethard wrote: >> Drew wrote: >>> def known_edits2(word): >>> return set(e2 for e1 in edits1(word) for e2 in edits1(e1) if e2 in >>> NWORDS) >> >> This is the same as: >> >> result = set() >> for e1 in edits1(word): >> for e2 in edits1(e1): >> if e2 in NWORDS: >> result.add(e2) >> return result >> >> The thing between the ``set(`` and ``)`` is called a generator >> comprehension if you'd like to look into it further. > > Thanks for the response. I'm somewhat familiar with generator/list > comprehension but was unsure how multiple statements were evaluated > when chained together. From your explanation, I'm assuming they are > evaluated from the "inside out" rather than left to right or right to > left. > > Does the mean that the comprehension on the inside is always evaluated > first? Not really (at least for the most literal interpretation of ``evaluated first``). I find it easiest to think of translating them into regular for loops by adding the appropriate indentation. Starting with: (e2 for e1 in edits1(word) for e2 in edits1(e1) if e2 in NWORDS) Adding newlines: (e2 for e1 in edits1(word) for e2 in edits1(e1) if e2 in NWORDS) Adding indentation: (e2 for e1 in edits1(word) for e2 in edits1(e1) if e2 in NWORDS) Moving the add/append to the bottom: for e1 in edits1(word) for e2 in edits1(e1) if e2 in NWORDS e2 Adding the remaining boiler-plate: result = set() for e1 in edits1(word): for e2 in edits1(e1): if e2 in NWORDS: result.add(e2) So multiple for- and if-expressions are evaluated in the same order that they would normally be in Python, assuming the proper whitespace was added. HTH, STeVe From frank.wagner.1983 at googlemail.com Tue Apr 17 12:16:37 2007 From: frank.wagner.1983 at googlemail.com (Johnny Blonde) Date: 17 Apr 2007 09:16:37 -0700 Subject: rewrite for achieving speedup In-Reply-To: References: <1176821334.217154.36350@y80g2000hsf.googlegroups.com> Message-ID: <1176826597.429493.263030@n76g2000hsh.googlegroups.com> thanks steve h., works like this just perfectly! steve b.: for the next time if i cannot figure it out i will just do it like this! thanks a lot guys, Frank From ecir.hana at gmail.com Mon Apr 16 13:05:27 2007 From: ecir.hana at gmail.com (ecir.hana at gmail.com) Date: 16 Apr 2007 10:05:27 -0700 Subject: yield, curry, mix-in, new.function, global, closure, .... what will work? In-Reply-To: <1176737762.629412.189270@y80g2000hsf.googlegroups.com> References: <1176657848.944538.169780@p77g2000hsh.googlegroups.com> <7xy7ktmrzn.fsf@ruckus.brouhaha.com> <1176684145.537202.68090@p77g2000hsh.googlegroups.com> <7xbqhp6sdu.fsf@ruckus.brouhaha.com> <1176730099.467774.212440@q75g2000hsh.googlegroups.com> <1176737762.629412.189270@y80g2000hsf.googlegroups.com> Message-ID: <1176743127.450980.236610@o5g2000hsb.googlegroups.com> On Apr 16, 5:36 pm, "Jason" wrote: > On Apr 16, 7:28 am, ecir.h... at gmail.com wrote: > > > > > On Apr 16, 3:05 am, Paul Rubin wrote: > > > > ecir.h... at gmail.com writes: > > > > > Please, can you elaborate further, I'm not sure if I understood. > > > > Should I lock global variables i, j during the execution of run()? In > > > > that case I have to apologize, I showed rather simplified version of > > > > the actual problem I have - in fact changer() and run() will be a bit > > > > more complex thus executing a bit longer and perhaps causing a dead-lock. > > > > Put both variables into one shared object with a lock (see the docs for > > > threading.RLock()). Acquire the lock before modifying or reading the > > > variables, and release it afterwards. That is the traditional way. > > > Thanks for the reply! And at the same time, please bear with me. > > > If I understand correctly: when one thread acquires the lock, every > > other thread has to wait. If so, this is not exacly what I would like > > to have since the thread might take a bit longer to finish. > > > The reason why I try so hard to use local variables is that they are > > inherently thread-safe. So I don't even mind to copy changer() every > > time run() is called - run() has it's own local variables i, j, no one > > has to touch them except it's ("local") function changer(). But the > > problem is, I don't know how to propagate run()'s variables into > > changer() without declarating them as changer()'s arguments (it would > > be ok to append the declaration during run-time, though, if I only > > knew how). > > In Python, names are bound to objects. The parameter names passed to > a function *are not inherently thread safe*! Python parameters are > not passed-by-value. To show you what I mean: > > >>> spam = ["delicious"] > >>> def test(meal): > > ... global spam > ... if spam is meal: > ... print "Spam is the same object as meal" > ...>>> test(spam) > > Spam is the same object as meal > > (While the "global spam" statement is optional in this case, I wanted > to make it painfully obvious where the "spam" name in function test is > coming from.) > > It is thread-safe to rebind the name "meal" in the function test (ie, > meal = "Green eggs"). It is not thread-safe to mutate or modify the > object that meal is bound to. In the example given above, appending > data to the list, removing data, changing elements, and other > operations will cause potential race conditions across multiple > threads. > > Follow Paul's advice and get acquainted with the issues of concurrent > and threaded programming. Judicious locking will help avoid most race > conditions. If you don't want to keep other threads waiting, make a > copy of your data then release the data lock. > > Depending on the data, you can usually have multiple threads "reading" > the data, as long as no other threads write to the data while there > are any readers. A writer can be allowed to change the data, but only > if there are no readers and no other writers. (This is commonly known > as a read/write lock.) I didn't see a read/write lock in the Python > documentation with some casual browsing, but one can be implemented > from the existing thread locking mechanisms. > > Your description of what you want to do is rather vague, so I can't > get too specific. You've described how you want to do things, but I > don't know what you're trying to accomplish. Where possible, simplify > your design. > > --Jason All I was trying to do, was to get rid of those 'k's in changer(): def change_i(k, arg): k[0] = arg def change_j(k, arg): k[1] = arg def changer(k): change_i(k, 'changed_i') change_j(k, 'changed_j') def run(i='', j=''): k = [i, j] changer(k) [i, j] = k return i, j print run() == ('changed_i', 'changed_j') Maybe I made a mistake, I should have asked this first, sorry. If the only way to accomplish this is through locks, then I guess I better use those 'k's, what do you think? Thanks Jason, thanks Paul! From tleeuwenburg at gmail.com Mon Apr 16 01:09:33 2007 From: tleeuwenburg at gmail.com (tleeuwenburg at gmail.com) Date: 15 Apr 2007 22:09:33 -0700 Subject: Getting started with python In-Reply-To: <1176598011.463543.96990@q75g2000hsh.googlegroups.com> References: <1176598011.463543.96990@q75g2000hsh.googlegroups.com> Message-ID: <1176700173.710433.222600@w1g2000hsg.googlegroups.com> The Python Papers (http://pythonpapers.org) is another resource for Python developers, especially those interested in keeping tabs on the various projects and articles out there in the community. Cheers, -T (Editor-In-Chief, The Python Papers) From slm_guzel at hotmail.com Tue Apr 3 16:52:17 2007 From: slm_guzel at hotmail.com (gslm) Date: 3 Apr 2007 13:52:17 -0700 Subject: doing standart window icons unvisible in python In-Reply-To: <1175625719.902932.36840@l77g2000hsb.googlegroups.com> References: <1175549454.378661.93570@y66g2000hsf.googlegroups.com> <1175625719.902932.36840@l77g2000hsb.googlegroups.com> Message-ID: <1175633537.694987.233110@o5g2000hsb.googlegroups.com> On 3 Nisan, 21:41, "gslm" wrote: > Only I want to print my application's view without these icons,ok. > Thanks. And is it possible to provide .exe file for any program in python or only we can change the file as .pyw? Can you answer this question, too? Regards... From deets at nospam.web.de Sat Apr 21 11:18:29 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sat, 21 Apr 2007 17:18:29 +0200 Subject: Do other Python GUI toolkits require this? In-Reply-To: References: <462697A6.6010007@codebykevin.com> <465B30B4-5BA0-459A-BE6F-1038874FA74B@jedimindworks.com> <58rq32F2fo980U1@mid.uni-berlin.de> Message-ID: <58uoa6F2ii7pcU1@mid.uni-berlin.de> Antoon Pardon schrieb: > On 2007-04-20, Diez B. Roggisch wrote: >>> So if you have the choice between a steep or a shalow income curve >>> you will prefer the shalow curve because a steep curve makes you >>> think about verticale clifs and such? >>> >>> The analogy with a walk is just silly because curves are not like walks. >>> Nobody will say something like: I won't invest in that company because >>> it has a steep profit curve or the reverse: I'll invest in this company >>> because it has an easy looking downhill going profit curve. >> Your whole argumentation bases on the fact that the result of the >> learning process, and the success of it, has something to do with the >> reached height - or y-axis-value - of your climb. >> >> Which is nonsense. The goal is to go from A - ignorance - to B - >> knowledge - which both lie on the X-Axis. > > Well if you want to do it that way, nobody can stop you, but people > in the habit of processing numbers usually put the time on the X-axis > like in time spend learning or exercising and put the other value > on the Y-axis. You seem to live in a very limited world, where bezier-curves (note the name...) are parametrized over t, but rendered on the x/y-axis happily going forth and back and whatnot. If using knowledge as the x-axis and effort on the y-axis, the figure of speech makes perfect sense. > That is because people prefer a curve going up and down while moving > to the right instead of going left and right while moving up. Which is obviously something people don't want to do in this context, because "going down" doesn't make too much sense here, doesn't it? Or do you want to cram the process of unlearning in the little figure of speech as well? But even a perfectly sense-making explanation can be found, I doubt that you will ever acknowledge that you did make a mistake on this one - as you always (or better never) do... From bj_666 at gmx.net Mon Apr 16 04:55:51 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Mon, 16 Apr 2007 10:55:51 +0200 Subject: pyparsing Catch-22 References: <1176686782.270354.164630@l77g2000hsb.googlegroups.com> <1176696704.924584.75720@e65g2000hsc.googlegroups.com> <1176710795.136757.26570@b75g2000hsg.googlegroups.com> Message-ID: In <1176710795.136757.26570 at b75g2000hsg.googlegroups.com>, 7stud wrote: > However, all of the beginning examples use a Word() in the parse > expression, but I couldn't find an adequate explanation of what the > arguments to Word() are and what they mean. I finally found the > information buried in one of the many documents--the one called > "Using the Pyparsing Module". If that seems like an obvious place to > look, I did start there, but I didn't find it at first. An obvious place should be the docstring of the `Word` class which says: Token for matching words composed of allowed character sets. Defined with string containing all allowed initial characters, an optional string containing allowed body characters (if omitted, defaults to the initial character set), and an optional minimum, maximum, and/or exact length. Ciao, Marc 'BlackJack' Rintsch From kw at codebykevin.com Sat Apr 14 21:33:49 2007 From: kw at codebykevin.com (Kevin Walzer) Date: Sat, 14 Apr 2007 21:33:49 -0400 Subject: Seeking list of Python applications on OS X In-Reply-To: References: Message-ID: <462180FD.1050206@codebykevin.com> Kevin Walzer wrote: > Hello, > > I am seeking to update this wiki page, which lists Mac OS X applications > using Python in a significant way: > > http://wiki.python.org/moin/MacPython/MacSoftwareUsingPython > I have updated the page. Thanks to all for their suggestions. -- Kevin Walzer Code by Kevin http://www.codebykevin.com From andrea.valle at unito.it Thu Apr 5 13:28:20 2007 From: andrea.valle at unito.it (Andrea Valle) Date: Thu, 5 Apr 2007 19:28:20 +0200 Subject: ascii-unicode replacement Message-ID: Hi to all, I scripted some text files with another language which cannot handle unicode. As I need special character in the resulting text files (IPA extension), my idea was to define some special ascii sequences in the text files, open the text files in Python, replace the special sequences with unicode and encode in utf8. I made some tests with consolle and everything seemed fine. But my script keeps on raising exceptions related to encoding. Sorry if it's obvious but I really can't figure out what to do. The script follows. Thanks a lot -a- # a class for replacing ascii with unicode import codecs import os class Unicoder: def __init__(self, folder): files = os.listdir(folder) paths = [] for x in files: paths.append(folder+"/"+x) self.files = paths # a list containing all the sc-generated .ly files def intoText(self, inFile): aFile = codecs.open(inFile, "r") text = aFile.read() # read all its content in text return text def replaceSpecials(self, text): replacementDict = ( {"[O]":u"\u0254", "[U]":u"\u0277", "[E]":u"\u025b", "[o|]":u"\xf8", "[oe]":u"\u0153", "[e:]":u"\u0259", "[I]":u"\u026a", "[ae]":u"\xe6", "[A]":u"\u0251", "[Q]":u"\u0252", "[V]":u"\u028c" } ) # hash table where to look up for replacement for ascii in replacementDict: print ascii utf = replacementDict[ascii] text = text.replace(ascii, utf.encode("utf-8")) return text def toFile(self, text, outFileName): outFile = codecs.open(outFileName, encoding='utf-8', mode="w") outFile.write(text) outFile.close() def run(self): for aFileName in self.files: outFileName = aFileName.split(".")[0]+"UTF.ly" text = self.intoText(aFileName) text = self.replaceSpecials(text) self.toFile(text, outFileName) if __name__ == "__main__": a = Unicoder("/musica/antigone/scores/") # EOF -------------------------------------------------- Andrea Valle -------------------------------------------------- CIRMA - DAMS Universit? degli Studi di Torino --> http://www.cirma.unito.it/andrea/ --> andrea.valle at unito.it -------------------------------------------------- I did this interview where I just mentioned that I read Foucault. Who doesn't in university, right? I was in this strip club giving this guy a lap dance and all he wanted to do was to discuss Foucault with me. Well, I can stand naked and do my little dance, or I can discuss Foucault, but not at the same time; too much information. (Annabel Chong) -------------- next part -------------- An HTML attachment was scrubbed... URL: From stj911 at rock.com Sat Apr 7 12:33:19 2007 From: stj911 at rock.com (stj911 at rock.com) Date: 7 Apr 2007 09:33:19 -0700 Subject: Test Tube Zealots: The American Chemical Society Terminates the Membership of Chemists from Iran Message-ID: <1175963599.167629.90830@y80g2000hsf.googlegroups.com> http://counterpunch.org/rahni04072007.html Test Tube Zealots: The American Chemical Society Terminates the Membership of Chemists from Iran By DAVID N. RAHNI The American Chemical Society (ACS) has once again led the way, with its "zealot" interpretation of "embargo" by the Department of Treasury's Office of Foreign Asset Control, by terminating the membership of its long-standing members in Iran, many of whom are post Ph.D. Alumni of American Universities. Several years ago, the ACS undertook a similar unprecedented action, under the same law. Then, it unilaterally stopped accepting scholarly and research manuscripts from Iranian scientists for its three dozen periodicals in the publication division. However, later, under embarrassing pressure from the American scientific community and its membership, the ACS retracted its decision and agreed to take it up instead with the federal government. Paradoxically and notwithstanding rhetoric, such ill- conceived measures are against the current U.S. Administration policy of promoting people-to-people contact as enunciated by the Assistant Secretary of State Nicholas Burns at the March 29 hearing of the Senate Foreign Relations Committee. Yudhijit Bhattacharjee, in Science Magazine, reported that the ACS Assistant General Counsel, David Smorodin when "re-reading the embargo rules, made the recommendation to terminate Iranian membership(Science Magazine, Vol. 315, 30 March 2007). One can not help but speculate whether or not such decision is truly serving the interests of member- based ACS or enforcing the laws to the limit as he has served as a U.S. Assistant District Attorney before joining the ACS. Nonetheless, despite the abrupt termination of individual membership of Iranian chemical scientists with no due process, the ACS has stated that while they [Iranians] can continue to purchase journals and other "non- sensitive products at full-rate, the ACS might apply for a special license from the Treasury Department to reinstate their memberships. This has in the meantime deprived American chemists to learn about the scholarly contributions of their Iranian peers. It should be noted that as in the past, the American Physical Society (APS), in contrast, stated, "We have NO plan to do anything similar, and continue to serve our members in Iran." Judy Franz, a director at the APS further stated that, "We would resist having to obtain a license to the extent we can." When interviewed by Science Magazine, the official publication of the American Association for the Advancement of Science (AAAS), David Rahni an Iranian-American chemistry professor in New York stated, "I, like most ACS members and peers in the scientific community, strongly question the ACS motive on this issue, and expect ACS,s leadership to refrain from allowing politics to taint the high stature the Organization has achieved." Rahni further stated that this has personally concerned him gravely since he has served the ACS with distinctions in the past thirty years, as typified by his positions as the chair of the ACS New York, the chair of the Middle Atlantic Regional Meeting, and the chair of Nichols Medal. 90% of the ACS projects, publications and activities are run by a huge cadre of volunteer professionals who, with no expectations, give their time, energy, money and intellects and talents to the advancement of the chemical sciences worldwide. It is painfully ironic to many, especially the ACS American members to witness the politicization of their disciplines through the ACS as they continue to register their grave concerns with the ACS lucratively remunerated executive directors. As a chemistry professor with having given fifty years of his life to the ACS and the profession so eloquently put it, "Never mind the Iranians as one may not give a darn about them and their plights, what, I am bewildered to speculate the ulterior motives of the ACS paid "professional leadership is to embarrass us as freethinking science. ACS is US and not its DC staff as they are required by our mandate to serve our interests and not create problems for us. The consensus among the nearly one million Americans of Iranian ancestry is to reaffirm their yearning commitment to the attainment of justice, security, stability, equity, transparency and human rights through "home-grown", indigenous and democratic reforms in Iran, but not at the expense of isolating the scientific community in their motherland from their peers worldwide. They further deplore any possible unilateral military action against Iran, as they firmly believe this is counter-productive to the organic, slow, but steady evolution of Iran through educational benchmark, cultural reforms and communication with the rest of the world. They further consider military action and/or isolation counter-productive to the credibility of their American homeland which would inevitably lead, once again, to the priceless loss of human life and loss of credibility for our nation in the international scene. Iran's chemist/chemical engineering professionals/scholars numbers tens of thousands. They are, by and large, members of the Iranian Chemical Society. However, many of them hold at least one overseas membership, mostly in the Royal Societies in the UK. There are currently 36 Iranian members in the American Chemical Society. The strong position of chemistry/chemical engineering in Iran is due to the oil and gas explorations by the petrochemical industry during the past 100 years, and due to some of Iran,s renowned past and contemporary chemists, scientists, and philosophers. The contributions of Americans of Iranian background to the chemistry and sciences, engineering and medicine, is unparalleled by other recent immigrant communities. There indeed exists an Iranian Chemists' Association of the ACS that since its inception in the 80, has reached out to over a thousand chemists of Iranian ancestry in the U.S. alone. It is well substantiated that as long as the diplomatic relations between the two nations remain at a hostile stalemate, a political cloud hovers over the personal and professional aspirations of Iranian-Americans. Specifically, senior and executive level professional opportunities for Iranian-Americans, particularly in government, higher education and the corporate world, remain chronically undermined. Iran, a multiethnic country of 70 million, traces its heritage to a long and illustrious history, 10,000 years in the making, with 2500 years of a continuous form of government. There are two million students in her higher education system, 60% of whom, especially in the sciences, engineering and medicine, are women. Its literacy rate is 90%, unprecedented in that part of the world. Iran or Persia as it was formerly known by the outside world until 1935, has indeed contributed immensely toward the advancement of science, technology and society for millennia. Rhazes, Avicenna, Algorithm, Omer Khayam, Farabi, Biruni, Hayyan, and many others are some of the epics that come to a western scholar,s mind. Despite the tremendous burden imposed on the Iranian students and scholars as they struggle to obtain a US visa (mostly denied) for doctoral studies, some of the brightest graduate students in Ivy League Universities (e.g., Stanford, Harvard, Berkeley, and MIT) are Iranians. Increasingly, however, they opt to pursue their doctoral studies in Australia, Canada and Europe. Iranian high school students have continuously ranked among the top few of the nations in the International Chemistry and other Science Olympiads, and Robotics and Computing Competitions. Isn't it ironic that when the ACS claims to be an international professional society, 130 years old, with a membership of 160,000, 10% of whom are from overseas, and an additional 20%, are naturalized Americans or permanent residents, that it forces the nationals of Iran out, deprives them from maintaining scientific communications with peers worldwide, and does not let them contribute toward the advancement of science worldwide? Notwithstanding the rhetoric and provocations leading to a possible disastrous confrontation by governments, a true scientist, or a credible organization of scientists such as the ACS, which does not recognize the boundaries of the world, should be capable to transcend all political barriers for the advancement of science. David N. Rahni, Ph.D. is a Professor of Chemistry at Pace University, in Pleasantville, New York and Adjunct Professor of Dermatology, New York Medical College. He is also an Adj. Prof. Envirnonmental Law at Pace U. He can be reached at: dnabirahni at pace.edu From carsten at uniqsys.com Mon Apr 23 15:23:42 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Mon, 23 Apr 2007 15:23:42 -0400 Subject: tftpy 0.41 errors In-Reply-To: <1177355851.998724.255140@p77g2000hsh.googlegroups.com> References: <1177355851.998724.255140@p77g2000hsh.googlegroups.com> Message-ID: <1177356222.3442.20.camel@dot.uniqsys.com> On Mon, 2007-04-23 at 12:17 -0700, manhhle at gmail.com wrote: > When trying to import the tftpy package, I've gotten the following > error messages: > > 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 tftpy > Traceback (most recent call last): > File "", line 1, in ? > File "/usr/lib/python2.4/site-packages/tftpy/__init__.py", line 18, > in ? > from TftpServer import * > File "/usr/lib/python2.4/site-packages/tftpy/TftpServer.py", line 50 > % (listenip if listenip else '0.0.0.0', listenport)) That if-else expression is Python 2.5 syntax. Apparently the tftpy package gave you false hope by erroneously allowing you to install it as a Python 2.4 package. -Carsten From nobody at invalid.com Fri Apr 13 16:23:38 2007 From: nobody at invalid.com (Erik Johnson) Date: Fri, 13 Apr 2007 14:23:38 -0600 Subject: Python editor/IDE on Linux? References: <1176488840.672572.101830@y80g2000hsf.googlegroups.com> Message-ID: <461fe699$1@nntp.zianet.com> "7stud" wrote in message news:1176488840.672572.101830 at y80g2000hsf.googlegroups.com... > Jack wrote: > > I wonder what everybody uses for Python editor/IDE on Linux? > > I use PyScripter on Windows, which is very good. Not sure if > > there's something handy like that on Linux. I need to do some > > development work on Linux and the distro I am using is Xubuntu. > > Everybody uses vim. And not just on Linux! ;) From jstroud at mbi.ucla.edu Sat Apr 14 19:57:56 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Sat, 14 Apr 2007 16:57:56 -0700 Subject: optparse -- anyway to find if the user entered an option? In-Reply-To: <1176594561.971801.211710@y80g2000hsf.googlegroups.com> References: <1176594561.971801.211710@y80g2000hsf.googlegroups.com> Message-ID: Karthik Gurusamy wrote: > Hi, > > I see that I can provide a default value for an option. But I couldn't > find out any way if the user really entered the option or the option > took that value because of default. A simple check for value with > default may not always work as the user might have manually > entered the same default value. > > Let's assume I want to take in the ip-address using -i . > If user didn't give it explicitly, I am going to use socket interface > to figure out this host's IP address. > > ip_addr_default = '100.100.100.100' > > parser.add_option("-i", "--ip-address", dest="ip", > default=ip_addr_default, > metavar="IP-ADDRESS", help="IP address. default:" + > ip_addr_default + "e.g. --i=1.1.1.1" > ) > > (options, args) = parser.parse_args() > > Now if options.ip == ip_addr_default, I still can't be 100% sure that > the user did not type -i 100.100.100.100. > Any way to figure out from options that the user typed it or not? > > (The reason I want to know this is if user did not mention -i, I can > compute IP later > using socket module) > > I could think of a hack of using None as default and since no user can > ever > enter a None value, I can be sure that the user didn't provide -i. > I'm wondering if there is a cleaner approach -- something like > parser.opt_seen("-i") > > Thanks, > Karthik > Using None wouldn't be a hack, it would rather be a common and straightforward python idiom. Compare: if parser.opt_seen("-i"): do_whatever() to if options.ip is None: do_whatever() Looks like the second even saves a little typing. After using the former a while, I would venture to guess that you might realize how the latter is actually cleaner. James From vbr at email.cz Wed Apr 18 16:57:22 2007 From: vbr at email.cz (vbr at email.cz) Date: Wed, 18 Apr 2007 22:57:22 +0200 (CEST) Subject: =?us-ascii?Q?Re=3A=20unicode=20data=20=2D=20accessing=20codepoints=20=3E=20FFFF=20on=20narrow=20python=20builts?= In-Reply-To: <462671ca$0$22126$9b622d9e@news.freenet.de> Message-ID: <1351.3067-31625-135915877-1176929842@email.cz> Hi, thanks for your answer, I'll try to check the source of unicodedata; Using the wide Unicode build seems to be a kind of overkill for now, as for the vast majority of my uses, the BMP is enough. I was rather looking for some "lower-cost" alternatives for those rare cases, when I need higher multilingual planes. Thanks again, Vlastimil Brom - vbr > From: "Martin v. L?wis" > Subj.: Re: unicode data - accessing codepoints > FFFF on narrow python builts > Datum: 18.4.2007 21:37:39 > ---------------------------------------- > > Is it a bug in unicodedata, or is this the expected behaviour on a > > narrow build? > > It's a bug. It should either raise an exception, or return the correct > result. If you know feel like submitting a bug report: please try to > come up with a patch instead. > > > Another problem I have is to access the "characters" and their > > properties by the respective codepoints: under FFFF it is possible, > > to use unichr(), which isn't valid for higher valules on a narrow > > build It is possible to derive the codepoint from the surrogate pair, > > which would be usable also for wider codepoints. > > See PEP 261. This is by design. > > > Currently, I'm using a kind of parallel database for some unicode > > ranges above FFFF, but I don't think, this is the most effective way. > > Just use a wide Unicode build instead. > > Regards, > Martin > -- > http://mail.python.org/mailman/listinfo/python-list > > > From erikwickstrom at gmail.com Mon Apr 2 14:43:22 2007 From: erikwickstrom at gmail.com (erikcw) Date: 2 Apr 2007 11:43:22 -0700 Subject: Error when trying to pass list into function. Message-ID: <1175539402.046635.196310@b75g2000hsg.googlegroups.com> Hi, I'm getting the following error when I try to pass a list into a function. My List: crea =[(u'218124172', u'536', u'32394'), (u'218320282', u'1323', u'77931')] Traceback (most recent call last): File "wa.py", line 118, in ? curHandler.walkData() File "wa.py", line 49, in walkData self.results[parent][child]['results'] = self.calculate(crea) #pass in list of tuples TypeError: calculate() takes exactly 1 argument (2 given) def calculate(dta): #stub How can I make this work? Thanks! Erik From Bulkan at gmail.com Thu Apr 26 00:54:57 2007 From: Bulkan at gmail.com (placid) Date: 25 Apr 2007 21:54:57 -0700 Subject: Would You Write Python Articles or Screencasts for Money? In-Reply-To: References: <462DCCE6.9060908@taupro.com><462E0D93.3090705@holdenweb.com> Message-ID: <1177563297.609958.223070@b40g2000prd.googlegroups.com> On Apr 25, 4:40 pm, "Tennessee Leeuwenburg" wrote: > Firstly, let me put up my hand and say that I would be happy to write > Python articles for cash. > I would be happy to write Python articles for a T-shirt with the Python logo printed on it. Maybe each article entrant can receive a t- shirt? Cheers From kyosohma at gmail.com Fri Apr 6 14:11:14 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: 6 Apr 2007 11:11:14 -0700 Subject: HTML Parser in python In-Reply-To: <1175882709.295125.289820@y66g2000hsf.googlegroups.com> References: <1175882709.295125.289820@y66g2000hsf.googlegroups.com> Message-ID: <1175883074.297641.235150@n59g2000hsh.googlegroups.com> On Apr 6, 1:05 pm, "ying... at gmail.com" wrote: > Hi, > > Is there a HTML parser (not xml) in python? > I need a html parser which has the ability to handle mal-format html > pages. > > Thank you. Yeah...it's called Beautiful Soup. http://www.crummy.com/software/BeautifulSoup/ Mike From apardon at forel.vub.ac.be Thu Apr 12 05:53:25 2007 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 12 Apr 2007 09:53:25 GMT Subject: redirecting stdout to a file as well as screen References: <1176362072.527678.201150@l77g2000hsb.googlegroups.com> <1176363641.493358.62560@y5g2000hsa.googlegroups.com> <1176370557.392734.156530@y80g2000hsf.googlegroups.com> Message-ID: On 2007-04-12, SamG wrote: > On Apr 12, 12:40 pm, "Ant" wrote: >> On Apr 12, 8:14 am, "SamG" wrote: >> >> > How could i make, from inside the program, to have the stdout and >> > stderr to be printed both to a file as well the terminal(as usual). >> >> One way would be to create a custom class which has the same methods >> as the file type, and held a list of file-like objects to write to. >> e.g. >> >> class multicaster(object): >> def __init__(self, filelist): >> self.filelist = filelist >> >> def write(self, str): >> for f in self.filelist: >> f.write(str) >> def writelines(self, str_list): >> #etc >> >> Then assign stdout and stderr to a new instance of one of these >> objects: >> >> mc = multicaster([sys.stdout, sys.stderr, log_file]) >> sys.stdout = mc >> sys.stderr = mc >> >> HTH > > > > I have written this.... > > import sys > > class multicaster(object): > def __init__(self, filelist): > self.filelist = filelist > > def write(self, str): > for f in self.filelist: > f.write(str) > > log_file='out.log' log_file is not a file but a string, So when you reach the write method in your multicaster you get an atttribute error because a string has no write method > mc = multicaster([sys.stdout, sys.stderr, log_file]) Since sys.stdout and sys.stderr usually both refer to the terminal, this will result in your output appearing twice on the terminal > sys.stdout = mc > sys.stderr = mc Maybe you are better of leaving sys.stderr as it is, at least until you are sure your multicaster itself is working as it should. > print "Hello" From bearophileHUGS at lycos.com Sat Apr 14 15:08:38 2007 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 14 Apr 2007 12:08:38 -0700 Subject: Making a tree out of a 2 column list In-Reply-To: <1176569321.762908.293800@o5g2000hsb.googlegroups.com> References: <1176569321.762908.293800@o5g2000hsb.googlegroups.com> Message-ID: <1176577718.830238.133040@w1g2000hsg.googlegroups.com> The solution I have found is quite similar to the martinskou at gmail.com one (it uses a defaultdict, and it yields the result lazily), but it lacks the quite useful max_depth (it can be added): from collections import defaultdict def finder(el, stor): if el in stor: for v in stor[el]: yield v for v2 in finder(v, stor): yield v2 data = [[131, 2], [335, 6], [6, 7], [9, 8], [131, 10], [99, 131], [10, 5]] storage = defaultdict(list) for k, v in data: storage[k].append(v) test_data = ([131, [2, 10, 5]], [335, [6, 7]], [9, [8]], ) print storage for k, vals in test_data: assert set(finder(k, storage)) == set(vals) Bye, bearophile From duncan.booth at invalid.invalid Wed Apr 4 04:05:44 2007 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 4 Apr 2007 08:05:44 GMT Subject: Need help on reading line from file into list References: <1175630106.220186.107900@y66g2000hsf.googlegroups.com> <4612b8f2$0$28546$426a74cc@news.free.fr> <1175633434.823351.69800@q75g2000hsh.googlegroups.com> Message-ID: "bahoo" wrote: > I don't see where the "str" came from, so perhaps the output of > "open('source.txt').readlines()" is defaulted to "str? Apart from Grant's explanation that str is the type of a string, what you perhaps haven't yet grasped is that if you have a type and an instance of that type there is an equivalence between calling a method on the instance, or calling the method directly on the type and passing the instance as the first parameter. i.e. Given a type T and an instance I (so that type(I)==T) the following two are equivalent: I.method(args) T.method(I, args) what that means in this particular case is that if you have a string 'line' and want to strip leading and trailing whitespace you can call either: line.strip() or: str.strip(line) So str.strip is just another way to refer to the strip method of a str (but you do have to know that the line is a str rather than another type or it won't work). From rohitsethidce at gmail.com Fri Apr 20 17:17:36 2007 From: rohitsethidce at gmail.com (rohit) Date: 20 Apr 2007 14:17:36 -0700 Subject: service for file monitoring In-Reply-To: References: <1177099611.498274.323180@y5g2000hsa.googlegroups.com> Message-ID: <1177103856.200965.139840@b75g2000hsg.googlegroups.com> On Apr 21, 1:36 am, "Gabriel Genellina" wrote: > En Fri, 20 Apr 2007 17:06:51 -0300, rohit > escribi?: > > > For windows you can use the techniques described here:http://tgolden.sc.sabren.com/python/win32_how_do_i/watch_directory_fo... > > -- > Gabriel Genellina hi, well i tried reading that but that way i'll have to make the program monitor each and every directory. when a file is created or deleted or filename modified , a call must be made to the os kernel . isn't there any way i can utilize that with any api or package functions so that i can monitor the whole filesystem but at lesser expense of cpu n memory regards From pippo at pippo.com Fri Apr 6 04:56:20 2007 From: pippo at pippo.com (Lorenzo Mainardi) Date: Fri, 06 Apr 2007 10:56:20 +0200 Subject: Python on MIPS Message-ID: <46160b35$0$36451$4fafbaef@reader5.news.tin.it> Hi everybody, I bought a very small embedded card, with a MIPS processor, running Linux. So, I would to use Python on that; I checked on python.org, but I did'nt find any release for this architecture. Could you help me? From spamtrap at dot-app.org Sat Apr 14 15:55:24 2007 From: spamtrap at dot-app.org (Sherm Pendley) Date: Sat, 14 Apr 2007 15:55:24 -0400 Subject: Python Feature Request: Allow changing base of member indices to 1 References: <1176546465.632410.52630@w1g2000hsg.googlegroups.com> <1176579205.948684.171640@q75g2000hsh.googlegroups.com> Message-ID: "Paddy" writes: > Having more than one index start point would be a maintenance > nightmare best avoided. Quite right. > (It can be done in Perl). When was the last time you used Perl? It was allowed in Perl 4 and earlier, because many Perl users were moving from Awk, which uses an array base of 1. Even then, having multiple index start points within a single program wasn't the idea; the idea was to allow programs originally written in Awk to be ported to Perl with minimal updating. It was deprecated as of 5.0 though - which was released in '94. It still works, for the sake of backwards compatibility, but its use in new code is highly discouraged. sherm-- -- Web Hosting by West Virginians, for West Virginians: http://wv-www.net Cocoa programming in Perl: http://camelbones.sourceforge.net From antroy at gmail.com Wed Apr 18 14:58:25 2007 From: antroy at gmail.com (Ant) Date: 18 Apr 2007 11:58:25 -0700 Subject: Win32com, and Excel issues. In-Reply-To: <1176901606.433286.225770@q75g2000hsh.googlegroups.com> References: <1176881939.612038.278770@y5g2000hsa.googlegroups.com> <1176901606.433286.225770@q75g2000hsh.googlegroups.com> Message-ID: <1176922705.587663.97940@y80g2000hsf.googlegroups.com> Hi Mike, > I can't find anything about copying a worksheet, but I found a some > fairly detailed information about COM objects and getting more > information about Python's bindings to them here:http://www.oreilly.com/catalog/pythonwin32/chapter/ch12.htmlor here:http://mathieu.fenniak.net/plotting-in-excel-through-pythoncom/ Thanks, I've already seen those pages (in fact I have the book) but no luck. In fact it's worse - I've tested it out on a different machine running Excel 2003, and it works fine :-( Which means that there's another variable at stake here... -- Ant. From irstas at gmail.com Mon Apr 2 11:09:28 2007 From: irstas at gmail.com (irstas at gmail.com) Date: 2 Apr 2007 08:09:28 -0700 Subject: Cascading ifs In-Reply-To: References: Message-ID: <1175526568.481437.266980@e65g2000hsc.googlegroups.com> On Apr 2, 4:20?pm, Ernesto Garc?a Garc?a wrote: > Hi experts, > > How would you do this without the more and more indenting cascade of ifs?: > > match = my_regex.search(line) > if match: > ? ?doSomething(line) > else: > ? ?match = my_regex2.search(line) > ? ?if match: > ? ? ?doSomething2(line) > ? ?else: > ? ? ?match = my_regex3.search(line) > ? ? ?if match: > ? ? ? ?doSomething3(line) > > etc. > > Thanks in advance and regards, > Ernesto You might be able to use "guard clauses": http://www.refactoring.com/catalog/replaceNestedConditionalWithGuardClauses.html match = my_regex.search(line) if match: ? ?doSomething(line) return match = my_regex2.search(line) if match: ? ?doSomething2(line) return But if all of the blocks contain the same code like they do in your example, you're better off using the solutions provided by Wojciech Mu?a and Duncan Booth, because they abstract away the repetition. From newsgroups at nospam.nowire.org Sun Apr 8 02:29:13 2007 From: newsgroups at nospam.nowire.org (=?ISO-8859-15?Q?Thomas_Kr=FCger?=) Date: Sun, 08 Apr 2007 08:29:13 +0200 Subject: Why does not my wx.html.HtmlWindow work? In-Reply-To: <1176003505.794328.62170@n76g2000hsh.googlegroups.com> References: <1176003505.794328.62170@n76g2000hsh.googlegroups.com> Message-ID: liqfemail at gmail.com schrieb: > html.LoadPage(" http://www.pythonthreads.com/articles/python/incorporating-into-wxpython-part-1.html") Quickshot: There's a space at the start of your URI. Thomas From gregpinero at gmail.com Tue Apr 10 14:19:01 2007 From: gregpinero at gmail.com (gregpinero at gmail.com) Date: 10 Apr 2007 11:19:01 -0700 Subject: exec statement Syntax Error on string pulled from MySQL In-Reply-To: References: <1176191064.840339.247160@d57g2000hsg.googlegroups.com> Message-ID: <1176229141.124962.73110@o5g2000hsb.googlegroups.com> On Apr 10, 4:49 am, Georg Brandl wrote: > gregpin... at gmail.com schrieb: > > > > > It's the strangest thing, I'm pulling some text out of a MySQL table > > and trying to run exec on it, and it keeps giving me a syntax error, > > always at the end of the first line. > > > Thanks in advance for any help. I'm really stuck on this one! > > > -Greg > > > I'm not sure what information would be most useful but here's a start: > > > The last code I stored in the table and pulled out was simply: > > print 'greg' > > print 'greg2' > > > To which my error log says: > > Traceback (most recent call last): > > File "/home/public/web/webapi.py", line 303, in wsgifunc > > result = func() > > File "/home/public/web/request.py", line 125, in > > func = lambda: handle(inp, fvars) > > File "/home/public/web/request.py", line 61, in handle > > return tocall(*([urllib.unquote(x) for x in args] + fna)) > > File "/home/public/EZsession.py", line 119, in proxyfunc > > return func(self, *args, **kw) > > File "/home/htdocs/code.py", line 94, in POST > > print utility.run(name,revision,inp) > > File "/home/public/utility.py", line 177, in run > > exec code+'\n' in context > > File "", line 1 > > print 'greg' > > ^ > > SyntaxError: invalid syntax > > (Note the ^ actually appears under after the ' ) > > You have Windows line endings (\r\n) in the string, which Python doesn't like. > > Don't store it like that, or if you must, do a .replace('\r', '') before > exec'ing it. Wow, exec code.replace('\r','') in context works! Now I just have to figure out how the '\r' are getting in there. I entered that piece of code using PHPMyAdmin so that could be doing it, or MySQLdb could be doing it when returning it, or it could be something about the DB encoding! I'll post back if I find out. Thanks for help! -Greg From nagle at animats.com Mon Apr 2 03:17:35 2007 From: nagle at animats.com (John Nagle) Date: Mon, 02 Apr 2007 07:17:35 GMT Subject: Shed Skin Python-to-C++ Compiler 0.0.21, Help needed In-Reply-To: <1175496721.899984.193690@n76g2000hsh.googlegroups.com> References: <576vhbF2ca1guU1@mid.individual.net> <1175376373.241744.6220@y80g2000hsf.googlegroups.com> <1175413310.295953.230840@e65g2000hsc.googlegroups.com> <1175455529.936887.249170@e65g2000hsc.googlegroups.com> <1175496721.899984.193690@n76g2000hsh.googlegroups.com> Message-ID: mark.dufour at gmail.com wrote: > but in any case, I believe there are several reasons why type > inference scalability is actually not _that_ important (as long as it > works and doesn't take infinite time): > > -I don't think we want to do type inference on large Python programs. > this is indeed asking for problems, and it is not such a bad approach > to only compile critical parts of programs (why would we want to > compile PyQt code, for example.) I do think type inference scales well > enough to analyze arbitrary programs of up to, say, 5,000 lines. I'm > not there yet with Shed Skin, but I don't think it's that far away (of > course I'll need to prove this now :-)) > > -type inference can be assisted by profiling Something else worth trying: type inference for separately compiled modules using the test cases for the modules. One big problem with compile-time type inference is what to do about separate compilation, where you have to make decisions without seeing the whole program. An answer to this is to optimize for the module's test cases. If the test cases always use an integer value for a parameter, generate hard code for the case where that variable is a integer. As long as there's some way to back down, at link time, to a more general but slower version, programs will still run. If the test cases reflect normal use cases for the module, this should lead to generation of reasonable library module code cases. > besides, (as john points out I think), there is a difference between > analyzing an actual dynamic language and a essentially static language > (such as the Python subset that Shed Skin accepts). it allows one to > make certain assumptions that make type inference easier. Yes. And, more than that, most programs have relatively simple type behavior for most variables. The exotic stuff just doesn't happen that often. John Nagle From wojciech_mula at poczta.null.onet.pl.invalid Sat Apr 7 11:37:02 2007 From: wojciech_mula at poczta.null.onet.pl.invalid (=?ISO-8859-2?Q?Wojciech_Mu=B3a?=) Date: Sat, 07 Apr 2007 17:37:02 +0200 Subject: Checking whether list element exists In-Reply-To: References: Message-ID: Rehceb Rotkiv wrote: > I want to check whether, for example, the element myList[-3] exists. So > far I did it like this: > > index = -3 > if len(myList) >= abs(index): > print myList[index] IMHO it is good way. > Another idea I had was to (ab-?)use the try...except structure: > > index = -3 > try: > print myList[index] > except: > print "Does not exist!" In general case it won't work, because lists accept negative indexes: http://docs.python.org/lib/typesseq.html, 3rd note. w. From ken at theoryyalgebra.com Wed Apr 18 01:51:57 2007 From: ken at theoryyalgebra.com (Ken Tilton) Date: Wed, 18 Apr 2007 01:51:57 -0400 Subject: is laziness a programer's virtue? In-Reply-To: References: <1176757271.282365.319740@n76g2000hsh.googlegroups.com> <1176797558.403629.53140@b75g2000hsg.googlegroups.com> <1176823224.099381.4630@n59g2000hsh.googlegroups.com> Message-ID: <5miVh.1733$r%3.1346@newsfe12.lga> George Neuner wrote: > On 17 Apr 2007 08:20:24 -0700, Ingo Menger > wrote: > > >>On 17 Apr., 12:33, Markus E Leypold >> wrote: >> >> >>>What makes Xah a troll is neither off-topic posts nor being >>>incoherent -- its the attitude. He's broadcasting his drivel to a >>>number of groups not with the intention to discuss (he hardly ever >>>answers to answers to his posts), but solely with the intention to >>>inform the world at large about his own magnificient thoughts. >> >>This hits the nail on the head. >>Perhaps one could understand this behaviour on cultural grounds. In >>chinese culture it may be not uncommon to write something that merely >>sounds like great wisdom and it is nevertheless appreciated because >>it's a piece of calligraphic art. >> >> >>>Trying to correct Xah's behaviour is probably impossible. >> >>Perhaps somebody could ask the chinese government to put him in jail >>for "hurting international society" :) > > > That's going to be tough because, according to his web page, he's > living in a Honda Civic somewhere in Illinois, USA. Oh, not to fear, we have The Patriots Act, if Dubbya was an Emacs fan Xah would be tanning nicely already at Gitmo. kzo -- http://www.theoryyalgebra.com/ "Algebra is the metaphysics of arithmetic." - John Ray From robert.rawlins at thinkbluemedia.co.uk Mon Apr 16 12:10:27 2007 From: robert.rawlins at thinkbluemedia.co.uk (Robert Rawlins - Think Blue) Date: Mon, 16 Apr 2007 17:10:27 +0100 Subject: Deleting or Empty a File Message-ID: <004001c78041$c022e390$4068aab0$@rawlins@thinkbluemedia.co.uk> I'm looking to clear those log files we were discussing earlier chaps, What the best method to do this? Delete the file completely? Or just empty its content? Thanks, Rob -------------- next part -------------- An HTML attachment was scrubbed... URL: From gagsl-py2 at yahoo.com.ar Mon Apr 9 17:32:59 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 09 Apr 2007 18:32:59 -0300 Subject: output of top on a linux box References: <80628d680704072342r60b57995mad6c505505a919a8@mail.gmail.com> <80628d680704091026u7e98719co3d63a7913832475a@mail.gmail.com> <82d28c40704091032p3c5fcc35p38ee9509ca3fa7c0@mail.gmail.com> <80628d680704091056h735fc0a7l6cf7b586f4bac715@mail.gmail.com> Message-ID: En Mon, 09 Apr 2007 14:56:03 -0300, Pradnyesh Sawant escribi?: > Thanks for the pointer to use /proc/stat > However, that does not answer my other question about string slicing > Any pointers in that direction would be helpful... > >> > top = os.popen("top -n 1") >> > rd = top.read().split("\n") >> > splt = rd[2].split() >> > # cpu = splt[2][:-4] # why ain't this working ??? >> > cpu = splt[2] >> > print "cpu usage: %s, %s" % (cpu, type(cpu)) Print rd[2] above and see how it is formatted. -- Gabriel Genellina From admin at loial.co.uk Thu Apr 12 03:58:54 2007 From: admin at loial.co.uk (loial) Date: 12 Apr 2007 00:58:54 -0700 Subject: Newbie help with array handling Message-ID: <1176364734.439383.252930@o5g2000hsb.googlegroups.com> I am new to python and am converting an awk script to python I need to store some data in an array/table of some form keyvalue1, value1, value2, value3 keyvalue2, value1,value2, value3 keyvalue3, value1,value2,value3 etc I will later need to sort in keyvalue order and also need to be able to check if a key already exists It is not clear how to do this in python. All the examples I see have just a key and a single value From martin at v.loewis.de Mon Apr 16 17:38:40 2007 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Mon, 16 Apr 2007 23:38:40 +0200 Subject: Python and SSL In-Reply-To: <1176737058.203036.53170@n59g2000hsh.googlegroups.com> References: <1176737058.203036.53170@n59g2000hsh.googlegroups.com> Message-ID: <4623ECE0.3010103@v.loewis.de> > - I noticed that socket module provides an SSL class (socket.ssl) but > even if documentation reports that it does not do any certificate > verification a lot of stdlib modules (imaplib, poplib, smtplib, > httplib and urllib2) provides SSL extension classes wherein socket.ssl > is used. What does it mean? It means that these modules can do encrypted communication for their respective protocol. They cannot validate that they are really talking to the server they think they talk to (so they are prone to a man-in-the-middle attack), however, as communication is encrypted, they are protected against wire-tapping. Also, some servers require encrypted connections (e.g. when passwords are transmitted), so they can use SSL for that. > - On top of that why such extension classes [examples: 1, 2, 3] > accepts key-files and cert-files as optional argouments if no > certificate verification occurs? > [1] poplib.POP3_SSL( host[, port[, keyfile[, certfile]]]) > [2] imaplib.IMAP4_SSL( [host[, port[, keyfile[, certfile]]]]) > [3] smtplib.starttls( [keyfile[, certfile]]) These are client certificates. Some servers require that clients authenticate through client certificates. This effectively avoids man-in-the-middle attacks, as the server will validate the client's certificate. > - By searching through the web I found some daemons supporting SSL > such as this one: > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/442473 > By looking at the code I notice that pyopenssl package is used and > that a certificate file is required. Why do I need to use pyopenssl > and how do I generate the cert file? You can generate certificate files using the openssl command line tool; see the openssl documentation for details. Martin From stephen04 at tiscali.co.uk Fri Apr 20 15:26:52 2007 From: stephen04 at tiscali.co.uk (Stephen Lewitowski) Date: Fri, 20 Apr 2007 20:26:52 +0100 Subject: Newbie question regarding string.split() In-Reply-To: <1177095062.826018.63590@n59g2000hsh.googlegroups.com> References: <1177095062.826018.63590@n59g2000hsh.googlegroups.com> Message-ID: <46291402$1_4@mk-nntp-2.news.uk.tiscali.com> kevinliu23 wrote: > Hey guys, > > So I have a question regarding the split() function in the string > module. Let's say I have an string... > > input = "2b 3 4bx 5b 2c 4a 5a 6" > projectOptions = (input.replace(" ", "")).split('2') > print projectOptions > > ['', 'b34bx5b', 'c4a5a6'] > > My question is, why is the first element of projectOptions an empty > string? What can I do so that the first element is not an empty > string? but the 'b34bx5b' string as I expected? > > Thanks so much guys. :) > split on c instead From aleax at mac.com Sun Apr 22 00:56:13 2007 From: aleax at mac.com (Alex Martelli) Date: Sat, 21 Apr 2007 21:56:13 -0700 Subject: Problem redefining __getitem__ for str subclass References: <1177212972.973086.319990@b58g2000hsg.googlegroups.com> Message-ID: <1hwxwvq.31cpz01iszpazN%aleax@mac.com> wrote: > I do not think I am understanding how to redefine the getitem function > for string. Why does the following not work: > > class NStr(str): > def __getitem__(self,idx): > print "NStr:getitem",idx,type(idx) > return str.__getitem__(self,idx) > > s=NStr("abcde") > > print s[1] > print s[1:4:2] > print s[1:2] > > if I run this program (python 2.5; Mac OSX) i get: > > $ python strProb.py > NStr:getitem 1 > b > NStr:getitem slice(1, 4, 2) > bd > b > > ie the last statement (s[1:2]) with a simple slice does not call the > new __getitem__???? What am I missing. For backwards compatibility, slicing without a step on some ancient built-in types (including strings, but also lists) goes to __getslice__ (an otherwise obsolete method) instead of __getitem__. Simply, override __getslice__ by properly delegating from it to __getitem__. Alex From KDawg44 at gmail.com Tue Apr 10 14:54:18 2007 From: KDawg44 at gmail.com (KDawg44) Date: 10 Apr 2007 11:54:18 -0700 Subject: Parsing log in SQL DB to change IPs to hostnames In-Reply-To: <1176221494.813800.78580@y80g2000hsf.googlegroups.com> References: <1176219463.407804.315560@y80g2000hsf.googlegroups.com> <1176221494.813800.78580@y80g2000hsf.googlegroups.com> Message-ID: <1176231258.626137.228220@d57g2000hsg.googlegroups.com> On Apr 10, 11:11 am, "Kushal Kumaran" wrote: > On Apr 10, 8:37 pm, "KDawg44" wrote: > > > > > Hi, > > > I am brand new to Python. In learning anything, I find it useful to > > actually try to write a useful program to try to tackle an actual > > problem. > > > I have a syslog server and I would like to parse the syslog messages > > and try to change any ips to resolved hostnames. Unfortunately, I am > > not getting any matches on my regular expression. > > > A message will look something like this: > > Apr 10 2007 00:30:58 DEVICE : %DEVICEINFO: 1.1.1.1 Accessed URL > > 10.10.10.10:/folder/folder/page.html > > > I would like to change the message to have the hostnames, or even > > better actually, have it appear as hostname-ip address. So a changed > > message would look like: > > > Apr 10 2007 00:30:58 DEVICE : %DEVICEINFO: pcname-1.1.1.1 Accessed > > URLwww.asite.com-10.10.10.10:/folder/folder/page.html > > > or some equivalent. > > > Here is what i have so far. Please be kind as it is my first python > > program.... :) > > > #! /usr/bin/python > > > import socket > > import re > > import string > > import MySQLdb > > > ipRegExC = r"\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}" > > ipRegEx = re.compile(ipRegExC) > > > try: > > conn = MySQLdb.connect(host="REMOVED", user="REMOVED", > > passwd="REMOVED", db="REMOVED") > > > except MySQLdb.Error, e: > > print "Error connecting to the database: %d - %s " % > > (e.args[0], e.args[1]) > > sys.exit(1) > > > cursor = conn.cursor() > > cursor.execute("SELECT msg, seq FROM REMOVED WHERE seq = 507702") > > # one specific message so that it doesn't parse the whole DB during > > testing... > > while(1): > > row = cursor.fetchone() > > if row == None: > > break > > if ipRegEx.match(row[0]): > > .... > > > > See the documentation of the re module for the difference between > matching and searching. > > -- > Kushal Thank you very much. I think I have it figured out, except for an error on the SQL statement: [----- BEGIN ERROR ---] Traceback (most recent call last): File "changeLogs.py", line 47, in ? cursor.execute("""UPDATE logs SET msg = %s WHERE seq = %i""", (newMsg,seqNum)) File "/usr/lib/python2.4/site-packages/MySQLdb/cursors.py", line 148, in execute query = query % db.literal(args) TypeError: int argument required [----- END ERROR ---] Here is my code [----- BEGIN CODE ---] #! /usr/bin/python import socket import sys import re import string import MySQLdb def resolveHost(ipAdds): ipDict = {} for ips in ipAdds: try: ipDict[ips] = socket.gethostbyaddr(ips)[0] except: ipDict[ips] = "Cannot resolve" return ipDict ipRegExC = r"\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}" ipRegEx = re.compile(ipRegExC) try: conn = MySQLdb.connect(host="REMOVED", user="REMOVED", passwd="REMOVED", db="REMOVED") except MySQLdb.Error, e: print "Error connecting to the database: %d - %s " % (e.args[0], e.args[1]) sys.exit(1) cursor = conn.cursor() cursor.execute("SELECT msg, seq FROM `logs` WHERE seq = 507702") while(1): row = cursor.fetchone() ipAddresses = [] resolvedDict = {} if row == None: break if ipRegEx.search(row[0]): seqNum = row[1] ipAddresses = ipRegEx.findall(row[0]) resolvedDict = resolveHost(ipAddresses) newMsg = row[0] for ip in resolvedDict.keys(): newMsg = newMsg.replace(ip,ip + "-" + resolvedDict[ip]) cursor.execute("""UPDATE REMOVED SET msg = %s WHERE seq = %i""", (newMsg,seqNum)) [----- END CODE ---] Thanks again! From erikwickstrom at gmail.com Thu Apr 5 19:31:47 2007 From: erikwickstrom at gmail.com (erikcw) Date: 5 Apr 2007 16:31:47 -0700 Subject: Extract zip file from email attachment Message-ID: <1175815907.434721.274190@w1g2000hsg.googlegroups.com> Hi all, I'm trying to extract zip file (containing an xml file) from an email so I can process it. But I'm running up against some brick walls. I've been googling and reading all afternoon, and can't seem to figure it out. Here is what I have so far. p = POP3("mail.server.com") print p.getwelcome() # authentication, etc. print p.user("USER") print p.pass_("PASS") print "This mailbox has %d messages, totaling %d bytes." % p.stat() msg_list = p.list() print msg_list if not msg_list[0].startswith('+OK'): # Handle error exit(1) for msg in msg_list[1]: msg_num, _ = msg.split() resp = p.retr(msg_num) if resp[0].startswith('+OK'): #print resp, '=======================\n' #extract message body and attachment. parsed_msg = email.message_from_string('\n'.join(resp[1])) payload= parsed_msg.get_payload(decode=True) print payload #doesn't seem to work else: pass# Deal with error retrieving message. How do I: a) retrieve the body of the email into a string so I can do some processing? (I can get at the header attributes without any trouble) b) retrieve the zip file attachment, and unzip into a string for xml processing? Thanks so much for your help! Erik From sjdevnull at yahoo.com Tue Apr 24 19:35:41 2007 From: sjdevnull at yahoo.com (sjdevnull at yahoo.com) Date: 24 Apr 2007 16:35:41 -0700 Subject: Tutorial creates confusion about slices In-Reply-To: References: Message-ID: <1177457741.037238.315050@r35g2000prh.googlegroups.com> Antoon Pardon wrote: > On 2007-04-24, Michael Bentley wrote: > > > > On Apr 24, 2007, at 6:35 AM, Antoon Pardon wrote: > > > >> People don't read tutorials in a strictly linear fashion. They can > >> continue to later subjects and then come back here to see how things > >> tie together. So the fact that it is only confusing to those who > >> know more than is already presented doesn't seem a very good reason > >> to leave it in. > > > > Yet they understand that earlier in the document, there is likely to > > be a less complete coverage of a given topic. There is in fact, a > > link on that page that includes a more complete coverage of that > > topic (which I mentioned to you in an earlier message IIRC). > > That there is more complete coverage elsewhere is no good reason > to come with an explanation that suggests things working in > a way that will be contradicted by that more complete coverage. I happen to agree with you, but that's not a completely non- controversial position. Many tutorials/manuals will prevent a simplified (and incorrect for the general case) description of how something works early on, and then clarify it later for the general case. Personally I'd usually rather have the complete description earlier rather than an incorrect simplification, or at least have a footnote to the effect of "this is a simple introduction, the full behavior will be described later". But there's a good argument to be made for omitting confounding details early on in a tutorial if there's a pedogogical reason for doing so--indeed, there's such a widespread belief that early oversimplification is actually helpful that I'd guess the majority of language tutorials engage in it to some degree. See, for instance, the C Tutorial at http://einstein.drexel.edu/courses/CompPhys/General/C_basics/ ; it contains all kinds of statements like "The while loop continues to loop until the conditional expression becomes false." (no mention of "break", which is mentioned later in the section only as a way to break out of an infinite loop). It also consistently uses "void main()" to declare main, which is simply not correct C (though it's accepted by many compilers)--but given that _many_ tutorials, and _many_ published books make similar decisions, it's not quite as simple as saying "that's just wrong. Do it right!". Rather, it seems that a certain segment of teachers have decided that oversimplification in early instruction, even when it's erroneous, can be a better way to get the point across than trying to convey all the details at once. What's my point? This is really in a large part a discussion about the philosophy of such tutorials--is it a bad idea to present simplifications that are incorrect in general? Or does it actually help people get up to speed so much faster that it's worth it even if a bit of time has to be taken later to re-teach the full details? I think that philisophical debate needs to be had before attacking individual cases in the docs that use such simplifications. From robert.rawlins at thinkbluemedia.co.uk Mon Apr 16 10:57:10 2007 From: robert.rawlins at thinkbluemedia.co.uk (Robert Rawlins - Think Blue) Date: Mon, 16 Apr 2007 15:57:10 +0100 Subject: Writing Log CSV (Efficiently) In-Reply-To: <46238800.1000302@timgolden.me.uk> References: <7554276584215132819@unknownmsgid> <6e42ec490704160700i20469453j6af39db62dd6b427@mail.gmail.com> <17955.33861.211843.361355@montanaro.dyndns.org> <002a01c78032$27190620$754b1260$@rawlins@thinkbluemedia.co.uk> <46238800.1000302@timgolden.me.uk> Message-ID: <003601c78037$879b5890$96d209b0$@rawlins@thinkbluemedia.co.uk> Thanks for that Tim, I could use a little more help with this CSV stuff this afternoon and I can't get it to write the output I want for the life of me. I'm trying to write a method for my logging class that receives a string as an argument, and then writes a row to the CSV with the string and a date/time stamp. ''' Add Application Log Entry ''' def addApp(self, event): writer = csv.writer(open("some.csv", "a")) writer.writerow(event) Now if I do something like this; addApp('Application Started') then it writes to the CSV file somthing like. A,p,p,l,i,c,a,t,i,o,n, ,S,t,a,r,t,e,d Which isn't much use to me :-D any ideas how I can get something like this: 2007-01-01,13:00:00,Application Started Thanks, Rob -----Original Message----- From: python-list-bounces+robert.rawlins=thinkbluemedia.co.uk at python.org [mailto:python-list-bounces+robert.rawlins=thinkbluemedia.co.uk at python.org] On Behalf Of Tim Golden Sent: 16 April 2007 15:28 Cc: python-list at python.org Subject: Re: Writing Log CSV (Efficiently) Robert Rawlins - Think Blue wrote: > The log at its highest rate of write may be looking at an operation a > second I think I can probably type stuff in faster than that if I try :) You probably don't have a performance issue there. , I've not got much experience with this kind of thing so I'm not sure > if that's 'a lot' or not, it just seems like it at the moment. It might not > get as busy as that, I'm not sure and its difficult to simulate as this > isn't likely to be a steady flow of traffic, they'll come in big fat lumps > every now and then. Sounds like you don't really need to profile that, but if you did, Python's a great language for knocking together that kind of test harness; combine the time, random and csv modules and you've got a "big fat lumps every now and then" simulation. (At which point I get jumped on by the serious model types for being so blase with their discipline!) TJG -- http://mail.python.org/mailman/listinfo/python-list From olsonas at gmail.com Tue Apr 24 16:35:30 2007 From: olsonas at gmail.com (Drew) Date: 24 Apr 2007 13:35:30 -0700 Subject: Blank rows resulting from simple csv script Message-ID: <1177446930.186383.213470@r35g2000prh.googlegroups.com> Hi all - I've written a simple script to read a .csv file and then write out rows to a new file only if the value in the 4th column is a 0. Here's the code: import csv reader = csv.reader(open('table_export.csv','rb')) writer = csv.writer(open('new_jazz.csv','w')) for row in reader: if row[3] == '0': writer.writerow(row) This is writing out the correct rows, however it is writing a blank row between each of the rows written out. Any ideas? Thanks, Drew From slug57_98 at yahoo.com Thu Apr 12 17:50:12 2007 From: slug57_98 at yahoo.com (Chad) Date: 12 Apr 2007 14:50:12 -0700 Subject: Need help with the get() method of a Text entry In-Reply-To: References: <1176409717.585710.184960@y80g2000hsf.googlegroups.com> Message-ID: <1176414612.620268.200780@e65g2000hsc.googlegroups.com> On Apr 12, 5:03 pm, James Stroud wrote: > James Stroud wrote: > > Chad wrote: > > >> I have a simple little program that brings up asks the user to enter a > >> note, then is supposed to place that note into a text file when the > >> user hits the submit button. However, when the user hits the submit > >> button, absolutely nothing happens. IDLE doesn't give an error > >> message and the note is not entered into the text file. For > >> troubleshooting puposes, I wanted to see if IDLE would at least print > >> the user's input; it doesn't do that either. Can someone please help > >> me? > > >> Here is the code: > > >> from Tkinter import * > > >> class Application(Frame): > >> """ GUI application that creates a story based on user input. """ > >> def __init__(self, master): > >> """ Initialize Frame. """ > >> Frame.__init__(self, master) > >> self.grid() > >> self.create_widgets() > > >> def create_widgets(self): > >> """ Create widgets to get note information. """ > >> # create instruction label and text entry for notes > >> Label(self, > >> text = "Notes" > >> ).grid(row = 0, column = 0, columnspan = 2 ) > > >> self.notes_ent = Text(self, width = 75, height = 10, wrap = > >> WORD) > >> self.notes_ent.grid(row = 2, column = 0 ,columnspan = 7, > >> rowspan = 3, sticky = W) > >> create submit button > >> text1 = StringVar(self) > >> text1 = self.notes_ent.get(1.0, END) > >> self.notes_ent.config(state=NORMAL) > >> Button(self, > >> text = "Add Note", > >> command = self.add_note(text1) > >> ).grid(row = 1, column = 0, sticky = W) > > >> def add_note(self, text1): > >> print text1 > >> text_file = open("write_it.txt", "a+") > >> text_file.write(text1) > > >> root = Tk() > >> root.title("Mad Lib") > >> app = Application(root) > >> root.mainloop() > > > On second look, it seems you have deeper problems, some of which are: > > > > text1 = StringVar(self) > > > text1 = self.notes_ent.get(1.0, END) > > > You obviously added the second because the first will never work. Get > > rid of both lines. Even if you intended the second, it immediately > > nullifies the first. Instead of my previous suggestions, do this: > > > 1. delete both "text1 =" lines > > 2. change "command = self.add_note(text1)" to > > "command = self.add_note" > > 3. change "def add_note(self, text1):" to > > "def add_note(self):" > > 4. delete "print text1" > > 5. change "text_file.write(text1)" to > > "text_file.notes_ent.get(1.0, END) > > > James > > Or rather > 5. change "text_file.write(text1)" to > "text_file.write(self.notes_ent.get(1.0, END))" Thank you, that worked very well. From reder at ieee.org Sun Apr 15 21:08:27 2007 From: reder at ieee.org (Leonard J. Reder) Date: Mon, 16 Apr 2007 01:08:27 GMT Subject: Python and XML? In-Reply-To: <4621F54A.3010008@web.de> References: <46209A55.9070102@web.de> <46217DAE.7040501@ieee.org> <4621F54A.3010008@web.de> Message-ID: Stefan Behnel wrote: > Leonard J. Reder wrote: >> What I as really after though was other possible solutions >> like JAX in the Java world or Gnosis in the Python world. >> >> Something that can take a Relax NG Schema and compile >> it into a bunch of parser/generator objects for handling >> an XML format. > > That's why I was asking why you need this. Validation is provided by RNG > itself, so all you would need is some kind of mapping that outputs and parses > it for you? What's your target format? Python objects? > > http://codespeak.net/lxml/objectify.html > > Stefan My target format are Python objects. What I want to do is auto-covert the Relax NG Schema into Python API objects that can be used to intelligently read in an XML file. Our XML files specify interfaces to flight software but in the future I have an interest in using XMI to do more complete modeling of software. Hopefully the OMG publishes a stand XMI schema. Looks like this stuff might do what I want. Need to work through the example. Are you the author? Why is this better then using gnossis? Thanks, Len -- =================================== Leonard J. Reder Home office email : reder at ieee.org Lab email : reder at jpl.nasa.gov Lab web page : http://reder.jpl.nasa.gov =================================== From aleax at mac.com Sat Apr 7 13:04:32 2007 From: aleax at mac.com (Alex Martelli) Date: Sat, 7 Apr 2007 10:04:32 -0700 Subject: block scope? References: <7xr6qwal50.fsf@ruckus.brouhaha.com> <7xtzvseqzo.fsf@ruckus.brouhaha.com> Message-ID: <1hw72cg.115yokgarr9enN%aleax@mac.com> Neal Becker wrote: ... > > i = 5 > > for my i in xrange(4): > > if i: # skips first when i is 0 > > my i = 100 > > if i: > > print i # of course 100 > > break > > print i # i is between 0 & 3 here > > print i # i is 5 here > > > > > > Doesn't leave a particularly bad taste in one's mouth, I guess (except > > for the intended abuse). > > > > James > > Yes, the above is pretty much what I had in mind. +1. I prefer Java's approach (14.4.2 in the JLS 2nd edition): forbid "inner" blocks from shadowing variables in "outer" ones. I quote: """ If a declaration of an identifier as a local variable of the same method, constructor, or initializer block appears within the scope of a parameter or local variable of the same name, a compile-time error occurs. Thus the following example does not compile: class Test { public static void main(String[] args) { int i; for (int i = 0; i < 10; i++) System.out.println(i); } } This restriction helps to detect some otherwise very obscure bugs. """ I entirely agree with the JLS here, having fought just such bugs in C++ and other languages that lack the restriction in question. I just wish Python had adopted the same restriction regarding nested functions, when proper lexical scoping was introduced -- I argued for it at the time, but backwards compatibility blocked its introduction. There are definitely NOT many Java-specific language characteristics that I like, but this one is a winner!-) [[but, I disagree with the lack in Java of a similar restriction against shadowing between instance variables and local variables, and the weak rationale for that in the JLS:-)]]. Alex From rhamph at gmail.com Fri Apr 20 02:41:18 2007 From: rhamph at gmail.com (Rhamphoryncus) Date: 19 Apr 2007 23:41:18 -0700 Subject: Python's handling of unicode surrogates In-Reply-To: <0QXVh.16735$M.14016@news-server.bigpond.net.au> References: <0QXVh.16735$M.14016@news-server.bigpond.net.au> Message-ID: <1177051278.104348.107370@e65g2000hsc.googlegroups.com> On Apr 19, 11:02 pm, Neil Hodgson wrote: > Adam Olsen: > > > To solve this I propose Python's unicode type using UTF-16 should have > > gaps in its index, allowing it to only expose complete unicode scalar > > values. Iteration would produce surrogate pairs rather than > > individual surrogates, indexing to the first half of a surrogate pair > > would produce the entire pair (indexing to the second half would raise > > IndexError), and slicing would be required to not separate a surrogate > > pair (IndexError otherwise). > > I expect having sequences with inaccessible indices will prove > overly surprising. They will behave quite similar to existing Python > sequences except when code that works perfectly well against other > sequences throws exceptions very rarely. "Errors should never pass silently." The only way I can think of to make surrogates unsurprising would be to use UTF-8, thereby bombarding programmers with variable-length characters. > > Reasons to treat surrogates as undivisible: > > * \U escapes and repr() already do this > > * unichr(0x10000) would work on all unicode scalar values > > unichr could return a 2 code unit string without forcing surrogate > indivisibility. Indeed. I was actually surprised that it didn't, originally I had it listed with \U and repr(). > > * "There is no separate character type; a character is represented by > > a string of one item." > > Could amend this to "a string of one or two items". > > > * iteration would be identical on all platforms > > There could be a secondary iterator that iterates over characters > rather than code units. But since you should use that iterator 90%+ of the time, why not make it the default? > > * sorting would be identical on all platforms > > This should be fixable in the current scheme. True. > > * UTF-8 or UTF-32 containing surrogates, or UTF-16 containing isolated > > surrogates, are ill-formed[2]. > > It would be interesting to see how far specifying (and enforcing) > UTF-16 over the current implementation would take us. That is for the 16 > bit Unicode implementation raising an exception if an operation would > produce an unpaired surrogate or other error. Single element indexing is > a problem although it could yield a non-string type. Err, what would be the point in having a non-string type when you could just as easily produce a string containing the surrogate pair? That's half my proposal. > > Reasons against such a change: > > * Breaks code which does range(len(s)) or enumerate(s). This can be > > worked around by using s = list(s) first. > > The code will work happily for the implementor and then break when > exposed to a surrogate. The code may well break already. I just make it explicit. > > * "Nobody is forcing you to use characters above 0xFFFF". This is a > > strawman. Unicode goes beyond 0xFFFF because real languages need it. > > Software should not break just because the user speaks a different > > language than the programmer. > > Characters over 0xFFFF are *very* rare. Most of the Supplementary > Multilingual Plane is for historical languages and I don't think there > are any surviving Phoenician speakers. Maybe the extra mathematical > signs or musical symbols will prove useful one software and fonts are > implemented for these ranges. The Supplementary Ideographic Plane is > historic Chinese and may have more users. Yet Unicode has deemed them worth including anyway. I see no reason to make them more painful then they have to be. A program written to use them today would most likely a) avoid iteration, and b) replace indexes with slices (s[i] -> s[i:i +len(sub)]. If they need iteration they'll have to reimplement it, providing the exact behaviour I propose. Or they can recompile Python to use UTF-32, but why shouldn't such features be available by default? > I think that effort would be better spent on an implementation that > appears to be UTF-32 but uses UTF-16 internally. The vast majority of > the time, no surrogates will be present, so operations can be simple and > fast. When a string contains a surrogate, a flag is flipped and all > operations go through more complex and slower code paths. This way, > consumers of the type see a simple, consistent interface which will not > report strange errors when used. Your solution would require code duplication and would be slower. My solution would have no duplication and would not be slower. I like mine. ;) > BTW, I just implemented support for supplemental planes (surrogates, > 4 byte UTF-8 sequences) for Scintilla, a text editing component. I dream of a day when complete unicode support is universal. With enough effort we may get there some day. :) -- Adam Olsen, aka Rhamphoryncus From bbxx789_05ss at yahoo.com Mon Apr 23 19:36:35 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: 23 Apr 2007 16:36:35 -0700 Subject: Learning Python - First Project In-Reply-To: References: <1177339942.371167.93970@b75g2000hsg.googlegroups.com> <1177367541.059834.18420@o5g2000hsb.googlegroups.com> <1177367890.088488.93290@l77g2000hsb.googlegroups.com> Message-ID: <1177371395.909707.24460@e65g2000hsc.googlegroups.com> On Apr 23, 5:04 pm, Kevin Haynes wrote: > Hello > > I was a python newbie just a month ago and found the following books a great > help. > > Beginning Python: From Novice to Professional (Beginning: From Novice to > Professional) by Magnus L. Hetland (Paperback - 29 Sep 2005)http://www.amazon.co.uk/Beginning-Python-Novice-Professional/dp/15905... > > WxPython in Action by Noel Rappin and Robin Dunn (Paperback - 30 Mar 2006)http://www.amazon.co.uk/WxPython-Action-Noel-Rappin/dp/1932394621/ref... > > Kevin > > On Monday 23 April 2007, 7stud wrote: > > > Uhhmm...how are you supposed to close a ShapedWindow(under > > Miscellaneous)? I am reading both now, and I would not recommend either one. If you just skim over the examples and don't play with them, you might mistakenly believe you know what's going on, but if you actually try the examples and alter them here and there to figure out how things really work, you will discover all the mistakes and gaps in both books. From Plissken.s at gmail.com Sun Apr 1 19:22:47 2007 From: Plissken.s at gmail.com (Plissken.s at gmail.com) Date: 1 Apr 2007 16:22:47 -0700 Subject: How can i compare a string which is non null and empty Message-ID: <1175469766.979636.65020@e65g2000hsc.googlegroups.com> Hi, how can i compare a string which is non null and empty? i look thru the string methods here, but cant find one which does it? http://docs.python.org/lib/string-methods.html#string-methods In java,I do this: if (str != null) && (!str.equals("")) .... how can i do that in python? From ah at hatzis.de Thu Apr 26 08:11:45 2007 From: ah at hatzis.de (Anastasios Hatzis) Date: Thu, 26 Apr 2007 14:11:45 +0200 Subject: Which are your favorite UML tools? Message-ID: <200704261411.45542.ah@hatzis.de> Hello, I'm working on the light-weight MDA tool pyswarm, http://pyswarm.sourceforge.net/ (it is about a code-generator for Python/PostgreSQL-based software. I plan to add support of UML CASE tools other than the one supported currently. I would like to learn which UML tools you use (if any), preferrably if it comes to modeling a Python application. So I'm asking you to tell me the name of your favorite UML CASE tool(s). Please also provide the version of the tool you use (and perhaps also the URL of the project/vendor). If this is not of general interest for this list you can also reply directly to my email address. Thank you in advance. Best regards Anastasios From kelvin.you at gmail.com Sun Apr 29 08:18:15 2007 From: kelvin.you at gmail.com (=?utf-8?B?5Lq66KiA6JC95pel5piv5aSp5rav77yM5pyb5p6B5aSp5rav5LiN6KeB5a62?=) Date: 29 Apr 2007 05:18:15 -0700 Subject: Could zipfile module process the zip data in memory? In-Reply-To: References: <1177845313.798239.71580@o5g2000hsb.googlegroups.com> <1177847479.803195.12820@c35g2000hsg.googlegroups.com> Message-ID: <1177849095.901489.107770@p77g2000hsh.googlegroups.com> On Apr 29, 8:14?pm, "Daniel Nogradi" wrote: > > > > I made a C/S network program, the client receive the zip file from the > > > > server, and read the data into a variable. how could I process the > > > > zipfile directly without saving it into file. > > > > In the document of the zipfile module, I note that it mentions the > > > > file-like object? what does it mean? > > > > > class ZipFile( file[, mode[, compression[, allowZip64]]]) > > > > ? ? ? ? ?Open a ZIP file, where file can be either a path to a file (a > > > > string) or a file-like object. > > > > Yes it is possible to process the content of the zipfile without > > > saving every file: > > > > [untested] > > > > ? ? ? ? from zipfile import ZipFile > > > ? ? ? ? from StringIO import StringIO > > > > ? ? ? ? zipp = ZipFile( this_is_the_zip_file_from_your_server, 'r' ) > > > ? ? ? ? for name in zipp.namelist( ): > > > ? ? ? ? ? ? ? ? content = zipp.read( name ) > > > ? ? ? ? ? ? ? ? s = StringIO( ) > > > ? ? ? ? ? ? ? ? s.write( content ) > > > ? ? ? ? ? ? ? ? # now the file 'name' is in 's' (in memory) > > > ? ? ? ? ? ? ? ? # you can process it further > > > ? ? ? ? ? ? ? ? # ............ > > > ? ? ? ? ? ? ? ? s.close( ) > > > ? ? ? ? zipp.close( ) > > > > HTH, > > > Daniel > > Thanks! > > Maybe my poor english makes you confusion:-). The client receive the > > zip file data from the server, and keep these data as a variable, not > > as a file in harddisk. such as "zipFileData", but the first argument > > of the "ZipFile" is filename. I would like to let the ZipFile() open > > the file from "zipFileData" directly but not file in harddisk > > > zipp = ZipFile( this_is_the_zip_file_from_your_server, 'r' ) > > ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ^ I don't have this file, all its data > > is in a variable. > > Well, as you correctly pointed out in your original post ZipFile can > receive a filename or a file-like object. If the zip archive data is > in zipFileData then you might do: > > from StringIO import StringIO > from zipfile import ZipFile > > data = StringIO( ) > data.write( zipFileData ) > data.close( ) > > zipp = ZipFile( data ) > ......... > > and continue in the same way as before. > > Daniel- Hide quoted text - > > - Show quoted text - Thanks all of your kindly help! From nagle at animats.com Sat Apr 21 14:36:06 2007 From: nagle at animats.com (John Nagle) Date: Sat, 21 Apr 2007 18:36:06 GMT Subject: newbie: HTTPS screen scraping In-Reply-To: References: Message-ID: user at domain.invalid wrote: > Hi, > Can anyone help me out here. I would like to authenticate myself to a > website which uses HTTPS and then after authentication, I would like to > get the contents of the webpage. How can this be done using python. > I have tried urllib and urllib2 but it has not solved my problem. > > TIA > /varun Most of the various URL libraries (urllib, urllib2, and pycurl) can do this. With "urllib", you can subclass FancyURLopener, then redefine "get_user_passwd(self, host, realm, clear_cache=0)" in the subclass. That function will be called when a password is needed, and you return (username, password) as a tuple, which gets sent to the web server. Python, instead of having one library for reading URLs that works, has at least three, all with different problems. John Nagle From bbxx789_05ss at yahoo.com Wed Apr 4 14:41:49 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: 4 Apr 2007 11:41:49 -0700 Subject: operator overloading In-Reply-To: <1175679412.741899.45990@l77g2000hsb.googlegroups.com> References: <1175679412.741899.45990@l77g2000hsb.googlegroups.com> Message-ID: <1175712109.655293.296720@o5g2000hsb.googlegroups.com> On Apr 4, 3:36 am, "looping" wrote: > Hi, > for the fun I try operator overloading experiences and I didn't > exactly understand how it works. > > Here is my try:>>> class myint(int): > > def __pow__(self, value): > return self.__add__(value) > > >>> a = myint(3) > >>> a ** 3 > > 6 > > OK, it works. Now I try different way to achieve the same result but > without much luck: > > > > >>> class myint(int): > pass > >>> myint.__pow__ = myint.__add__ > > or:>>> class myint(int): > > __pow__ = int.__add__ > > or: > > >>> class myint(int): > pass > >>> a.__pow__ = a.__add__ > > but for every try the result was the same:>>> a = myint(3) > >>> a ** 3 > > 27 > > Why it doesn't works ? Look at the output of the following code: class myint(int): pass print myint.__pow__ print myint.__add__ -----output:----- That shows that the names '__pow__' and '__add__' are __slots__. According to Python in a Nutshell(p.102), a name that is a slot can only be "bound"(i.e. assigned to) inside the class body. Any later attempt to assign something to a name that is a slot has no effect. In your case, I think that means that the only place you can assign something to an int slot is inside the int class. As an alternative, you could override __pow__(). Something like this: class myint(int): def __pow__(self, num): return super(myint, self).__add__(num) n = myint(3) print n**3 ---output:--- 6 That doesn't attempt to reassign something to the slot int.__pow__; rather it creates a new __pow__ name that hides int.__pow__. From gagsl-py2 at yahoo.com.ar Tue Apr 24 08:02:49 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 24 Apr 2007 09:02:49 -0300 Subject: Catching a specific IO error References: Message-ID: En Tue, 24 Apr 2007 08:44:05 -0300, Tina I escribi?: > Hi group :) > > I have this standard line: > > export = open(self.exportFileName , 'w') > > 'exportFileName' is a full path given by the user. If the user gives an > illegal path or filename the following exception is raised: > "IOError: [Errno 2] No such file or directory: /some/path/file.txt" > > So at the moment I do this: > > try: > export = open(self.exportFileName , 'w') > export.write("Something") > export.close() > except IOError: > # calling an error handling method. > > Now, this works but of course it catches every IOError, and I can not > figure out how to restrict it to only catch the "[Errno 2]"? You can get the 2 as the errno exception attribute. BTW, 2 == errno.ENOENT try: export = open(self.exportFileName , 'w') except IOError, e: if e.errno==errno.ENOENT: # handle the "No such file or directory" error # calling an error handling method. See http://docs.python.org/lib/module-exceptions.html -- Gabriel Genellina From leuchte at gmail.com Wed Apr 25 10:08:42 2007 From: leuchte at gmail.com (leuchte at gmail.com) Date: 25 Apr 2007 07:08:42 -0700 Subject: Python not giving free memory back to the os get's me in real problems ... Message-ID: <1177510121.882503.145560@n15g2000prd.googlegroups.com> So I read quite a few things about this phenomenon in Python 2.4.x but I can hardly believe that there is really no solution to my problem. We use a commercial tool that has a macro functionality. These macros are written in python. So far nothing extraordinary. Our (python-)macro uses massively nested loops which are unfortunately necessary. These loops perform complex calculations in this commercial tool. To give you a quick overview how long this macros runs: The outer loop takes 5-7 hours for one cycle. Each cycle creates one outputfile. So we would like to perform 3-5 outer cycles en bloc. Unfortunately one of our computers (768MB RAM) crashes after just ~10% of the first cycle with the following error message: http://img2.freeimagehosting.net/uploads/7157b1dd7e.jpg while another computer (1GB RAM) crashes after ~10% of the fourth loop. While the virtual memory on the 1gb machine was full to the limit when it crashed the memory usage of the 768mb machine looked this this: http://img2.freeimagehosting.net/uploads/dd15127b7a.jpg The moment I close the application that launched the macro, my ressources get freed. So is there a way to free my memory inside my nested loops? thanks in advance, tim From 12cc104 at gmail.com Sun Apr 22 15:49:42 2007 From: 12cc104 at gmail.com (proctor) Date: 22 Apr 2007 12:49:42 -0700 Subject: recursion depth problem In-Reply-To: References: <1177267774.416169.276780@e65g2000hsc.googlegroups.com> Message-ID: <1177271382.859369.104790@q75g2000hsh.googlegroups.com> On Apr 22, 1:24 pm, Michael Bentley wrote: > On Apr 22, 2007, at 1:49 PM, proctor wrote: > > > > > i have a small function which mimics binary counting. it runs fine as > > long as the input is not too long, but if i give it input longer than > > 8 characters it gives > > > RuntimeError: maximum recursion depth exceeded in cmp > > > i'm not too sure what i am doing improperly. is there really a lot of > > recursion in this code? > > > ================== > > > import sys > > > def ch4(item, n=0): > > if n < len(item): > > if item[n] == '0': > > item[n] = '1' > > print ''.join(item) > > ch4(item) > > elif item[n] == '1': > > item[n] = '0' > > ch4(item, n+1) > > > ch4(list(sys.argv[1])) > > > ================== > > Yes. There really is *that* much recursion in that code. 502 levels > with input length of 8 characters, 1013 with 9 characters, 2035 with > 10 characters... There's a pattern there ;-) ok, thanks michael! is there a way to avoid it here? how could i write this better, (if at all)? proctor. From steve at holdenweb.com Fri Apr 20 11:23:11 2007 From: steve at holdenweb.com (Steve Holden) Date: Fri, 20 Apr 2007 11:23:11 -0400 Subject: HTTP getreply() never returns In-Reply-To: <1177080935.589366.204740@o5g2000hsb.googlegroups.com> References: <1177009226.847229.34210@n76g2000hsh.googlegroups.com> <1177022299.791968.154520@b75g2000hsg.googlegroups.com> <1177080935.589366.204740@o5g2000hsb.googlegroups.com> Message-ID: Marko.Cain.23 at gmail.com wrote: > On Apr 20, 12:06 am, Steve Holden wrote: >> Marko.Cain... at gmail.com wrote: [about httplib problems] >> >> If so, would it be a usable workaround just to use the 2.4 httplib for >> that one program? >> > > Thanks. Can you please tell me how can I 'borrow' a copy of 2.4 > httplib and run that in 2.3? > The easiest way is just to drop it in the directory that contains the Python program you are running - that should make it available in preference to the 2.3 library version: sholden at bigboy ~ $ cat Projects/Python/httplib.py print "My Own Library!" sholden at bigboy ~ $ cat Projects/Python/test24.py import httplib print "I just imported something" sholden at bigboy ~ $ python Projects/Python/test24.py My Own Library! I just imported something sholden at bigboy ~ $ rm Projects/Python/httplib.py* # remember the .pyc! sholden at bigboy ~ $ python Projects/Python/test24.py I just imported something sholden at bigboy ~ $ 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 sbassi at clubdelarazon.org Thu Apr 26 19:01:22 2007 From: sbassi at clubdelarazon.org (Sebastian Bassi) Date: Thu, 26 Apr 2007 20:01:22 -0300 Subject: Python CGI and Browser timeout In-Reply-To: <1177624109.532664.105840@t39g2000prd.googlegroups.com> References: <1177624109.532664.105840@t39g2000prd.googlegroups.com> Message-ID: <9e2f512b0704261601s39e0772fp39636ff09b98521e@mail.gmail.com> On 26 Apr 2007 14:48:29 -0700, skulka3 at gmail.com wrote: > In order to work around this problem, I started printing empty strings > (i.e. print "") so that the browser does not timeout. How do you print something while doing the query and waiting for the results? I saw some pages that display something like: "This page will be updated in X seconds to show the results" (X is an estimated time depending of server load), after a JS countdown, it refresh itself and show the result or another "This page will be updated in X seconds to show the results". -- Sebasti?n Bassi (???????) Diplomado en Ciencia y Tecnolog?a. GPG Fingerprint: 9470 0980 620D ABFC BE63 A4A4 A3DE C97D 8422 D43D Club de la raz?n (www.clubdelarazon.org) From marcpp at gmail.com Thu Apr 19 16:38:10 2007 From: marcpp at gmail.com (Marcpp) Date: 19 Apr 2007 13:38:10 -0700 Subject: PYQT 3 communication with 2 windows Message-ID: <1177015090.289961.306590@o5g2000hsb.googlegroups.com> Hi, I'm introducing to program in python + pyqt. I have a main window that call a second window (to introduce a info with textedit) when press the second window button I need to return to the main window the info introduced in the second window. I've seek in the pyqt doc examples but i don't find it. Have you any example? From danb_83 at yahoo.com Thu Apr 12 21:47:37 2007 From: danb_83 at yahoo.com (Dan Bishop) Date: 12 Apr 2007 18:47:37 -0700 Subject: Calling private base methods In-Reply-To: References: <1176374675.347453.89340@n76g2000hsh.googlegroups.com> <1176404325.211501.26610@w1g2000hsg.googlegroups.com> Message-ID: <1176428856.998080.13470@n76g2000hsh.googlegroups.com> On Apr 12, 3:02 pm, Duncan Booth wrote: > "7stud" wrote: > > On Apr 12, 5:04 am, Duncan Booth wrote: > >> "7stud" wrote: > >> > On Apr 12, 2:47 am, "Jorgen Bodde" wrote: > >> >> Is it possible to call a private base method? I come from a C++ > >> >> background, and I liked this construction as my base class has helper > >> >> methods so that I do not have to duplicate code. > > >> > I'd like to see some C++ code that does that! > > >> Easy: > > >> #define private public > >> #include > >> #undef private > > >> then call the private methods as much as you want. > > > lol. I don't see any private methods being created there. > > You should have looked in someheader: > > class Whatever { > private: > void ohnoyoudont(int); > > } > > then back in the C file: > > ... > Whatever foo = new Whatever(); > int ohyesido = 42; > foo.ohnoyoudont(ohyesido); > ... > > Really, it does work (probably). There are other ways to get at private > members in C++ but this is the easiest. I have a job as a C++ programmer and once tried this trick in order to get at a private member function I needed. Didn't work: Apparently, VC ++ includes the access level in its name mangling, so you get linker errors. After that, I had a much greater appreciation for Python's lack of "private". From sjmachin at lexicon.net Mon Apr 16 18:09:27 2007 From: sjmachin at lexicon.net (John Machin) Date: 16 Apr 2007 15:09:27 -0700 Subject: OverflowError: mktime argument out of range ??? In-Reply-To: <1176735739.422686.227960@d57g2000hsg.googlegroups.com> References: <11e49df10704150341p1a9056e7hfba36a523517fad3@mail.gmail.com> <1176640607.972087.153470@o5g2000hsb.googlegroups.com> <1176735739.422686.227960@d57g2000hsg.googlegroups.com> Message-ID: <1176761366.967796.102110@y5g2000hsa.googlegroups.com> On Apr 17, 1:02 am, "Paul Boddie" wrote: > John Machin wrote: > > > Maybe it does. It sure would be nice to get a definite answer. Pity > > nobody documented the time module. > > "The epoch is the point where the time starts. On January 1st of that > year, at 0 hours, the ``time since the epoch'' is zero. For Unix, the > epoch is 1970. To find out what the epoch is, look at gmtime(0)." > > "The functions in this module do not handle dates and times before the > epoch or far in the future." > > http://docs.python.org/lib/module-time.html > Hypothesis 1: I must have missed that somehow! Hypothesis 2: That page wasn't there yesterday! Hypothesis 3: You may need to consider rebooting your irony detector. FWIW you didn't quote what it says about the function that the OP was calling (mktime): """If the input value cannot be represented as a valid time, either OverflowError or ValueError will be raised (which depends on whether the invalid value is caught by Python or the underlying C libraries). The earliest date for which it can generate a time is platform- dependent.""" Cheers, John From aleax at mac.com Sun Apr 15 22:38:32 2007 From: aleax at mac.com (Alex Martelli) Date: Sun, 15 Apr 2007 19:38:32 -0700 Subject: Any Pythonistas in Mexico? References: <1176386191.990363.112350@y80g2000hsf.googlegroups.com> Message-ID: <1hwmm9b.1ge28l5894a98N%aleax@mac.com> Gabriel Genellina wrote: > En Thu, 12 Apr 2007 10:56:32 -0300, Marcpp escribi?: > > > On 12 abr, 09:41, Hugo Gonz?lez Monteverde wrote: > >> Le? este mail viej?simo en una lista. Yo uso Python y tambi?n quer?a > >> saber qui?n pythoneaba en M?xico. Todav?a est?s por ah?? > > > > Yo vivo en Espa?a. > > Yo en Argentina. Hay un grupo comp.lang.python.general.castellano y su > correspondiente lista, no se si habr? alguien de Mexico ahi. I know there's a thriving Python community in Argentina (at least in Buenos Aires), as Anna and I were there to speak at CaFeConf last fall and enjoyed their delightful hospitality (plus, we were already friends with Facundo Batista, the Argentinian author of Python standard library's decimal module and some other cool stuff). While I don't know about any Python activity in Mexico, newsgroups or mailing lists in Spanish seem to be the natural place to start looking. (The Argentinians were so kind as to let me present in English -- I could have tried Italian, my native language, but that's about as close to Spanish as I could get, sigh -- so I hope you'll be equally lenient of my responding in English... my undersanding of what you guys are writing in Spanish is, I believe, pretty good, but _producing_ Spanish myself is a completely different issue!-). Alex From jstroud at mbi.ucla.edu Tue Apr 17 00:11:57 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Mon, 16 Apr 2007 21:11:57 -0700 Subject: multirember&co In-Reply-To: <1176768854.720234.23320@w1g2000hsg.googlegroups.com> References: <1176768854.720234.23320@w1g2000hsg.googlegroups.com> Message-ID: bearophileHUGS at lycos.com wrote: > Once in while I too have something to ask. This is a little problem > that comes from a Scheme Book (I have left this thread because this > post contains too much Python code for a Scheme newsgroup): > http://groups.google.com/group/comp.lang.scheme/browse_thread/thread/a059f78eb4457d08/ > > The function multiremberandco is hard (for me still) if done in that > little Scheme subset, but it's very easy with Python. It collects two > lists from a given one, at the end it applies the generic given fun > function to the two collected lists and returns its result: > > def multiremberandco1(el, seq, fun): > l1, l2 = [], [] > for x in seq: > if x == el: > l2.append(el) > else: > l1.append(el) > return fun(l1, l2) > > data = [1, 'a', 3, 'a', 4, 5, 6, 'a'] > print multiremberandco1('a', data, lambda l1,l2: (len(l1), len(l2))) > > More compact: > > def multiremberandco2(el, seq, fun): > l1, l2 = [], [] > for x in seq: > [l1, l2][x == el].append(el) > return fun(l1, l2) > > > A bit cleaner (but I don't like it much): > > def multiremberandco3(el, seq, fun): > l1, l2 = [], [] > for x in seq: > (l2 if x == el else l1).append(el) > return fun(l1, l2) > > > For fun I have tried to make it lazy, if may be useful if seq is a > very long iterable. So I've used tee: > > from itertools import ifilter, tee > > def multiremberandco4(el, iseq, fun): > iseq1, iseq2 = tee(iseq) > iterable1 = ifilter(lambda x: x == el, iseq1) > iterable2 = ifilter(lambda x: x != el, iseq2) > return fun(iterable1, iterable2) > > def leniter(seq): > count = 0 > for el in seq: > count += 1 > return count > > idata = iter(data) > print multiremberandco4('a', idata, lambda l1,l2: (leniter(l1), > leniter(l2))) > > > But from the docs: >in general, if one iterator is going to use most > or all of the data before the other iterator, it is faster to use > list() instead of tee().< > > So I have tried to create two iterables for the fun function scanning > seq once only, but I haven't succed so far (to do it I have tried to > use two coroutines with the enhanced generators, sending el to one or > to the other according to the value of x == el, this time I don't show > my failed versions), do you have suggestions? > > (Note: in some situations it may be useful to create a "splitting" > function that given an iterable and a fitering predicate, returns two > lazy generators, of the items that satisfy the predicate and of the > items that don't satisfy it, so this exercise isn't totally useless). > > Bye, > bearophile > I think it might be provable that two iterators are required for this exercise. In this example, for example, leniter() will be called on one list and then the other. How will it get an accurate count of one list without iterating through the other? I.e.: data = [1, 'a', 3, 'a', 4, 5, 6, 'a'] ^ To count this 'a', it must have gone through the numbers, so the leniter() can not act independently on the lists using a single iterator. James From martin.laloux at gmail.com Tue Apr 3 03:03:28 2007 From: martin.laloux at gmail.com (martin.laloux at gmail.com) Date: 3 Apr 2007 00:03:28 -0700 Subject: python on mac os 10.4.x In-Reply-To: <1175576455.471249.58740@q75g2000hsh.googlegroups.com> References: <1175576455.471249.58740@q75g2000hsh.googlegroups.com> Message-ID: <1175583808.882993.282750@p15g2000hsd.googlegroups.com> Go to http://wiki.python.org/moin/MacPython and http://pythonmac.org/packages/ if you want to download macpython 2.5 or macpython 2.4.4 ("framework" builds). Installation is very easy (package) and you have all you want without problem with the 2.3.5 version wich remains installed and functional (you have 2 python installed) From faulkner891 at gmail.com Sat Apr 14 15:09:04 2007 From: faulkner891 at gmail.com (faulkner) Date: 14 Apr 2007 12:09:04 -0700 Subject: Python Feature Request: Allow changing base of member indices to 1 In-Reply-To: <1176546465.632410.52630@w1g2000hsg.googlegroups.com> References: <1176546465.632410.52630@w1g2000hsg.googlegroups.com> Message-ID: <1176577744.688946.317740@y5g2000hsa.googlegroups.com> On Apr 14, 6:27 am, samj... at gmail.com wrote: > This is like the previous one. Please check for sanity and approve for > posting at python-dev. > > I would like to have something like "option base" in Visual Basic. > IIRC it used to allow me to choose whether 0 or 1 should be used as > the base of member indices of arrays. In Python, the same can be used > with strings, lists, tuples etc. > > This would mean: > foo = "foo" > => foo[1] == 'f' > > foo = ['foo', 'bar', 'spam' ] > => foo[1] == 'foo' > > foo = ('spam', 'eggs') > => foo[1] == 'spam' > > For convenience it should also affect the range function so that: > > range(3) = [1, 2, 3] > > because this is often used where arrays would be used in VB. > > Finally, when the programmer does not specify his choice of base at > the beginning of the program, the current behaviour of using 0 as base > should continue so that there is no problem with backward > compatibility. __future__ is used to access upcoming features, and changing the base offset is not [and never will be] slated for future development. zero has been used as the base offset in all real languages since the dawn of time, and isn't something that can be changed without seriously breaking heads. i can't believe nobody's posted this yet: http://www.xkcd.com/c163.html From castironpi at gmail.com Sun Apr 29 16:13:42 2007 From: castironpi at gmail.com (castironpi at gmail.com) Date: 29 Apr 2007 13:13:42 -0700 Subject: exclusive shelve open In-Reply-To: <1177873921.270358.259310@l77g2000hsb.googlegroups.com> References: <1177873921.270358.259310@l77g2000hsb.googlegroups.com> Message-ID: <1177877622.660437.299810@y5g2000hsa.googlegroups.com> On Apr 29, 2:12 pm, castiro... at gmail.com wrote: > I'm trying to be safe and make sure only one python instance opens the > shelf. Any ideas? Using Windows. From ptmcg at austin.rr.com Mon Apr 16 01:14:32 2007 From: ptmcg at austin.rr.com (Paul McGuire) Date: 15 Apr 2007 22:14:32 -0700 Subject: How to initialize a table of months. In-Reply-To: <1176694407.102613.37460@w1g2000hsg.googlegroups.com> References: <1176694257.338172.217660@y80g2000hsf.googlegroups.com> <1176694407.102613.37460@w1g2000hsg.googlegroups.com> Message-ID: <1176700472.052332.226350@d57g2000hsg.googlegroups.com> On Apr 15, 10:33 pm, "7stud" wrote: > On Apr 15, 9:30 pm, "7stud" wrote: > > > On Apr 15, 7:30 pm, "Steven W. Orr" wrote: > > Arrgh. > > import calendar > > months = calendar.month_abbr > #returns an array with the 0 element empty > #so the month names line up with the indexes 1-12 > > d = {} > for i in range(1, 13): > d[months[i]] = i > > print d This dict construction idiom is worth learning: d = dict( (a,b) for a,b in ... some kind of list comprehension or generator expr... ) In this case: d = dict( (mon,i) for i,mon in enumerate(calendar.month_abbr) ) Or to avoid including that pesky 0'th blank element: d = dict( [(mon,i) for i,mon in enumerate(calendar.month_abbr)][1:] ) -- Paul From steven.bethard at gmail.com Thu Apr 19 01:08:45 2007 From: steven.bethard at gmail.com (Steven Bethard) Date: Wed, 18 Apr 2007 23:08:45 -0600 Subject: Text Suffix to Prefix Conversion In-Reply-To: <1176958038.116780.104660@n59g2000hsh.googlegroups.com> References: <1176958038.116780.104660@n59g2000hsh.googlegroups.com> Message-ID: EMC ROY wrote: > Original Sentence: An apple for you. > Present: An apple for you .<.> > Desire: An apple for you <.>. >>> text = 'An apple for you .<.>' >>> import re >>> re.sub(r'(\S+)(<[^>]+>)(\s*)', r'\2\1\3', text) 'An apple for you <.>.' From robert.kern at gmail.com Wed Apr 11 16:18:19 2007 From: robert.kern at gmail.com (Robert Kern) Date: Wed, 11 Apr 2007 15:18:19 -0500 Subject: About Trolltech QT OpenSource license. In-Reply-To: <1176285062.178372.15090@d57g2000hsg.googlegroups.com> References: <1176233376.712861.67160@o5g2000hsb.googlegroups.com> <1176237050.409742.8760@30g2000cwc.googlegroups.com> <1176285062.178372.15090@d57g2000hsg.googlegroups.com> Message-ID: king kikapu wrote: > On Apr 11, 10:56 am, Robert Kern wrote: >> Others have given good answers. I would only like to clarify what I think is the >> source of confusion here. While the FSF and many open source advocates make a >> distinction between the words "commercial" (meaning that someone derives money >> from distributing the software, whether it is GPLed or not) and "proprietary" >> (meaning that the software is not being distributed under an open source license >> but one that restricts user's rights), Trolltech abuses the term "commercial" to >> mean "proprietary" in this case. > > Ok, i see...So i can use Qt OS edition and earn money from this as > long as i explicitly say (is a reference to a GPL in a readme text > file enough for this ?) that this software is under the GPL lisence > and i have the obligation to give the source code with it. It's a bit more complicated than that. There are good resources for understanding the implications of the GPL on the FSF's site which other people have pointed out. I also recommend Larry Rosen's (free) book _Open Source Licensing_, particularly Chapter 6 for understanding the GPL: http://www.rosenlaw.com/oslbook.htm > I will reply to that email of Trolltec's today and i will tell them > about the things mentioned here, basically just the sentence i wrote > above. > I see what they will reply and post it here... I don't recommend it. You are talking to their salesman, not your lawyer. You are being given a sales pitch, not legal advice. -- 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 please.ask at for.it Sat Apr 14 10:57:59 2007 From: please.ask at for.it (Army1987) Date: Sat, 14 Apr 2007 16:57:59 +0200 Subject: Python Feature Request: Explicit variable declarations References: <1176546078.934340.253810@y5g2000hsa.googlegroups.com> <1176557734.456820.275780@p77g2000hsh.googlegroups.com> Message-ID: "jamadagni" ha scritto nel messaggio news:1176557734.456820.275780 at p77g2000hsh.googlegroups.com... >> Languages like Perl and VB need a strict mode because they will >> auto-vivify variable for you. I.e. they will bring variables to life >> with defined or undefined values if you use them in a l-value (left hand >> side of an assignment) without having declared them prior. If you do >> that in Python you get an exception. > > I don't comprehend. I can just type a = 5 in a new Python session and > I get no exception. Python currently does not require variables to be > declared before they are used on the LHS. I think (s)he meant right hand. From michael at jedimindworks.com Mon Apr 23 06:45:45 2007 From: michael at jedimindworks.com (Michael Bentley) Date: Mon, 23 Apr 2007 05:45:45 -0500 Subject: Do other Python GUI toolkits require this? In-Reply-To: <57C90994-391D-4350-A2F2-29C1590A3335@jedimindworks.com> References: <462697A6.6010007@codebykevin.com> <57C90994-391D-4350-A2F2-29C1590A3335@jedimindworks.com> Message-ID: OK. In order to kill the-thread-that-would-not-die(tm), I think I know what I must do. I'll print a correction: On Apr 19, 2007, at 2:22 AM, Michael Bentley wrote: > ... I switched to PyObjC. The > learning curve is rather steep IMO, but worth it. One thing I think > I should mention though is that if you move to PyObjC -- do some > projects in Objective C first. Otherwise your brain will implode. Should be changed to: .. I switched to PyObjC. The learning-effort curve is rather steep IMO, but worth it. One thing I think I should mention though is that if you move to PyObjC -- do some projects in Objective C first. Otherwise your brain will implode. Hope this helps, Michael ;-) From dtgeadamo at yahoo.com Tue Apr 24 13:51:23 2007 From: dtgeadamo at yahoo.com (Viewer T.) Date: 24 Apr 2007 10:51:23 -0700 Subject: Modules for peer-to-peer chat program Message-ID: <1177437083.702888.4480@r3g2000prh.googlegroups.com> I would like to know which modules I would need in order to create peer-to-peer chat program in python using Tkinter. If I would need modules that do not come packaged with python, I would appreciate information on where I can get them. Thanks. From bbxx789_05ss at yahoo.com Thu Apr 12 04:20:58 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: 12 Apr 2007 01:20:58 -0700 Subject: reading from sys.stdin Message-ID: <1176366058.261031.111870@p77g2000hsh.googlegroups.com> I can't break out of the for loop in this example: ------ import sys lst = [] for line in sys.stdin: lst.append(line) break print lst ----------- But, I can break out of the for loop when I do this: --------- import sys lst = [] for line in open("aaa.txt"): lst.append(line) break print lst ---------- Why doesn't break work in the first example? From jstroud at mbi.ucla.edu Sat Apr 14 18:18:47 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Sat, 14 Apr 2007 15:18:47 -0700 Subject: Useful decorator In-Reply-To: <7xtzvik417.fsf@ruckus.brouhaha.com> References: <7xtzvik417.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > In the course of writing a bunch of generator-oriented code I kept > wanting to temporarily truncate the output of generators for debugging, > i.e. I might have a function like > > def generate_bazillion_items(): > for line in bazillion_line_file: > yield itemify(line) > > where I wanted to test the program on just the first 20 lines of the > file. After a number of rounds of editing the program to wrap an > xrange(20) loop I went to using islice(bazillion_line_file, 20), but > even more handy was to write this decorator: > > def truncate(n): > from itertools import islice > def trunc(gen): # truncate generator to n items > return lambda *a,**kw: islice(gen(*a,**kw), n) > return trunc > > Then to chop bazillion_items to 20 items, I just write: > > @truncate(20) > def generate_bazillion_items(): > for line in bazillion_line_file: > yield itemify(line) > > When I want to run the whole file, I comment out the @truncate line, > and if I want to debug again, I just uncomment it. Thes may be overkill, but how about allowing None as a parameter to truncate, to allow for programmatic truncation? # top of module if DEBUG: FILETRUNC = 20 else: FILETRUNC = None # imported, etc. def truncate(n): if n is None: return lambda gen: gen from itertools import islice def trunc(gen): # truncate generator to n items return lambda *a,**kw: islice(gen(*a,**kw), n) return trunc # in the body somewhere @truncate(FILETRUNC) def generate_bazillion_items(): # etc. James From castironpi at gmail.com Sun Apr 29 15:12:01 2007 From: castironpi at gmail.com (castironpi at gmail.com) Date: 29 Apr 2007 12:12:01 -0700 Subject: exclusive shelve open Message-ID: <1177873921.270358.259310@l77g2000hsb.googlegroups.com> I'm trying to be safe and make sure only one python instance opens the shelf. Any ideas? From sjmachin at lexicon.net Thu Apr 19 17:22:34 2007 From: sjmachin at lexicon.net (John Machin) Date: 19 Apr 2007 14:22:34 -0700 Subject: Significance of "start" parameter to string method "endswith" In-Reply-To: <1177014971.167843.293190@n76g2000hsh.googlegroups.com> References: <1177012694.726434.142660@q75g2000hsh.googlegroups.com> <1177014971.167843.293190@n76g2000hsh.googlegroups.com> Message-ID: <1177017754.479205.33530@q75g2000hsh.googlegroups.com> On Apr 20, 6:36 am, subscriber123 wrote: > On Apr 19, 3:58 pm, Boris Du?ek wrote: > > > > > > > > > Hello, > > > what is the use-case of parameter "start" in string's "endswith" > > method? Consider the following minimal example: > > > a = "testing" > > suffix="ing" > > a.endswith(suffix, 2) > > > Significance of "end" is obvious. But not so for "start". > > > Let's assume the "end" parameter is not used - then the function > > should simple check that the last "len(suffix)" characters of "a" are > > equal to "ing", no matter where we start (the function does not *scan* > > the string from the "start", does it?) > > Only case where it would make difference is if we had start + > > len(suffix) < len(a) (excuse possible "of-by-one" error :-) > > Then the function would never return True. But is there a real use > > case when we would test for endswith like this? (knowing that it must > > return false?) > > > Thanks for any ideas/experience. > > Boris > > Basically, this must be so in order for this to be Pythonic. This is > because it is an object oriented language, and functions can be passed > as arguments. Say, for example, you have the following function: > > def foo(function,instance,param): > if function(instance,param,2,4): > return True > else: return False Perhaps return function(instance, param, 2, 4) would have a higher pythonicity index :-) > > The function must work whether you pass it > foo(str.endswith,"blaahh","ahh"), or > foo(str.startswith,"blaahh","aah"). This is a really bad example, but > it gets the point across that similar functions must have similar > parameters in order to be Pythonic. > > I personally have never used the second or third parameters in this > function nor in str.startswith. From pythoneiro at gmail.com Sun Apr 1 09:10:04 2007 From: pythoneiro at gmail.com (Py Thorneiro) Date: Sun, 1 Apr 2007 10:10:04 -0300 Subject: CRC CCITT UPDATE in Python In-Reply-To: <460F4E6C.9050308@v.loewis.de> References: <1175393727.233247.254500@n76g2000hsh.googlegroups.com> <460F4E6C.9050308@v.loewis.de> Message-ID: <73b38a6e0704010610o719d1651w518045ce59559b66@mail.gmail.com> Hi Martin! OK, thanks; but its work in AVR... After compile it and work in agree with the device that I need to talk, the software work fine, but I would like port it to PC in Python... Hi Folks, So sorry, but I try find it googling, searkoding ( http://www.koders.com) and try understand so bether and unhapilly don?t had sucess... I try normally the hands-on technique and to practise the DIY philosophy; but in this case my mind isn?t helping me!:-) Please, could you help me? :-) How to port this hi8 and lo8 to Python, is there some function similar? Tnx, ./Fernando -Py - thorneiro -vvvv On 4/1/07, "Martin v. L?wis" wrote: > > > > Please, is there here some good soul that understand this > > functions hi8 and lo8 (from GCC AVR) and can help me to port it to > > Python? > > > > uint16_t > > crc_ccitt_update (uint16_t crc, uint8_t data) > > { > > data ?= lo8 (crc); > > data ?= data << 4; > > return ((((uint16_t)data << 8) | hi8 (crc)) ? (uint8_t)(data >> 4) > > ? ((uint16_t)data << 3)); > > } > > Most likely, lo8(crc) == crc & 0xFF, and hi8(crc) == (crc >> 8) & 0xFF > (the last bit masking might be redundant, as crc should not occupy more > than 16 bits, anyway). > > HTH, > Martin > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From Roka100 at gmail.com Wed Apr 18 11:13:04 2007 From: Roka100 at gmail.com (Jia Lu) Date: 18 Apr 2007 08:13:04 -0700 Subject: Combinate 2 lists to a dict ? Message-ID: <1176909184.588107.136720@e65g2000hsc.googlegroups.com> Hi all. I have 2 lists, a = [1,2,3] b = ["ooo","aaa","ppp"] What is the fastest way to make a dict like {1:"ooo",2:"aaa", 3:"ppp"} ? Thanx From rrr at ronadam.com Wed Apr 25 17:55:13 2007 From: rrr at ronadam.com (Ron Adam) Date: Wed, 25 Apr 2007 16:55:13 -0500 Subject: pydoc and imported modules In-Reply-To: <1177080853.261895.224440@q75g2000hsh.googlegroups.com> References: <1177080853.261895.224440@q75g2000hsh.googlegroups.com> Message-ID: <462FCE41.2030400@ronadam.com> schpok at gmail.com wrote: > When I "from foo import *" in my __init__.py, sometimes module foo's > docs will be expanded in the pydocs. It seems to depend in what > language foo was implemented. > > For example, if you "from math import *" in your __init__.py, you will > see math's members will appear in the resulting pydocs, as though it's > part of your module. The behavior is consistent across the C modules I > am writing. > > However, if you "from foo import *" in your __init__.py, and foo is a > python file (not a module written in C), foo's members don't appear in > the resulting pydocs. This also seems to occur in some boost::python > bindings. > > What is expected behavior? How do ensure foo's docs do or don't appear > in help, regardless of their implementation language? > > Thanks, > Schpok Pydoc doesn't check the __module__ attribute of the items imported, it just displays what is in the modules name space as if it was defined in that module. In __init__.py files where an __all__ variable is defined, it won't show items that aren't in __all__. This is probably what you are seeing. I'm currently rewriting pydoc, so what behavior would you like to see? Cheers, Ron From junkdump2861 at hotmail.com Thu Apr 12 14:25:03 2007 From: junkdump2861 at hotmail.com (junkdump2861 at hotmail.com) Date: 12 Apr 2007 11:25:03 -0700 Subject: Inconsistent result from urllib.urlopen Message-ID: <1176402303.340868.165510@o5g2000hsb.googlegroups.com> Here's the problem: using Netscape 7.1, I type use the view page source command (url is http://en.wikipedia.org/wiki/Cain) and save the raw HTML file and it's 67 kb, and has the addresses of all the images in it. I want the exact same thing from my Python script, but I'm not getting it. Instead, I get a file only 21 kb that has no image addresses. Here's the code I use: import urllib f = urllib.urlopen('http://en.wikipedia.org/wiki/Cain') data = f.read(9999999) f.close() f1 = open('junk.txt', 'w') f1.write(data) f1.close() Any ideas why I don't get the same result from the python script as I do from a web browser? This problem seems to be a recent development. The scripts I wrote like this worked fine for a while and then stopped working within the past couple of weeks. From rhamph at gmail.com Thu Apr 19 19:34:42 2007 From: rhamph at gmail.com (Adam Olsen) Date: Thu, 19 Apr 2007 17:34:42 -0600 Subject: Python's handling of unicode surrogates Message-ID: As was seen in another thread[1], there's a great deal of confusion with regard to surrogates. Most programmers assume Python's unicode type exposes only complete characters. Even CPython's own functions do this on occasion. This leads to different behaviour across platforms and makes it unnecessarily difficult to properly support all languages. To solve this I propose Python's unicode type using UTF-16 should have gaps in its index, allowing it to only expose complete unicode scalar values. Iteration would produce surrogate pairs rather than individual surrogates, indexing to the first half of a surrogate pair would produce the entire pair (indexing to the second half would raise IndexError), and slicing would be required to not separate a surrogate pair (IndexError otherwise). Note that this would not harm performance, nor would it affects programs that already handle UTF-16 and UTF-32 correctly. To show how things currently differ across platforms, here's an example using UTF-32: >>> a, b = u'\U00100000', u'\uFFFF' >>> a, b (u'\U00100000', u'\uffff') >>> list(a), list(b) ([u'\U00100000'], [u'\uffff']) >>> sorted([a, b]) [u'\uffff', u'\U00100000'] Now contrast the output of sorted() with what you get when using UTF-16: >>> a, b = u'\U00100000', u'\uFFFF' >>> a, b (u'\U00100000', u'\uffff') >>> list(a), list(b) ([u'\udbc0', '\udc00'], [u'\uffff']) >>> sorted([a, b]) [u'\U00100000', u'\uffff'] As you can see, the order has be reversed, because the sort operates on code units rather than scalar values. Reasons to treat surrogates as undivisible: * \U escapes and repr() already do this * unichr(0x10000) would work on all unicode scalar values * "There is no separate character type; a character is represented by a string of one item." * iteration would be identical on all platforms * sorting would be identical on all platforms * UTF-8 or UTF-32 containing surrogates, or UTF-16 containing isolated surrogates, are ill-formed[2]. Reasons against such a change: * Breaks code which does range(len(s)) or enumerate(s). This can be worked around by using s = list(s) first. * Breaks code which does s[s.find(sub)], where sub is a single surrogate, expecting half a surrogate (why?). Does NOT break code where sub is always a single code unit, nor does it break code that assumes a longer sub using s[s.find(sub):s.find(sub) + len(sub)] * Alters the sort order on UTF-16 platforms (to match that of UTF-32 platforms, not to mention UTF-8 encoded byte strings) * Current Python is fairly tolerant of ill-formed unicode data. Changing this may break some code. However, if you do have a need to twiddle low-level UTF encodings, wouldn't the bytes type be better? * "Nobody is forcing you to use characters above 0xFFFF". This is a strawman. Unicode goes beyond 0xFFFF because real languages need it. Software should not break just because the user speaks a different language than the programmer. Thoughts, from all you readers out there? For/against? If there's enough support I'll post the idea on python-3000. [1] http://groups.google.com/group/comp.lang.python/browse_thread/thread/7e9327a896c242e7/4876e191831da6de [2] Pages 23-24 of http://unicode.org/versions/Unicode4.0.0/ch03.pdf -- Adam Olsen, aka Rhamphoryncus From sgeiger at ncee.net Wed Apr 11 13:11:19 2007 From: sgeiger at ncee.net (Shane Geiger) Date: Wed, 11 Apr 2007 12:11:19 -0500 Subject: bittorent In-Reply-To: <461D110F.8080908@rpath.com> References: <1eb3a0e10704110922v17f83f79se5972dce07415a5@mail.gmail.com> <461D110F.8080908@rpath.com> Message-ID: <461D16B7.9090407@ncee.net> Jonathan Smith wrote: > Linus Nordstr?m wrote: > >> Hello >> Im planing playing a bit whit bittorrent, but I'm having some trouble >> about where to start. So if anyone could point me in the right >> direction it would be much appreciated. >> The best would be if there are some already written modules that >> handle downloading and seeding torrents, but if that cant be found a >> good source on how one dose to build some sort of bitorrent client >> would be nice. >> >> thanks in advance >> > > you might start with bittorrent itself [1] - it is written in python. > > [1]: http://www.bittorrent.com/download > > -smithj > Snakebite is written entirely in Python. This sounds like exactly what you need. This covers my successful attempt to set up Snakebite (some time ago). It will likely be even easier for you. These are crude instructions I made for myself at the time. I think reading the documentation and using these notes will get you over any hurdles you need to surmount. Let me know if you cannot get it to work. # I used wget to download the two .deb files and then installed those with dpkg -i because I had problems with their sources.list instructions wget http://actlab.tv/debian/binary/bittorrent_4.20.8_python2.3.deb; \ wget http://actlab.tv/debian/binary/snakebite.deb ; \ sudo dpkg -i {snakebite.deb,bittorrent_4.20.8_python2.3.deb} sudo apt-get install libwxgtk2.6-0 python-wxgtk2.6 python-twisted python-crypto python-psyco sudo apt-get update ; sudo apt-get -f install # I had to do "apt-get -f install" to deal with some dependency problems before I could install that Then modify "sudo vi /etc/snakebite.ini" (See "CONFIG FILE EXAMPLE" below.) copy files to /var/snakebite/files/ -- Do you have to restart snakebite in order to get it to serve files? If you want to change the look of the Web page, do that in /var/snakebite/web THINGS I MIGHT NEED TO FIX SO THAT IT WILL LISTEN ON PORT 80: s = self.r.create_serversocket(6060, '', True) -- /usr/lib/python2.3/site-packages/snakebite/server.py: unmodified: line 27 of 120 [22%] CHANGE IT TO THIS: s = self.r.create_serversocket(80, '', True) APPARENTLY THAT NUMBER IS HARD-CODED Then "sudo /etc/init.d/snakebite start" Edit this file to create notes about how to download bittorrent clients: /var/snakebite/web/blurb To change the stylesheet copy everything between "" from http://www.ncee.net/index.php to /var/snakebite/web/snakebite.css Then go to: http://actlab.tv/snakebite/redirect/sgeiger - I'm not sure why the redirect doesn't update sometimes. Is it because I didn't set up my snakebite.ini properly? http://localhost:6060/links -- THAT WORKED!! http://70.13.149.185:6060/links -- THAT WORKED!! ------ CONFIG FILE EXAMPLE: (Note: I used username: sgeiger and password foobar. ) [Project Snakebite] dir_web_=/var/snakebite/web dir_torrents_=/var/snakebite/torrents dir_files_=/var/snakebite/files dir_temp_=/var/snakebite/temp web_server_port=6060 config_port=2020 tracker_port=5050 url_to_update=http://actlab.tv/snakebite/update username=random password=random ------ Read this: http://actlab.tv/snakebite_guide.html Step 2 - Configure You can edit your config file manually (/etc/snakebite.ini) or you can use the web interface (http://localhost:2020/config). The only thing you really need to change out of the box is to enter in your username and password for the redirect service. This can be any username and password that you want. Your account is automatically created the first time you run snakebite. Step 3 - Run snakebite You can launch snakebite like any Debian service: /etc/init.d/snakebite start. Step 4 - Check out your links page If you entered in a username and password, you should be able to look at your links page at http://actlab.tv/snakebite/redirect/username. This will actually redirect you to your IP on the machine on which you are currently running snakebite. This is registered automatically every time you run snakebite, so it will be kept up to date if you switch computers or have a dynamic IP address. You can also go to http://localhost:6060/links to view your links page. There should be one link, to gag.jpg, a simple strangely-named work-safe test file which is just a picture of some guy chilling. Step 5 - Make some files available for sharing Just put the files in the snakebite directory (by default /var/snakebite/files). Wait a minute or so and then reload your links page. The new files should show up on the page and be ready for download. Step 6 - Download some files Clicking on any of the links on your links page should cause your browser to ask you if you want to save the file or open it in BitTorrent. Installing snakebite installs BitTorrent, so if you're browser is on the same machine as snakebite it should be installed. If you're testing from another machine, you can use the BitTorrent download link at the bottom of the links page to download BitTorrent (or just go to bittorrent.com). You can use any BitTorrent client that you like. We just link to the mainline one because our friends wrote it. Step 7 - Customize your page There are three customizable parts to your links page: the user picture, the CSS stylesheet, and the blurb at the bottom. These are all in the snakebite web directory (by default /var/snakebite/web). Change them to whatever you'd like. I find that customizing your user picture makes the page feel about ten times more awesome. Step 8 - Send your link to all of your friends Remember, the link http://actlab.tv/snakebite/redirect/username will always send you to your currently running snakebite even if your IP changes. We think this is really handy because we always forget our IP. If you already using dyndns or something, you can use that instead, we won't be hurt. Step 9 - Reflect Now you're sharing files over BitTorrent. Who knew that it could be this easy? If you have more files to share, you just drop them in the directory. Everything is automatic, everything is fun! With all the time we just saved setting this up, we can spend more time finding cool files to share and making funny user pictures. It's kind of like myspace really, except it's not broken every other day. (Well, let's hope.) -- 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 nawijn at gmail.com Tue Apr 3 03:39:06 2007 From: nawijn at gmail.com (nawijn at gmail.com) Date: 3 Apr 2007 00:39:06 -0700 Subject: Generic logic/conditional class or library for classification of data In-Reply-To: <1175571813.229254.210580@l77g2000hsb.googlegroups.com> References: <1175403286.809692.100080@n59g2000hsh.googlegroups.com> <1175571813.229254.210580@l77g2000hsb.googlegroups.com> Message-ID: <1175585946.937228.160660@o5g2000hsb.googlegroups.com> On Apr 3, 5:43 am, "Basilisk96" wrote: > Thanks for the help, guys. > Dictionaries to the rescue! > > Steven, it's certainly true that runtime creation of attributes does > not fit well here. At some point, an application needs to come out of > generics and deal with logic that is specific to the problem. The > example I gave was classification of books, which is relatively easy > to understand. The particular app I'm working with deals with > specialty piping valves, where the list of rules grows complicated > fairly quickly. > > So, having said that "attributes are not known at design time", it > seems that dictionaries are best for the generic core functionality: > it's easy to iterate over arbitrary "key, value" pairs without > hiccups. I can even reference a custom function by a key, and call it > during the iteration to do what's necessary. The input/output > dictionaries would dictate that behavior, so that would be the > implementation-specific stuff. Easy enough, and the core functionality > remains generic enough for re-use. > > Michael, I looked at the sample snippets at that link, and I'll have > to try it out. Thanks! Hello, If your rules become more complicated and maybe increase in number significantly, it might be an idea to switch to a rule-based system. Take a look at CLIPS and the associated Python bindings: http://www.ghg.net/clips/CLIPS.html http://pyclips.sourceforge.net/ Kind regards, Marco From mensanator at aol.com Sun Apr 8 14:22:16 2007 From: mensanator at aol.com (mensanator at aol.com) Date: 8 Apr 2007 11:22:16 -0700 Subject: How do I get a slice of a string held in a tuple? In-Reply-To: References: <25ine4-rvt.ln1@Hedley.internal.thethurmans.com> <1176050876.835238.68560@d57g2000hsg.googlegroups.com> Message-ID: <1176056536.157883.247830@d57g2000hsg.googlegroups.com> On Apr 8, 12:29???pm, Lorenzo wrote: > In article <1176050876.835238.68... at d57g2000hsg.googlegroups.com>, > > > > > > ?"mensana... at aol.com" wrote: > > On Apr 8, 11:34?am, Lorenzo Thurman > > wrote: > > > I have tuple which hold a string in tup[0]. I want to get a slice of > > > that string. I thought I would do something like: > > > tup[0][start:end] > > > But this fails. > > > No, it doesn't. > > > >>> a = ('abcdefg','hijkl') > > >>> a[0] > > 'abcdefg' > > >>> a[0][1:2] > > 'b' > > > > How do I go about it? > > > Do it correctly. Post your actual example that fails > > and the related error message. Possibnly your indexes > > were out of range. > > > > I googled this and found a couple > > > of references, but no solution. > > > Well, there wouldn't be ?a solution to a non-existent > > problem, would there? > > > > TIA > > How would you get a slice of a[0] from your example? 'cde' for example? 'b' _was_ a slice of a[0]. but for your specific example >>> a[0][2:5] 'cde' Keep in mind the "end" value is not returned and indexing starts with 0, so "cde" represents the 3rd, 4th & 5th characters making the slice 2:5. > > -- > "My Break-Dancing days are over, but there's always the Funky Chicken" > --The Full Monty From nogradi at gmail.com Sat Apr 21 05:56:58 2007 From: nogradi at gmail.com (Daniel Nogradi) Date: Sat, 21 Apr 2007 11:56:58 +0200 Subject: Styled Output In-Reply-To: <5f56302b0704210244m738f3cb7n84d2b0cbc7091b5e@mail.gmail.com> References: <3512790415788360620@unknownmsgid> <5f56302b0704210244m738f3cb7n84d2b0cbc7091b5e@mail.gmail.com> Message-ID: <5f56302b0704210256g1827e0d4h89a09f33db97164a@mail.gmail.com> > > I'm running a program of mine from Linux bash script and it currently > > outputs status messages to the command prompt, but they all look a little > > boring to say the least, it'll be like this. > > [snip] > > > And perhaps have the word 'success' in green, or red for 'failed' and > things > > like that, just to make it a little more presentable to the user. Something like this might also help on linux: def blue( text ): print '\033[1m' + text + '\033[0m' blue( 'this will be blue' ) See http://tldp.org/HOWTO/Bash-Prompt-HOWTO/x329.html HTH, Daniel From phil at riverbankcomputing.co.uk Thu Apr 26 11:05:33 2007 From: phil at riverbankcomputing.co.uk (Phil Thompson) Date: Thu, 26 Apr 2007 16:05:33 +0100 Subject: passing tuple with pyqt4 signal/slot mechanism In-Reply-To: <59bs0gF2iutnsU1@mid.uni-berlin.de> References: <59bs0gF2iutnsU1@mid.uni-berlin.de> Message-ID: <200704261605.33614.phil@riverbankcomputing.co.uk> On Thursday 26 April 2007 3:41 pm, Diez B. Roggisch wrote: > Pradnyesh Sawant schrieb: > > Hello, > > I have a pyqt4 code in which i'm trying the signal/slot mechanism. The > > (stripped) code is as follows: > > > > class D(QtCore.QThread): > > def __init__(self): > > QtCore.QThread.__init__(self) > > tpl = ("Primary", "priSec") > > print "tpl:", tpl > > self.emit(QtCore.SIGNAL("setLabel"), tpl) > > class Gui(QtGui.QDialog): > > def __init__(self, parent = None): > > QtGui.QDialog.__init__(self, parent) > > def setLabel(self, tpl): > > print "####tpl:", tpl > > print "**********tpl:", str(tpl) > > return > > if __name__ == "__main__": > > app = QtGui.QApplication(sys.argv) > > dialog = Gui() > > d = D() > > QtCore.QObject.connect(d, QtCore.SIGNAL("setLabel"), > > dialog.setLabel, QtCore.Qt.QueuedConnection) > > sys.exit(dialog.exec_()) > > > > The output i'm getting is as follows: > > > > tpl: ('Primary', 'priSec') > > ####tpl: (,) > > **********tpl: ((((((((,),),),),),),),) > > > > Can anyone kindly tell me what's happening here? Why is the tuple > > ("Primary", "priSec") getting converted to this thingy? And > > what is this thingy anyways (It looks to be a deeply nested tuple, but > > am not sure). > > It's just wild guessing back from my Qt3-days - but isn't PYSIGNAL > instead of SIGNAL necessary here? No, PyQt4 used SIGNAL for both Qt and Python signals. Phil From johnjsal at NOSPAMgmail.com Tue Apr 10 15:32:08 2007 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Tue, 10 Apr 2007 15:32:08 -0400 Subject: OT: Question about RGB color method Message-ID: <461be63b$0$31839$c3e8da3@news.astraweb.com> Sorry for this non-Python question, but since it's computer related I know you guys will have an answer, and I don't really know where else to ask. Mainly I'm just curious anyway. I'm wondering, why do computers use a RGB color scheme instead of the primary colors? Is there something you can't do with yellow? It seems weird that RGB can be combined to make all colors, when that's supposed to be the job of the primary colors. I'm sure there some technical computer-related reason that it had to be this way. Thanks. From carsten at uniqsys.com Thu Apr 5 16:20:12 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Thu, 05 Apr 2007 16:20:12 -0400 Subject: RFC: Assignment as expression (pre-PEP) In-Reply-To: <1175802680.021987.39220@p77g2000hsh.googlegroups.com> References: <1175802680.021987.39220@p77g2000hsh.googlegroups.com> Message-ID: <1175804412.3438.93.camel@dot.uniqsys.com> On Thu, 2007-04-05 at 12:51 -0700, TimeHorse at gmail.com wrote: > I would like to gauge interest in the following proposal: > > Problem: > > Assignment statements cannot be used as expressions. > > Performing a list of mutually exclusive checks that require data > processing can cause excessive tabification. For example, consider > the following python snipet... > > temp = my_re1.match(exp) > if temp: > # do something with temp > else: > temp = my_re2.match(exp) > if temp: > # do something with temp > else: > temp = my_re3.match(exp) > if temp: > # do something with temp > else: > temp = my_re4.match(exp) > > # etc. > > Even with 2-space tabification, after about 20 matches, the > indentation will take up half an 80-column terminal screen. If that's your only justification for this proposal, that's almost certainly not enough to convince anybody of its necessity. Your code example should be rewritten as a loop: match_actions = [(my_re1, action1), (my_re2, action2), ...] for my_re, action in match_actions: if my_re.match(exp): action(exp) break Hope this helps, Carsten From apardon at forel.vub.ac.be Mon Apr 23 03:06:55 2007 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 23 Apr 2007 07:06:55 GMT Subject: Do other Python GUI toolkits require this? References: <462697A6.6010007@codebykevin.com> <465B30B4-5BA0-459A-BE6F-1038874FA74B@jedimindworks.com> <58rq32F2fo980U1@mid.uni-berlin.de> <1177077506.429242.161690@e65g2000hsc.googlegroups.com> <1177083703.203360.220020@b75g2000hsg.googlegroups.com> Message-ID: On 2007-04-20, Paul Boddie wrote: > On 20 Apr, 16:34, Antoon Pardon wrote: >> On 2007-04-20, Paul Boddie wrote: >> >> > You could have knowledge or accomplishment >> > on the X axis and effort or work on the Y axis. >> >> What else is effort than the time you spent on it? > > What's the difference between watching a television programme called > "Useless Celebrity Factoids" for half an hour and spending the same > amount of time studying for an exam involving useful information where > you might also need to show some level of understanding of the subject > matter? Do you want to discus principals or the practical problem in setting up a study? > If that's not comparing similar measures of information, what's the > difference between studying for an exam in a subject whose > prerequisites are familiar to you and studying for one in an > unfamiliar field, both for the same amount of time? Same question. If you are looking at the principals there is no problem, those already familiar now, already have spent time/effort at the subject. So you should calculate that time too. In practice those setting up a study, try to pick a activity noone is very familiar with. -- Antoon Pardon From notrealaddress at all.com Sat Apr 14 05:36:12 2007 From: notrealaddress at all.com (Dropkick Punt) Date: Sat, 14 Apr 2007 18:36:12 +0900 Subject: list comparison help? Message-ID: Hi. I have a list of common prefixes: >>> prefixes = [ "the", "this", "that", "da", "d", "is", "are", "r", "you", "u"] And I have a string, that I split() into a list. >>> sentence = "what the blazes is this" >>> sentence = sentence.split() Now I want to strip the sentence of all words in the prefix list. I tried this method: >>> for x in prefixes: ... if sentence.index(x): ... del sentence[sentence.index(x)] This raises, the error: Traceback (most recent call last): File "", line 3, in ? ValueError: list.index(x): x not in list This puzzles me, because if x isn't in the list, the subroutine shouldn't attempt to delete it from the list, so I'm not sure why it's complaining. Can anybody explain this to me, &/or show me a better way to do it? From flyzone at technologist.com Mon Apr 30 11:22:57 2007 From: flyzone at technologist.com (Flyzone) Date: 30 Apr 2007 08:22:57 -0700 Subject: regexp match string with word1 and not word2 In-Reply-To: <9rGdnQGHaNy1mqvbnZ2dnUVZ_v_inZ2d@comcast.com> References: <1177920984.247487.54620@c35g2000hsg.googlegroups.com> <9rGdnQGHaNy1mqvbnZ2dnUVZ_v_inZ2d@comcast.com> Message-ID: <1177946577.080567.73400@u30g2000hsc.googlegroups.com> On 30 Apr, 17:11, Steven Bethard wrote: > You don't need a regexp:; I need a regexp.....i'm parsing a file with a rule-file that contains also regexp and strings too.... Read my post to James Stroud. From stefan.behnel-n05pAM at web.de Sun Apr 22 11:22:55 2007 From: stefan.behnel-n05pAM at web.de (Stefan Behnel) Date: Sun, 22 Apr 2007 17:22:55 +0200 Subject: No speedup on multi-processor machine? In-Reply-To: <1177252466.855178.58010@y5g2000hsa.googlegroups.com> References: <1177189332.916296.205280@d57g2000hsg.googlegroups.com> <1177197495.821701.140390@b58g2000hsg.googlegroups.com> <1177200844.134908.192110@q75g2000hsh.googlegroups.com> <1177252466.855178.58010@y5g2000hsa.googlegroups.com> Message-ID: <462B7DCF.5000307@web.de> danfan1981 at yahoo.com schrieb: > Thanks guys. But I think IronPython only works on Windows machine, but > I am using a Sun machine. Isn't there a mono port for Sun? Stefan From global_3333 at sbcglobal.net Mon Apr 2 13:19:55 2007 From: global_3333 at sbcglobal.net (Global Infotech Corporation) Date: Mon, 02 Apr 2007 17:19:55 GMT Subject: Need SW Quality Engineers (with Digital Imaging / ePublishing exp.) in Silicon Valley, CA Message-ID: <%WaQh.5181$Kd3.3515@newssvr27.news.prodigy.net> Hi We have the following two positions open at one of our Client's site in the Silicon Valley, CA area. Our client, apart from being a pioneer in desktop publishing software provider, also makes web publishing products. We are looking for two individuals with thorough understanding of the Quality Engineering process, testing tools and techniques. Please reveiew the positions listed below and let us know which of these you may want to explore. In case you are not interested in either, please feel free to forward the requirements on to any acquaintance who may be .. PAY RATES FOR BOTH ROLES ARE BETWEEN US$ 40 - 53/hr, (W2 - no benefits, or C2C; negotiable depending on level of experience) 1. TITLE: Software Quality Engineer (electronic Publishing) LOC: Santa Clara/San Jose, CA area DUR: 6 - 12 mths, extendable JOB: This person will work closely with the development team to identify appropriate test strategies, communicate and work with other Quality Engg teams to leverage and coordinate test efforts, implement test plans and test cases, test tools and utilities for automoating the test process. KEY SKILLS: Must possess thorough knowledge of of the software Quality eningeenring process and should be well-familiar with the product life-cycle processes. Other key skills, they should possess are - experience with PDF, HTML, XML, CSS, good understanding of Scalable Vector Graphics (SVG). Must be able to write scripts in Javascripting. Prior work experience in both WIN and MAC platforms will be a definite edge. Must have a Bachelors degree in Computer Sciences or equivalent work experience. 2. TITLE: Software Quality Engineer LOC: Santa Clara/San Jose, CA area DUR: 12 mths, extendable JOB: This person will work closely with the test team to provide user-level testing and some scripted testing of our new Client imaging application. This position will involve working closely with Engg teams, which focusses on the needs of a professional photographer. Work will include ad hoc testing, bug detection and reporting as well as conducting structured testing using self-created nad maintained test plans, files and scripts. KEY SKILLS: Must have a Bachelors degree in Computer Sciences or equivalent work experience, with at least 3 yrs of end-user testing of a complex application on WIN and/or MAC platforms. Should be able to write scripts in Javascripting or similar language. Other desirable skills include: PDF, HTML, XML, CSS, good understanding of Scalable Vector Graphics (SVG). Digital Photography skills will be a definite asset! HOW TO APPLY: If you are interested in either of these opprtunities, please e-mail us a MS Word copy of your recent resume quoting the "JOB TITLE: Software Quality Engineer (electronic Publishing)" OR "Software Quality Engineer" - as applicable, in the subject line of their e-mail. Please DO NOT WRITE COVER LETTERS; instead, please include the following on top of your resume or on the body of the e-mail to help quicken the application review and shorlisting process: 1. Your current location 2. Current work authorization status in US 3. Current pay and expected rate of pay (please specify whether quoted rate is on W2 or C2C) 4. Contact Ph#s and best time to call you (please specify the time-zone, you are in) CONTACT: arnab at global-infotech.com Tel # 408-567-0600 xt 310 URL: www.global-infotech.com From sjmachin at lexicon.net Mon Apr 30 07:37:20 2007 From: sjmachin at lexicon.net (John Machin) Date: 30 Apr 2007 04:37:20 -0700 Subject: Importing a csv file In-Reply-To: References: <1177923524.747364.182460@h2g2000hsg.googlegroups.com> Message-ID: <1177933040.032953.278860@o5g2000hsb.googlegroups.com> On Apr 30, 7:21 pm, Tim Golden wrote: > sagar wrote: > > Hi all , > > I want to read data in a csv file using the python scripts. > > when i gave the following code : > > import csv > > reader = csv.reader(open("some.csv", "rb")) > > for row in reader: > > print row > > > it is showing : > > > Traceback (most recent call last): > > File "csv.py", line 1, in > > import csv > > File "C:\Documents and Settings\meesa02\csv.py", line 2, in Only *almost* certainly, Tim? *Maybe*? You don't believe what the above traceback lines are telling you? > > reader = csv.reader(open("some.csv", "rb")) > > AttributeError: 'module' object has no attribute 'reader' > > You almost certainly have a file called "csv.py" in > the current directory. (Maybe even the one that's > running this script?). Rename it to "mycsv.py" or > whatever and try again. > From a.schmolck at gmail.com Sun Apr 22 20:01:37 2007 From: a.schmolck at gmail.com (Alexander Schmolck) Date: 23 Apr 2007 01:01:37 +0100 Subject: [ANN] mlabwrap-1.0final References: Message-ID: Stef Mientki writes: > Alexander Schmolck wrote: > > I'm pleased to finally announce mlabwrap-1.0: > > Project website > > > --------------- > > > > Description > > > ----------- > > Mlabwrap-1.0 is a high-level python to matlab(tm) bridge that makes calling > > > matlab functions from python almost as convenient as using a normal python > > library. It is available under a very liberal license (BSD/MIT) and should > > work on all major platforms and (non-ancient) python and matlab versions and > > either numpy or Numeric (Numeric support will be dropped in the future). > > > > > Probably quit a large and nice job, to embed MatLab in Python. Actually, it's not much code -- mlabwrap.py is less than 500 lines of code. > But, I've the idea I'm missing something ... ... coming from MatLab, a few > months ago I tried Python, ... and at the moment I've decided to move > completely from MatLab to Python. All new programs will be written in Python > and the old programs will be translated. > > Is my decision wrong ? Depends on your circumstances, but in many cases just switching to a different language and rewriting everything from scratch (possibly even at a single go, if there are many interdependencies) isn't practical. Mlabwrap help here, because it allows you to either migrate piecemeal or mix and match (i.e. mostly use python, resorting to matlab libraries where necessary). > What can do MatLab, that can't be done in Python (SciPy) ? > (Ok I accept there's no SimuLink/PowerSim). There are plenty of commercial and free libraries and environments for matlab that have seen considerable development by domain experts don't have a comparable python equivalent. I'm currently sitting in a cafe in Berkeley, because researchers at the universities of Berkeley and Cambridge are interested in doing their neuroimaging analysis in python, but still need to interface to existing matlab packages like SPM. > Both environments can create any program you like. Not really. > If MatLab is your standard / favorite why not stick to MatLab ? Because matlab is much limited as a programming language once you stray outside linear algebra. Many people also seem to be unhappy about licencing issues . Finally, how often did matlab crash on you? And python? > Please enlighten me. My pleasure. 'as From ceball at gmail.com Tue Apr 24 00:37:54 2007 From: ceball at gmail.com (Chris) Date: 23 Apr 2007 21:37:54 -0700 Subject: Strange terminal behavior after quitting Tkinter application In-Reply-To: <4626d728$0$75704$c30e37c6@lon-reader.news.telstra.net> Message-ID: <1177389473.935407.20950@o40g2000prh.googlegroups.com> > Is there some Tkinter clean up that you have omitted ? Not that I know about - I was hoping someone would tell me I'd omitted something. > Have you ensured that the clean up runs on both normal > exit and abnormal exit (eg ^C) ? (^C doesn't make the application exit, it just raises a KeyboardInterrupt error.) Quitting with ^D from the interpreter (the usual way to quit Python) causes the application to quit normally without any subsequent terminal trouble. Quitting by typing 'sys.exit()' in the interpreter also works fine. Only quitting via the GUI seems to cause the problem. For the moment, including the line 'os.system("stty sane")' before sys.exit() is the solution I'll use. Thanks for everyone's help. From wojciech_mula at poczta.null.onet.pl.invalid Sat Apr 14 05:49:47 2007 From: wojciech_mula at poczta.null.onet.pl.invalid (=?ISO-8859-2?Q?Wojciech_Mu=B3a?=) Date: Sat, 14 Apr 2007 11:49:47 +0200 Subject: list comparison help? In-Reply-To: References: Message-ID: Dropkick Punt wrote: >>>> prefixes = [ "the", "this", "that", "da", "d", "is", "are", "r", "you", "u"] > > And I have a string, that I split() into a list. > >>>> sentence = "what the blazes is this" >>>> sentence = sentence.split() > > Now I want to strip the sentence of all words in the prefix list. > > I tried this method: > >>>> for x in prefixes: > ... if sentence.index(x): > ... del sentence[sentence.index(x)] > > > This raises, the error: > > Traceback (most recent call last): > File "", line 3, in ? > ValueError: list.index(x): x not in list > > This puzzles me, because if x isn't in the list, the subroutine shouldn't attempt to delete it > from the list, so I'm not sure why it's complaining. list.index raised ValueError, see error message. > Can anybody explain this to me, &/or show me a better way to do it? prefixes = set(prefixes) sentence = [word for word in sentence.split() if word not in prefixes] w. From jackson at hotmail.com Fri Apr 20 12:49:20 2007 From: jackson at hotmail.com (Bill Jackson) Date: Fri, 20 Apr 2007 09:49:20 -0700 Subject: When to clear a dictionary... In-Reply-To: References: Message-ID: Bill Jackson wrote the following on 04/20/2007 09:48 AM: > >>> import some_function > > >>> a = {1:2,3:4} > >>> b = {1:2:4:3} > >>> a.clear() > >>> a.update(b) > > >>> a = {1:2,3:4} > >>> b = {1:2,4:3} > >>> for key in b: > .... a[key] = b[key] Clearly, this won't have the same result as the other two examples. > > >>> a = {1:2,3:4} > >>> b = {1:2,4:3} > >>> a = b > From larry.bates at websafe.com Tue Apr 10 11:33:59 2007 From: larry.bates at websafe.com (Larry Bates) Date: Tue, 10 Apr 2007 10:33:59 -0500 Subject: convert html entities into real chars In-Reply-To: References: Message-ID: <461BAE67.2070901@websafe.com> Laszlo Nagy wrote: > > Hi, > > I would like to have a function that can convert '>' into '>', > '&' into '&' etc. I could not find how to do it easily (I have a > code snippet for the opposite). > Thanks, > > Laszlo > You can use htmlentitydefs module to help with this. import htmlentitydefs chr(htmlentitydefs.name2codepoint['gt']) and (to go the other way) htmlentitydefs.codepoint2name[ord('>')] -Larry From first.last at com.be Fri Apr 20 03:33:14 2007 From: first.last at com.be (Toon Knapen) Date: Fri, 20 Apr 2007 09:33:14 +0200 Subject: launching python in parallel Message-ID: <46286ca6$0$1282$6c56d894@reader0.news.be.easynet.net> Dear all, I'm looking into launching python in parallel using MPI. There are many projects already doing this but I would like to understand how this can be done in a portable way. For instance, is it possible to launch myscript.py (which calls MPI_Init through an extension module) like: mpirun -np 2 /path/to/python myscript.py Using mpichgm this works, using stock mpich-1.2.5.2 (ch_p4) however, this does not work. I have been looking into the implemenation of p4 and the behavious (as described above) is understandable. The reason is that p4 creates the remote processes _in_ the MPI_Init of the master. The MPI_Init performs and execlp specifying the name of the executable only. Once the 'slave' is launched and also calls the MPI_Init, the command-line arguments are passed on to the slave. But the slave will thus only launch python, not the myscript.py. Therefore it will never call MPI_Init. I would like to know how other parallel python projects handle this. Thanks in advance, Toon Knapen From jan.m.danielsson at gmail.com Fri Apr 13 19:50:40 2007 From: jan.m.danielsson at gmail.com (Jan Danielsson) Date: Sat, 14 Apr 2007 01:50:40 +0200 Subject: mod_python & Cookie - unexpected dictionary value In-Reply-To: <46200b3b$1@griseus.its.uu.se> References: <46200b3b$1@griseus.its.uu.se> Message-ID: <46201750$1@griseus.its.uu.se> Jan Danielsson wrote: [---] Never mind. Cookie objects have a "value" attribute -- that's what I was doing wrong. -- Kind regards, Jan Danielsson ------------ And now a word from our sponsor ------------------ Want to have instant messaging, and chat rooms, and discussion groups for your local users or business, you need dbabble! -- See http://netwinsite.com/sponsor/sponsor_dbabble.htm ---- From michael at jedimindworks.com Sun Apr 22 19:51:52 2007 From: michael at jedimindworks.com (Michael Bentley) Date: Sun, 22 Apr 2007 18:51:52 -0500 Subject: recursion depth problem In-Reply-To: <90679236-0D2C-42EF-B93F-06A1DD561944@jedimindworks.com> References: <1177267774.416169.276780@e65g2000hsc.googlegroups.com> <1177275314.846022.249000@e65g2000hsc.googlegroups.com> <1177276111.720137.315710@b75g2000hsg.googlegroups.com> <1177282027.798037.48210@o5g2000hsb.googlegroups.com> <90679236-0D2C-42EF-B93F-06A1DD561944@jedimindworks.com> Message-ID: Oops! Note to self: *ALWAYS* try code before posting to a public forum :-( def binary(val, width): print '%10s = the sum of' % val for i in [2 ** x for x in range(width - 1, -1, -1)]: a = val / i print ' ' * 13 + '%s * (2 ** %s)' % (a, width) val -= i * a width -= 1 binary(233, 8) From http Sun Apr 15 19:11:37 2007 From: http (Paul Rubin) Date: 15 Apr 2007 16:11:37 -0700 Subject: Portably generating infinity and NaN References: <462008d1$0$11763$9b622d9e@news.freenet.de> Message-ID: <7xhcrh2pxy.fsf@ruckus.brouhaha.com> skip at pobox.com writes: > But PEP 754 will only work for architectures supporting IEEE 754. I realize > that's the vast majority of systems, but aren't there still a few Crays and > VMS machines out there? (Do those architectures support NaN and Inf?) I wouldn't worry about it. There are Python subsystems (like threads) that don't work on certain OS's, fine, total portability means not being able to rely on them, and that's ok. I doubt any Crays are still running, or at least running any numerical code written in Python. Same for VMS. From boggom at comcast.net Wed Apr 18 11:36:25 2007 From: boggom at comcast.net (boggom at comcast.net) Date: 18 Apr 2007 08:36:25 -0700 Subject: What makes an iterator an iterator? In-Reply-To: References: Message-ID: <1176910585.108044.116540@y80g2000hsf.googlegroups.com> > I find myself perplexed as to this behaviour. You can not iterate over a dead object! From tjreedy at udel.edu Wed Apr 18 18:15:58 2007 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 18 Apr 2007 18:15:58 -0400 Subject: comparison with None References: <3IqdnfRnCNWPC7vbnZ2dnUVZ_jqdnZ2d@rcn.net> Message-ID: "Alan G Isaac" wrote in message news:3IqdnfRnCNWPC7vbnZ2dnUVZ_jqdnZ2d at rcn.net... | >>> None >= 0 | False | >>> None <= 0 | True | | Explanation appreciated. Should be in the reference manual section on comparisons. From jstroud at mbi.ucla.edu Mon Apr 9 07:49:50 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Mon, 09 Apr 2007 04:49:50 -0700 Subject: Crypto Suggestion/Help In-Reply-To: References: Message-ID: Jimmy E Touma wrote: > Hi all, > > I need some advise on doing the following. I have a Linux application > that allows users to access it via a code (password). At the end of the > day, I gather a log of activities of the users and zip the file and > would like to encrypt it so that the users can not access it or tamper > with it. Only manager should. If I use a private/public key for doing so > I have to store the private key on my computer. What is a good way to > encrypt a file and have the key well hidden on the same computer? If you > have any other way to do, like MD5 or similar, please let me know. > > > Thanks, > Jimmy You describe not encryption but obfuscation if the key on the computer is stored in any usable form. Now, if you encrypted the key with an algorithm as strong as the one you used for the data, then you would preserve the security, but then you'd need a key for the key, etc. Algorithms do exist for multiple keys to decrypt the same cipher text (in the case of multiple managers), but I don't know of any python libraries that implement said algorithms. James From bbxx789_05ss at yahoo.com Sun Apr 1 23:29:02 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: 1 Apr 2007 20:29:02 -0700 Subject: can a method access/set another's variables? In-Reply-To: <1175484283.702475.76740@b75g2000hsg.googlegroups.com> References: <1175477764.549115.159410@n59g2000hsh.googlegroups.com> <1175484283.702475.76740@b75g2000hsg.googlegroups.com> Message-ID: <1175484542.641967.89280@n59g2000hsh.googlegroups.com> On Apr 1, 9:24 pm, "7stud" wrote: > On Apr 1, 7:43 pm, Michael Hoffman wrote: > > > > > asdf1234234 wrote: > > > -a.py- > > > import b > > > > class A: > > > def __init__(self): > > > pass > > > def my_method(self): > > > var = 1 > > > self.var = 2 > > > b.set_var(self) > > > print var > > > print self.var > > > > my_a = A() > > > my_a.my_method() > > > > -b.py- > > > def set_var(self): > > > var = 2 > > > self.var = 2 > > > > I want both var and self.var to be 2 at the end. Is there anything I > > > can pass to set_var() that will give it access to the variables in > > > my_method() like I can use self for the variables in the class A? > > > I hope there isn't a way to do this that simply. :) Why do you want to > > do this, or is it idle curiosity? There is almost surely a better way to > > solve your underlying problem. > > > You can *read* your caller's local variables (either pass locals() as an > > argument or use inspect to get the frame locals), but writing to this > > dictionary has undefined behavior. > > -- > > Michael Hoffman > > class A(object): > def early_parse(self): > self.result1 = eval("10+5") > def later_parse(A_obj): > A_obj.result2 = eval("20*2") > > a = A() > a.early_parse() > later_parse(a) > print a.result1 > print a.result2 Oops. That def should be: def later_parse(A_obj): A_obj.result2 = A_obj.result1 + eval("20*2") From bearophileHUGS at lycos.com Fri Apr 13 05:59:28 2007 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 13 Apr 2007 02:59:28 -0700 Subject: split and regexp on textfile In-Reply-To: <1176451192.364949.8260@w1g2000hsg.googlegroups.com> References: <1176451192.364949.8260@w1g2000hsg.googlegroups.com> Message-ID: <1176458368.386799.46810@n59g2000hsh.googlegroups.com> Flyzone: > i have a problem with the split function and regexp. > I have a file that i want to split using the date as token. My first try: data = """ error text Mon Apr 9 22:30:18 2007 text text Mon Apr 9 22:31:10 2007 text text Mon Apr 10 22:31:10 2007 text text """ import re date_find = re.compile(r"\d\d:\d\d:\d\d \d{4}$") section = [] for line in data.splitlines(): if date_find.search(line): if section: print "\n" + "-" * 10 + "\n", "\n".join(section) section = [line] else: if line: section.append(line) print "\n" + "-" * 10 + "\n", "\n".join(section) itertools.groupby() is fit to split sequences like: 1111100011111100011100101011111 as: 11111 000 111111 000 111 00 1 0 1 0 11111 While here we have a sequence like: 100001000101100001000000010000 that has to be splitted as: 10000 1000 10 1 10000 10000000 10000 A standard itertool can be added for such quite common situation too. Along those lines I have devised this different (and maybe over- engineered) version: from itertools import groupby import re class Splitter(object): # Not tested much def __init__(self, predicate): self.predicate = predicate self.precedent_el = None self.state = True def __call__(self, el): if self.predicate(el): self.state = not self.state self.precedent_el = el return self.state date_find = re.compile(r"\d\d:\d\d:\d\d \d{4}$") splitter = Splitter(date_find.search) sections = ("\n".join(g) for h,g in groupby(data.splitlines(), key=splitter)) for section in sections: if section: print "\n" + "-" * 10 + "\n", section The Splitter class + the groupby can become a single simpler generator, like in this this version: def grouper(seq, key=bool): # A fast identity function can be used instead of bool() # Not tested much group = [] for part in seq: if key(part): if group: yield group group = [part] else: group.append(part) yield group import re date_find = re.compile(r"\d\d:\d\d:\d\d \d{4}$") for section in grouper(data.splitlines(), date_find.search): print "\n" + "-" * 10 + "\n", "\n".join(section) Maybe that grouper can be modified to manage group lazily, like groupby does, instead of building a true list. Flyzone (seen later): >Amm..not! I need to get the text-block between the two data, not the data! :) Then you can modify the code like this: def grouper(seq, key=bool): group = [] for part in seq: if key(part): if group: yield group group = [] # changed else: group.append(part) yield group Bye, bearophile From laurent.pointal at limsi.fr Thu Apr 26 03:13:29 2007 From: laurent.pointal at limsi.fr (Laurent Pointal) Date: Thu, 26 Apr 2007 09:13:29 +0200 Subject: Access to raw command line? In-Reply-To: <1177571070.229968.155710@t39g2000prd.googlegroups.com> References: <1177571070.229968.155710@t39g2000prd.googlegroups.com> Message-ID: Pieter Edelman a ?crit : > One possible way to work around this is to get the raw command line > and do the shell expansions ourselves from within Python. Ignoring the > question of whether it is worth the trouble, does anybody know if it > is possible to obtain the raw (unexpanded) command line? > Alternatively, does anybody have suggestion of how to do this in a > clean way? To avoid shell extension, try to quote args: ./myprog.py -t "*.gpx" "*.jpg" Or (IMHO simpler) define anoter switch to identify other files: ./myprog.py -t *.gpx -u *.jpg A+ Laurent. From janencarl at aznex.net Sun Apr 8 00:34:58 2007 From: janencarl at aznex.net (Carl Trachte) Date: Sat, 7 Apr 2007 21:34:58 -0700 Subject: opinion needed References: <1173454035.316124.307620@h3g2000cwc.googlegroups.com> Message-ID: I first found out about Python's Natural Language Processing Toolkit on this Georgia professor's web page: http://www.ai.uga.edu/mc/ He is big on having his students use Prolog for natural language processing. I'm not sure if your interest lies there, but that is one area where (according to the professor), he likes to use Prolog, and sometimes Python as well. I'm very much a dilettante in the area of natural language processing, so this a reference, not an opinion. Carl T. From syedamjad_a at yahoo.com Mon Apr 23 12:10:55 2007 From: syedamjad_a at yahoo.com (CSUIDL PROGRAMMEr) Date: 23 Apr 2007 09:10:55 -0700 Subject: Redirection problem Message-ID: <1177344655.365318.50940@q75g2000hsh.googlegroups.com> I am new to python. so be patient with me I am trying to redirect the output of os.popen command to a file. I want to append to that file. but instead of appending. The file only shows last command that was writtenn to it. filehandle= open("/root/yhpc-2.0/installer/yhpc-log" ,"a+"); filehandle.write(" Command executed is " + cmd); try: pipe= os.popen('%s > /root/yhpc-2.0/installer/yhpc-log' %cmd ); except : IOError; filehandle.close(); Any suggestion would help. filehandle.close(); From null at null.null Mon Apr 2 07:58:44 2007 From: null at null.null (nullified) Date: Mon, 02 Apr 2007 11:58:44 GMT Subject: Any "consumer review generators" available? References: <1175514490.263622.138320@y80g2000hsf.googlegroups.com> Message-ID: On 2 Apr 2007 04:48:10 -0700, "Octo" wrote: >On 29 Mar, 20:00, Uri Guttman wrote: >> >>>>> "a" == aralsky writes: >> >> a> I am looking for a fake consumer review generator that could >> a> generate realistic looking reviews for any products, kind of like >> a> on amazon.com but generated by Artificial Intelligence. Is there a >> a> package available in your favorite programing language... thx alan >> >> it's called a human being. and hope you find some with ethics which you >> don't seem to have. > >People don't have ethics, they have morals. Ethics are characteristics >of collectives, not individuals. > I dont think the OP has either... Wish I knew his domain, to put it in my block list :o) From aahz at pythoncraft.com Sun Apr 22 12:22:01 2007 From: aahz at pythoncraft.com (Aahz) Date: 22 Apr 2007 09:22:01 -0700 Subject: Support for new items in set type References: <1177211624.069474.3960@y5g2000hsa.googlegroups.com> <1hwxx1e.1un7urc1de872aN%aleax@mac.com> <1177239045.216195.245580@e65g2000hsc.googlegroups.com> Message-ID: In article <1177239045.216195.245580 at e65g2000hsc.googlegroups.com>, Prateek wrote: > >Thanks Alex, but we're actually implementing a (non-relational) >database engine. Why are you reinventing the wheel? Why not just implement your functionality on top of an existing database as your backing store? -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Help a hearing-impaired person: http://rule6.info/hearing.html From ndbecker2 at gmail.com Fri Apr 6 12:07:21 2007 From: ndbecker2 at gmail.com (Neal Becker) Date: Fri, 06 Apr 2007 12:07:21 -0400 Subject: block scope? Message-ID: One thing I sometimes miss, which is common in some other languages (c++), is idea of block scope. It would be useful to have variables that did not outlive their block, primarily to avoid name clashes. This also leads to more readable code. I wonder if this has been discussed? From zhonghua.m.yang at gmail.com Tue Apr 17 15:23:30 2007 From: zhonghua.m.yang at gmail.com (ZMY) Date: 17 Apr 2007 12:23:30 -0700 Subject: Numpy problem: Arrays in a list of dictionaries Message-ID: <1176837810.276473.55020@e65g2000hsc.googlegroups.com> I am new to Numpy/Pylab, and I am trying to construct a list of dictionaries with arrays as the items, for example: >>> dict = {1: array([2, 3, 4]), 2: ''} >>> list1 = [] >>> for i in range(3): list1.append(dict.copy()) ... >>> list1 [{1: array([2, 3, 4]), 2: ''}, {1: array([2, 3, 4]), 2: ''}, {1: array([2, 3, 4]), 2: ''}] >>> list1[0][1][1]=100 >>> list1 [{1: array([ 2, 100, 4]), 2: ''}, {1: array([ 2, 100, 4]), 2: ''}, {1: array([ 2, 100, 4]), 2: ''}] >>> list1[0][2]='Jack' >>> list1 [{1: array([ 2, 100, 4]), 2: 'Jack'}, {1: array([ 2, 100, 4]), 2: ''}, {1: array([ 2, 100, 4]), 2: ''}] So the strings can be assigned seperately but arrays can not. What is the problem here? I am using python2.4+Numpy1.0.1 on Fedora Thanks a lot in advance. - ZMY From michele.simionato at gmail.com Thu Apr 26 10:06:49 2007 From: michele.simionato at gmail.com (Michele Simionato) Date: 26 Apr 2007 07:06:49 -0700 Subject: Would You Write Python Articles or Screencasts for Money? In-Reply-To: <1177564989.359400.74160@c18g2000prb.googlegroups.com> References: <1177564989.359400.74160@c18g2000prb.googlegroups.com> Message-ID: <1177596408.954809.211510@r30g2000prh.googlegroups.com> On Apr 26, 7:23 am, Michele Simionato wrote: > I would be +1 for offering symbolic prices Oops, I meant prizes! M. S. From nospam at nospam.com Mon Apr 23 10:38:06 2007 From: nospam at nospam.com (Gilles Ganault) Date: Mon, 23 Apr 2007 16:38:06 +0200 Subject: [SQLite] Recommended wrapper? References: Message-ID: <86hp23hkbjbrp9hesdihtkj46iptfne0im@4ax.com> On Mon, 23 Apr 2007 16:03:05 +0200, Thomas Kr?ger wrote: >It's all there: >http://docs.python.org/lib/module-sqlite3.html Thanks. From please.ask at for.it Sun Apr 15 09:46:54 2007 From: please.ask at for.it (Army1987) Date: Sun, 15 Apr 2007 15:46:54 +0200 Subject: Getting started with python References: <1176598011.463543.96990@q75g2000hsh.googlegroups.com> <1176608302.928513.274400@y5g2000hsa.googlegroups.com> Message-ID: "Paddy" ha scritto nel messaggio news:1176608302.928513.274400 at y5g2000hsa.googlegroups.com... > On a different tack, from: > http://tickletux.wordpress.com/2007/01/24/using-fizzbuzz-to-find-developers-who-grok-coding/ > It seems you need to learn how to write a Fizz-Buzz > program to get a job now-a-days :-) Something less idiotic? I took longer to type a program to do that than to figure out how to do that. From aleax at mac.com Sat Apr 28 23:51:14 2007 From: aleax at mac.com (Alex Martelli) Date: Sat, 28 Apr 2007 20:51:14 -0700 Subject: How to get HTTP error when using urlretrieve() References: <1177816457.190845.100980@l77g2000hsb.googlegroups.com> Message-ID: <1hxasiy.142td19utruhaN%aleax@mac.com> silverburgh.meryl at gmail.com wrote: > Hi, > > I use urlretrieve to retrieve resources from a http server. > Can you please tell me how can I get the HTTP error (whenever > happens)? > > And what kind of different exception urlretrieve will throw? e.g. > unknown host? connection timeout? HTTP error? I think gives good information about these issues. Alex From beliavsky at aol.com Fri Apr 27 08:39:56 2007 From: beliavsky at aol.com (Beliavsky) Date: 27 Apr 2007 05:39:56 -0700 Subject: Generalized range In-Reply-To: <1hx77al.50av4312e1ysaN%aleax@mac.com> References: <1177598743.352743.290730@t39g2000prd.googlegroups.com> <1177616211.476888.38360@r30g2000prh.googlegroups.com> <1hx77al.50av4312e1ysaN%aleax@mac.com> Message-ID: <1177677596.616769.246070@r35g2000prh.googlegroups.com> On Apr 27, 1:32 am, a... at mac.com (Alex Martelli) wrote: > Michael Hoffman wrote: > > tkp... at hotmail.com wrote: > > > Thanks - you have covered a fair bit of gorund here - I will modify > > > myRange taking your suggestions into account. The one suggestion that > > > I'm going to have to think through is repeatedly incrementing res. > > > > I deliberately did not use this as repeated addition can cause > > > rounding errors to accumulate, making the loop run a little longer or > > > shorter than necessary. I thought I would be far less likely to run > > > into rounding issues with a multiplicative construct - hence my use of > > > epsilon, and my question about an appropriate value for it > > > You are right about rounding issues--with a sufficiently small step, the > > way I have done it, it could become an infinite loop. But you can still > > do it with multiplication, without using an epsilon constant. How about > > something like this: > > > index = 0 > > while res < maximum: > > yield minimum + (step * index) > > index += 1 > > Absolutely (with your later correction of actually assigning res), MUCH > better than the misguided attempts based on repeatedly adding 'step'. > > I've taught "numerical computing" in university, and I would have had to > fail anybody who'd misunderstood floating-point computations badly > enough to try that "+=step" idea (including, sigh, the coders of several Fortran compilers who were popular at that time). You may be referring to the Fortran DO loop with a REAL loop variable, for example do x=1.5,3.5,0.5 print*,x end do This was part of standard Fortran 77, so one should blame the standards committee, not the compiler writers. Very few features of F77 were deleted in Fortran 95, but this was one of them. In practice, nothing gets deleted from commercial Fortran compilers. At the SciPy site http://www.scipy.org/Cookbook/OptimizationAndFitDemo1 there is some code 1 from enthought.chaco.wx import plt 2 from scipy import arange, optimize, special 3 4 plt.figure() 5 plt.hold() 6 w = [] 7 z = [] 8 x = arange(0,10,.01) 9 10 for k in arange(1,5,.5): 11 y = special.jv(k,x) 12 plt.plot(x,y) 13 f = lambda x: -special.jv(k,x) 14 x_max = optimize.fminbound(f,0,6) 15 w.append(x_max) 16 z.append(special.jv(k,x_max)) 17 18 plt.plot(w,z, 'ro') 19 from scipy import interpolate 20 t = interpolate.splrep(w, z, k=3) 21 s_fit3 = interpolate.splev(x,t) 22 plt.plot(x,s_fit3, 'g-') 23 t5 = interpolate.splrep(w, z, k=5) 24 s_fit5 = interpolate.splev(x,t5) 25 plt.plot(x,s_fit5, 'y-') I think the use of arange with a non-integer increment is poor style, for reasons discussed in this thread. From quentel.pierre at wanadoo.fr Thu Apr 5 16:34:45 2007 From: quentel.pierre at wanadoo.fr (Pierre Quentel) Date: 5 Apr 2007 13:34:45 -0700 Subject: how to build a forum in Python? In-Reply-To: <1175672984.836097.21610@n76g2000hsh.googlegroups.com> References: <1175672984.836097.21610@n76g2000hsh.googlegroups.com> Message-ID: <1175805285.072045.166230@n59g2000hsh.googlegroups.com> Hi, I think you should take a look at Karrigell : http://karrigell.sourceforge.net It's a Python web framework and the package includes a forum application Regards, Pierre From steve at holdenweb.com Wed Apr 25 10:17:15 2007 From: steve at holdenweb.com (Steve Holden) Date: Wed, 25 Apr 2007 10:17:15 -0400 Subject: PIL and font colour In-Reply-To: <1177441923.378487.210310@r3g2000prh.googlegroups.com> References: <1177441923.378487.210310@r3g2000prh.googlegroups.com> Message-ID: Johny wrote: > I use PIL to write some text to a picture.The text must be seen wery > clearly. > I write the text to different pictures but to the same position. As > pictures maybe different, colour, in the position where I write the > text, is also different. > Is there a way how to set the font colour so that it will be seen very > clearly in the picture? > For example, if the picture is bright ( for example yellow), the font > colour should be dark( e.g. black) and vice versa. > Can anyone help? > Thanks > L. > The easy way to ensure this is to paint a background rectangle of an appropriate color to ensure good font contrast before writing the text. Of course, this obscures rather more of the image in the background than you might otherwise. Apart from that you could try averaging the pixel values in the area you are going to paint on, and then choose a font color that contrasts well with the average. If there are large variations in color, however, this can give disappointing results. If you'd like to get some insight into color contrast you could do worse than start at http://wellstyled.com/tools/colorscheme2/index-en.html regards Steve -- Steve Holden +1 571 484 6266 +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 cam.ac.uk at mh391.invalid Thu Apr 12 15:20:37 2007 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Thu, 12 Apr 2007 20:20:37 +0100 Subject: Portably generating infinity and NaN In-Reply-To: References: Message-ID: Michael Hoffman wrote: > 2. Using an extension module (for example, numarray.ieeespecial will do > it). I guess I could always use ctypes as well, and say, get -inf from libc.log(ctypes.c_double(0.0)). Although we're venturing away from portable territory then, since specifying how to load libc will be different on different platforms. -- Michael Hoffman From sbassi at clubdelarazon.org Mon Apr 16 07:49:10 2007 From: sbassi at clubdelarazon.org (Sebastian Bassi) Date: Mon, 16 Apr 2007 08:49:10 -0300 Subject: File DB instead of real database? In-Reply-To: <1176524076.446204.70730@w1g2000hsg.googlegroups.com> References: <1176524076.446204.70730@w1g2000hsg.googlegroups.com> Message-ID: <9e2f512b0704160449q7db4eebdv58d81c7d978c0dd9@mail.gmail.com> On 13 Apr 2007 21:14:36 -0700, Jia Lu wrote: > I donot want to use a real DB like MySQL ... But I need something to > save about more than 1000 articles. > Is there any good ways? SQLite is a good option, as you were told. But what about put them in a dictionary and then cPickle it to disk? (using 2 as optimization setting in cPickle command). From gagsl-py2 at yahoo.com.ar Tue Apr 10 16:35:22 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 10 Apr 2007 17:35:22 -0300 Subject: Can I get the exit code "n" passed to sys.exit(n) ? References: <1176228956.865875.295980@p77g2000hsh.googlegroups.com> Message-ID: En Tue, 10 Apr 2007 15:15:57 -0300, Yujo escribi?: > In the following code of the finish() function, is there any way to > get the exit code passed to sys.exit() ? > > def finish() : > RETURN_CODE_FROM_SYS_EXIT = ???? # how can I get it ? > if RETURN_CODE_FROM_SYS_EXIT = 0 : > # process ended OK > else : > # process ended with some error > # execute something > > atexit.register(finish) > > # this is my main program.... > > ERR_CODE=3 > sys.exit(ERR_CODE) Uhm, I think you can't, unfortunately (at least on 2.4; I don't have the 2.5 sources at hand). But you can instead wrap your main function with a try/except SystemExit: def main(): return 3 try: sys.exit(main()) except SystemExit, exitcode: finish(exitcode) -- Gabriel Genellina From abgrund at silberdrache.net Sun Apr 22 00:55:25 2007 From: abgrund at silberdrache.net (=?iso-8859-1?B?Qmr2cm4gS2VpbA==?=) Date: 21 Apr 2007 21:55:25 -0700 Subject: Returning a date as string In-Reply-To: <1177201613.014645.72530@y80g2000hsf.googlegroups.com> References: <1177189171.147254.35920@n76g2000hsh.googlegroups.com> <1177201613.014645.72530@y80g2000hsf.googlegroups.com> Message-ID: <1177217725.557325.191140@y5g2000hsa.googlegroups.com> On 22 Apr., 02:26, John Machin wrote: > On Apr 22, 6:59 am, Bj?rn Keil wrote: > > > Hello pythons, > > > I have little problem with understanding conversions in python. I've > > written a little class - nothing much, just to try out Python a little > > - containing the following method: > > > def __repr__(self): > > """Serializes the note. > > > Currently the format of notes isn't decided upon. XML output > > is > > projected.""" > > Insert here: > > print "Due: %r" % self.dateDue > print "Created: %r" % self.dateCreated > print "Subject: %r" % self.subject > print "Content: %r % self.content > > > > > return "Due: " + str(self.dateDue) + \ > > "\nDate: " + str(self.dateCreated) + \ > > "\nSubject: " + self.subject + \ > > "\n" + self.content > > > The fields "dateDue" and "dateCreated" contain datetime.date objects. > > Now when I try to serialize the whole thing: > > > >>> myNote > > > Traceback (most recent call last): > > File "", line 1, in ? > > File "notes.py", line 81, in __repr__ > > return "Due: " + str(self.dateDue) + \ > > TypeError: cannot concatenate 'str' and 'datetime.date' objects > > > I tryed different variant before I wrapped "self.dateDue" in a str() > > constructor: > > I tried to put it in brackets, or call its .isoformat() method. > > Nothing works. It still complains that I was trying to concatenate a > > string with a date, but I really wanna concatenate a string with a > > string! > > > Could anyone please tell me what I am doing wrong? > > Not showing us the *whole* code that you are executing. > > Suggestions: > (1) Maybe dates have crept into self.subject and self.content. The > print statements above should show exactly what you've got. > > (2) Maybe you didn't save it before you ran it. Maybe you forgot to > reload(yourModule). Try making up the smallest possible script that > demonstrates your problem. Get out of whatever IDE you may be using > and go to the OS command-line prompt. Use type (windows) or cat (*x) > to print your script on the console. Run your script. Copy the console > contents and paste it into your mail/news client. > > HTH, > John Ah, yes point (2) is it. I didn't do "reload" but simply "del mylibrary, myobject" and the import the library again. In effect the code quoted in the error message was up to date but the code used was still the cached bytecode. Some problems do in fact solve themselves when you sleep a night over it, it seems. Thank you. Good fight, good night! From kyosohma at gmail.com Mon Apr 30 12:24:34 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: 30 Apr 2007 09:24:34 -0700 Subject: Can python find HW/SW installed on my PC - like Belarc? In-Reply-To: <1177948030.122063.48520@y5g2000hsa.googlegroups.com> References: <1177948030.122063.48520@y5g2000hsa.googlegroups.com> Message-ID: <1177950274.482887.204240@q75g2000hsh.googlegroups.com> On Apr 30, 10:47 am, walterbyrd wrote: > Lets suppose, I want a listing of what hardware and software is > installed on my > windows box. Can I do that with Python? Yes, it is possible for Windows. I don't know how to grab the info for other OS's though. There is a caveat that is annoying. If the software doesn't put itself into the registry somehow, it is much harder to discover if it is indeed installed. For hardware, you'll need the WMI module and the win32 module. For the computer memory and the name of the PC, see below: c = wmi.WMI() for i in c.Win32_ComputerSystem(): mem = int(i.TotalPhysicalMemory) compname = i.Name For the CPU: for i in c.Win32_Processor (): cputype = i.Name For other cool WMI tricks: http://tgolden.sc.sabren.com/python/wmi_cookbook.html For the majority of the software on your system, you'll want to iterate over the following registry key (and its subkeys) using the _winreg module and WMI's Registry() function: HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Uninstall Some code that worked for me (may need modification for your setup): from _winreg import HKEY_LOCAL_MACHINE, KEY_ALL_ACCESS, OpenKey, EnumValue, QueryValueEx r = wmi.Registry () result, names = r.EnumKey (hDefKey=HKEY_LOCAL_MACHINE, sSubKeyName=r"Software\Microsoft\Windows\CurrentVersion\Uninstall") for subkey in names: try: appFile.write('++++++++++++++++++++++++++++++++++++++++++++++++ +++++++++++++++++++++++++\n\n') key = OpenKey(HKEY_LOCAL_MACHINE, r"Software\Microsoft\Windows\CurrentVersion \Uninstall\%s" % subkey,0, KEY_ALL_ACCESS) try: temp = QueryValueEx(key, 'DisplayName') display = str(temp[0]) appFile.write('Display Name: ' + display + '\nRegkey: ' + subkey + '\n') except: appFile.write('Regkey: ' + subkey + '\n') except: print 'Error opening key' # appFile is where I write the list to. You can just print to console. That should get you going. Mike From null at null.null Tue Apr 3 05:53:35 2007 From: null at null.null (nullified) Date: Tue, 03 Apr 2007 09:53:35 GMT Subject: Any "consumer review generators" available? References: <1175225665.929475.183360@n59g2000hsh.googlegroups.com> <0sfp03d9epf50d1o9jj22ni1al4o69ut9k@4ax.com> <1175263276.576403.10930@l77g2000hsb.googlegroups.com> <460d6fd8$0$333$e4fe514c@news.xs4all.nl> Message-ID: On Fri, 30 Mar 2007 22:15:20 +0200, Schraalhans Keukenmeester wrote: >nullified wrote: >> On 30 Mar 2007 07:01:16 -0700, "Evil Otto" wrote: >> >>> On Mar 30, 3:46 am, nullified wrote: >>>> On 29 Mar 2007 20:34:26 -0700, "Evil Otto" wrote: >>>> >>>>> On Mar 29, 2: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 really, really hope that you're looking to generate test data or >>>>> filler text. >>>>> If you're not, then DIAF. >>>> Die In A Fire? Drop In A Fryer? Doug Is A Fucker? Drown In A Fart? >>> Any of those would accurately describe the underlying sentiment, but I >>> had "Die In A Fire" in mind specifically. >> >> FM!, IWRFT! >Perhaps if he finds his miracle script he can also train it to create >and 'solve' funny acronyms? Sorry. That was "Fuck Me! I Was Right First Time!" From pavlovevidence at gmail.com Thu Apr 5 20:25:51 2007 From: pavlovevidence at gmail.com (Carl Banks) Date: 5 Apr 2007 17:25:51 -0700 Subject: Why NOT only one class per file? In-Reply-To: <1175721799.714907.52770@o5g2000hsb.googlegroups.com> References: <1175721799.714907.52770@o5g2000hsb.googlegroups.com> Message-ID: <1175819151.572750.229030@y66g2000hsf.googlegroups.com> On Apr 4, 5:23 pm, "Chris Lasher" wrote: > A friend of mine with a programming background in Java and Perl places > each class in its own separate file in . I informed him that keeping > all related classes together in a single file is more in the Python > idiom than one file per class. He asked why, and frankly, his valid > question has me flummoxed. A: Because you don't have to. Less smart aleck: Python allows programmers to put more than one class per file. Given that freedom, most people didn't obey one-to-one correspondence between classes and files. Therefore, it's the more common idiom in Python. > I tried to rationalize this Python idiom by claiming a file--a single > module--makes for a great container of code which is logically tied > together, such as a class and its subclasses. He posited that > directories (packages) can tie the files together just as well, Which is not incorrect. > and by > having the classes as separate files, he can "diff" them to see how > they differ, something he wouldn't be able to do with the code all in > one file. I agree with Bruno: feeling the need to do this is a big red flag that the code is way too cut-and-paste. (diff'ing different versions is useful, of course, but you can usefully diff modules with many classes in them.) > I also offered that having related classes under one file gives more > direct access to those classes, e.g.: [snip examples] > He doesn't find my arguments convincing, so I thought I'd ask here to > see why the Python idiom is the way it is: why should we NOT be > placing classes in their own separate files? There's no overwhelming reason not to, IMO. As long you have some organization, be it with packages or modules, everything's ok. Most things you have to gain or lose by doing one way or the other are of minor importance. Carl Banks From robert.rawlins at thinkbluemedia.co.uk Thu Apr 19 10:32:23 2007 From: robert.rawlins at thinkbluemedia.co.uk (Robert Rawlins - Think Blue) Date: Thu, 19 Apr 2007 15:32:23 +0100 Subject: Byte-Array to String Message-ID: <000f01c7828f$8b8ce770$a2a6b650$@rawlins@thinkbluemedia.co.uk> Hello Guys, I have a byte array passed to me by dbus and I'm looking to convert it into a string? Is that possible? Sorry for seeming like a putts with these questions, I'm not used to all these complex data types :-D The byte array looks something like this when printed to screen. dbus.Array([dbus.Byte(54), dbus.Byte(0), dbus.Byte(24), dbus.Byte(9), dbus.Byte(0), dbus.Byte(0), dbus.Byte(10), dbus.Byte(0), dbu s.Byte(0), dbus.Byte(0), dbus.Byte(0), dbus.Byte(9), dbus.Byte(0), dbus.Byte(1), dbus.Byte(53), dbus.Byte(3), dbus.Byte(25), dbus. Byte(16), dbus.Byte(0), dbus.Byte(9), dbus.Byte(2), dbus.Byte(0), dbus.Byte(53), dbus.Byte(3), dbus.Byte(9), dbus.Byte(1), dbus.By te(1)], signature=dbus.Signature('y')) Thanks again, Rob -------------- next part -------------- An HTML attachment was scrubbed... URL: From __peter__ at web.de Sun Apr 15 01:27:25 2007 From: __peter__ at web.de (Peter Otten) Date: Sun, 15 Apr 2007 07:27:25 +0200 Subject: Method calls and stack consumption References: Message-ID: Martin Manns wrote: > Calling methods of other object instances seems quite expensive on the > stack (see example below). Is there a better way of traversing through > methods of instances that are connected in a cyclic graph? (The real > program's graph contains multiple successors in lists.) > > class A(object): > ????def?__init__(self): > ????????self.i?=?0 > ????def?a(self): > ????????if?self.i?%?1000?==?0: > ????????????print?self.i > ????????self.i?+=?1????????????????????? ????????return?S[self].a > > a = A() > b = A() > S = {a:b, b:a} a = a.a while True: a = a() That's how you can do it if your real program is similar enough to the example... Peter From see_signature at nospam.nowire.org Wed Apr 25 17:05:42 2007 From: see_signature at nospam.nowire.org (=?ISO-8859-1?Q?Thomas_Kr=FCger?=) Date: Wed, 25 Apr 2007 23:05:42 +0200 Subject: bitwise shift? In-Reply-To: References: Message-ID: desktop schrieb: > I have found a code example with this loop. > > for k in range(10, 25): > n = 1 << k; > > > I have never read Python before but is it correct that 1 get multiplied > with the numbers 10,11,12,12,...,25 assuming that 1 << k means "1 shift > left by k" which is the same as multiplying with k. 1 << n is a more efficient replacement for 2**n Thomas -- sinature: http://nospam.nowire.org/signature_usenet.png From durumdara at gmail.com Wed Apr 25 10:20:03 2007 From: durumdara at gmail.com (Durumdara) Date: Wed, 25 Apr 2007 16:20:03 +0200 Subject: Python not giving free memory back to the os get's me in real problems ... In-Reply-To: <9e384ef60704250719w75443727j94ac4cbbfb86d706@mail.gmail.com> References: <1177510121.882503.145560@n15g2000prd.googlegroups.com> <9e384ef60704250719w75443727j94ac4cbbfb86d706@mail.gmail.com> Message-ID: <9e384ef60704250720v1d2fe4eei7b41749bb2239ad0@mail.gmail.com> Hi! I got same problem with Lotus Domino + Python. The lotus COM objects are not freed, so I get out from memory. I solve this problem with a little trick: I make two py applications. The first is call the second as like another application. The first is put some work to the seconds datadir. Whe second is finished with it, it is close itself. Because the memory operations are existing in only the second script, all memory get freed after it is finished, and the first (controller) py script can call the next session without any problem. dd 25 Apr 2007 07:08:42 -0700, leuchte at gmail.com : > > So I read quite a few things about this phenomenon in Python 2.4.x but > I can hardly believe that there is really no solution to my problem. > > We use a commercial tool that has a macro functionality. These macros > are written in python. So far nothing extraordinary. > > Our (python-)macro uses massively nested loops which are unfortunately > necessary. These loops perform complex calculations in this commercial > tool. To give you a quick overview how long this macros runs: > > The outer loop takes 5-7 hours for one cycle. Each cycle creates one > outputfile. So we would like to perform 3-5 outer cycles en bloc. > Unfortunately one of our computers (768MB RAM) crashes after just ~10% > of the first cycle with the following error message: > > http://img2.freeimagehosting.net/uploads/7157b1dd7e.jpg > > while another computer (1GB RAM) crashes after ~10% of the fourth > loop. While the virtual memory on the 1gb machine was full to the > limit when it crashed the memory usage of the 768mb machine looked > this this: > > http://img2.freeimagehosting.net/uploads/dd15127b7a.jpg > > The moment I close the application that launched the macro, my > ressources get freed. > > So is there a way to free my memory inside my nested loops? > > thanks in advance, > tim > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From bbxx789_05ss at yahoo.com Thu Apr 19 02:40:48 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: 18 Apr 2007 23:40:48 -0700 Subject: Text Suffix to Prefix Conversion In-Reply-To: References: <1176958038.116780.104660@n59g2000hsh.googlegroups.com> Message-ID: <1176964848.464918.89690@n59g2000hsh.googlegroups.com> On Apr 18, 11:08 pm, Steven Bethard wrote: > EMC ROY wrote: > > Original Sentence: An apple for you. > > Present: An apple for you .<.> > > Desire: An apple for you <.>. > >>> text = 'An apple for you .<.>' > >>> import re > >>> re.sub(r'(\S+)(<[^>]+>)(\s*)', r'\2\1\3', text) > > 'An apple for you <.>.' If you end up calling re.sub() repeatedly, e.g. for each line in your file, then you should "compile" the regular expression so that python doesn't have to recompile it for every call: import re text = 'An apple for you .<.>' myR = re.compile(r'(\S+)(<[^>]+>)(\s*)', r'\2\1\3') re.sub(myR, r'\2\1\3', text) Unfortunately, I must be doing something wrong because I can't get that code to work. When I run it, I get the error: Traceback (most recent call last): File "2pythontest.py", line 3, in ? myR = re.compile(r'(\S+)(<[^>]+>)(\s*)', r'\2\1\3') File "/Library/Frameworks/Python.framework/Versions/2.4/lib/ python2.4/sre.py", line 180, in compile return _compile(pattern, flags) File "/Library/Frameworks/Python.framework/Versions/2.4/lib/ python2.4/sre.py", line 225, in _compile p = sre_compile.compile(pattern, flags) File "/Library/Frameworks/Python.framework/Versions/2.4/lib/ python2.4/sre_compile.py", line 496, in compile p = sre_parse.parse(p, flags) File "/Library/Frameworks/Python.framework/Versions/2.4/lib/ python2.4/sre_parse.py", line 668, in parse p = _parse_sub(source, pattern, 0) File "/Library/Frameworks/Python.framework/Versions/2.4/lib/ python2.4/sre_parse.py", line 308, in _parse_sub itemsappend(_parse(source, state)) File "/Library/Frameworks/Python.framework/Versions/2.4/lib/ python2.4/sre_parse.py", line 396, in _parse if state.flags & SRE_FLAG_VERBOSE: TypeError: unsupported operand type(s) for &: 'str' and 'int' Yet, these two examples work without error: ------ import re text = 'An apple for you .<.>' #myR = re.compile(r'(\S+)(<[^>]+>)(\s*)', r'\2\1\3') print re.sub(r'(\S+)(<[^>]+>)(\s*)', r'\2\1\3', text) myR = re.compile(r'(hello)') text = "hello world" print re.sub(myR, r"\1XXX", text) ---------output: An apple for you <.>. helloXXX world Can anyone help? From steve at holdenweb.com Sat Apr 28 13:57:46 2007 From: steve at holdenweb.com (Steve Holden) Date: Sat, 28 Apr 2007 13:57:46 -0400 Subject: how to create/ref globals in an alternate namespace? In-Reply-To: References: Message-ID: Steven W. Orr wrote: > On Friday, Apr 27th 2007 at 14:07 -0700, quoth James Stroud: > > =>Steven W. Orr wrote: > =>> I have two seperate modules doing factory stuff which each have the > =>> similar function2: > =>> > =>> In the ds101 module, def DS101CLASS(mname,data): > =>> cname = mname+'DS101' > =>> msg_class = globals()[cname] > =>> msg = msg_class(data) > =>> return msg > =>> > =>> and in the fdu module, > =>> > =>> def FDUCLASS(mname,data): > =>> cname = mname+'FDU' > =>> msg_class = globals()[cname] > =>> msg = msg_class(data) > =>> return msg > =>> > =>> I was thinking I'd be clever and create a common function: > =>> def procCLASS(mname, objname, data): > =>> cname = mname+objname > =>> msg_class = globals()[cname] > =>> msg = msg_class(data) > =>> return msg > =>> > =>> but the call to globals fouls it all up. Is there a way to write it so > =>> that the call to globals can be parameterized to be in the context of a > =>> specific module? > =>> > =>> Also, I need to go the other way, a la, > =>> globals()[name] = nclass > =>> > =>> Is this doable? > =>> > =>> TIA > =>> > => > =>Why do you need all of the msg_class(es) global? Why not put them into a > =>module and import the module where you need them? This would be the > =>conventional way to avoid such problems. > > The idea is that DS101 is being called in a loop in the ds101 module to > create a lot of msg_classes. The same is true for the FDUCLASS function; > it creates a lot of classes in a loop. > > In addition, I have two other functions, almost alike, in two seperate > modules (mdefs is a structure with all of the stuff needed to drive the > loops) > > def __InitDS101Classes(): > for m in mdefs: > mdef = mdefs[m] > name = mdefs[m]['name']+'DS101' > nclass = new.classobj(name,(DS101,),{}) > nclass.mdef = mdef > nclass.mid = m > globals()[name] = nclass > > > def __InitFDUClasses(): > for m in mdefs: > mdef = mdefs[m] > name = mdefs[m]['name']+'FDU' > nclass = new.classobj(name,(FDU,),{}) > nclass.mdef = mdef > nclass.mid = m > globals()[name] = nclass > > I'm trying to see if by being clever, I can factor out the common code of > the four different functions and still end up with what they create ending > up in the namespaces where they are intended to reside in. Does this make > sense or am I way off base? > > Even if you *can* factor out the common code there's no reason why that shouldn't go in a fifth module that the other four import ... regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden ------------------ Asciimercial --------------------- Get Python in your .sig and on the web. Blog and lens holdenweb.blogspot.com squidoo.com/pythonology tag items: del.icio.us/steve.holden/python All these services currently offer free registration! -------------- Thank You for Reading ---------------- From anthony at python.org Wed Apr 11 00:16:09 2007 From: anthony at python.org (Anthony Baxter) Date: Wed, 11 Apr 2007 14:16:09 +1000 Subject: RELEASED Python 2.5.1, release candidate 1 Message-ID: <200704111416.09853.anthony@python.org> On behalf of the Python development team and the Python community, I'm happy to announce the release of Python 2.5.1 (release candidate 1). This is the first bugfix release of Python 2.5. Python 2.5 is now in bugfix-only mode; no new features are being added. According to the release notes, over 150 bugs and patches have been addressed since Python 2.5, including a fair number in the new AST compiler (an internal implementation detail of the Python interpreter). For more information on Python 2.5.1, including download links for various platforms, release notes, and known issues, please see: http://www.python.org/2.5.1/ Highlights of this new release include: Bug fixes. According to the release notes, at least 150 have been fixed. Highlights of the previous major Python release (2.5) are available from the Python 2.5 page, at http://www.python.org/2.5/highlights.html Enjoy this release, Anthony Anthony Baxter anthony at python.org Python Release Manager (on behalf of the entire python-dev team) From nogradi at gmail.com Mon Apr 16 05:28:58 2007 From: nogradi at gmail.com (Daniel Nogradi) Date: Mon, 16 Apr 2007 11:28:58 +0200 Subject: string methods of a str subclass Message-ID: <5f56302b0704160228uf5eaa23k1ed0621a65f7ae8e@mail.gmail.com> I am probably misunderstanding some basic issue here but this behaviour is not what I would expect: Python 2.4 (#1, Mar 22 2005, 21:42:42) [GCC 3.3.5 20050117 (prerelease) (SUSE Linux)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> class mystr( str ): ... pass ... >>> x = mystr( 'x' ) >>> isinstance( x, mystr ) True >>> isinstance( x.strip( ), mystr ) False >>> Why is the strip( ) method returning something that is not a mystr instance? I would expect all methods operating on a string instance and returning another string instance to correctly operate on a mystr instance and return a mystr instance. How would I achieve something like this without manually copying all string returning methods from str and stuffing the result to mystr( ) before returning? From buzzard at urubu.freeserve.co.uk Sun Apr 1 23:30:43 2007 From: buzzard at urubu.freeserve.co.uk (Duncan Smith) Date: Mon, 02 Apr 2007 04:30:43 +0100 Subject: reverse engineering Excel spreadsheet In-Reply-To: <1175481426.182703.250400@q75g2000hsh.googlegroups.com> References: <460fd6d0.0@entanet> <1175481426.182703.250400@q75g2000hsh.googlegroups.com> Message-ID: <461078e4.0@entanet> John Machin wrote: > On Apr 2, 1:59 am, Duncan Smith wrote: > >>Hello, >> I am currently implementing (mainly in Python) 'models' that come >>to me as Excel spreadsheets, with little additional information. I am >>expected to use these models in a web application. Some contain many >>worksheets and various macros. >> >>What I'd like to do is extract the data and business logic so that I can >>figure out exactly what these models actually do and code it up. An >>obvious (I think) idea is to generate an acyclic graph of the cell >>dependencies so that I can identify which cells contain only data (no >>parents) and those that depend on other cells. If I could also extract >>the relationships (functions), then I could feasibly produce something >>in pure Python that would mirror the functionality of the original >>spreadsheet (using e.g. Matplotlib for plots and more reliable RNGs / >>statistical functions). > > > There are two things you have to consider that can create those > dependencies (1) formulas (2) macros. If it were only formulas, you > wouldn't need to generate an acyclic graph. A no-parents cell will be > defined by a type-specific record (e.g. NUMBER). Dependent cells are > defined by a FORMULA etc record. Similar story with the XML format in > Office 2007. > Well yes, partitioning the cells according to format would be start. Now you have me wondering about the new XML format. Maybe that would be easier to deal with? > I'm not aware of any way to use Python to access the content of > macros. It may be possible using COM ... > I suppose I can do that manually. Most of them seem to do with presentation rather than the business logic. > I'm a bit puzzled by your notion of creating a dependency graph > *without* first extracting the "relationships (functions)" [which you > could do only by parsing the formulas and macros]. > Incomplete parsing :-). I thought I might be able to pull out the dependencies relatively easily, then go back to the spreadsheet to examine the formulae. > "pure Python that would mirror the functionality of the original > spreadsheet": mammoth job; speed? > Basically to try and separate the data, business logic and presentation for coding up in Python. Particularly, I don't want to rely on Excel's statistical functions. But it's also possible that other similar models will be making there way to me, and I'd rather have a few simple classes to handle the business logic, and have model parameters etc. tucked away in text files. > Before you do that, have a look at (1) xlrd docs (2) xlrd source (3) > Openoffice.org docs of XLS format (4) MS docs (now an ECMA standard) > of Office 2007 XML-based files. > Yes, will do. > >>The final application will be running on a Linux server, but I can use a >>Windows box (i.e. win32all) for processing the spreadsheets (hopefully >>not manually). Any advice on the feasibility of this, and how I might >>achieve it would be appreciated. >> >>I assume there are plenty of people who have a better knowledge of e.g. >>COM than I do. I suppose an alternative would be to convert to Open >>Office and use PyUNO, but I have no experience with PyUNO and am not >>sure how much more reliable the statistical functions of Open Office >>are. At the end of the day, the business logic will not generally be >>complex, it's extracting it from the spreadsheet that's awkward. Any >>advice appreciated. TIA. Cheers. >> >>Duncan > > > PyUNO: Google around a bit. My experience was: tried it, got lost in > the jungle of its documentation. > Yep. Me too. I might have another go at it. Cheers (to all who replied). Duncan From jeff at jmcneil.net Mon Apr 9 22:38:05 2007 From: jeff at jmcneil.net (Jeff McNeil) Date: Mon, 9 Apr 2007 22:38:05 -0400 Subject: output of top on a linux box In-Reply-To: <80628d680704091056h735fc0a7l6cf7b586f4bac715@mail.gmail.com> References: <80628d680704072342r60b57995mad6c505505a919a8@mail.gmail.com> <80628d680704091026u7e98719co3d63a7913832475a@mail.gmail.com> <82d28c40704091032p3c5fcc35p38ee9509ca3fa7c0@mail.gmail.com> <80628d680704091056h735fc0a7l6cf7b586f4bac715@mail.gmail.com> Message-ID: <82d28c40704091938l561d4e44ib8798a23984a8ae@mail.gmail.com> The code snippet prints "cpu usage: us,, " on my workstation, bumping the splt index to 3 prints the correct sys. usage. What does the header of your 'top' command look like? There's a very good chance it's different than what I'm testing with. As for the slice, assuming 'splt[2]' is '0.5%sy', then you should be able to remove '%sy' using an indexof -3: Python 2.4.3 (#1, Oct 23 2006, 14:19:47) [GCC 4.1.1 20060525 (Red Hat 4.1.1-1)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> a = "0.5%sy" >>> a[:-3] '0.5' >>> Also note that you may very well have some curses/terminal chars tagged on to that '0.5%sy' string, which causes the slice to return something that you're not expecting. For example: Python 2.4.3 (#1, Oct 23 2006, 14:19:47) [GCC 4.1.1 20060525 (Red Hat 4.1.1-1)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import os >>> top = os.popen("top -n 1") >>> rd = top.read().split("\n") >>> splt = rd[2].split() >>> print splt ['Cpu(s):\x1b(B\x1b[m\x1b[39;49m\x1b(B\x1b[m', ' 1.2%', '\x1b(B\x1b[m\x1b[39;49mus,\x1b(B\x1b[m\x1b[39;49m\x1b(B\x1b[m', '0.2%', '\x1b(B\x1b[m\x1b[39;49msy,\x1b(B\x1b[m\x1b[39;49m\x1b(B\x1b[m', '0.1%', '\x1b(B\x1b[m\x1b[39;49mni,\x1b(B\x1b[m\x1b[39;49m\x1b(B\x1b[m', ' 98.4%', '\x1b(B\x1b[m\x1b[39;49mid,\x1b(B\x1b[m\x1b[39;49m\x1b(B\x1b[m', '0.1%', '\x1b(B\x1b[m\x1b[39;49mwa,\x1b(B\x1b[m\x1b[39;49m\x1b(B\x1b[m', '0.0%', '\x1b(B\x1b[m\x1b[39;49mhi,\x1b(B\x1b[m\x1b[39;49m\x1b(B\x1b[m', ' 0.0%', '\x1b(B\x1b[m\x1b[39;49msi,\x1b(B\x1b[m\x1b[39;49m\x1b(B\x1b[m', '0\x1b(B\x1b[m\x1b[39;49m\x1b[K'] >>> Jeff Are you sure that splt only contains text? Are there any terminal control characters? On 4/9/07, Pradnyesh Sawant wrote: > Thanks for the pointer to use /proc/stat > However, that does not answer my other question about string slicing > Any pointers in that direction would be helpful... > > Thanks a lot! > > On 4/9/07, Jeff McNeil wrote: > > Can you pull the same information from /proc/stat as opposed to using > > a pipe to top? The first line(s) should contain (at least): > > > > cpu usermode, lowprio, system, idle, hz. > > > > The 2.6 kernel adds iowait, irq, and soft irq. It seems that this > > might be a better solution than executing that additional command. > > > > Take a look at proc(5). > > > > Thanks, > > > > Jeff > > > > > > > > > > > > On 4/9/07, Pradnyesh Sawant wrote: > > > Hello, > > > I need the cpu usage of a linux box, for which i capture the output of > > > "top" using "popen". However, i am facing problems during string > > > handling. The code snippet is:- > > > > > > top = os.popen("top -n 1") > > > rd = top.read().split("\n") > > > splt = rd[2].split() > > > # cpu = splt[2][:-4] # why ain't this working ??? > > > cpu = splt[2] > > > print "cpu usage: %s, %s" % (cpu, type(cpu)) > > > > > > the "print" statement prints, "cpu usage: 0.5%sy, ". i > > > tried my best to get rid of the "%sy" after the "0.5", but couldn't > > > succeed (even though the type of "cpu" is "string"). > > > > > > Also, one weird thing that was happening was that if i still "split" > > > the cpu string (removed the last 4 characters), the output of the next > > > print statement was wrong (specifically, the first 2 characters got > > > chipped off). This output is totally unexpected, and wrong... > > > > > > Can anyone kindly help me in understanding what exactly is going on here. > > > > > > Thanks a lot! > > > -- > > > http://mail.python.org/mailman/listinfo/python-list > > > > > > From steven.bethard at gmail.com Tue Apr 3 14:04:47 2007 From: steven.bethard at gmail.com (Steven Bethard) Date: Tue, 03 Apr 2007 12:04:47 -0600 Subject: troubles building python 2.5 on Windows XP x64 Windows Server 2003 sp1 Platform SDK In-Reply-To: <1175622506.730227.37060@p77g2000hsh.googlegroups.com> References: <1175622506.730227.37060@p77g2000hsh.googlegroups.com> Message-ID: bhochstetler at gmail.com wrote: > I am needing to build python 2.5 on Windows XP x64 Windows Server 2003 > sp1 Platform SDK and am not finding anything documented on the process > to use. Has anyone had any success with this? If so has anyone > documented it? The documentation that resides in pcbuild/readme.txt is > not helpful at all. What have you tried already? From the readme: All you need to do is open the workspace "pcbuild.sln" in MSVC++, select the Debug or Release setting (using "Solution Configuration" from the "Standard" toolbar"), and build the projects. Did that not work for you? If not, how did it fail? STeVe From C.delete_this.Sanders at BoM.GOv.AU Fri Apr 13 02:31:39 2007 From: C.delete_this.Sanders at BoM.GOv.AU (Charles Sanders) Date: Fri, 13 Apr 2007 16:31:39 +1000 Subject: Problem with algorithm In-Reply-To: <7xwt0gke79.fsf@ruckus.brouhaha.com> References: <1176434160.047703.214600@q75g2000hsh.googlegroups.com> <1176434937.258002.162220@p77g2000hsh.googlegroups.com> <461f1831$0$6621$c30e37c6@lon-reader.news.telstra.net> <7xwt0gke79.fsf@ruckus.brouhaha.com> Message-ID: <461f23cd$0$6621$c30e37c6@lon-reader.news.telstra.net> Paul Rubin wrote: [snip] > > def a(n): > if n==0: > yield '' > return > for c in s: > for r in a(n-1): > yield c+r > > print list(a(3)) Of course, obvious in retrospect, recursion instead of iteration. I have yet to completely wean myself off Fortran style thinking. Charles From python at rcn.com Fri Apr 27 01:24:52 2007 From: python at rcn.com (Raymond Hettinger) Date: 26 Apr 2007 22:24:52 -0700 Subject: Support for new items in set type In-Reply-To: <1hwxx1e.1un7urc1de872aN%aleax@mac.com> References: <1177211624.069474.3960@y5g2000hsa.googlegroups.com> <1hwxx1e.1un7urc1de872aN%aleax@mac.com> Message-ID: <1177651492.242686.283170@o40g2000prh.googlegroups.com> [Alex Martelli] > In your shoes, I would write a class whose instances hold three sets: > -- the "master set" is what you originally read from the file > -- the "added set" is the set of things you've added since then > -- the "deleted set" is the set of things you've deleted since them FWIW, I've posted a trial implementation in the Python cookbook: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/511496 Raymond Hettinger From ginstrom at tree.odn.ne.jp Wed Apr 4 00:41:32 2007 From: ginstrom at tree.odn.ne.jp (ginstrom) Date: 3 Apr 2007 21:41:32 -0700 Subject: Refactoring question In-Reply-To: References: Message-ID: <1175661692.837687.146350@q75g2000hsh.googlegroups.com> > On Behalf Of Kevin Walzer > What's the best way to do this? Can anyone point me in the > right direction? How could, for instance, the top snippet be > rewritten to separate the Tkinter parts from the generic stuff? I like to use the broadcaster/broker recipe at http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/81983 I added a few features (such as decorators for listener functions -- see below sig). There are other recipes out there, such as PyDispatcher. Basically, I have GUI events translated into broadcaster events (by passing lambdas that call broadcaster.Broadcast() to the event binders), which are received by controller functions/classes. Feedback (status/progress) is also communicated via broadcaster events. Something I tried on my current project, which is going fairly well, is first writing a command-line version, then writing a GUI version, with the same controller back-end used in each case, and the controller communicating progress/results via the same interface. This approach has made me keep presentation and logic very loosely coupled. So for instance, the view class would send request for processing, which the controller gets. The controller performs the requested action, sending broadcasts of progress (note that the controller can start a worker thread for the processing, but the broadcasts should be made on the GUI thread...) broadcaster.Broadcast( "progress", "start", (100, "Doing your bidding now..." ) ) # number of items we will process # ... broadcaster.Broadcast( "progress", "progress", (i, "Working on item %i" % i ) ) # current item # ... broadcaster.Broadcast( "progress", "end", (100, "Done!") ) Depending on who is showing the progress, this might go onto a status bar, progress dialog, the console, a log file, and so on, or some combination thereof -- the controller doesn't know or care. When the controller is finished, it asks the broker for a view, and calls show results on the view view = broker.Request( "view" ) view.ShowResults( results ) That could have been done equally with the broadcaster, but for some reason I like the broker here (it makes the view "dumber"). Regards, Ryan -- Ryan Ginstrom ================== # listener decorators def BrokerRequestHandler( title ): """A decorator for broker listeners @param title: the title to provide The decorated function must take no arguments (it can retrieve them using CurrentData()) """ def decorator(func): broker.Register( title, func ) return func return decorator def BroadcasterEventHandler( source, title ): """A decorator for broadcaster event handlers @param source: the broadcast source @param title: the title of the broadcast The decorated function must take no arguments (it can retrieve them using CurrentData()) """ def decorator(func): broadcaster.Register( func, source, title ) return func return decorator # example ... @BrokerRequestHandler( "meaning of life" ) def getMeaningOfLife(): return 42 ## A little more complicated for class methods. I stole this technique from WCK # Lifted shamelessly from WCK (effbot)'s wckTkinter.bind def EventHandler( source, title ): """Dectorator for event-handling methods""" def decorator(func): func.BroadcasterEvent = (source, title) return func return decorator class FrameController: """Controller for the main frame window""" def __init__( self ): for key in dir(self): method = getattr(self, key) if hasattr(method, "BroadcasterEvent") and callable(method): source, title = method.BroadcasterEvent broadcaster.Register( method, source=source, title=title ) @EventHandler( "event", "onExport" ) def onExport( self ): """Handles the onExport broadcast by exporting the database to the requested format""" format = broadcaster.CurrentData() # Perform export... From kw at codebykevin.com Tue Apr 3 20:05:58 2007 From: kw at codebykevin.com (Kevin Walzer) Date: Tue, 03 Apr 2007 20:05:58 -0400 Subject: Refactoring question Message-ID: I currently have a GUI application (using Tkinter) in which all the code is placed in a single script. This means that the GUI bits are a bit too tightly bound to the "under-the-hood" logic of the app. Here's an example snippet: def installPackage(self): self.package = self.infotable.getcurselection() if not self.package: showwarning('Error', 'Please select a package name.') return else: self.packagename = self.package[0][1] self.status.set('Installing %s' % self.packagename) self.showProgress() self.file = os.popen('echo %s | sudo -S /sw/bin/fink -y install %s' % (self.passtext, self.packagename), 'r', os.O_NONBLOCK) for line in self.file: self.textdisplay.configure(state='normal') self.textdisplay.insert(END, line) self.update() self.textdisplay.see(END) self.textdisplay.configure(state='disabled') self.endProgress() self.categorytree.selection_set('All') self.listCategoryPackages() I'd like to refactor and separate the GUI code from the back-end code; for instance, to move the "self.file = os.popen" bits into a separate category. I want to do this so that I can redesign the GUI using another toolkit, if I so choose, such as wxPython. What's the best way to do this? Can anyone point me in the right direction? How could, for instance, the top snippet be rewritten to separate the Tkinter parts from the generic stuff? -- Kevin Walzer Code by Kevin http://www.codebykevin.com From jstroud at mbi.ucla.edu Sat Apr 28 16:39:24 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Sat, 28 Apr 2007 13:39:24 -0700 Subject: My Python annoyances In-Reply-To: <1177790269.523160.276060@l77g2000hsb.googlegroups.com> References: <1177790269.523160.276060@l77g2000hsb.googlegroups.com> Message-ID: Andr? wrote: > I'm really annoyed at Python - and not for the reasons already > mentioned on this list. > > Everyone know that programming is supposed to be a dark art, nearly > impossible to learn. Computer code is supposed to be something > impossible to read to the common person and yet reveal their secrets > to the initiated - just remember the code displayed in the Matrix... > > Python takes all of that away. It is just too readable. Even > beginners can quickly learn to read code written by experts. > > To make it even friendlier to beginners, Python uses ugly double > underscores both as prefix and suffix on "magic methods" to be invoked > only by more advanced programmers. What's the fun in hiding the > complexity so that beginners can stay away from potential problems. > > And why, oh why, does raw_input() have to go? Here was at least one > good example of something that gave a hint (what does "raw" mean?) at > the underlying complexity. Combined with the evil of the hidden eval > in the more obvious input(), there was at least a chance to trip > beginners into doing something "dangerous". Alas, that will no longer > be the case... > > Python does not even make good use of weird symbols like $ and @ and % > to define variable types like Perl does. Now, that's a language to > learn if you want to be respected. I think that Georg Brandl had it > right in his recent proposal: > http://mail.python.org/pipermail/python-dev/2007-April/072419.html > > If not Perl, perhaps Python should be inspired by a language like C++, > full of arcane stuff and, thankfully, requiring typing declaration. > This dynamic typing thing makes it just too easy to write working > programs quickly, especially combined with the ease of use of the > interpreter. And this other thing called "duck typing" is just too > flexible to use. > > No, Python should be more difficult. It should take a full two > minutes to compile a "Hello World" program on a modern computer. > > Also, this "docstring" business has to go. Any programmer should, as > a rite of passage, have to spend countless hours reading obscure > documentation to learn other people's code before finding out what > methods can be used and how they should be used. Having to use things > like "dir" and "help" just makes it too easy. > > And don't get me started about the absence of curly braces to define > blocks of code. What's the fun in making it so darn visually easy to > define such blocks of code, removing the possibility of creating > subtle bugs due to the misplacement of a curly bracket. No sir, with > Python, the structure has to be obvious at a glance - newbies can see > it just as well as experts, thereby decreasing the aura surrounding > the latter. This is not fair for people that have spent dozens of > hours in learning to program using Python! > > And don't talk to me about functions, classes and methods, not to > mention modules. Python makes it too easy to write code in many > different styles, trying to please people who like to write only > object-oriented code as well as those that follow the more traditional > procedural approach. Even "functional" type people find their way to > write code in their preferred method using Python. This is not right. > > Fortunately, Python has incorporated some newbie-unfriendly features, > like metaclasses and, to a lesser extent, decorators which, at last, > make use of a special character. There should be more of these, to > make Python something more challenging to learn. > > Programming should be more difficult than this - otherwise, how can > programmers be respected by the common folks? > --- > Andr? > I want to complain about the fact that I wrote 200 lines the other day and it worked first time. Problem was, I spent 20 minutes before I realized that the lack of errors was a result of the lack of bugs. From huwenyan at gmail.com Thu Apr 5 12:11:08 2007 From: huwenyan at gmail.com (campos) Date: 5 Apr 2007 09:11:08 -0700 Subject: Support SSL for Solaris 10 Message-ID: <1175789468.487182.217750@w1g2000hsg.googlegroups.com> Hi all, Last time I installed Python 2.5 by default, it didn't support SSL. When I tried to use HTTPS, the following error occured: AttributeError: 'module' object has no attribute 'ssl' In README file: ---------------------------------------------------------------------------------------------- (a) the band-aid fix is to link the _socket module statically rather than dynamically (which is the default). To do this, run "./configure --with-threads=no" including any other options you need (--prefix, etc.). Then in Modules/Setup uncomment the lines: #SSL=/usr/local/ssl #_socket socketmodule.c \ # -DUSE_SSL -I$(SSL)/include -I$(SSL)/include/openssl \ # -L$(SSL)/lib -lssl -lcrypto and remove "local/" from the SSL variable. Finally, just run "make"! ---------------------------------------------------------------------------------------------- I followed these steps. However I am puzzled with: "remove "local/" from the SSL variable" I tried several cases such as "/usr/ssl", "~/local/ssl", "/usr/local/ ssl" All failed in building ssl module. How to solve it? Thanks in advance! From EneUran at yahoo.com Sun Apr 1 15:21:11 2007 From: EneUran at yahoo.com (Ene) Date: 1 Apr 2007 12:21:11 -0700 Subject: Character set woes with binary data In-Reply-To: References: <1175415685.21349.79.camel@pepper.trausch.us> Message-ID: <1175455271.758386.27060@l77g2000hsb.googlegroups.com> On Apr 1, 11:44 am, John Nagle wrote: > Michael B. Trausch wrote: > > In short: How do I create a string that contains raw binary content > > without Python caring? Is that possible? > > Given where we're now at with strings in Python, Python should > really have a "byte" type and a way to deal with arrays of bytes, > independent of the string operators. > > Efficient handling of lists of bytes would do it. > > John Nagle Python has a module base64 that allows you to handle binary data as a string. From robert.kern at gmail.com Thu Apr 26 01:56:50 2007 From: robert.kern at gmail.com (Robert Kern) Date: Thu, 26 Apr 2007 00:56:50 -0500 Subject: Preferred Random Library In-Reply-To: References: Message-ID: Bill Jackson wrote: > Is there a preferred random library? > > scipy.random > random > > Besides scipy's library returning ndarrays, is there any other > advantage/disadvantage? numpy.random (since that's where scipy.random comes from, I recommend always referring to it as numpy.random) can be a bit faster since it is implemented as entirely an extension module; parts of random are implemented in Python and incur Python function call overhead. It's certainly faster if you need a lot of numbers at once. numpy.random has several more non-uniform distributions implemented. numpy.random does not implement jumpahead(). random, naturally, does not require a third-party package. By and large, I'd say the distinguishing factor is whether or not you want to use numpy in your program. If so, then use numpy.random. If not, then use random. -- 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 mail at timgolden.me.uk Wed Apr 25 08:01:53 2007 From: mail at timgolden.me.uk (Tim Golden) Date: Wed, 25 Apr 2007 13:01:53 +0100 Subject: Now() In-Reply-To: <000301c78728$ba634ce0$2f29e6a0$@rawlins@thinkbluemedia.co.uk> References: <000301c78728$ba634ce0$2f29e6a0$@rawlins@thinkbluemedia.co.uk> Message-ID: <462F4331.8060004@timgolden.me.uk> Robert Rawlins - Think Blue wrote: > I'm using the following function 'str (now)' to place a date time stamp into > a log file, which works fine, however it writes the stamp like this. > 2007-04-25 11:06:53.873029 > But I need to expel those extra decimal places as they're causing problems > with the application that parses the log data, all I need is something like > this: > 2007-04-25 11:06:53 > With time depicted to the nearest second, from my background in ColdFusion > development we used to have a datetimeformat() function that I could use as > DateTimeFormat(now(), "yyyy-mm-dd HH:mm:ss") > Which would give the current time a mask. > Any equivalent for this in python? You want the strftime method which is documented under the time module. import datetime print datetime.datetime.now ().strftime ("%Y-%m-%d etc.") TJG From thorsten at thorstenkampe.de Sun Apr 1 14:45:59 2007 From: thorsten at thorstenkampe.de (Thorsten Kampe) Date: Sun, 1 Apr 2007 19:45:59 +0100 Subject: I18n issue with optik References: Message-ID: * Steven Bethard (Sun, 01 Apr 2007 10:26:54 -0600) > Thorsten Kampe wrote: > > I guess the culprit is this snippet from optparse.py: > > > > # used by test suite > > def _get_encoding(self, file): > > encoding = getattr(file, "encoding", None) > > if not encoding: > > encoding = sys.getdefaultencoding() > > return encoding > > > > def print_help(self, file=None): > > """print_help(file : file = stdout) > > > > Print an extended help message, listing all options and any > > help text provided with them, to 'file' (default stdout). > > """ > > if file is None: > > file = sys.stdout > > encoding = self._get_encoding(file) > > file.write(self.format_help().encode(encoding, "replace")) > > > > So this means: when the encoding of sys.stdout is US-ASCII, Optparse > > sets the encoding to of the help text to ASCII, too. But that's > > nonsense because the Encoding is declared in the Po (localisation) > > file. > > > > How can I set the encoding of sys.stdout to another encoding? Of > > course this would be a terrible hack if the encoding of the > > localisation changes or different translators use different > > encodings... > > If print_help() is what's wrong, you should probably hack print_help() > instead of sys.stdout. You could try something like:: > > def print_help(self, file=None): > """print_help(file : file = stdout) > > Print an extended help message, listing all options and any > help text provided with them, to 'file' (default stdout). > """ > if file is None: > file = sys.stdout > file.write(self.format_help()) > > optparse.OptionParser.print_help = print_help > > cmdlineparser = optparse.OptionParser(description=...) > ... > > That is, you could monkey-patch print_help() before you create an > OptionParser. Yes, I could do that but I'd rather know first if my code is wrong or the optparse code. Thorsten From gagsl-py2 at yahoo.com.ar Sat Apr 28 03:14:26 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: 28 Apr 2007 00:14:26 -0700 Subject: Dedicated CPU core for Python? In-Reply-To: <46323f34$0$16283$88260bb3@free.teranews.com> References: <1177607759.916727.180950@t39g2000prd.googlegroups.com> <4630e90c$0$16272$88260bb3@free.teranews.com> <46323f34$0$16283$88260bb3@free.teranews.com> Message-ID: <1177744466.587152.229550@e65g2000hsc.googlegroups.com> Joshua J. Kugler ha escrito: > On Thursday 26 April 2007 14:07, Gabriel Genellina wrote: > > > En Thu, 26 Apr 2007 15:54:38 -0300, Joshua J. Kugler > > escribi?: > >> CPython only > >> uses one > >> CPU core right now because it's threads are all internal, and do not > >> spawn system threads (IIRC). > > > > Python threads are OS threads: > > http://docs.python.org/lib/module-thread.html > > "[The thread module] is supported on Windows, Linux, SGI IRIX, Solaris > > 2.x, as well as on systems that have a POSIX thread (a.k.a. ``pthread'') > > implementation." > > Yes, that may be, but they are not true system threads, or at least do not > appear to be. Threads on linux each show up as a separate process. I can > have several threads in my Python program, but no additional processes show > up in ps -A. I don't see how Python threads can be system threads with the > GIL. But, I've been wrong before, and threads are something I have very > light knowledge of. Try with ps -L gag at 4[~]$ ps -L -C python PID LWP TTY TIME CMD 3952 3952 pts/1 00:00:03 python 3952 3956 pts/1 00:00:00 python 3952 3957 pts/1 00:00:00 python 3952 3958 pts/1 00:00:00 python 3952 3959 pts/1 00:00:00 python 3952 3960 pts/1 00:00:00 python 3952 3961 pts/1 00:00:00 python 3952 3962 pts/1 00:00:00 python Or ps --help depending on your system. -- Gabriel Genellina From peter.maas at nospam.de Tue Apr 17 17:17:56 2007 From: peter.maas at nospam.de (Peter Maas) Date: Tue, 17 Apr 2007 23:17:56 +0200 Subject: scipy 0.52 det crashes python Message-ID: I tried some scipy examples using scipy 0.52, numpy 1.02 and python 2.5 on a WinXP SP2 machine. numpy.linalg.det() works but scipy.linalg.det() crashes python. Has anybody experienced this and can point me to a solution? Thanks for your help. Peter Maas, Aachen From bdesth.quelquechose at free.quelquepart.fr Sat Apr 21 14:45:31 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sat, 21 Apr 2007 20:45:31 +0200 Subject: Shebang or Hashbang for modules or not? In-Reply-To: References: <1176308951.932721.197630@y80g2000hsf.googlegroups.com> <461d56e9$0$27586$426a74cc@news.free.fr> <461fe2d8$0$11935$426a74cc@news.free.fr> Message-ID: <462a5259$0$26883$426a74cc@news.free.fr> Jorgen Grahn a ?crit : > On Fri, 13 Apr 2007 22:46:03 +0200, Bruno Desthuilliers wrote: > >>Jorgen Grahn a ?crit : > (snip) > >>More seriously, and as far as I'm concerned, when I want to make a >>python script (by opposition to a python 'module') available as a unix >>command, I either use a symlink or a shell script calling the python >>script. > > > A symlink yes, but a shell script? Wouldn't it be easier to write a > one-liner (well, two-liner) Python script in that case? Not necessarily. Just like there are cases where it makes sens to use Perl instead of Python, some things are really far simpler to do with shell scripts... From jorgen.maillist at gmail.com Thu Apr 5 13:46:20 2007 From: jorgen.maillist at gmail.com (Jorgen Bodde) Date: Thu, 5 Apr 2007 19:46:20 +0200 Subject: PyDispatcher question Message-ID: <11e49df10704051046p65ac623fqcae6d3a010a7e415@mail.gmail.com> Hi all, Hopefully someone can help me. I am fairly new to Python, and I am looking into PyDispatcher. I am familiar with the C++ sigslot variant, and I wonder how similar PyDispatches is. I run in to the following 'problem' (pseudo code, untested here) import pydispatch.dispatcher class A: def __init__(self): dispatcher.connect(self.someSignal, signal = 1) def someSignal(self): print 'Hello world' obj = A() # send a trial signal dispatcher.send(signal = 1) >>> Hello world # now for the catch, how to clean up? # if I do: obj = None # clean up dispatcher.send(signal = 1) >>> Hello world The object still extists... Which is logical, the method is still bound to the signal, and the object itself is not yet deleted. Is there an elegant way to delete the object and let the signal unbind itself? Or do I need to do this in the destructor of the object? AFAIK there is no real destructor in Python? Do I need to do it differently? Or is there a better signal mechanism to use? Any help is appreciated! - Jorgen From wyldwolf at gmail.com Fri Apr 13 08:39:42 2007 From: wyldwolf at gmail.com (Kevin Kelley) Date: Fri, 13 Apr 2007 07:39:42 -0500 Subject: "Cloning" file attributes and permissions In-Reply-To: <1176434728.43319@jubilee.claranet.pt> References: <1176394818.428367@jubilee.claranet.pt> <1176406707.711609.211110@q75g2000hsh.googlegroups.com> <1176419326.395692@jubilee.claranet.pt> <1176423552.199317.129400@n59g2000hsh.googlegroups.com> <1176423910.777066.45850@y80g2000hsf.googlegroups.com> <1176434728.43319@jubilee.claranet.pt> Message-ID: <77895c1d0704130539o5e516e1ds67da360d6527bd5b@mail.gmail.com> If you know what the permissions are going to be then you can use umask to set the default file creation permissions to match. Then any files created in that directory will have the correct permissions. I think the "pythonic" way to solve this problem would be to code up your own module which handles all the dirty parts in the background. It would create the new file, stat the original, and chmod/chown the new file as needed to match the original. All you would have to do after creating the module is pass the new function the original and new file information. -- Kevin Kelley On 4/12/07, Paulo da Silva wrote: > > attn.steven.kuo at gmail.com escreveu: > > On Apr 12, 5:19 pm, attn.steven.... at gmail.com wrote: > >> On Apr 12, 4:09 pm, Paulo da Silva wrote: > >> > ... > > > > After poking around a bit I also discovered the > > shutil module. It looks like you can use > > shutil.copy2. More Pythonic, yes? > > > > > I have seen that in the index but I thought it was a different thing > because it was referenced as "high-level operations". > Anyway that helps but I still need to copy the whole file or to use stat > and chown for the user/group ids. > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From spradml at gmail.com Mon Apr 9 13:56:03 2007 From: spradml at gmail.com (Pradnyesh Sawant) Date: Mon, 9 Apr 2007 23:26:03 +0530 Subject: output of top on a linux box In-Reply-To: <82d28c40704091032p3c5fcc35p38ee9509ca3fa7c0@mail.gmail.com> References: <80628d680704072342r60b57995mad6c505505a919a8@mail.gmail.com> <80628d680704091026u7e98719co3d63a7913832475a@mail.gmail.com> <82d28c40704091032p3c5fcc35p38ee9509ca3fa7c0@mail.gmail.com> Message-ID: <80628d680704091056h735fc0a7l6cf7b586f4bac715@mail.gmail.com> Thanks for the pointer to use /proc/stat However, that does not answer my other question about string slicing Any pointers in that direction would be helpful... Thanks a lot! On 4/9/07, Jeff McNeil wrote: > Can you pull the same information from /proc/stat as opposed to using > a pipe to top? The first line(s) should contain (at least): > > cpu usermode, lowprio, system, idle, hz. > > The 2.6 kernel adds iowait, irq, and soft irq. It seems that this > might be a better solution than executing that additional command. > > Take a look at proc(5). > > Thanks, > > Jeff > > > > > > On 4/9/07, Pradnyesh Sawant wrote: > > Hello, > > I need the cpu usage of a linux box, for which i capture the output of > > "top" using "popen". However, i am facing problems during string > > handling. The code snippet is:- > > > > top = os.popen("top -n 1") > > rd = top.read().split("\n") > > splt = rd[2].split() > > # cpu = splt[2][:-4] # why ain't this working ??? > > cpu = splt[2] > > print "cpu usage: %s, %s" % (cpu, type(cpu)) > > > > the "print" statement prints, "cpu usage: 0.5%sy, ". i > > tried my best to get rid of the "%sy" after the "0.5", but couldn't > > succeed (even though the type of "cpu" is "string"). > > > > Also, one weird thing that was happening was that if i still "split" > > the cpu string (removed the last 4 characters), the output of the next > > print statement was wrong (specifically, the first 2 characters got > > chipped off). This output is totally unexpected, and wrong... > > > > Can anyone kindly help me in understanding what exactly is going on here. > > > > Thanks a lot! > > -- > > http://mail.python.org/mailman/listinfo/python-list > > > From upftftip at gmail.com Tue Apr 3 21:09:03 2007 From: upftftip at gmail.com (upftftip at gmail.com) Date: 3 Apr 2007 18:09:03 -0700 Subject: Tkinter, how to get a button's bg color Message-ID: <1175648943.553642.201330@y66g2000hsf.googlegroups.com> I am new to Tkinter. Following an example, I executed the following: window = Tk() b = Button(window) b.configure(bg = '#FF00FF') b.grid(row = 0, column = 0) how can I later get the value of this button's background color? Thanks. From rokkamraja at gmail.com Wed Apr 25 01:00:54 2007 From: rokkamraja at gmail.com (Raja) Date: 24 Apr 2007 22:00:54 -0700 Subject: Overide settrace Message-ID: <1177477254.540084.115500@u32g2000prd.googlegroups.com> Hi, I want to override the sys.settrace() call, create a way to trace the execution of a python program. Keep track of all objects created and destroyed. Keep track of the call pattern throughout the execution of the program and output a simplified "call graph" to standard out. Please help me in this regard. Thank You, From python at rcn.com Thu Apr 5 11:43:45 2007 From: python at rcn.com (Raymond Hettinger) Date: 5 Apr 2007 08:43:45 -0700 Subject: Review/commit patch? In-Reply-To: References: Message-ID: <1175787825.722182.93410@n59g2000hsh.googlegroups.com> [Kevin Walzer] > How long does it take for a patch at the Python SF tracker to be > reviewed and/or committed? I am unfamiliar with how the process works. > > (I originally submitted a bug report, then figured out how to patch the > item in question, and subsequently submitted a patch.) Which bug report and patch is yours? Raymond From anthony at python.org Thu Apr 19 04:45:59 2007 From: anthony at python.org (Anthony Baxter) Date: Thu, 19 Apr 2007 18:45:59 +1000 Subject: RELEASED Python 2.5.1, FINAL Message-ID: <200704191846.06857.anthony@python.org> On behalf of the Python development team and the Python community, I'm happy to announce the release of Python 2.5.1 (FINAL) This is the first bugfix release of Python 2.5. Python 2.5 is now in bugfix-only mode; no new features are being added. According to the release notes, over 150 bugs and patches have been addressed since Python 2.5, including a fair number in the new AST compiler (an internal implementation detail of the Python interpreter). This is a production release of Python, and should be a painless upgrade from 2.5. Since the release candidate, we have backed out a couple of small changes that caused 2.5.1 to behave differently to 2.5. See the release notes for more. For more information on Python 2.5.1, including download links for various platforms, release notes, and known issues, please see: http://www.python.org/2.5.1/ Highlights of this new release include: Bug fixes. According to the release notes, at least 150 have been fixed. Highlights of the previous major Python release (2.5) are available from the Python 2.5 page, at http://www.python.org/2.5/highlights.html Enjoy this release, Anthony Anthony Baxter anthony at python.org Python Release Manager (on behalf of the entire python-dev team) -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/pgp-signature Size: 196 bytes Desc: not available URL: From laurent.pointal at limsi.fr Mon Apr 30 07:35:00 2007 From: laurent.pointal at limsi.fr (Laurent Pointal) Date: Mon, 30 Apr 2007 13:35:00 +0200 Subject: Chart drawing tool in python In-Reply-To: <1177897942.532255.317000@y80g2000hsf.googlegroups.com> References: <1177897942.532255.317000@y80g2000hsf.googlegroups.com> Message-ID: yinglcs at gmail.com a ?crit : > Hi, > > In Perl, there is a GD module to draw custom chart. > > http://www-128.ibm.com/developerworks/opensource/library/os-perlgdchart/?ca=dgr-lnxw01Perl-GD-Charts > > Can you please tell me if there is an equivalent library in python? > > Thank you. > You may look at DISLIN too. http://www.mps.mpg.de/dislin/ http://www.mps.mpg.de/dislin/examples.html http://www.mps.mpg.de/dislin/server.html A+ Laurent. From aboudouvas at panafonet.gr Thu Apr 12 04:01:45 2007 From: aboudouvas at panafonet.gr (king kikapu) Date: 12 Apr 2007 01:01:45 -0700 Subject: About Trolltech QT OpenSource license. In-Reply-To: References: <1176233376.712861.67160@o5g2000hsb.googlegroups.com> <1176237050.409742.8760@30g2000cwc.googlegroups.com> <1176285062.178372.15090@d57g2000hsg.googlegroups.com> <1176326271.183571.286710@l77g2000hsb.googlegroups.com> Message-ID: <1176364905.342440.295520@l77g2000hsb.googlegroups.com> On Apr 12, 1:02 am, Robert Kern wrote: > All parts of the software have to be licensed compatibly with the GPL. The FSF > has a fairly comprehensive list of the licenses they believe are GPL-compatible. > The source that you provide needs to be the preferred form for making > modifications; i.e., you can't use a tool that obfuscates the code. You need to > provide the scripts that you use to build the software. You have to be careful > about using patented techniques in your code. The source code must be offered at > no extra charge (this part of the license is a bit tricky, so please read the > license and the commentaries). Ok, i see...You said "All parts of the software have to be licensed compatibly with the GPL". What if, let's say, my application's GUI is made by Qt (Open Source edition that is indeed under GPL license) and in this application i use some module(s) that i bought from some other company and they aren't under GPL, do you see any implication to this ? Thanks you all again! From caleb.hattingh at gmail.com Sat Apr 21 19:24:45 2007 From: caleb.hattingh at gmail.com (Caleb Hattingh) Date: 21 Apr 2007 16:24:45 -0700 Subject: No speedup on multi-processor machine? In-Reply-To: <1177189332.916296.205280@d57g2000hsg.googlegroups.com> References: <1177189332.916296.205280@d57g2000hsg.googlegroups.com> Message-ID: <1177197885.077863.314470@n59g2000hsh.googlegroups.com> On Apr 21, 11:02 pm, danfan1... at yahoo.com wrote: > Hi, > I am using Python Thread library for my parallel processing course > project. I am doing matrix convolution on a multi-processor machine > running Solaris. I just found out that no speed-up is obtained with > threading. It is probably because of something called GIL in Python. > How can I get around > that GIL and get speed-up? > Thanks in advance. > Daniel Perhaps try http://www.parallelpython.com/ or http://www.its.caltech.edu/~astraw/seppo.html Caleb From rridge at caffeine.csclub.uwaterloo.ca Mon Apr 23 13:25:55 2007 From: rridge at caffeine.csclub.uwaterloo.ca (Ross Ridge) Date: Mon, 23 Apr 2007 13:25:55 -0400 Subject: Python's handling of unicode surrogates References: <1177122874.524447.85130@p77g2000hsh.googlegroups.com> <462C4305.1000809@v.loewis.de> Message-ID: Ross Ridge writes: > The Unicode standard doesn't require that you support surrogates, or > any other kind of character, so no you wouldn't be lying. wrote: > There is the notion of Unicode implementation levels, and each of them > does include a set of characters to support. There are different levels of implemtentation for ISO 10646, but not of Unicode. > It is probably an interpretation issue what "supported" means. The strongest claim to support Unicode that you can meaningfully make is that of conformance to the Unicode standard. The Unicode standard's conformance requirements make it explicit that you don't need to support any particular character: C8 A process shall not assume that it is required to interpret any particular coded character representation. . Processes that interpret only a subset of Unicode characters are allowed; there is no blanket requirement to interpret all Unicode characters. [...] > Python clearly supports Unicode level 1 (if we leave alone the issue > that it can't render all these characters out of the box, as it doesn't > ship any fonts); It's not at all clear to to me that Python does support ISO 10646's implementation level 1, if only because I don't, and I assume you don't, have a copy of ISO 10646 available to verify what the requirements actually are. Ross Ridge -- l/ // Ross Ridge -- The Great HTMU [oo][oo] rridge at csclub.uwaterloo.ca -()-/()/ http://www.csclub.uwaterloo.ca/~rridge/ db // From stj911 at rock.com Wed Apr 4 15:07:30 2007 From: stj911 at rock.com (stj911 at rock.com) Date: 4 Apr 2007 12:07:30 -0700 Subject: *** It is IMPOSSIBLE to create a RABBIT FARM using the hat a MAGICIAN pulls a rabbit out of *** Message-ID: <1175713650.228538.165920@p77g2000hsh.googlegroups.com> Please visit www.nkusa.org, www.911blogger.com, www.stj911.org: I am surprised at the number of un-informed, ill-informed sheeple on earth as well as politically correct hypocrites. Several polls have consistently shown that about 84% of the American people believe that 911 was an inside job. The fact is the 911 was a RACIST AND HEINOUS CRIME by a group of criminal and racist Americans themselves. There is no video that Federal Bureau of Incompetence could produce of plane hitting the Pentagon. On the contrary, they acted as Foolish PATSIES for the criminal operators of 911 by confiscating and destroying all other camera footage from buildings around Pentagon. Next, WTC7 just committed suicide. Thermate residue has been found as finger print left by the criminals. Please visit 911blogger.com, st911.org and many other sites. 911 official story is a forgery like the protocols of the learned elders of zion. It is as fake as a magician pulling a rabbit out of his hat, and does that mean you can have a rabbit farm from that hat? I cant believe how many idiots that we have. And the most interesting thing is that most lead researchers of the movement are either Christian or Jewish. The MIT engineer, Jeff King does not sound like an Arab name. Now what is the connection with Europe? Note the very first post in this discussion starts with Islamophobia. Its probably a patsy of the criminal cabal that pulled off 911. We have a strong feeling that almost ALL THE INTELLIGENCE CHIEFS of EUROPE knew instantly that 911 was a fraud. President Putin himself had carried out such a false flag operation based on blowing Moscow apartment buildings to enter the second Chechen war. Jon Carlson has written an excellent investigative piece entitled "Russia Watched 9/11 In Real Time On Satellite" which you can find via google using these clues. Racists of Europe, such as in France, Holland were immediately ready to take full advantage of 911 hoax. India, immediately understood that 911 was a hoax and staged its own fake terrorist attacks to harass Pakistan. Bush used it to harass Pakistan into submitting the father of their nuclear bomb, Dr Abdul Qadeer Khan to CIA interrogation. There was another goal of 911. Scare Muslim leader into becoming patsies to destroy their society from within. Once it is internally weak, then a stone can be shattered by one blow. Iraq was thus first weakened by sanctions, and then attack to shatter it. By God, they will not succeed. Elohim has power over all things. The universe has hidden dimension and God watches everything from there. That is what is happening. They can conspire but they will be defeated. All those who have died in Iraq from crimes are going to go to heaven. All the Americans who have committed atrocities will go to hell. All Americans or Iraqis who will do good deeds will be judged accordingly. God has absolutely no partiality towards any religion or race. You are seeing events move extremely fast. Iran has brought UK to a stalemate. Hezbollah has essentially defeated Israel, in the sense that the latter has failed to obtain its objectives of the war. The racist and heinous crime of the 911 operators has been exposed. This is the lynchpin from which will follow a large change in the world, but not in the way the 911 operators of controlled demolition intended, but totally opposite. The wife cheaters, the newt gingrichs, the pedophiles reagans herbert bush, as in the video "conspiracy of silence" where FBI criminals tried to criminally coverup is now exposed. This is never going to go away. The video evidence is far and wide dispersed on earth and archived. The true believers from all faiths have joined hands and will not be divided by pedophile, sex crazed, wife cheaters and genocidal murderers and their deception and lies based on psychological tactics of Edward Bernays. I ask you all for a moment of silence in the honor of 911 truth movement people, Alex Jones, Dr Steven Jones, Dr Fetzer, Dr Jeff King and many others I am failing to mention but God knows them and their reward is with Him. From sbassi at clubdelarazon.org Tue Apr 3 11:51:52 2007 From: sbassi at clubdelarazon.org (Sebastian Bassi) Date: Tue, 3 Apr 2007 12:51:52 -0300 Subject: Problem installing Python 2.5 In-Reply-To: References: Message-ID: <9e2f512b0704030851n39bda9e9i9437ad038edff732@mail.gmail.com> On 4/3/07, Jaroslaw Zabiello wrote: > After executing > ./configure > you have to edito > Modules/Setup > file and uncomment the following line: > #zlib zlibmodule.c -I$(prefix)/include -L$(exec_prefix)/lib -lz > Then continue with normal make; make install. Thank you. I already did this: make -i altinstall and then: make altinstall And added a comment in bug#1669349 Best, SB. From clarence1126 at gmail.com Wed Apr 11 15:26:21 2007 From: clarence1126 at gmail.com (Clarence) Date: 11 Apr 2007 12:26:21 -0700 Subject: MRO theory In-Reply-To: References: <1176317929.068559.263330@o5g2000hsb.googlegroups.com> Message-ID: <1176319581.754293.151420@p77g2000hsh.googlegroups.com> On Apr 11, 12:09 pm, Steve Holden wrote: > Without wishing to lay claim to genius, I'd suggest that you don;'t > write programs relying on multiple inheritance until you have a thorough > understanding of its principles. > > The inability of the interpreter to create a consistent mro has nothing > to do with the order in which the base classes were created or where > they appear in memory. It's probably because you have introduced a > circularity: you are trying to define something based on A, which is > based on B, which is based on A or something similar. > No, there is no circularity. The problem is coming about in the JPype application. It creates a Python class to proxy any Java class or Java interface that the program uses (directly or indirectly). As far as the Java proxies go, when it creates a class it can have at most one superclass that is a proxy of a Java class, and arbitrarily many superclasses which are proxies of Java interfaces. The problem basically comes about because interfaces are not classes, but a class is being created to stand in for each one. There is real Java code that is causing a class construction failure because of an inability to construct a consistent mro. I've tried several approaches to make it work, and by accident, sorting the list of interface proxy classes, using the default comparison, make it work. That made me wonder if the theory had something to say. Obviously, if class A is created before class B, then B cannot be a base class of A, hence the chronological order of class creation _might_ have something to do with creating acceptable or unacceptable mro's. From robert.kern at gmail.com Sun Apr 15 20:27:00 2007 From: robert.kern at gmail.com (Robert Kern) Date: Sun, 15 Apr 2007 19:27:00 -0500 Subject: working of round() In-Reply-To: <1176682019.215351.114560@y80g2000hsf.googlegroups.com> References: <1176682019.215351.114560@y80g2000hsf.googlegroups.com> Message-ID: Krishna.K.1900 at gmail.com wrote: > Does round() always perfectly return the output expected or are there > some artifacts which don't allow perfect functionality > > Using python 2.5: >>>> round(12.234, 2) > 12.23 >>>> round(12.234, 3) > 12.234 >>>> round(12.234, 1) > 12.199999999999999 > > but was expecting 12.2 http://docs.python.org/tut/node16.html > Also, for round(x,n), can't 'x' be an expression > > round(5.25/2, 2) > > was expecting 2.62 , but > >>>> round(5.25/2, 2) > 2.6299999999999999 round(x, n) essentially does the following: math.floor(x * 10**n + 0.5) / 10**n Since (5.25/2)*100 == 262.5, adding 0.5 gives 263.0 and ultimately 2.63 as the rounded number. round() does not do anything more complicated like round-to-even. Use the decimal module if you want decimal arithmetic rather than binary floating point. -- 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 gagsl-py2 at yahoo.com.ar Thu Apr 5 12:55:08 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 05 Apr 2007 13:55:08 -0300 Subject: Windows service and pyc files References: <1175709094.352514.64920@y66g2000hsf.googlegroups.com> <46151D34.50608@designaproduct.biz> Message-ID: En Thu, 05 Apr 2007 13:00:52 -0300, Laszlo Nagy escribi?: > p = subprocess.Popen(params, bufsize=1, stdout=fout.fileno(), > stderr=fout.fileno()) > > When I call spawn() from a service, this is written into the logfile: > > 2007-04-05 17:52:53,828 INFO .Spawner Spawing > ['C:\\Python25\\lib\\site-packages\\win32\\PythonService.exe', > 'T:\\Python\\Projects\\Test\\Application.py'] > 2007-04-05 17:52:53,828 ERROR .Spawner Traceback (most recent call last): > File "T:\Python\Projects\Test\Processor.py", line 40, in spawn_downloader > p = subprocess.Popen(params, bufsize=1, stdout=fout.fileno(), > stderr=fout.fileno()) > File "C:\Python25\lib\subprocess.py", line 586, in __init__ > errread, errwrite) = self._get_handles(stdin, stdout, stderr) > File "C:\Python25\lib\subprocess.py", line 681, in _get_handles > p2cread = self._make_inheritable(p2cread) > File "C:\Python25\lib\subprocess.py", line 722, in _make_inheritable > DUPLICATE_SAME_ACCESS) > TypeError: an integer is required With a bit of guessing, I think I've found what's happening. Since you don't provide a value for stdin, None is used. Inside subprocess.py, method _get_handles, line 670, GetStdHandle *may* return None; in that case _make_inheritable fails. If you print the value of p2cread in line 670 I bet you'll get None. The fix is to test for None in _make_inheritable (line 720): if handle is not None: return DuplicateHandle(...) (else return None, implicit) > When I call spawn() from an application, it works just fine. Any ideas? According to http://msdn2.microsoft.com/en-us/library/ms683231.aspx GetStdHandle may return NULL (translated to None in Python) when invoked from a service with no redirected standard handles. From an application, there is no problem. Please try the simple fix above to comfirm it works; I'll submit a patch if that's the case. -- Gabriel Genellina From howachen at gmail.com Wed Apr 18 11:54:49 2007 From: howachen at gmail.com (howa) Date: 18 Apr 2007 08:54:49 -0700 Subject: Compiling python from soruce vs RPM ? Message-ID: <1176911689.026633.230390@l77g2000hsb.googlegroups.com> I have compiled python 2.5 from source i.e. ./configure make make install but when i try to install another package require python, seems it can't regonize python... e.g.. /usr/bin/python is needed by xyz From beliavsky at aol.com Sun Apr 29 09:56:01 2007 From: beliavsky at aol.com (Beliavsky) Date: 29 Apr 2007 06:56:01 -0700 Subject: Numbers and truth values In-Reply-To: <1hxa95b.13zrrmv1wucw71N%aleax@mac.com> References: <1hxa95b.13zrrmv1wucw71N%aleax@mac.com> Message-ID: <1177854961.385898.221410@n59g2000hsh.googlegroups.com> On Apr 28, 4:05 pm, a... at mac.com (Alex Martelli) wrote: > John Nagle wrote: > > > I'd have to consider that a bug. > > > Some very early FORTRAN compilers allowed you to redefine > > integer constants: > > > CALL SET(25,99) > > WRITE (6,100) 25 > > 100 FORMAT(I6) > > > SUBROUTINE SET(IVAR, INEWVAL) > > IVAR = INEWVAL > > > would print > > > 99 > > > It was generally agreed by 1970 or so that this was a bad idea, > > and was taken out of the language. > > It was still perfectly legal in the Fortran 1977 standard for a compiler > to cause this effect, because the Fortran source you quote has > *undefined behavior* -- the compiler doesn't have to diagnose this error > and can cause any effects as a consequence. > > The point of Fortran is to let the compiler generate the fastest code it > can, NOT to "tenderly hold your hand" lest scary bugs disturb your > blessed and dreamy innocence. The point of Fortran has been to make scientific programmers more productive, and catching errors and producing fast programs are BOTH ways of doing that. Compilers are judged on BOTH criteria: speed: http://www.polyhedron.com/pb05/linux/f90bench_p4.html diagnostics: http://www.polyhedron.com/pb05/linux/diagnose.html If there is a compiler with great compile- and run-time debugging capability with the right options turned on, and if the compiler also produces optimally fast code with another set of options (or if another compiler does this), isn't that the best of both worlds? > If this has changed in the Fortran 1990 standard or later, then I can > only say I'm happy I stopped using Fortran heavily before such standards > became widespread in commonly available compilers -- by the late '90s, > when I was still using _some_Fortran, it was Fortran '77, as that was > the version that was widely available and well optimized. I don't think the official status of such has changed -- it's still illegal to change a constant and the compiler is still not required to catch the error -- but compilers may be more likely to reject such code as before, helping programmers spot errors. IMO that's a good thing. When is no longer using a language, one has the luxury of thinking about it in an ideological rather than practical manner. From andrew.jefferies at gmail.com Thu Apr 26 08:19:10 2007 From: andrew.jefferies at gmail.com (andrew.jefferies at gmail.com) Date: 26 Apr 2007 05:19:10 -0700 Subject: File not read to end In-Reply-To: <-LWdnRS04OCCCLLbnZ2dnUVZ_uSgnZ2d@comcast.com> References: <1177522730.327454.121120@s33g2000prh.googlegroups.com> <-LWdnRS04OCCCLLbnZ2dnUVZ_uSgnZ2d@comcast.com> Message-ID: <1177589949.885985.164380@c18g2000prb.googlegroups.com> On Apr 25, 2:51 pm, Larry Bates wrote: > andrew.jeffer... at gmail.com wrote: > > Hi, > > > I'm trying to write a simple log parsing program. I noticed that it > > isn't reading my log file to the end. > > > My log is around 200,000 lines but it is stopping at line 26,428. I > > checked that line and there aren't any special characters. > > > This is the file reading code segment that I'm using: > > sysFile=open(sysFilename,'r') > > lineCount = 0 > > for line in sysFile: > > lineCount +=1 > > print str(lineCount) + " -- " + line > > > I also stuck this same code bit into a test script and it was able to > > parse the entire log without problem. Very quirky. > > > This is my first foray from Perl to Python so I appreciate any help. > > > Thanks in advance. > > > --Andrew > > Show us more of your surrounding code so we have some chance of figuring > out why this working code stops. There's nothing wrong with this code, > the problem is somewhere else. > > Suggestion: > > lineCount = 0 > for line in sysFile: > lineCount +=1 > print str(lineCount) + " -- " + line > > can be written: > > for lineCount, line in enumerate(sysFile): > print "%i--%s" % (lineCount, line) > > -Larry Hi Larry, I've attached the whole script. Thanks again for your help. --Andrew import getopt, sys, re, os def main(): try:# Get options for processing o, a = getopt.getopt(sys.argv[1:], 'a:d:hl') except getopt.GetoptError: # print help information and exit: usage() sys.exit(2) opts = {} for k,v in o: #Parse parameters into hash opts[k] = v #make sure that all of the needed options are included if opts.has_key('-h'): #Return help for - h usage() sys.exit(0) if opts.has_key('-l'): pathname = opts['-l'] if not (opts.has_key('-a')): usage() sys.exit() else: address=opts['-a'] if not (opts.has_key('-d')): usage() sys.exit() if not (opts.has_key('-l')): # Use current path if not provided pathname = os.path.abspath(os.path.dirname(sys.argv[0])) # Get file names and open files sysFilename = os.path.abspath(pathname) + "\sys" + opts["-d"] + ".txt" #logFilename = opts["-l"] + "\log" + opts["-d"] + ".txt" spamFilename = os.path.abspath(pathname) + "\spam" + opts["-d"] + ".log" print "Loading Files:\n" + sysFilename + "\n" + spamFilename + "\n" try: #Open log files sysFile=open(sysFilename,'rb') #logFile=open(logFilename,'r') spamFile=open(spamFilename,'rb') except: print "could not open file for reading" , sys.exc_info()[0] sys.exit() ToAddr = {} # This will hold Messages TO the address FrAddr = {} # This will hold Messages FROM the address numFound = 0 # For Testing notFound = 0 # For Testing lineCount = 0 # For Testing #Read file and get message IDs that correspond to the searched address for line in sysFile: lineCount +=1 # For Testing # print str(lineCount) + " -- " + line daRegex = re.compile(address) if daRegex.search(line): #Found address in line - Continue processing #re.search(address,line): #If line has address print line + "\n" # For Testing numFound +=1 # For Testing if re.search('MAIL FROM:',line): #Add it (message id) to the From list if needed MID = getMID(line) if FrAddr.has_key(MID): break else: FrAddr[MID]="" #print "From: " + MID + "\n" elif re.search('RCPT TO:',line): #Add it (message id) to the To list if needed MID = getMID(line) if ToAddr.has_key(MID): break else: ToAddr[MID]="" else: notFound +=1 #For Testing # Close and re-open file for re-processes (there is probably a better way to do this) sysFile.close sysFile=open(sysFilename,'r') for line in sysFile: # Get all messages with message IDs that have been found MID = getMID(line) if FrAddr.has_key(MID): FrAddr[MID]+=line # print line + "\n" elif ToAddr.has_key(MID): ToAddr[MID]+=line sysFile.close for line in spamFile: # Get similar messages from spam file MID = getMID(line) if FrAddr.has_key(MID): FrAddr[MID]+='SPAM>>>'+ line elif ToAddr.has_key(MID): ToAddr[MID]+='SPAM>>>'+ line spamFile.close #open output files fname = pathname + "\\" + address + ".txt" fout = open(fname,'w') # Output and format for key in FrAddr.keys(): fout.write("<<<<<<< FROM "+ address+ " Message ID "+ key + "------------\n") fout.write(FrAddr[key]+"\n") for key in ToAddr.keys(): fout.write(">>>>>>> To "+ address+ " Message ID "+ key + "------------\n") fout.write(ToAddr[key]+"\n") print "------------------- Done processing ---------------------" print "Found: " + str(numFound) #Test print "Not matching: " + str(notFound) #Test print "Line Cound: " + str(lineCount) #test fout.close def getMID(daLine): #Extracts the message ID from the message p = re.compile("\(.*?\)") pid=p.search(daLine) if pid: id=pid.group() id=id.lstrip('\(') id=id.rstrip('\)') #print id return id else: return def usage(): # Provides usage feedback print """ Syntax: -a email account to find -l location of log files (OPTIONAL) -d date, in file date format (####) """ if __name__ == "__main__": # Call mail loop main() From jstroud at mbi.ucla.edu Tue Apr 17 03:16:00 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Tue, 17 Apr 2007 07:16:00 GMT Subject: Getting started with python In-Reply-To: References: <1176598011.463543.96990@q75g2000hsh.googlegroups.com> <1176608302.928513.274400@y5g2000hsa.googlegroups.com> <%LyUh.10121$YL5.5753@newssvr29.news.prodigy.net> Message-ID: Steve Holden wrote: > James Stroud wrote: >> Steve Holden wrote: >>> You'd be worth more if you'd used elif and omitted the continue >>> statements, but for a first solution it's acceptable. >> >> Depends on what you are after. >> >> py> s = """ >> ... for i in xrange(1,101): >> ... if not i % 15: >> ... continue >> ... if not i % 5: >> ... continue >> ... if not i % 3: >> ... continue >> ... else: >> ... pass >> ... """ >> py> t = timeit.Timer(stmt=s) >> py> print "%.2f usec/pass" % (1000000 * t.timeit(number=100000)/100000) >> 40.49 usec/pass >> py> s = """ >> ... for i in xrange(1,101): >> ... if not i % 15: >> ... pass >> ... elif not i % 5: >> ... pass >> ... elif not i % 3: >> ... pass >> ... else: >> ... pass >> ... """ >> py> t = timeit.Timer(stmt=s) >> py> print "%.2f usec/pass" % (1000000 * t.timeit(number=100000)/100000) >> 40.88 usec/pass >> > > To be strictly comparable you should have pass statements before the > continue statements as well. Ignoring that, clearly it's well worth > saving that extra 390 nanoseconds each time round the loop. > > Repeat after me "premature optimization is the root of all evil". > > http://en.wikipedia.org/wiki/Optimization_(computer_science) > > regards > Steve The point is that both work equally as well unless (1) you are biased by a particular style or (2) you split little bitty hairs to even finer hairs. From steve at REMOVEME.cybersource.com.au Thu Apr 19 22:38:39 2007 From: steve at REMOVEME.cybersource.com.au (Steven D'Aprano) Date: Fri, 20 Apr 2007 12:38:39 +1000 Subject: class __getitem__ when item is not a sequence ??? References: <1177026475.610239.22720@q75g2000hsh.googlegroups.com> Message-ID: On Thu, 19 Apr 2007 16:47:55 -0700, cfriedalek wrote: > Sorry for the vague subject. Not sure what the right terminology is. > > How can I use an instance's data by reference to the instance name, > not the instance attribute? OK the question is probably really poor > but hopefully an example will make it clear. > >> x=1 >> type(x) > >> x.__add__(1) > 2 >> print x > 1 >> 3*x > 3 > > In this case x is an integer. My understanding is that x in an > instance of an integer class. Since it refers to only a single value > things like print x, 3*x etc operate on the instance name which seems > to refer to the instance data, not the instance itself. No, names are separate from instances. Instances don't know what name(s) they have been called. Everything in Python is an object, so you can think of it like this... Here's an int: Python knows that instance as the literal 7, so any time you write 7 in your code, that tells Python to use that specific instance. When you write "x = 7" that tells Python to bind the _name_ "x" to the instance 7. But notice that the instance itself doesn't know what name, or names, it is bound to. In fact, there may be no name at all. When you say "x.__add__(1)" Python looks up the name "x", finds that it is the instance 7, and then calls 7.__add__(1). And yes, you can write that, although you have to sneak a space between 7 and the dot so it doesn't look like a float: >>> 7 .__add__(1) # the long way of writing 7+1 8 Now, you might be thinking that ints have an attribute like "value", and that x.__add__(1) does something like this: def __add__(self, other): return self.value + other That's what you will probably do for custom classes that you create yourself, but that's not what ints do. They understand how to do addition "magically". 7.__add__(1) knows the answer is 8 (because under the hood it does arithmetic on bits) and it returns the instance 8, creating it if it doesn't already exist. > I want to do > the same for my own classes. > > For example: >> class y: > def __init__(self,val): > self.val = val >> y1 = y(10) >> print y1 > <__main__.y instance at 0x043C7B20> >> 3*y1 > : unsupported operand type(s) for *: > 'int' and 'instance > > I have been able to do this by overriding __getitem__ when self.val is > a sequence. How did you do that? > But I can't find out what to do when self.val is a simple > type like int, float etc. In the same way that the + operator is turned into the __add__ method, the * operator is turned into __mul__. y1*3 => y1.__mul__(3) 3*y1 => y1.__rmul__(3) Can you see why you need both a __mul__ and a __rmul__ operator? Here is a simple way to do what I think you want: class Y: # the convention is the class names start with a capital letter def __init__(self,val): self.val = val # assume val is an int def __mul__(self, other): value = self.val*other # Now value will be an int; if you are happy with that, # just "return value". # But I assume you want to return the same type: return self.__class__(value) __rmul__ = __mul__ -- Steven D'Aprano From aisaac at american.edu Wed Apr 25 10:41:16 2007 From: aisaac at american.edu (Alan Isaac) Date: Wed, 25 Apr 2007 14:41:16 GMT Subject: gotcha or bug? random state reset on irrelevant import References: <33yXh.5839$Fc1.4387@trnddc05> <462EB311.2010508@lexicon.net> <1hx3dv0.1888i74w45xnhN%aleax@mac.com> Message-ID: Alex Martelli said: > What do you mean? Just instantiate the random.Random class and you can > call .seed on it as well as anything else, and no other module will > infringe on "your" module's Random instance. The "global functions" of > module random exist for those who *SPECIFICALLY* want globally shared > behavior, of course. I consider this an unduly kind response. "RTFM" would have been appropriate. The functions supplied by this module are actually bound methods of a hidden instance of the random.Random class. You can instantiate your own instances of Random to get generators that don't share state. Sheesh. I must have been asleep when reading the documentation. Thanks, Alan From len-l at telus.net Thu Apr 5 13:12:38 2007 From: len-l at telus.net (Lenard Lindstrom) Date: Thu, 05 Apr 2007 17:12:38 GMT Subject: AttributeError: 'tuple' object has no attribute 'encode' In-Reply-To: <1175787095.862712.297480@n76g2000hsh.googlegroups.com> References: <1175787095.862712.297480@n76g2000hsh.googlegroups.com> Message-ID: erikcw wrote: > Hi, > > I'm trying to build a SQL string > > sql = """INSERT INTO ag ('cid', 'ag', 'test') VALUES(%i, %s, %d)""", > (cid, ag, self.data[parent][child]['results']['test']) > I am guessing you want the string formatting operator here: sql = """...""" % (cid, ...) The comma creates a tuple. From frankdotlogullo at dol.net Sun Apr 8 08:01:49 2007 From: frankdotlogullo at dol.net (frank.logullo) Date: Sun, 8 Apr 2007 08:01:49 -0400 Subject: Test Tube Zealots: The American Chemical Society Terminates the Membership of Chemists from Iran References: <1175963599.167629.90830@y80g2000hsf.googlegroups.com> Message-ID: <4618d9c1$0$18162$f9d64f1d@news.dol.net> Sounds like a good idea to me. ACS is normally a left wing organization but if true, I applaud them for this. The only way the Iranian government problem is going to be rationally solved is from forces within. From noreply at python.org Fri Apr 27 15:15:03 2007 From: noreply at python.org (Mail Administrator) Date: Fri, 27 Apr 2007 15:15:03 -0400 Subject: Returned mail: see transcript for details Message-ID: <200704271920.l3RJKlhc028594@email.beaufortco.com> -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: file.scr.txt URL: From cam.ac.uk at mh391.invalid Fri Apr 20 10:26:12 2007 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Fri, 20 Apr 2007 15:26:12 +0100 Subject: setDaemon problem. In-Reply-To: References: <1177057029.688992.160020@o5g2000hsb.googlegroups.com> <58rk68F2hof6mU1@mid.uni-berlin.de> <1177076608.110673.305970@d57g2000hsg.googlegroups.com> Message-ID: Richard Brodie wrote: > "Ramashish Baranwal" wrote in message > news:1177076608.110673.305970 at d57g2000hsg.googlegroups.com... > >> I was also wondering about "daemonizing" a thread, but I interpreted >> that it would daemonize the process which it didn't. I think setDaemon >> should be renamed to setDetached or something similar. > > Neither is particularly intuitive; it just depends whether you are more > familiar with the Posix terminology or the Java one. I personally prefer > detached but there is little chance of a name change now. Why not? That's what Python 3.0 is for. -- Michael Hoffman From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Sat Apr 28 04:58:25 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Sat, 28 Apr 2007 10:58:25 +0200 Subject: My newbie annoyances so far References: <1177688082.758043.133920@r30g2000prh.googlegroups.com> <59f5btF2k70baU2@mid.individual.net> Message-ID: <59gglhF2l1u43U2@mid.individual.net> Dennis Lee Bieber wrote: > You didn't take account of what b, c, and d were... > > RPL: if else end > Python: if else > > (RPL is a somewhat common reference to the stack based language of > the later calculators -- HP48, for instance) I still don't see the "more sense". Python's variant seems logical to me -- " if else ". The HP equivalent will be, if I understand correctly: " if [else ]" I see two problems here: - Also from my error in the last posting it's quite clear that the RPL statement doesn't do what one would suppose. Isn't this what Python always tries to avoid: Doing something different from what is "obvious". RP order doesn't fit in Python, IMHO. - What should the expression's value be if the else is omitted? None? What's it in the original? I can't imagine a use case here since I always have two alternatives when I use "a if b else c". Regards, Bj?rn -- BOFH excuse #110: The rolling stones concert down the road caused a brown out From jstroud at mbi.ucla.edu Tue Apr 10 00:04:17 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Mon, 09 Apr 2007 21:04:17 -0700 Subject: tuples are useless??? In-Reply-To: References: Message-ID: <461B0CC1.4070008@mbi.ucla.edu> Steven D'Aprano wrote: > On Sun, 08 Apr 2007 22:20:45 -0700, James Stroud wrote: > > >>Steven D'Aprano wrote: >> >>>On Mon, 09 Apr 2007 02:26:37 +0000, James Stroud wrote: >>> >>> >>>>Bart Willems wrote: >>>> >>>>>James Stroud wrote: >>>>> >>>>>>... It boils down to the fact that tuples are useless as a result >>>>>>unless you know you really need them--and you never really NEED them. >>>>> >>>>>Could you clarify that for me? I use tuples *a lot* and I really *NEED* >>>>>them - I'm building a lot of multi-tier reports where detail-level data >>>>>is pulled out of a dictionary based on a composed key. It is impossible >>>>>to build those dictionaries *without* using tuples. >>>> >>>>"Impossible" is a strong word, as is "need" (especially when in all caps). >>>> >>>>py> import md5 >>>>py> class HashedList(list): >>>>... def __hash__(self): >>>>... h = md5.new() >>>>... for item in self: >>>>... h.update(str(hash(item))) >>>>... return int(h.hexdigest(), 16) >>>>... >>>>py> hl = HashedList('bob', 'carol', 'ted') >>>>py> {hl:3} >>>>{['bob', 'carol', 'ted']: 3} >>>> >>>>Impossible? I wouldn't even say that this was all that difficult. >>> >>>Possible, if by possible you mean "broken". >>> >>> >>> >>>>>>D = {hl: 3} >>>>>>D >>> >>>{['bob', 'carol', 'ted']: 3} >>> >>>>>>hl[0] = 'Bob' >>>>>>D >>> >>>{['Bob', 'carol', 'ted']: 3} >>> >>>>>>D.keys()[0] is hl >>> >>>True >>> >>>>>>D[hl] >>> >>>Traceback (most recent call last): >>> File "", line 1, in >>>KeyError: ['Bob', 'carol', 'ted'] >>> >>> >> >> def __setitem__(self, *args): >> raise TypeError, '%s doesn't support item assignment.' % >>self.__class__.__name__ >> >> >>Problem fixed. Next? > > > hl.reverse() > hl.sort() # if the list isn't already sorted > del hl[0] > hl.append() > etc. > > > Yes, you can block those as well... To prevent abuse. but by the time you've finished making > your HashedList immutable, it is just a slower tuple with a different > name. But has an index() method. > In other words... you can avoid using tuples by using a tuple with a > different name. You might as well just do this: > > HashedList = tuple You can avoid using tuples any number of ways. For example, you can catenate strings. You seem to be under the misapprehension that I authored the Subjet line. Please read the original quote: > It boils down to the fact that tuples are useless as a result unless > you know you really need them--and you never really NEED them. Bear in mind that this was also a response to someone admittedly less familiar to the language--to encourage him to use lists in favor of tuples to avoid inconveniences later. The HashedList is to show that you can always get around the requirement for a tuple and thus an absolute need for a tuple doesn't exist, as implied by the quote. I make no assertions as to the HashedLists efficiency. I use tuples all of the time, but I could just as well catenate strings etc. They are a language convenience that are ultimately dispensible. James From gregcorradini at gmail.com Thu Apr 5 16:20:02 2007 From: gregcorradini at gmail.com (Greg Corradini) Date: Thu, 5 Apr 2007 13:20:02 -0700 (PDT) Subject: Trouble w/ 'create table' sql on mx.ODBC In-Reply-To: References: <9860747.post@talk.nabble.com> Message-ID: <9863381.post@talk.nabble.com> Thanks for responding everyone, I never received a traceback, the program did complete without changes to the database. However, the conn.commit() did work (Thanks Steve). I should've know that was the problem (or at least tried), b/c I saw so many posts about a similar problem with Update and Insert. Thanks to all Greg Corradini Steve Holden wrote: > > Greg Corradini wrote: >> Hello, >> Lately I've been using the mx.ODBC module to query Access (mdb) tables. >> For >> the life of me, I can't get the 'create table' sql command to work. I use >> this command in Oracle and I've seen other mx.ODBC users weave into their >> scripts for Access. But I still can't get this simple test run below to >> work >> (ignore the geoprocessor object for ArcGIS): >> >> #Import Python Standard Library Modules >> import win32com.client, sys, os, string, copy, glob >> import mx.ODBC.Windows as odbc >> >> # Create the Geoprocessor Object >> gp = win32com.client.Dispatch("esriGeoprocessing.GpDispatch.1") >> gp.overwriteoutput = 1 >> >> # Variables >> tempspace = "C:\Documents and Settings\corr1gre\Desktop\Workspace\DBFs & >> Shapefiles\TEST.mdb" >> workspace = string.replace(tempspace,"\\","/") >> >> #Conection to Access >> driv = 'DRIVER={Microsoft Access Driver (*.mdb)};DBQ='+workspace >> conn = odbc.DriverConnect(driv) >> curse = conn.cursor() >> >> #Upload Tbl 1 as a List of Tuples >> curse.execute('SELECT TISCODE,EXISTSIN,STATUS,NOTES from Mower_I') >> x = curse.fetchall() >> >> #Create New Table >> curse.execute('Create table TEST (TISCODE Integer)') >> curse.close() >> conn.close() >> del gp > > So what happens? Do you see a traceback, or does the program complete > without any apparent change to the database? > > It might be because Access doesn't automatically commit DDL changes like > some other databases do. Try adding a conn.commit() before your > conn.close(). > > 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 > > -- > http://mail.python.org/mailman/listinfo/python-list > > -- View this message in context: http://www.nabble.com/Trouble-w--%27create-table%27-sql-on-mx.ODBC-tf3532982.html#a9863381 Sent from the Python - python-list mailing list archive at Nabble.com. From kushal.kumaran at gmail.com Tue Apr 10 12:11:34 2007 From: kushal.kumaran at gmail.com (Kushal Kumaran) Date: 10 Apr 2007 09:11:34 -0700 Subject: Parsing log in SQL DB to change IPs to hostnames In-Reply-To: <1176219463.407804.315560@y80g2000hsf.googlegroups.com> References: <1176219463.407804.315560@y80g2000hsf.googlegroups.com> Message-ID: <1176221494.813800.78580@y80g2000hsf.googlegroups.com> On Apr 10, 8:37 pm, "KDawg44" wrote: > Hi, > > I am brand new to Python. In learning anything, I find it useful to > actually try to write a useful program to try to tackle an actual > problem. > > I have a syslog server and I would like to parse the syslog messages > and try to change any ips to resolved hostnames. Unfortunately, I am > not getting any matches on my regular expression. > > A message will look something like this: > Apr 10 2007 00:30:58 DEVICE : %DEVICEINFO: 1.1.1.1 Accessed URL > 10.10.10.10:/folder/folder/page.html > > I would like to change the message to have the hostnames, or even > better actually, have it appear as hostname-ip address. So a changed > message would look like: > > Apr 10 2007 00:30:58 DEVICE : %DEVICEINFO: pcname-1.1.1.1 Accessed > URLwww.asite.com-10.10.10.10:/folder/folder/page.html > > or some equivalent. > > Here is what i have so far. Please be kind as it is my first python > program.... :) > > #! /usr/bin/python > > import socket > import re > import string > import MySQLdb > > ipRegExC = r"\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}" > ipRegEx = re.compile(ipRegExC) > > try: > conn = MySQLdb.connect(host="REMOVED", user="REMOVED", > passwd="REMOVED", db="REMOVED") > > except MySQLdb.Error, e: > print "Error connecting to the database: %d - %s " % > (e.args[0], e.args[1]) > sys.exit(1) > > cursor = conn.cursor() > cursor.execute("SELECT msg, seq FROM `logs` WHERE seq = 507702") > # one specific message so that it doesn't parse the whole DB during > testing... > while(1): > row = cursor.fetchone() > if row == None: > break > if ipRegEx.match(row[0]): > .... > See the documentation of the re module for the difference between matching and searching. -- Kushal From bhochstetler at gmail.com Tue Apr 3 13:48:26 2007 From: bhochstetler at gmail.com (bhochstetler at gmail.com) Date: 3 Apr 2007 10:48:26 -0700 Subject: troubles building python 2.5 on Windows XP x64 Windows Server 2003 sp1 Platform SDK Message-ID: <1175622506.730227.37060@p77g2000hsh.googlegroups.com> I am needing to build python 2.5 on Windows XP x64 Windows Server 2003 sp1 Platform SDK and am not finding anything documented on the process to use. Has anyone had any success with this? If so has anyone documented it? The documentation that resides in pcbuild/readme.txt is not helpful at all. Any help is greatly appreciated. Thanks Brad From bearophileHUGS at lycos.com Thu Apr 12 19:01:51 2007 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 12 Apr 2007 16:01:51 -0700 Subject: Lists and Tuples and Much More In-Reply-To: References: Message-ID: <1176418911.743940.251300@l77g2000hsb.googlegroups.com> Scott: Others will give you many more answers, here is just a bit. > And how would you sort the list that's in the list? I guess that goes in > conjunction with the section above, but still: >>> my_list = [6, 4, 3, 5, 2, 1] > >>> my_list.append([7, 9, 8, 10]) > >>> my_list.sort() > >>> my_list > > [1, 2, 3, 4, 5, 6, [7, 9, 8, 10]] Such sorting may be impossible in Python 3.0 (comparing the order of lists with integers may be seen as meaningless. Otherwise you can see single numbers as lists of len=1, like another language does). > This is, again, something I'm finding nothing on. Maybe because documentation requires some generalization capabilities. A list is a single object, and it can contain a sequence of objects. Bye, bearophile From sickcodemonkey at gmail.com Thu Apr 5 16:10:47 2007 From: sickcodemonkey at gmail.com (Sick Monkey) Date: Thu, 5 Apr 2007 16:10:47 -0400 Subject: Looping issues In-Reply-To: <2adc542f0704051307x5d9fd992ofec5ad4b66358250@mail.gmail.com> References: <1175796069.501575.157410@w1g2000hsg.googlegroups.com> <2adc542f0704051307x5d9fd992ofec5ad4b66358250@mail.gmail.com> Message-ID: <2adc542f0704051310v2bf2f2a8i53eb39b0cbbf4ea6@mail.gmail.com> Ooops, Sorry I left .lower() out. ################################################################ def fopen(fname): try: return open(fname, 'U') except IOError, detail: return fail("couldn't open " + fname + ": " + str(detail)) ################################################################ f1 = fopen('file1.txt') a = f1.readlines(); f1.close() d1 = {} for c in a: d1[c.lower()] = None #print d1 f2 = fopen('file2.txt') data = f2.readlines(); f2.close() for line in data: if d1.has_key( line.lower() ): print line On 4/5/07, Sick Monkey wrote: > > Try this. > NOTE: The script below will compare lines of both files (even hidden > characters such as \n)... > > ################################################################ > def fopen(fname): > try: > return open(fname, 'U') > except IOError, detail: > return fail("couldn't open " + fname + ": " + str(detail)) > ################################################################ > f1 = fopen('file1.txt ') > a = f1.readlines(); f1.close() > d1 = {} > for c in a: > d1[c.lower()] = None > #print d1 > f2 = fopen('file2.txt') > data = f2.readlines(); f2.close() > for line in data: > if d1.has_key( line ): > print line > ################################################################ > > wdh > > On 5 Apr 2007 11:01:09 -0700, brochu121 at gmail.com > wrote: > > > > What I am trying to do is compare two files to each other. > > > > If the 2nd file contains the same line the first file contains, I want > > to print it. I wrote up the following code: > > > > > > > > correct_settings = open("C:\Python25\Scripts\Output > > \correct_settings.txt","r") > > current_settings = open("C:\Python25\Scripts\Output\output.txt","r") > > > > for line in correct_settings: > > for val in current_settings: > > if val == line: > > print line + " found." > > > > > > correct_settings.close() > > current_settings.close() > > > > > > For some reason this only looks at the first line of the > > correct_settings.txt file. Any ideas as to how i can loop through each > > line of the correct_settings file instead of just looking at the first? > > > > -- > > http://mail.python.org/mailman/listinfo/python-list > > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From psdasilvaX at esotericaX.ptX Tue Apr 3 11:36:21 2007 From: psdasilvaX at esotericaX.ptX (Paulo da Silva) Date: Tue, 03 Apr 2007 16:36:21 +0100 Subject: getattr/setattr q. In-Reply-To: References: <1175573213.682671@jubilee.claranet.pt> Message-ID: <1175614741.823795@jubilee.claranet.pt> Steven Bethard escreveu: > Paulo da Silva wrote: ... > If you're at the module level, you can do:: > > globals()['x'] = 10 > > If you're inside a function, you probably want to look for another way > of doing what you're doing. > > What's the actual task you're trying to accomplish here? None. I asked just for curiosity. My problem has to do with the normal case of a class or class instance. When I saw setattr/getattr as the way to solve my problem I just felt curiosity on if and how it could be done outside a class. Thank you very much for your response. Paulo From michael at jedimindworks.com Mon Apr 9 04:35:26 2007 From: michael at jedimindworks.com (Michael Bentley) Date: Mon, 9 Apr 2007 03:35:26 -0500 Subject: Is there a simple function to generate a list like ['a', 'b', 'c', ... 'z']? In-Reply-To: <1176107364.000517.68580@q75g2000hsh.googlegroups.com> References: <1176107364.000517.68580@q75g2000hsh.googlegroups.com> Message-ID: <033B75D2-599B-4137-92B9-98A548732983@jedimindworks.com> On Apr 9, 2007, at 3:29 AM, ????????????? ?? wrote: > Is there a simple function to generate a list like ['a', 'b', 'c', ... > 'z']? The range() just can generate the numeric list. import string list(string.lowercase) From paddy3118 at googlemail.com Thu Apr 19 23:18:25 2007 From: paddy3118 at googlemail.com (Paddy) Date: 19 Apr 2007 20:18:25 -0700 Subject: List of Objects In-Reply-To: <1177037915.042476.153190@n76g2000hsh.googlegroups.com> References: <1177037915.042476.153190@n76g2000hsh.googlegroups.com> Message-ID: <1177039105.373843.56420@p77g2000hsh.googlegroups.com> On Apr 20, 3:58 am, datamonkey.r... at gmail.com wrote: > Howdy, a (possibly) quick question for anyone willing to listen. > I have a question regarding lists and Classes; I have a class called > "gazelle" with several attributes (color, position, etc.) and I need > to create a herd of them. I want to simulate motion of individual > gazelles, but I don't want to have to go through and manually update > the position for every gazelle (there could be upwards of 50). I was > planning to create an array of these gazelle classes, and I was going > to iterate through it to adjust the position of each gazelle. That's > how I'd do it in C, anyway. However, Python doesn't support pointers > and I'm not quite sure how to go about this. Any help you can provide > would be greatly appreciated. > Thanks a lot! > > -Ryan Something like: import random class Gazelle(object): def __init__(self): self.pos = 0, 0 # create a list of instances gazelles= [ Gazelle() for x in range(5)] # update gazelle positions deltaxmin, deltaxmax = -100, +100 deltaymin, deltaymax = -100, +100 for g in gazelles: g.pos = (g.pos[0] + random.randint(deltaxmin, deltaxmax), g.pos[1] + random.randint(deltaymin, deltaymax) ) The above is untested by the way. - Paddy. From collinstocks at gmail.com Thu Apr 19 16:36:11 2007 From: collinstocks at gmail.com (subscriber123) Date: 19 Apr 2007 13:36:11 -0700 Subject: Significance of "start" parameter to string method "endswith" In-Reply-To: <1177012694.726434.142660@q75g2000hsh.googlegroups.com> References: <1177012694.726434.142660@q75g2000hsh.googlegroups.com> Message-ID: <1177014971.167843.293190@n76g2000hsh.googlegroups.com> On Apr 19, 3:58 pm, Boris Du?ek wrote: > Hello, > > what is the use-case of parameter "start" in string's "endswith" > method? Consider the following minimal example: > > a = "testing" > suffix="ing" > a.endswith(suffix, 2) > > Significance of "end" is obvious. But not so for "start". > > Let's assume the "end" parameter is not used - then the function > should simple check that the last "len(suffix)" characters of "a" are > equal to "ing", no matter where we start (the function does not *scan* > the string from the "start", does it?) > Only case where it would make difference is if we had start + > len(suffix) < len(a) (excuse possible "of-by-one" error :-) > Then the function would never return True. But is there a real use > case when we would test for endswith like this? (knowing that it must > return false?) > > Thanks for any ideas/experience. > Boris Basically, this must be so in order for this to be Pythonic. This is because it is an object oriented language, and functions can be passed as arguments. Say, for example, you have the following function: def foo(function,instance,param): if function(instance,param,2,4): return True else: return False The function must work whether you pass it foo(str.endswith,"blaahh","ahh"), or foo(str.startswith,"blaahh","aah"). This is a really bad example, but it gets the point across that similar functions must have similar parameters in order to be Pythonic. I personally have never used the second or third parameters in this function nor in str.startswith. From Jun.Jin.act at gmail.com Mon Apr 16 22:04:36 2007 From: Jun.Jin.act at gmail.com (Jun.Jin.act+group.python@gmail.com) Date: 16 Apr 2007 19:04:36 -0700 Subject: list insertion question In-Reply-To: References: <1176771916.236282.206500@n59g2000hsh.googlegroups.com> Message-ID: <1176775476.482350.125450@q75g2000hsh.googlegroups.com> On Apr 17, 9:47 am, Michael Hoffman wrote: > eight02645... at yahoo.com wrote: > > hi > > i have a list (after reading from a file), say > > data = [ 'a','b','c','d','a','b','e','d'] > > > I wanted to insert a word after every 'a', and before every 'd'. so i > > use enumerate this list: > > for num,item in enumerate(data): > > if "a" in item: > > data.insert(num+1,"aword") > > if "d" in item: > > data.insert(num-1,"dword") #this fails > > but the above only inserts after 'a' but not before 'd'. What am i > > doing wrong? is there better way?thanks > > If you modify a list while you are iterating over it, you may get > unexpected results (an infinite loop in this case for me). Also ("a" in > item) will match "aword" since "a" is a component of it. I imagine you > mean (item == "a"). > > Try this: > > output = [] > for item in data: > if item == "d": > output.append("dword") > output.append(item) > if item == "a": > output.append("aword") > > >>> output > ['a', 'aword', 'b', 'c', 'dword', 'd', 'a', 'aword', 'b', 'e', 'dword', 'd'] > -- > Michael Hoffman Infinite loop for me too! ^_^, should think of it b4 pressing F5. From steve at holdenweb.com Thu Apr 5 07:18:19 2007 From: steve at holdenweb.com (Steve Holden) Date: Thu, 05 Apr 2007 07:18:19 -0400 Subject: Python and Java In-Reply-To: References: Message-ID: Sreelatha G wrote: > Hi > > I am new to python .I need your help in solving my problem. > Is there any way to call python files in a java file .How is it possible? > Jython is an implementation of Python that compiles to Java bytecode, but at the moment there's some version lag so it won't handle the mos recent language enhancements. Probably worth a look, though. http://www.jython.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 dj at david-web.co.uk Mon Apr 9 08:59:10 2007 From: dj at david-web.co.uk (David Johnson) Date: Mon, 9 Apr 2007 13:59:10 +0100 Subject: Managing a file buffer Message-ID: <200704091359.10975.dj@david-web.co.uk> Hi, I have an application that reads video from a socket and saves it to a file, which I then play using GStreamer. The major problem with this approach is that the file keeps getting bigger and bigger until the disk is full ;-) What I'd like to do is have a buffer, say 5MB in size, which I can point GStreamer at. So every time I write 60K to the tail of the file, I'd need to remove 60K from the head of the file. How can I achieve this in Python? I looked at truncate() but it seems to do the opposite of what I want. Thanks in advance, David. -- David Johnson www.david-web.co.uk From juanvazquez at gmail.com Tue Apr 10 13:18:28 2007 From: juanvazquez at gmail.com (Juan Vazquez) Date: Tue, 10 Apr 2007 12:18:28 -0500 Subject: grabbing Pictures from the web Message-ID: <5dbef1c10704101018w13a13ca7i53be4564cec4784@mail.gmail.com> I am new to python (2 weeks old) and I would like to write a script that grabs pictures from the web (specifically flickr) and put them on a Tk Canvas for a slide show/editing program. my 2 questions are 1) How do I grab a picture from the web 2) is the use of the Tk canvas for working with the picture the best approach? Any help or references to resources that point me in the right direction would be greatly appreciated. Thanks in Advance. -Juan -------------- next part -------------- An HTML attachment was scrubbed... URL: From murkland at gmail.com Thu Apr 19 14:24:09 2007 From: murkland at gmail.com (Martin) Date: 19 Apr 2007 11:24:09 -0700 Subject: Relative import problem In-Reply-To: References: Message-ID: <1177007049.713662.169760@b75g2000hsg.googlegroups.com> On Apr 19, 6:54 pm, "Jorgen Bodde" wrote: > Hi all, > > I want to structure my app so that I have two dirs like; > > obj/{object files} > > gui/{gui files} > > Here comes the catch. From the GUI dir, I would like to access the obj > submodule path. I need to go one dir back.. I read there was something > like from .. import x in python 2.5 so that I could access my obj dir > from a lower level, but I have problems getting this to work. > > Example; > > In the main dir I have; > > main.py: > -------- > import gui > > gui.gui.startme() > -------- > > In the obj dir I have; > > obj/obj.py > --------- > > def start(): > print 'Started OBJ' > --------- > > In the GUI dir I have > > gui/gui.py > --------- > from .. import obj > > def start(): > obj.obj.start() > --------- > > This does not work. It gives me; > > D:\personal\src\GuitarPortfolio\tmp>python start.py > Traceback (most recent call last): > File "start.py", line 4, in > gui.gui.start() > AttributeError: 'module' object has no attribute 'gui' > > Am I shooting myself in the foot by trying to structure? Or are there > better more elegant ways? > > Regards, > - Jorgen You need to add the path to where your files are located since they are not in any of the "standard" path directories where Python looks. To do this, you can add the following lines in your files: import sys sys.path.append(/path/to/obj) sys.path.append(/path/to/gui) import obj import gui #etc.. Hope this helps From a.schmolck at gmail.com Wed Apr 4 05:09:03 2007 From: a.schmolck at gmail.com (Alexander Schmolck) Date: 04 Apr 2007 10:09:03 +0100 Subject: zip list with different length References: <1175673207.231212.28310@n76g2000hsh.googlegroups.com> Message-ID: MC writes: > Hi! > > Brutal, not exact answer, but: > > a = range(5) > b = range(3) > print zip(a+[None]*(len(b)-len(a)),b+[None]*(len(a)-len(b))) You reinvented map(None,a,b). 'as From szhorvat at gmail.com Sat Apr 28 09:36:19 2007 From: szhorvat at gmail.com (Szabolcs) Date: Sat, 28 Apr 2007 15:36:19 +0200 Subject: Numbers and truth values In-Reply-To: References: Message-ID: Steven D'Aprano wrote: > >>>> 1 == True > True >>>> 0 == False > True >>>> 2 == True > False Oh my goodness! Now I also get 2 != True. I really don't know what happened. Most probably this (as a result of mistyping): > >>>> True = 2 # DON'T DO THIS!!! >>>> 2 == True > True > But shouldn't Python forbid this? Is it possible to get a warning when unintentionally redefining built-in thing? From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Thu Apr 12 16:09:54 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Thu, 12 Apr 2007 22:09:54 +0200 Subject: wxPython, mac, wx.HSCROLL not working References: <1176364597.741079.25840@n59g2000hsh.googlegroups.com> <586qvsF2fbq3rU1@mid.individual.net> <1176392605.298630.8210@y5g2000hsa.googlegroups.com> <1176404918.079527.148440@d57g2000hsg.googlegroups.com> Message-ID: <587i0iF2fu57fU1@mid.individual.net> 7stud wrote: > Where is that list? Argh! http://www.wxpython.org/maillist.php Regards, Bj?rn -- BOFH excuse #330: quantum decoherence From nitte.sudhir at gmail.com Wed Apr 4 23:34:51 2007 From: nitte.sudhir at gmail.com (kath) Date: 4 Apr 2007 20:34:51 -0700 Subject: how to build a forum in Python? In-Reply-To: <1175703488.290861.317760@y80g2000hsf.googlegroups.com> References: <1175672984.836097.21610@n76g2000hsh.googlegroups.com> <1175686188.212319.292750@q75g2000hsh.googlegroups.com> <1175703488.290861.317760@y80g2000hsf.googlegroups.com> Message-ID: <1175744091.517633.117620@e65g2000hsc.googlegroups.com> On Apr 4, 9:18 pm, "Goldfish" wrote: > Sounds like phpBB (http://www.phpbb.com/) would do great. I'm not sure > why you want to go write another forum management tool when others are > already out there for usage. I know its not in python, but not > everything has to be in python. thanks you all, for your reply. I want to do for my corporate environment. I had two option one is Python and other is Perl. I came to know Django is Python framework, so chose Python. Not only that I would like to code in Python. Thanks again, kath. From bbxx789_05ss at yahoo.com Sun Apr 29 13:55:45 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: 29 Apr 2007 10:55:45 -0700 Subject: howto check is object a func, lambda-func or something else? In-Reply-To: <1177867182.115406.4640@h2g2000hsg.googlegroups.com> References: <1177867182.115406.4640@h2g2000hsg.googlegroups.com> Message-ID: <1177869345.069355.85760@q75g2000hsh.googlegroups.com> On Apr 29, 11:19 am, dmitrey wrote: > > callable(lambda-func) returnes False > I'm not seeing that. Try this: f = lambda x: x print callable(f) ---output:-- True From aleax at mac.com Fri Apr 27 01:32:51 2007 From: aleax at mac.com (Alex Martelli) Date: Thu, 26 Apr 2007 22:32:51 -0700 Subject: Generalized range References: <1177598743.352743.290730@t39g2000prd.googlegroups.com> <1177616211.476888.38360@r30g2000prh.googlegroups.com> Message-ID: <1hx77al.50av4312e1ysaN%aleax@mac.com> Michael Hoffman wrote: > tkpmep at hotmail.com wrote: > > Thanks - you have covered a fair bit of gorund here - I will modify > > myRange taking your suggestions into account. The one suggestion that > > I'm going to have to think through is repeatedly incrementing res. > > > > I deliberately did not use this as repeated addition can cause > > rounding errors to accumulate, making the loop run a little longer or > > shorter than necessary. I thought I would be far less likely to run > > into rounding issues with a multiplicative construct - hence my use of > > epsilon, and my question about an appropriate value for it > > You are right about rounding issues--with a sufficiently small step, the > way I have done it, it could become an infinite loop. But you can still > do it with multiplication, without using an epsilon constant. How about > something like this: > > index = 0 > while res < maximum: > yield minimum + (step * index) > index += 1 Absolutely (with your later correction of actually assigning res), MUCH better than the misguided attempts based on repeatedly adding 'step'. I've taught "numerical computing" in university, and I would have had to fail anybody who'd misunderstood floating-point computations badly enough to try that "+=step" idea (including, sigh, the coders of several Fortran compilers who were popular at that time). These days, I _heartily_ recommend "Real Computing Made Real" by Foreman Acton -- the best programming book without one line of code in any language (it's all formulas and graphs). Anybody who has trouble following it must understand they should NOT use floating point numbers until they've gotten the prereqs (which aren't all that deep: engineering-undergrad-level algebra and calculus, plus and a couple weeks' worth of refresher courses on fundamental algorithms such as Newton's root-finding approach and the like -- I shudder to think how many people with CS bachelor degrees and even post-grad degrees are just never taught these fundamentals, yet end up having to program _some_ floating point computations, mistakenly thinking they can...). Alex From kw at codebykevin.com Mon Apr 30 09:59:16 2007 From: kw at codebykevin.com (Kevin Walzer) Date: Mon, 30 Apr 2007 09:59:16 -0400 Subject: Launching an independent Python program in a cross-platform way (including mac) In-Reply-To: <1177890695.308785.165580@l77g2000hsb.googlegroups.com> References: <1177889540.489960.176380@u30g2000hsc.googlegroups.com> <1177890695.308785.165580@l77g2000hsb.googlegroups.com> Message-ID: <838d5$4635f634$4275d90a$5047@FUSE.NET> Prateek wrote: > On Apr 30, 4:32 am, Andr? wrote: >> I would like to find out how I can launch an independent Python >> program from existing one in a cross-platform way. The result I am >> after is that a new terminal window should open (for io independent of >> the original script). >> >> The following seems to work correctly under Ubuntu and Windows ... but >> I haven't been able to find a way to make it work under Mac OS. >> >> def exec_external(code, path): >> """execute code in an external process >> currently works under: >> * Windows NT (tested) >> * GNOME (tested) [January 2nd and 15th change untested] >> This also needs to be implemented for OS X, KDE >> and some form of linux fallback (xterm?) >> """ >> if os.name == 'nt': >> current_dir = os.getcwd() >> target_dir, fname = os.path.split(path) >> >> filename = open(path, 'w') >> filename.write(code) >> filename.close() >> >> if os.name == 'nt': >> os.chdir(target_dir) # change dir so as to deal with paths >> that >> # include spaces >> Popen(["cmd.exe", ('/c start python %s'%fname)]) >> os.chdir(current_dir) >> elif os.name == 'posix': >> try: >> os.spawnlp(os.P_NOWAIT, 'gnome-terminal', 'gnome- >> terminal', >> '-x', 'python', '%s'%path) >> except: >> raise NotImplementedError >> else: >> raise NotImplementedError >> ========================== >> Any help would be greatly appreciated. >> >> Andr? > > Well, > > You need to check sys.platform on the Mac instead of os.name. > os.name returns 'posix' on all *nix based systems. sys.platform > helpfully returns "darwin" on the Mac. > > Not sure how to start Terminal. Here's what I got when I tried it: > >>>> if sys.platform == "darwin": os.spawnlp(os.P_NOWAIT, '/Applications/Utilities/Terminal.app/Contents/MacOS/Terminal') > 9460 >>>> 2007-04-30 05:19:59.255 [9460] No Info.plist file in application bundle or no NSPrincipalClass in the Info.plist file, exiting > There are extension modules on the Mac for integrating Python and AppleScript (the best one is appscript). However, if you want to limit yourself to core Python, your best best is osascript, a system command-tool that lets you call AppleScript code with arguments from other programs. This can be called via os.system. The basis syntax for doing this from Python might look something like this: os.system('osascript -e \'tell app \"Terminal\" to activate\'') This simply launches Terminal. Note that you have to deal with quoting issues. The equivalent syntax from AppleScript would be: tell app "Terminal" to activate If you want to Terminal to run a command-line program from AppleScript, you can do this with the "do script" command. Code to do this could look something like this: myscript = "python -e foo.py" os.system('osascript -e '\tell app \"Terminal"\ to do script %s\'', myscript) I haven't tested this, but you get the basic idea--define the script and command-line paramaters in a string, then pass that to AppleScript/osascript as a variable. This code should launch Terminal, then run the external Python script. HTH, Kevin -- Kevin Walzer Code by Kevin http://www.codebykevin.com From goodTweetieBird at hotmail.com Thu Apr 26 16:32:37 2007 From: goodTweetieBird at hotmail.com (gtb) Date: 26 Apr 2007 13:32:37 -0700 Subject: Python keywords In-Reply-To: References: <1177599386.204340.65680@r35g2000prh.googlegroups.com> Message-ID: <1177619557.827397.8550@n15g2000prd.googlegroups.com> Thanks Marc. From joel.granados at gmail.com Sun Apr 8 05:17:46 2007 From: joel.granados at gmail.com (Joel Granados) Date: Sun, 8 Apr 2007 04:17:46 -0500 Subject: Comments in ConfigParser module In-Reply-To: <1175977146.653832.245350@p77g2000hsh.googlegroups.com> References: <1175977146.653832.245350@p77g2000hsh.googlegroups.com> Message-ID: <7ad76b520704080217q5b35efc3jcec4751d9d84654c@mail.gmail.com> On 7 Apr 2007 13:19:06 -0700, Gabriel Genellina wrote: > > Joel Andres Granados wrote: > > > The module also allows the comments to appear in the same line as the > > "name = value" constructs. The only difference being that this is only > > possible with ";" and not with "#" character. I did not see this in the > > documentation but this is how it is behaving. > > Yes, it's not documented. There is only a comment in the source code: > > # ';' is a comment delimiter only if it > follows > # a spacing character > > I think it's either a bug in the code or in the documentation. Yep, IMO its a weirdness in the behavior that is not documented. > QUESTION...So the question is: > > Can you use "#" and ";" as comment characters? and if so why does the > > "#" not apply for the same situations as the ";"? > > If you follow the documentation, comments are ONLY allowed to start a > line. > The actual implementation discards any text following a ; > sequence. Yep. This is just one of the situations where the documentation is different from the actual behavior. > Just for reference: > > On the RFC 822 (a document > > referenced in the documentation) there is a mention of ";" being used as > > comment character but not necessarily at the beginning of the line. > > RFC822 uses ";" to include comments in the syntax rules, not for > comments in the actual message headers (parenthesis are used there). Yep. Here I just wanted to stress that in the RFC it states that the comment doesn't necessarily have to be at the beginning of the line. -- > Gabriel Genellina > > -- > http://mail.python.org/mailman/listinfo/python-list > -- Joel Andr?s Granados Medell?n Colombia -- jgranad1 at eafit.edu.co joel.granados at ieee.org -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at holdenweb.com Fri Apr 20 07:35:32 2007 From: steve at holdenweb.com (Steve Holden) Date: Fri, 20 Apr 2007 07:35:32 -0400 Subject: Do other Python GUI toolkits require this? In-Reply-To: References: <462697A6.6010007@codebykevin.com> <1177014799.004875.262060@y80g2000hsf.googlegroups.com> Message-ID: Antoon Pardon wrote: > On 2007-04-20, Steve Holden wrote: >> Antoon Pardon wrote: >>> On 2007-04-19, sjdevnull at yahoo.com wrote: >>>> On Apr 19, 6:54 am, Antoon Pardon wrote: >>>>> I don't know how you come to the conclusion that it is a mathematical >>>>> absurdity but consider this: If you find that common usage propagates >>>>> something that is incorrect, should we just shrug it off or should we >>>>> attemp a correction? >>>> a) In English, "learning curve" is not restricted to a mathematical >>>> plot--Webster's also defines it as "the course of progress made in >>>> learning something". In that context, adding the adjective steep >>>> ("extremely or excessively high...STEEP implies such sharpness of >>>> pitch that ascent or descent is very difficult") makes sense. >>> How much sense does it really make? Suppose we would talk about >>> an income curve. Would you not prefer a steep curve over a shalow >>> one? What about a productivity curve? It is all about the progress >>> made in something. >>> >>> So how much sense does it make that a steep curve in earnings and >>> productivity is good but a steep curve in learning is bad? >>> >> Just as much sense as that a motor car is great for driving around in >> but bad for being run over by. Context is everything. Do *all* steep >> curves have to be good or all bad? What the hell happened to common sense? > > You are just grabbing for straws. Sure context is everything. But you > don't make a case that the context makes a difference here. Are you > suggesting progres in productivity is good but progres in learning is bad? > No, I'm suggesting that in the company of thousands of people, most of whom agree that a "steep learning curve" means, in the face of all logic, that something is difficult to learn, you stop banging your head against the wall and trying to "prove" them "wrong" (presumably because it's important to you to be "right"). As has been said already at least twice in this thread, language is about communication. Human beings aren't always entirely rational no matter how much we may individually strive for correctness, and sometimes our only options are to either go with the flow or stand valiantly, pissing into the wind. > Just asserting how something can make a difference withouth arguing > how in the particular case it actucally makes a difference is just > a divertion tactic without real merrit. > In the face of a notion that all steep curves determining "progress made in something" must be good I stand with my mouth agape. I am aware that common usage does not concur with academic rigor, but in this particular instance I'm with the common herd. 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 fctoma at gmail.com Tue Apr 10 17:45:54 2007 From: fctoma at gmail.com (ilikewine) Date: 10 Apr 2007 14:45:54 -0700 Subject: menu drop down icons (inactive) look horrible in Windows Classic Theme Message-ID: <1176241554.152632.79090@o5g2000hsb.googlegroups.com> The menu drop down icons (only the gray inactive icons) look horrible in Windows Classic Theme. Once they are active and have color, they look fine. If we switch to XP theme, they look just fine. Anyone else run into this problem with python rewriting "shotty" inactive icons in the Windows Classic Theme? ANY help appreciated. Best, FT From duncan.booth at invalid.invalid Mon Apr 2 09:40:45 2007 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 2 Apr 2007 13:40:45 GMT Subject: Cascading ifs References: Message-ID: Ernesto Garc?a Garc?a wrote: > Hi experts, > > How would you do this without the more and more indenting cascade of > ifs?: > > match = my_regex.search(line) > if match: > doSomething(line) > else: > match = my_regex2.search(line) > if match: > doSomething2(line) > else: > match = my_regex3.search(line) > if match: > doSomething3(line) > > etc. > > Thanks in advance and regards, > Ernesto > PATTERNS = [ (my_regex, doSomething), (my_regex2, doSomething2), (my_regex3, doSomething3), ] ... for regex, action in PATTERNS: match = regex.search(line) if match: action(line) break Also be aware that repeatedly calling the search method with different regular expressions is horribly inefficient. You would be much better to combine the regular expressions into one and check which groups match (although admittedly that behaves differently since it would find the regex which matches earliest in the string instead of finding the first regex which matches anywhere). From michael at jedimindworks.com Sat Apr 14 01:50:41 2007 From: michael at jedimindworks.com (Michael Bentley) Date: Sat, 14 Apr 2007 00:50:41 -0500 Subject: Append data to a list within a dict In-Reply-To: References: Message-ID: On Apr 14, 2007, at 12:39 AM, Tina I wrote: > Say I have the following dictionary: > > ListDict = { > 'one' : ['oneone' , 'onetwo' , 'onethree'], > 'two' : ['twoone' , 'twotwo', 'twothree'], > 'three' : ['threeone' , 'threetwo', threethree']} > > Now I want to append 'twofour' to the list of the 'two' key but I > can't > figure out how to that? > Some pointers would be greatly appreciated. ListDict['two'].append('twofour') But you'll have to insert the missing single quote before "threethree" first. hope this helps, Michael From maxm at mxm.dk Thu Apr 26 15:57:47 2007 From: maxm at mxm.dk (Max M) Date: Thu, 26 Apr 2007 21:57:47 +0200 Subject: Parsing HTML/XML documents In-Reply-To: <4630B243.3070501@web.de> References: <4630B243.3070501@web.de> Message-ID: <4631043B.6030000@mxm.dk> Stefan Behnel skrev: > pabloski at giochinternet.com wrote: >> I need to parse real world HTML/XML documents and I found two nice python >> solution: BeautifulSoup and Tidy. > > There's also lxml, in case you want a real XML tool. > http://codespeak.net/lxml/ > http://codespeak.net/lxml/dev/parsing.html#parsers I have used both BeautiullSoup and lxml. They are both good tools. lxml is blindingly fast compared to BeautifulSoup though. A simple tool for importing contact information from 6000 xml files of 23 MBytes into Zope runs in about 30 seconds. No optimisations at all. Just inefficient xpath expressions. That is pretty good in my book. -- hilsen/regards Max M, Denmark http://www.mxm.dk/ IT's Mad Science From bdesth.quelquechose at free.quelquepart.fr Tue Apr 3 15:35:25 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Tue, 03 Apr 2007 21:35:25 +0200 Subject: Retrieve an item from a dictionary using an arbitrary object as the key In-Reply-To: <1175621638.588320.70790@b75g2000hsg.googlegroups.com> References: <1175617563.169153.150430@d57g2000hsg.googlegroups.com> <1175617854.977507.236730@n59g2000hsh.googlegroups.com> <1175621638.588320.70790@b75g2000hsg.googlegroups.com> Message-ID: <4612a39b$0$14561$426a74cc@news.free.fr> abcd a ?crit : >>You'll need __eq__ for testing if two objects are equivalent, and >>__hash__ for calculating object's hash value. >> >>class Type: While we're at it, and unless you're stuck with an aging Python version, make Type and Person new-style classes: class Type(object): >> def __init__(self, val): >> self.val = val >> >> def __eq__(self, other): >> return self.val == other.val >> >> def __hash__(self): >> return hash(self.val) > > > that's exactly what I needed, thanks. > And to answer your original question, ie "I am thinking there is some method that is used by the dictionary to know if the key exists, just not sure which.", you can: - test if a dict as a given key: d = {"a" : 42, "b" : "foo"} "a" in d => True "x" in d: => False - and/or use dict.get(key, default=None): d.get("a") => 42 d.get("x") => None d.get("x", "woops") => "woops" HTH From samjnaa at gmail.com Sat Apr 14 06:30:15 2007 From: samjnaa at gmail.com (samjnaa at gmail.com) Date: 14 Apr 2007 03:30:15 -0700 Subject: Python Feature Request: (?) Group all file-directory-related stdlib functions in one place Message-ID: <1176546615.450418.268090@y5g2000hsa.googlegroups.com> Please check for sanity and approve for posting at python-dev. Currently file-directory-related functionality in the Python standard library is scattered among various modules such as shutil, os, dircache etc. So I request that the functions be gathered and consolidated at one place. Some may need renaming to avoid conflicts or for clarification. From rNOSPAMon at flownet.com Sun Apr 22 14:03:29 2007 From: rNOSPAMon at flownet.com (Ron Garret) Date: Sun, 22 Apr 2007 11:03:29 -0700 Subject: Select weirdness References: Message-ID: In article , Ron Garret wrote: > Here's my code. It's a teeny weeny little HTTP server. (I'm not really > trying to reinvent the wheel here. What I'm really doing is writing a > dispatching proxy server, but this is the shortest way to illustrate the > problem I'm having): > > from SocketServer import * > from socket import * > from select import select > > class myHandler(StreamRequestHandler): > def handle(self): > print '>>>>>>>>>>>' > while 1: > sl = select([self.rfile],[],[])[0] > if sl: > l = self.rfile.readline() > if len(l)<3: break > print l, > pass > pass > print>>self.wfile, 'HTTP/1.0 200 OK' > print>>self.wfile, 'Content-type: text/plain' > print>>self.wfile > print>>self.wfile, 'foo' > self.rfile.close() > self.wfile.close() > print '<<<<<<<<<<<<' > pass > pass > > def main(): > server = TCPServer(('',8080), myHandler) > server.serve_forever() > pass > > if __name__ == '__main__': main() > > > If I telnet into this server and type in an HTTP request manually it > works fine. But when I try to access this with a browser (I've tried > Firefox and Safari -- both do the same thing) it hangs immediately after > reading the first line in the request (i.e. before reading the first > header). > > When I click the "stop" button in the browser it breaks the logjam and > the server reads the headers (but then of course it dies trying to write > the response to a now-closed socket). > > The only difference I can discern is that the browser send \r\n for > end-of-line while telnet just sends \n. But I don't see why that should > make any difference. So I'm stumped. Any clues would be much > appreciated. I have reproduced the problem using Telnet, so that proves it's not an EOL issue. The problem seems to be timing-related. If I type the request in manually it works. If I paste it in all at once, it hangs. It's actually even weirder than that: if I pipe the request into a telnet client then it hangs after the request line, just with a browser (or wget). But if I literally paste the request into a window running a telnet client, it gets past the request line and four out of seven headers before it hangs. rg From steve at holdenweb.com Wed Apr 25 11:10:11 2007 From: steve at holdenweb.com (Steve Holden) Date: Wed, 25 Apr 2007 11:10:11 -0400 Subject: override settrace In-Reply-To: <1177477557.493519.124620@u32g2000prd.googlegroups.com> References: <1177477557.493519.124620@u32g2000prd.googlegroups.com> Message-ID: Raja wrote: > Hi, > I want to override the sys.settrace() call, create a way to trace > the execution of a python program. Keep track of all objects created > and destroyed. Keep track of the call pattern throughout the execution > of the program and output a simplified "call graph" to standard out. > Please help me in this regard. > > Thank You, > How many times do you intend to post this question before waiting patiently for an answer? regards Steve -- Steve Holden +1 571 484 6266 +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 Mon Apr 23 10:33:57 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 23 Apr 2007 16:33:57 +0200 Subject: Do other Python GUI toolkits require this? References: <462697A6.6010007@codebykevin.com> <57C90994-391D-4350-A2F2-29C1590A3335@jedimindworks.com> Message-ID: <593uelF2jaf04U1@mid.uni-berlin.de> > I had originally thought that learning PyObjC might preclude me from > having to learn Objective-C, but that seems not to be the case. I have > previously found the same to be true with PyQt and wxPython--not knowing > the toolkits as they are implemented in C++ is a serious handicap. I've > even found this to be the case with Tkinter: understanding the Tcl > implementation of Tk (which I do, because I am also a Tcl developer) is > a huge advantage. > > Am I wrong to conclude that, if you want to do GUI programming in > Python, then some level of proficiency with another language is not just > recommended, but almost required? This is the case at least in my > experience. When I first started learning Python a couple of years ago, > I spun my wheels with it for months, because I couldn't figure out where > to get started with GUI programming. Finally I set Python aside and took > up Tcl/Tk for awhile--its simplicity in building GUI's is more > beginner-friendly. (No "there's more than one way to do it"--there's > only one way to do it, and that's Tk.) > > Now, coming back to Python with the Tk model of GUI development burned > in my brain, I appreciate the breadth of functions that Python > supports--but I still find myself "dropping down into Tcl" (!) to > assemble elements of my GUI's--either to write a Python wrapper, or > figure out how to implement something in pure Python. > > I understand the argument for Python having lots of bindings to > different GUI toolkits. If you are already proficient with a GUI toolkit > in a compiled language (Gtk, wxWidgets, Cocoa, Qt) then presumably > switching to Python will speed up your development--learning Python is > easy if you already know C++, for instance, and usually the Python > bindings are just a "thin wrapper" over the compiled bits. But if you > come to Python from the other direction--you're a relative beginner and > you want to learn GUI programming without the complexities of compiled > languages--then it's a lot harder to get started, ironically. Even > Tkinter is a challenge for someone who doesn't know Tcl. The basics are > easy enough--buttons, menus, labels, images--but doing anything > sophisticated, such as trees, column views, drag-and-drop, and so on, > requires extensions that may or may not be implemented in Python. I personally can't conclude with your conclusions :) Some background: I've started with Tcl/Tk as a scripting language precisely because of Tk - I liked the easy GUI creation, the layout management, and it was available for Unix/Linux, my OS of choice. So when I discovered Python about 7 or 8 years ago, I certainly had the right mindset for Tk. So, I was able to create GUIs in Tkinter, yet it never felt very comfortable - it just has too much Tclisms in there for my taste. So for GUI-development, I moved on to Qt - and simply loved it. I do have some C++-skillz, although these are somewhat rusty. And all I needed them for was reading the excellent reference Qt-documentation. Just the class-docs, not examples! The last step then was PyObjC. I bought a mac roughly two years ago, and immediately got interested in GUI-development there. I've never done a single bit of ObjectiveC before, and even though I now have some few classes done (mainly for interfacing with parts of OS X or other libraries that weren't exposed to python, e.g. CIImage and CGImage processing), I wouldn't say that I'm an ObjectiveC-programmer. The hardships for me with PyObjc stemmed from the unawareness and unfamiliarity with the specifics of GUI-development under the mac in general. E.g. the concepts of NIBs, NIB-classes, bundles and the like. Now admittedly I'm not a totally fair comparison to you for judging the matters at hand - I had a fair amount of exposure to different languages before and while learning python. But especially for PyObjC I can say that I became productive pretty fast without having to actually do serious or even not so serious ObjectiveC-development. I'd rather say that using a gui-toolkit usually requires to adapt to whatever concepts that toolkit has implemented. And certainly there are some of these that are influenced by the language the toolkit has been developed for. But for example ObjectiveC and Python both allow for dynamic dispatch - thus lots of the design decisions would have been the same. And as ObjecC and Cocoa heavily rely on NSArray and NSDictionary, which the bridge has good marshalling code for, using python's lists & dicts is natural and easy. In Qt OTOH they implemented their dynamic dispatch themselves - but using slots and signals is easy as cake as well. To me at least :) Diez From robert.kern at gmail.com Wed Apr 4 14:43:37 2007 From: robert.kern at gmail.com (Robert Kern) Date: Wed, 04 Apr 2007 13:43:37 -0500 Subject: BeautifulSoup vs. real-world HTML comments In-Reply-To: <1175711322.448629.20300@y80g2000hsf.googlegroups.com> References: <1175711322.448629.20300@y80g2000hsf.googlegroups.com> Message-ID: Carl Banks wrote: > On Apr 4, 2:08 pm, John Nagle wrote: >> BeautifulSoup can't parse this page usefully at all. >> It treats the entire page as a text chunk. It's actually >> HTMLParser that parses comments, so this is really an HTMLParser >> level problem. > > Google for a program called "tidy". Install it, and run it as a > filter on any HTML you download. "tidy" has invested in it quite a > bit of work understanding common bad HTML and how browsers deal with > it. It would be pointless to duplicate that work in the Python > standard library; let HTMLParser be small and tight, and outsource the > handling of floozy input to a dedicated program. Well, BeautifulSoup is just such a dedicated library. However, it defers its handling of comments to HTMLParser. That's the problem. -- 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 paddy3118 at googlemail.com Sat Apr 14 06:32:18 2007 From: paddy3118 at googlemail.com (Paddy) Date: 14 Apr 2007 03:32:18 -0700 Subject: Python Feature Request: Explicit variable declarations In-Reply-To: <1176546078.934340.253810@y5g2000hsa.googlegroups.com> References: <1176546078.934340.253810@y5g2000hsa.googlegroups.com> Message-ID: <1176546738.355555.256990@p77g2000hsh.googlegroups.com> On Apr 14, 11:21 am, samj... at gmail.com wrote: > Hello. Please tell me whether this feature request is sane (and not > done before) for python so it can be posted to the python-dev mailing > list. I should say first that I am not a professional programmer with > too much technical knowledge. > > I would like to have something like the "option explicit" statement in > Visual Basic which turns on C-like checking for declaration of > variables. This is highly helpful for people who are coming from C/C+ > +, for people who are learning programming using Python, and even > professionals, since this helps prevent typo errors like: > > sunlognitude = sunlongitude + 180.0 > > where the user has inadvertantly typed "g" before "n" and will later > wonder why his application is not working as expected. Please read this: http://www.python.org/doc/faq/programming.html#is-there-a-tool-to-help-find-bugs-or-perform-static-analysis PyChecker and Pylint might help you. - Paddy. From isaac.rodriguez at comcast.net Mon Apr 30 06:25:25 2007 From: isaac.rodriguez at comcast.net (Isaac Rodriguez) Date: 30 Apr 2007 03:25:25 -0700 Subject: My Python annoyances In-Reply-To: <1177791627.691137.324780@l77g2000hsb.googlegroups.com> References: <1177790269.523160.276060@l77g2000hsb.googlegroups.com> <1177791627.691137.324780@l77g2000hsb.googlegroups.com> Message-ID: <1177928725.466550.225970@h2g2000hsg.googlegroups.com> > Hmm, on my PyCon mug there are words "Python: so easy...even your BOSS > can use it!" Oh man! I would've killed for a mug like that a year ago. I was working for this guy, who had the entire build process automated in .BAT scripts. We spent more time fixing the build process than devoloping our product. Anyway, I started to move the entire thing to Python. Using a real programming language, allows creating a more robust process. It also allows separating data and code, which comes very handy when the data changes to not have to touch the code. So a year ago, I moved to another department. I would not get into the details of why, but I am just going to say that I'm much happier now. One day, I walking down the hall, and I see a book in my old boss' desk: "Learning Perl." I thought to my self, "You gotta be kiddin". So I saw him in the coffee area, and I asked him about it. His answer was, "Yeah, I'm re-writing the build scripts in Perl because you are the only one that knew Python, and we need to maintain them." Well, there is no-one in that team that knows Perl either, and if they haven't been able to learn Python in the couple of years I tried to push it, I really doubt they are going to learn Perl. Or maybe, the problem was that I was trying to push Python, so they are doing this just to prove me wrong. Like I said, I'm much happier now, and so much glad to be out of that team. Thanks, - Isaac. From liqfemail at gmail.com Sun Apr 8 21:31:45 2007 From: liqfemail at gmail.com (liqfemail at gmail.com) Date: 8 Apr 2007 18:31:45 -0700 Subject: Why does not my wx.html.HtmlWindow work? In-Reply-To: References: <1176003505.794328.62170@n76g2000hsh.googlegroups.com> Message-ID: <1176082305.001647.152860@n59g2000hsh.googlegroups.com> On Apr 9, 1:01 am, Rob Williscroft wrote: > liqfem... at gmail.com wrote innews:1176003505.794328.62170 at n76g2000hsh.googlegroups.comin > comp.lang.python: > > > > > Below are my source code: > > > import wx > > import wx.html > > > class MyHtmlFrame(wx.Frame): > > > def __init__(self, parent, title): > > wx.Frame.__init__(self, parent, -1, title, size=(600,400)) > > html = wx.html.HtmlWindow (self) > > if "gtk2" in wx.PlatformInfo: > > html.SetStandardFonts() > > html.LoadPage(" > > http://www.pythonthreads.com/articles/python/incorporating-into > > -wxpython-part-1.html") > > > app = wx.PySimpleApp() > > frm = MyHtmlFrame(None, "Simple HTML Browser") > > frm.Show() > > app.MainLoop() > > > It is just an example in the book "wxPython in action". But every time > > when I try to get it run, my CPU is fully occupied, and there is no > > frame that comes into existence. Why? > > I think your problem is that you call LoadPage before app.MainLoop() is > called, IOW you need to call LoadPage in an event handler: > > import wx > import wx.html > > class MyHtmlFrame(wx.Frame): > > HOME = "http://www.google.co.uk" > > def __init__(self, parent, title): > wx.Frame.__init__(self, parent, -1, title, size=(600,400)) > self.html = wx.html.HtmlWindow (self) > if "gtk2" in wx.PlatformInfo: > self.html.SetStandardFonts() > self.done_show = False > wx.EVT_IDLE( self, self.OnShow ) > self.html.SetPage( > "Loading ..." % self.HOME > ) > > def OnShow( self, event ): > if self.done_show: > return > self.done_show = True > self.html.LoadPage( self.HOME ) > > app = wx.PySimpleApp() > frm = MyHtmlFrame(None, "Simple HTML Browser") > frm.Show() > app.MainLoop() > > Note: the URL you loading takes ages to show, which is why I > use:http://www.google.co.ukabove. > > Rob. > --http://www.victim-prime.dsl.pipex.com/ To Rob Williscroft, It works when I call LoadPage() in any event handler, though I don't know the reason. I'll try to learn it. Thank you. And the example in the book "wxPython In Action" is wrong? From kyosohma at gmail.com Tue Apr 3 17:23:21 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: 3 Apr 2007 14:23:21 -0700 Subject: How to check if OS is unix or pc In-Reply-To: <1175634724.398396.48720@y80g2000hsf.googlegroups.com> References: <1175634724.398396.48720@y80g2000hsf.googlegroups.com> Message-ID: <1175635400.411430.87730@n59g2000hsh.googlegroups.com> On Apr 3, 4:12 pm, "bahoo" wrote: > In Matlab, there is a "isunix" command. > Is there something similar in python? > > Thanks! > bahoo Check out the platform module. It should do what you need. The "release()" method is especially useful. Mike From usenet at elehack.net Wed Apr 4 21:10:29 2007 From: usenet at elehack.net (Michael Ekstrand) Date: Thu, 5 Apr 2007 03:10:29 +0200 (CEST) Subject: Prevent Modification of Script? References: <1175735097.856840.177510@e65g2000hsc.googlegroups.com> Message-ID: On Wed, 04 Apr 2007 18:04:57 -0700, ts-dev wrote: > Is it possible to prevent modification of a python file once its been > deployed? File permissions of the OS could be used..but that doesn't > seem very secure. > > The root of my question is verifying the integrity of the application > and the scripts being run. Is this possible, if so, how? Your best bet is probably some sort of cryptographic signature mechanism. However, if they can modify it, they can likely modify it so that the signature check is disabled. So you need something you "trust" to verify said signature. So basically, except in a "trusted" computing environment, you cannot entire ensure what you're wanting. OS permissions are probably the most practical thing you've got; the signature thing could fool some slightly more intrepid attackers. One significant factor: are you worried about other users on your systems (or other users who share systems with you under a third party's control), or are you worried about what people will do on their own systems? - Michael From nospam at nospam.com Sat Apr 21 17:28:56 2007 From: nospam at nospam.com (Gilles Ganault) Date: Sat, 21 Apr 2007 23:28:56 +0200 Subject: Building browser-like GET request Message-ID: Hello I'd like to download pages from a site, but it checks whether the requests are coming from a live user or a script; If the latter, the server returns a blank page. Using a proxy (Paros), I can see what information my script and FireFox send, and there are a lot of information that Python is missing: ======== PYTHON =============== http://www.acme.com/cgi-bin/read?code=123 HTTP/1.1 Accept-Encoding: identity Host: www.acme.com Connection: close User-Agent: Python-urllib/2.4 Paros/3.2.12 ======== FIREFOX =============== http://www.acme.com/cgi-bin/read?code=123 HTTP/1.1 Host: www.acme.com User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.3) Gecko/20070309 Firefox/2.0.0.3 Paros/3.2.12 Accept: text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5 Accept-Language: fr-fr,en-us;q=0.7,en;q=0.3 Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7 Keep-Alive: 300 Proxy-Connection: keep-alive ============================= How can Python be told to send the same information? Thank you. From mathieu.malaterre at gmail.com Fri Apr 6 04:08:30 2007 From: mathieu.malaterre at gmail.com (mathieu) Date: 6 Apr 2007 01:08:30 -0700 Subject: Freeze vs cx_Freeze Message-ID: <1175846910.468253.271490@q75g2000hsh.googlegroups.com> Hello, I am currently investigating how to distribute a python based application on a targeted linux system (debian) and so far I only found two options: - Freeze (shipped with python dist) - cx_Freeze (*) As far as I understand those two options are very close. According to the cx_Freeze README cx_Freeze is simply easier to use (no dependencie of gcc, faster to create binaries) and it is cross-platform (no interest for me in this case). Anything else ? thanks, -MM (*) http://python.net/crew/atuining/cx_Freeze/ From gigs at hi.t-com.hr Wed Apr 4 14:53:48 2007 From: gigs at hi.t-com.hr (gigs) Date: Wed, 4 Apr 2007 20:53:48 +0200 Subject: pyscripter on windows vista Message-ID: does pyscriter work on windows vista From skip at pobox.com Fri Apr 13 19:02:24 2007 From: skip at pobox.com (skip at pobox.com) Date: Fri, 13 Apr 2007 18:02:24 -0500 Subject: Portably generating infinity and NaN In-Reply-To: <462008d1$0$11763$9b622d9e@news.freenet.de> References: <462008d1$0$11763$9b622d9e@news.freenet.de> Message-ID: <17952.3072.690960.419104@montanaro.dyndns.org> >> (Note the absence of a demonstration on Windows.) Can't the above be >> blessed as the One True Way and wormed around in floatmodule.c for >> those platforms where float'ing "NaN" or "Inf" doesn't currently >> work? Martin> How would you do the worming-around? I don't know. On I was just asking. On unixoid systems I sort of assume you could add tests to the configure script to detect what worked. If converting the strings works you're done. If not, maybe Robert Kern's numpy code could be run in the configure script to generate constants for NaN and Inf that could be used in floatmodule.c. Windows would probably have to be hard-coded, but except for 32-bit and 64-bit differences it should be the same all over, yes? Skip From b.r.willems at gmail.com Sun Apr 29 18:39:11 2007 From: b.r.willems at gmail.com (Bart Willems) Date: Sun, 29 Apr 2007 18:39:11 -0400 Subject: Any Good tools to create CSV Files? In-Reply-To: References: <1177811756.255774.315260@q75g2000hsh.googlegroups.com> Message-ID: Aahz wrote: > In all fairness, the csv module is new in Python 2.3, and I'm sure I'm > not the only person still using Python 2.2 for production. That is true, on the other hand, Reportlab is made for at least Python 2.4, "although it will work with 2.3" - so he has 2.3 at least :) From claird at lairds.us Mon Apr 30 16:46:33 2007 From: claird at lairds.us (Cameron Laird) Date: Mon, 30 Apr 2007 20:46:33 +0000 Subject: Python-URL! - weekly Python news and links (Apr 30) References: <1177963548_23061@sp12lax.superfeed.net> Message-ID: <961ig4-hti.ln1@lairds.us> In article <1177963548_23061 at sp12lax.superfeed.net>, Roger Upole wrote: >Cameron Laird wrote: >> QOTW: "That is just as feasible as passing a cruise ship through a phone >> line." - Carsten Haese, on transporting a COM object across a network. >> Less vividly but more formally, as he notes, "A COM object represents a >> connection to a service or executable that is running on one computer. >> Transferring that connection to another computer is impossible." >> > >While this is indeed a nice turn of phrase, in substance it's incorrect. >You can marshal a live COM object and unmarshal it on a different >machine. . . . ... but the *references* in that object are unlikely to be meaningful on the second machine (or, in many cases, on the original machine, if at a sufficiently later time). From steve at REMOVE.THIS.cybersource.com.au Sun Apr 15 00:02:13 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Sun, 15 Apr 2007 14:02:13 +1000 Subject: Python Feature Request: Add the "using" keyword which works like "with" in Visual Basic References: <1176547372.584539.89170@q75g2000hsh.googlegroups.com> Message-ID: On Sat, 14 Apr 2007 03:42:52 -0700, samjnaa wrote: > Please check for sanity and approve for posting at python-dev. > > In Visual Basic there is the keyword "with" which allows an object- > name to be declared as governing the following statements. For > example: > > with quitCommandButton > .enabled = true > .default = true > end with > > This is syntactic sugar for: > > quitCommandButton.enabled=true > quitCommandButton.default=true Which is very much like Pascal's with block. This question has been asked before: http://effbot.org/pyfaq/why-doesn-t-python-have-a-with-statement-like-some-other-languages.htm Despite what the Effbot says, I believe that there is no ambiguity that can't be resolved. Specifying that names used in a using-block have a leading dot makes it obvious to the compiler which names are shortened: using longname: x = .attribute # must be longname.attribute If we forbid nested using-blocks, then all you need is a pre-processor to change ".attribute" to "longname.attribute". There's never any ambiguity. But if you want to be really ambitious, one might allow nested using-blocks. Now the compiler can't resolve names with leading dots at parse-time, and has to search namespaces at runtime, but that's no different from what Python already does. using longname: using anotherlongname: x = .attr In this case, at Python has to determine at runtime which object has an attribute "attr". If that sounds familiar, it should: that's exactly what happens when you say instance.attribute: Python searches instance.__dict__ then instance.__class__.__dict__, and any superclasses. There is one slight ambiguity left: should Python search longname first or anotherlongname? But that decision has come up before, for nested scopes in functions. It seems obvious to me that Python should search deepest to most shallow, the same way that function nested scopes work. So the above nested block would be equivalent to: try: x = anotherlongname.attr except AttributeError: try: x = longname.attr except AttributeError: raise UsingError('no such attribute') One might even allow a construct like this: using longname, anotherlongname: x = .attr In this case, the search resolution order would be from left to right, that is, longname before anotherlongname. -- Steven. From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Thu Apr 26 06:42:13 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Thu, 26 Apr 2007 12:42:13 +0200 Subject: How to find complementary colour for pixel References: <1177578583.205643.65200@r35g2000prh.googlegroups.com> Message-ID: <59be05F2k1cbdU1@mid.individual.net> Johny wrote: > As pictures maybe different, colour, in the position where I > write the text, is also different. > Is there a way how to set the font colour so that it will be seen > very clearly in the picture? > For example, if the picture is bright ( for example yellow), the > font colour should be dark( e.g. black) and vice versa. > Is there a routine in PIL available that calculates complementary > colour for RGB pixel format? IMHO, this looks weird, especially in complex images. A better solution is to draw a background box behind the text that has the image colors, butt low contrast (or saturation, or whatever). > Can anyone help? ... Regards, Bj?rn -- BOFH excuse #405: Sysadmins unavailable because they are in a meeting talking about why they are unavailable so much. From kay.schluehr at gmx.net Mon Apr 2 06:31:04 2007 From: kay.schluehr at gmx.net (Kay Schluehr) Date: 2 Apr 2007 03:31:04 -0700 Subject: Shed Skin Python-to-C++ Compiler 0.0.21, Help needed In-Reply-To: References: <576vhbF2ca1guU1@mid.individual.net> <1175376373.241744.6220@y80g2000hsf.googlegroups.com> <1175413310.295953.230840@e65g2000hsc.googlegroups.com> <1175455529.936887.249170@e65g2000hsc.googlegroups.com> <1175496721.899984.193690@n76g2000hsh.googlegroups.com> Message-ID: <1175509864.346577.67370@o5g2000hsb.googlegroups.com> On Apr 2, 9:17 am, John Nagle wrote: > mark.duf... at gmail.com wrote: > > but in any case, I believe there are several reasons why type > > inference scalability is actually not _that_ important (as long as it > > works and doesn't take infinite time): > > > -I don't think we want to do type inference on large Python programs. > > this is indeed asking for problems, and it is not such a bad approach > > to only compile critical parts of programs (why would we want to > > compile PyQt code, for example.) I do think type inference scales well > > enough to analyze arbitrary programs of up to, say, 5,000 lines. I'm > > not there yet with Shed Skin, but I don't think it's that far away (of > > course I'll need to prove this now :-)) > > > -type inference can be assisted by profiling > > Something else worth trying: type inference for separately > compiled modules using the test cases for the modules. Seem like we agree on this point. The idea of defining a type recording phase and identifying it with UT execution was actually my original motivation to consider alternative frameworks for compiling Python. > One > big problem with compile-time type inference is what to do > about separate compilation, where you have to make decisions > without seeing the whole program. An answer to this is to > optimize for the module's test cases. If the test cases > always use an integer value for a parameter, generate hard > code for the case where that variable is a integer. As long > as there's some way to back down, at link time, to a more general > but slower version, programs will still run. If the test > cases reflect normal use cases for the module, this should > lead to generation of reasonable library module code cases. The nice thing about this idea is that your type system is complient with your test base. When a test succeeds it can not be invalidated by a recorded type that gets annotated. You really get some metadata and program description elements for free. There are also some caveats about subtyping and using type information that is to special - or not special enough. In the first case the maximal nominal type that includes the recorded type as a subtype can be chosen that is complient to the structural properties of the type i.e. the interface description of the class accordingly. I have no idea about deeper specialization. Guess this can't be handled automatically. Methodologically this means that testing and important aspects of optimizing Python code are not separated from each other. This is elegant and will increase overall code quality and acceptance of the language. Ciao, Kay From time.swift at gmail.com Wed Apr 4 23:19:37 2007 From: time.swift at gmail.com (ts-dev) Date: 4 Apr 2007 20:19:37 -0700 Subject: Prevent Modification of Script? In-Reply-To: References: <1175735097.856840.177510@e65g2000hsc.googlegroups.com> Message-ID: <1175743177.489242.214700@w1g2000hsg.googlegroups.com> On Apr 4, 6:10 pm, Michael Ekstrand wrote: > One significant factor: are you worried about other > users on your systems (or other users who share systems with you under a > third party's control), or are you worried about what people will do on > their own systems? Michael, Ben & others: The short answer is others on a shared system, or malware that could modify the scripts. I'm new to python programming and there are just some paradigms I'm having trouble grasping. If the scripts can be modified (very easily), how can the application be trusted? i.e. If its an address book, then it would be trivial for malware to modify the script to override data or send it somewhere else... It would also seem like it makes user authentication through a password/ username, or encryption useless. The script could easily be modified to by-pass authentication and encryption could be disabled. Please correct any wrong assumptions that I might be making.. In a compiled application its not impossible to by pass the code.. but its not so easy. Perhaps this is just a side-effect of being a scripted language - not a flaw, just me trying to use it for something its not well suited for. - Kiel From bdesth.quelquechose at free.quelquepart.fr Mon Apr 16 18:27:07 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Tue, 17 Apr 2007 00:27:07 +0200 Subject: Python editor/IDE on Linux? In-Reply-To: <1176540372.025899.27690@o5g2000hsb.googlegroups.com> References: <8ZadnS79krqFwL3bnZ2dnUVZ_sWdnZ2d@comcast.com> <1176540372.025899.27690@o5g2000hsb.googlegroups.com> Message-ID: <4623eeef$0$1138$426a34cc@news.free.fr> Ali a ?crit : > On 14 Apr, 05:48, "Jack" wrote: > >>That's a good one. I got to find out what's special with Emacs :) > > > The users. > +10 OT-QOTW !-) (ouch, it hurts...) From nospam at nospam.com Sun Apr 22 17:30:16 2007 From: nospam at nospam.com (Gilles Ganault) Date: Sun, 22 Apr 2007 23:30:16 +0200 Subject: [re.finditer] Getting all occurences in one go? References: Message-ID: On Sun, 22 Apr 2007 23:28:23 +0200, Gilles Ganault wrote: >I'd like to make sure there isn't an easier way to extract all the >occurences found with re.finditer: Oops, s/match/item/: req = urllib2.Request(url, None, headers) response = urllib2.urlopen(req).read() matches = re.compile("(\d+).html").finditer(response) # ----------- BEGIN for item in matches: if mytable[item]=="": mytable[item]= match.group(1) else: mytable[item]= mytable[item] + "," + match.group(1) # ----------- END From robert.rawlins at thinkbluemedia.co.uk Fri Apr 27 09:43:41 2007 From: robert.rawlins at thinkbluemedia.co.uk (Robert Rawlins - Think Blue) Date: Fri, 27 Apr 2007 14:43:41 +0100 Subject: what python technology for my app? In-Reply-To: <4631fbc2$0$641$426a74cc@news.free.fr> References: <4631dc06$0$15457$426a74cc@news.free.fr> <4631fbc2$0$641$426a74cc@news.free.fr> Message-ID: <006201c788d2$13e876a0$3bb963e0$@rawlins@thinkbluemedia.co.uk> Haha, no Troll, just a shameless plug for my life's one true love ;-) Rob -----Original Message----- From: python-list-bounces+robert.rawlins=thinkbluemedia.co.uk at python.org [mailto:python-list-bounces+robert.rawlins=thinkbluemedia.co.uk at python.org] On Behalf Of Bruno Desthuilliers Sent: 27 April 2007 14:35 To: python-list at python.org Subject: Re: what python technology for my app? Robert Rawlins - Think Blue a ?crit : > Just thought I'd make a little suggestion about this, I don?t know how > strict you want to be with the web development side of things, but I'm a web > developer by trade and have recently started using python for my non-web > type applications. > > If you're looking for a web based server side solution, then you can't go > wrong with Adobe ColdFusion. Err... is this a troll ? -- http://mail.python.org/mailman/listinfo/python-list From python at hope.cz Fri Apr 6 14:16:28 2007 From: python at hope.cz (Johny) Date: 6 Apr 2007 11:16:28 -0700 Subject: Picture resolution and PIL Message-ID: <1175883388.743729.111850@o5g2000hsb.googlegroups.com> Is it possible to find out a picture resolution by using PIL package? Thanks for help L. From bbxx789_05ss at yahoo.com Tue Apr 3 14:33:58 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: 3 Apr 2007 11:33:58 -0700 Subject: File Object behavior In-Reply-To: <1175624784.625914.14660@e65g2000hsc.googlegroups.com> References: <1175624784.625914.14660@e65g2000hsc.googlegroups.com> Message-ID: <1175625238.443349.189330@o5g2000hsb.googlegroups.com> On Apr 3, 12:26 pm, "7stud" wrote: > The file.writelines() documentation says that it > doesn't add line separators. Is adding a carriage return something > different? No. > Is this expected behavior? According to Python in a Nutshell(p. 217), it is. On windows, in text mode, when you write a \n to a file, the \n is converted to the system specific newline (which is specified in os.linesep). For windows, a newline is \r\n. Conversely, on windows, in text mode, when you read a \r\n newline from a file, it is converted to a \n. I forgot to add that when you read or write in binary mode, no conversion takes place. So, if you read \r\n from the file, your input will contain the \r\n; and if you write \r\n to the file, then the file will contain \r\n. From horpner at yahoo.com Wed Apr 25 09:19:50 2007 From: horpner at yahoo.com (Neil Cerutti) Date: 25 Apr 2007 15:19:50 +0200 Subject: When are immutable tuples *essential*? Why can't you just use lists *everywhere* instead? References: <1177088796.622928.224890@d57g2000hsg.googlegroups.com> <1177089206.550423.288670@q75g2000hsh.googlegroups.com> <58sf33F2b1q8tU1@mid.individual.net> <1177103370.022138.110320@n59g2000hsh.googlegroups.com> <1177108560.660288.171890@n76g2000hsh.googlegroups.com> <1177451173.176235.216270@t38g2000prd.googlegroups.com> Message-ID: On 2007-04-24, Thomas Nelson wrote: > On Apr 23, 10:38 pm, Mel Wilson wrote: >> Even with a balanced tree, if a key in a node changes value, >> you may have to re-balance the tree. Nothing in a Python list >> says that a dictionary tree would have to be re-balanced if >> you changed that particular list. > > You don't have to look at any implementation. A dictionary > maps every key to exactly one object. If the objects were > mutable, you could change one key to another key, and then > which item would the dictionary pull? > (Imaginary code) > d = {[1,2,3]: 'hat', [1,2,4]: 'sock' } > for key in d: > key.pop() > print d[[1,2]] #does this print hat or sock? That would be documented as undefined behavior, and users exhorted not to do such things. Python's dictionaries are a proven winner--I'm definitely not an advocate for changing them. But the general requirement for a mapping container *isn't* that keys be immutable, but that you either don't mutate keys, or don't do so without also reording (rehashing?) the mapping. -- Neil Cerutti From duncan.booth at invalid.invalid Thu Apr 12 16:02:54 2007 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 12 Apr 2007 20:02:54 GMT Subject: Calling private base methods References: <1176374675.347453.89340@n76g2000hsh.googlegroups.com> <1176404325.211501.26610@w1g2000hsg.googlegroups.com> Message-ID: "7stud" wrote: > On Apr 12, 5:04 am, Duncan Booth wrote: >> "7stud" wrote: >> > On Apr 12, 2:47 am, "Jorgen Bodde" wrote: >> >> Is it possible to call a private base method? I come from a C++ >> >> background, and I liked this construction as my base class has helper >> >> methods so that I do not have to duplicate code. >> >> > I'd like to see some C++ code that does that! >> >> Easy: >> >> #define private public >> #include >> #undef private >> >> then call the private methods as much as you want. > > lol. I don't see any private methods being created there. > > You should have looked in someheader: class Whatever { private: void ohnoyoudont(int); } then back in the C file: ... Whatever foo = new Whatever(); int ohyesido = 42; foo.ohnoyoudont(ohyesido); ... Really, it does work (probably). There are other ways to get at private members in C++ but this is the easiest. From jstroud at mbi.ucla.edu Fri Apr 27 17:07:17 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Fri, 27 Apr 2007 14:07:17 -0700 Subject: how to create/ref globals in an alternate namespace? In-Reply-To: References: Message-ID: Steven W. Orr wrote: > I have two seperate modules doing factory stuff which each have the > similar function2: > > In the ds101 module, def DS101CLASS(mname,data): > cname = mname+'DS101' > msg_class = globals()[cname] > msg = msg_class(data) > return msg > > and in the fdu module, > > def FDUCLASS(mname,data): > cname = mname+'FDU' > msg_class = globals()[cname] > msg = msg_class(data) > return msg > > I was thinking I'd be clever and create a common function: > def procCLASS(mname, objname, data): > cname = mname+objname > msg_class = globals()[cname] > msg = msg_class(data) > return msg > > but the call to globals fouls it all up. Is there a way to write it so > that the call to globals can be parameterized to be in the context of a > specific module? > > Also, I need to go the other way, a la, > globals()[name] = nclass > > Is this doable? > > TIA > Why do you need all of the msg_class(es) global? Why not put them into a module and import the module where you need them? This would be the conventional way to avoid such problems. From adrian_p_smith at yahoo.com Tue Apr 24 10:49:47 2007 From: adrian_p_smith at yahoo.com (Adrian Smith) Date: 24 Apr 2007 07:49:47 -0700 Subject: python cgi problem with textarea In-Reply-To: <1177412425.066398.199080@r35g2000prh.googlegroups.com> References: <1177222084.696307.128620@n59g2000hsh.googlegroups.com> <1177247362.014926.12500@n76g2000hsh.googlegroups.com> <1177254110.057238.315240@o5g2000hsb.googlegroups.com> <1177315259.401721.62040@l77g2000hsb.googlegroups.com> <17ar23drof4nsdhcdoa0jconcb6sjuljk0@4ax.com> <1177412425.066398.199080@r35g2000prh.googlegroups.com> Message-ID: <1177426187.582317.279290@t39g2000prd.googlegroups.com> On Apr 24, 8:00 pm, placid wrote: > oops...i did read the problem description, but i when i tried the code > it worked for me and when i put spaces into the TextArea it wasn't > reflected correctly back. So i thought this was the problem. > > Adrian, can you still try replacing spaces with   via the > following; > > #!/usr/bin/python > import cgi > import urllib > import cgitb > cgitb.enable() > print "Content-type: text/html\n" > form = cgi.FieldStorage() > #print urllib.quote_plus(form["essay"].value) > > for char in form["essay"].value: > if char == ' ': > print " " > else: > print char > > Cheers I'll try it...but I think it may be a problem on the server end. It's not showing up in the server logs, either. From jgodoy at gmail.com Sat Apr 14 13:30:01 2007 From: jgodoy at gmail.com (Jorge Godoy) Date: Sat, 14 Apr 2007 14:30:01 -0300 Subject: Python editor/IDE on Linux? References: <1176488840.672572.101830@y80g2000hsf.googlegroups.com> <461fe88c$0$6420$426a74cc@news.free.fr> Message-ID: <87647yc19i.fsf@gmail.com> aahz at pythoncraft.com (Aahz) writes: > In article , > Michael Bentley wrote: >> >>>> >>>> Everybody uses vim. >>>> >>> Except for real programmers... >> >>Who instead use emacs ;-) > > "Emacs makes a good OS, but a lousy editor." Yep. Emacs comes with a lot of those funny phrases. It is so good that it even helps people using other editors to have some fun. ;-) -- Jorge Godoy From dwcoll01 at gmail.com Wed Apr 18 10:28:15 2007 From: dwcoll01 at gmail.com (lucidparadox) Date: 18 Apr 2007 07:28:15 -0700 Subject: X root Operator help In-Reply-To: References: <1176898887.530470.222830@p77g2000hsh.googlegroups.com> Message-ID: <1176906495.306287.194820@b75g2000hsg.googlegroups.com> On Apr 18, 8:52 am, Michael Hoffman wrote: > lucidparadox wrote: > > I'm currently new to Python and I haven't been able to find the > > operator/math function to find the square root or even the x root of a > > number. > > For square root, use math.sqrt(y) > > For x root use y**(1/x) > > > I'm rewriting a program that I wrote in BASIC that does the > > math of a quadratic equation (user puts in a, b, and c values) and > > tells the user whether it has 1 root, 2 roots, or no real roots and > > displays the roots if it has real roots. > > In floating point arithmetic, the naive way of calculating both roots > always using the formula (-b +/- sqrt(b**2 - 4*a*c))/2*a will give you > inaccurate results sometimes. See > . > > For a better formula, see how r_1 and r_2 are defined in > . > -- > Michael Hoffman Thanks. As of right now I'm just trying to familiarize myself with the syntax of Python. Actually I should have thought of y**(1/x). I'm currently a freshman in college so the alternative formula hasn't been introduced to me yet. Thanks for the pointers though. Dan Collins From jstroud at mbi.ucla.edu Sun Apr 29 18:48:09 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Sun, 29 Apr 2007 15:48:09 -0700 Subject: fastest way to find the intersection of n lists of sets In-Reply-To: <1177883328.835058.138990@p77g2000hsh.googlegroups.com> References: <1177883328.835058.138990@p77g2000hsh.googlegroups.com> Message-ID: Prateek wrote: > I have 3 variable length lists of sets. I need to find the common > elements in each list (across sets) really really quickly. > > Here is some sample code: > > # Doesn't make sense to union the sets - we're going to do > intersections later anyway > l1 = reduce(operator.add, list(x) for x in l1) > l2 = reduce(operator.add, list(x) for x in l2) > l3 = reduce(operator.add, list(x) for x in l3) > > # Should I do this in two steps? Maybe by intersecting the two > shortest lists first? > s = frozenset(l1) & frozenset(l2) & frozenset(l3) > > I'm assuming frozensets are (somehow) quicker than sets because > they're immutable. > > Any code suggestions? Maybe using something in the new fancy-schmancy > itertools module? > > Thanks, > Prateek > I don't understand why you cast to list. I would propose: lists_of_sets = [l1, l2, l3] reduce(set.intersection, (reduce(set.union, x) for x in lists_of_sets)) Since this is simplest, I'm guessing it should be fastest because I'm also guessing that set impelmentation is as optimized as list--I think this would hold true especially for large sets with sparse overlap between lists. So it might be reasonable consider the content of your sets and lists and write your code based on the content or on assuming a particular composition. James From phil at riverbankcomputing.co.uk Fri Apr 27 03:10:33 2007 From: phil at riverbankcomputing.co.uk (Phil Thompson) Date: Fri, 27 Apr 2007 08:10:33 +0100 Subject: pyqt4 signal/slot using PyObject* and shortcut In-Reply-To: <80628d680704262305k779c59fkc4535619a6c06594@mail.gmail.com> References: <80628d680704262259o46d06926n6d5f7b9e375c08b2@mail.gmail.com> <80628d680704262305k779c59fkc4535619a6c06594@mail.gmail.com> Message-ID: <200704270810.33555.phil@riverbankcomputing.co.uk> On Friday 27 April 2007 7:05 am, Pradnyesh Sawant wrote: > On 4/27/07, Pradnyesh Sawant wrote: > > Hello, i have the following code: > > ################################################################# > > import time > > import sys > > from PyQt4 import QtGui, QtCore > > > > class Counter(QtCore.QThread): > > def __init__(self): > > QtCore.QThread.__init__(self) > > def run(self): > > cntr = 0 > > while cntr < 10: > > cntr += 1 > > self.emit(QtCore.SIGNAL("showCntr1(PyObject*)"), (cntr, > > "a")) # line 1 > > self.emit(QtCore.SIGNAL("showCntr2"), (cntr, "a")) > > # line 2 > > time.sleep(0.2) > > class Gui(QtGui.QDialog): > > def __init__(self, parent = None): > > QtGui.QDialog.__init__(self, parent) > > frameStyle = QtGui.QFrame.Sunken | QtGui.QFrame.Panel > > > > self.lCntr = QtGui.QLabel() > > self.lCntr.setFrameStyle(frameStyle) > > loGrd = QtGui.QGridLayout() > > loGrd.addWidget(self.lCntr, 0, 0) > > self.setLayout(loGrd) > > self.setWindowTitle(self.tr("Counter")) > > def showCntr1(self, val): > > print val, str(val) > > self.lCntr.setText(str(val)) > > def showCntr2(self, val): > > print val, str(val) > > self.lCntr.setText(str(val)) > > if __name__ == "__main__": > > app = QtGui.QApplication(sys.argv) > > dialog = Gui() > > cntr = Counter() > > cntr.start() > > QtCore.QObject.connect(cntr, QtCore.SIGNAL("showCntr1(PyObject*)"), > > dialog.showCntr1, QtCore.Qt.QueuedConnection) > > QtCore.QObject.connect(cntr, QtCore.SIGNAL("showCntr2"), > > dialog.showCntr1, QtCore.Qt.QueuedConnection) > > There's a small bug in the above line, it should be dialog.showCntr2, > and not dialog.showCntr1. However, even with this change, the output > shown below remains the same :( > > > sys.exit(dialog.exec_()) > > ################################################################# > > If i comment out "line 1", then i get the following output: > > 0.2 0.2 > > 0.2 0.2 > > 0.2 0.2 > > 0.2 0.2 > > 0.2 0.2 > > 0.2 0.2 > > 0.2 0.2 > > 0.2 0.2 > > 0.2 0.2 > > 0.2 0.2 > > Notice that 0.2 is the time value of the sleep instruction. Why is > > this happening? > > > > On the other hand, if i comment out "line 2", then i get the following > > output: (, 'a') (, ) > > (, 'a') (, ) > > (, 'a') (, ) > > (, 'a') (, ) > > (, 'a') (, ) > > (, 'a') (, ) > > (, 'a') (, ) > > (, 'a') (, ) > > (, 'a') (, ) > > (, 'a') (, ) > > What i get from the above is that a reference to "cntr" is being > > passed, but by the time the gui thread is actually run, both the > > values (cntr and "a") have been destroyed, hence the NULL values. > > ***How do i circumvent this problem?*** > > > > Lastly, if i don't comment out any of line 1 or 2, then i get the foll > > output: (<__main__.Gui object at 0xb6a8f12c>, (<__main__.Gui object at > > 0xb6a8f12c>, (<__main__.Gui object at 0xb6a8f12c>, (<__main__.Gui > > object at 0xb6a8f12c>, (<__main__.Gui object at 0xb6a8f12c>, > > (<__main__.Gui object at 0xb6a8f12c>, (<__main__.Gui object at > > 0xb6a8f12c>, (<__main__.Gui object at 0xb6a8f12c>, (<__main__.Gui > > object at 0xb6a8f12c>, (<__main__.Gui object at 0xb6a8f12c>, > > (<__main__.Gui object at 0xb6a8f12c>, (<__main__.Gui object at > > 0xb6a8f12c>, (<__main__.Gui object at 0xb6a8f12c>, (<__main__.Gui > > object at 0xb6a8f12c>, (<__main__.Gui object at 0xb6a8f12c>, > > (<__main__.Gui object at 0xb6a8f12c>, (<__main__.Gui object at > > 0xb6a8f12c>, (<__main__.Gui object at 0xb6a8f12c>, .......... > > i don't know what this means??? Can anyone kindly explain what's > > happening... > > > > I'm using: > > python: 2.4.4~c1-0ubuntu1 > > qt4-dev-tools: not installed > > python-qt4: 4.0.1-1ubuntu1 > > sip4: (4.4.5-2ubuntu1 > > os: ubuntu edgy As I said in the other thread, upgrade to a current release of PyQt. Also "PyObject*" should no longer be used in signal signatures - use "PyQt_PyObject" instead. Phil From aleax at mac.com Wed Apr 4 00:39:01 2007 From: aleax at mac.com (Alex Martelli) Date: Tue, 3 Apr 2007 21:39:01 -0700 Subject: passing options to __import__ References: <1175639497.973152.281270@e65g2000hsc.googlegroups.com> Message-ID: <1hw0k1v.xxbjsh1k7rj68N%aleax@mac.com> Harold Fellermann wrote: ... > Within my program, I am importing a module via > __import__(module_name,globals(),locals()) The globals() you're passing are those of the *importing* module, and have no effect on those of the *imported* module. > and I want to pass comand line options to this module. I would prefer command-line options are sys.argv -- a list you can set in any way you want before you __import__. Generally unwise to "fake" it, but it may sometimes come in handy for purposes of testing (and no others). Alex From cam.ac.uk at mh391.invalid Mon Apr 16 05:59:05 2007 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Mon, 16 Apr 2007 10:59:05 +0100 Subject: Portably generating infinity and NaN In-Reply-To: <7xhcrh2pxy.fsf@ruckus.brouhaha.com> References: <462008d1$0$11763$9b622d9e@news.freenet.de> <7xhcrh2pxy.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > skip at pobox.com writes: >> But PEP 754 will only work for architectures supporting IEEE 754. I realize >> that's the vast majority of systems, but aren't there still a few Crays and >> VMS machines out there? (Do those architectures support NaN and Inf?) > > I wouldn't worry about it. There are Python subsystems (like threads) that > don't work on certain OS's, fine, total portability means not being able to > rely on them, and that's ok. I doubt any Crays are still running, or at least > running any numerical code written in Python. Same for VMS. Do these systems provide infinities or NaN? If so, then fpconst could be extended to include them. -- Michael Hoffman From jjl at pobox.com Wed Apr 11 17:01:22 2007 From: jjl at pobox.com (John J. Lee) Date: Wed, 11 Apr 2007 21:01:22 GMT Subject: Support SSL for Solaris 10 References: <1175789468.487182.217750@w1g2000hsg.googlegroups.com> Message-ID: <87bqhu7hi0.fsf@pobox.com> "campos" writes: > Hi all, > > Last time I installed Python 2.5 by default, it didn't support SSL. > When I tried to use HTTPS, the following error occured: > AttributeError: 'module' object has no attribute 'ssl' ISTR that the sunfreeware.com 2.5 build supports that, if you have OpenSSL installed, assuming that by "use HTTPS" you mean "use httplib as an HTTPS client". At least, I needed the openssl package installed for some reason like getting module md5, or some such, so I assume that installing openssl will also give you HTTPS support in httplib. John From anthonydevine69 at hotmail.com Fri Apr 13 15:05:33 2007 From: anthonydevine69 at hotmail.com (tonydevlin) Date: Fri, 13 Apr 2007 12:05:33 -0700 (PDT) Subject: Automated email response In-Reply-To: <9883575.post@talk.nabble.com> References: <9883575.post@talk.nabble.com> Message-ID: <9984870.post@talk.nabble.com> I am only guessing as I have never done python code before, but i have had another look at the code and was wondering if anyone knew if the below code needs a for loop to look through members in plone and email out members with a certain permission like Manager instead of just emailing 1 member like the below code does. obj=sti.object creator = obj.Creator() history = sti.getHistory() wf_tool = context.portal_workflow mMsg = """ Content has been submitted for your review. The url was %s. The reason was %s. """ member = context.portal_membership.getMemberById(creator) creator = {'member':member, 'id':member.getId(), 'fullname':member.getProperty('fullname', 'Fullname missing'), 'email':member.getProperty('email', None)} actorid = wf_tool.getInfoFor(obj, 'actor') actor = context.portal_membership.getMemberById(actorid) reviewer = {'member':actor, 'id':actor.getId(), 'fullname':actor.getProperty('fullname', 'Fullname missing'), 'email':actor.getProperty('email', None)} mTo = reviewer['email'] mFrom = creator['email'] mSubj = 'Your item has transitioned' obj_url = obj.absolute_url() #use portal_url + relative_url comments = wf_tool.getInfoFor(obj, 'comments') message = mMsg % (obj_url, comments) context.MailHost.send(message, mTo, mFrom, mSubj) The loop i was thinking of was for user in context.portal_membership.listMembers(): if "Manager" in context.portal_membership.getMemberById(user.id).getRoles(): But unsure of whether this is right and how to implement this into the code. Does anybody have any thoughts at all? -- View this message in context: http://www.nabble.com/Automated-email-response-tf3540615.html#a9984870 Sent from the Python - python-list mailing list archive at Nabble.com. From leuchte at gmail.com Wed Apr 25 11:04:59 2007 From: leuchte at gmail.com (TimC) Date: 25 Apr 2007 15:04:59 GMT Subject: Python not giving free memory back to the os get's me in real problems ... References: <1177510121.882503.145560@n15g2000prd.googlegroups.com> <_LidnenBcrz7-rLbnZ2dnUVZ_tCtnZ2d@comcast.com> Message-ID: <59990rF2ja6c7U3@mid.dfncis.de> Larry Bates wrote: > Let's see for this I need to get out my crystal ball... > > If it is a commercial application, you should contact their tech > support for a solution. The problem isn't specifically a Python > problem but rather an implementation problem with their app. > > -Larry Well one part of the problem maybe really is on the side of this tool. Because the implementation of the macro functionality is really crappy. But unfortunately there are no competitive-product we could switch too, so we have to live with this poor environment. But I don't think that the WHOLE problem lies inside this tool. Because I read http://mail.python.org/pipermail/python-dev/2005-January/051255.html and http://evanjones.ca/python-memory.html Sadly we can't switch from Python 2.4 to 2.5 because this stupid macro functionality only supports 2.4.x I really know that all this is not the best setup to get happy with but there really is no other setup available. So I'm happy for every input all of you can give me. greetings, tim From bbxx789_05ss at yahoo.com Thu Apr 12 23:31:27 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: 12 Apr 2007 20:31:27 -0700 Subject: Calling private base methods In-Reply-To: References: <1176374675.347453.89340@n76g2000hsh.googlegroups.com> <1176404325.211501.26610@w1g2000hsg.googlegroups.com> Message-ID: <1176435087.708516.66470@o5g2000hsb.googlegroups.com> On Apr 12, 2:02 pm, Duncan Booth wrote: > "7stud" wrote: > > On Apr 12, 5:04 am, Duncan Booth wrote: > >> "7stud" wrote: > >> > On Apr 12, 2:47 am, "Jorgen Bodde" wrote: > >> >> Is it possible to call a private base method? I come from a C++ > >> >> background, and I liked this construction as my base class has helper > >> >> methods so that I do not have to duplicate code. > > >> > I'd like to see some C++ code that does that! > > >> Easy: > > >> #define private public > >> #include > >> #undef private > > >> then call the private methods as much as you want. > > > lol. I don't see any private methods being created there. > > You should have looked in someheader: > > class Whatever { > private: > void ohnoyoudont(int); > > } > > then back in the C file: > > ... > Whatever foo = new Whatever(); > int ohyesido = 42; > foo.ohnoyoudont(ohyesido); > ... > > Really, it does work (probably). There are other ways to get at private > members in C++ but this is the easiest. I can also access private methods of a class if my sister backspaces over "private" and types "public" instead. In your example, no private methods were ever created, and therefore you are not accessing private methods. From erikwickstrom at gmail.com Wed Apr 11 13:46:18 2007 From: erikwickstrom at gmail.com (erikcw) Date: 11 Apr 2007 10:46:18 -0700 Subject: UnicodeEncodeError - a bit out of my element... In-Reply-To: References: <1176304567.142673.69710@y5g2000hsa.googlegroups.com> Message-ID: <1176313578.150669.219300@n76g2000hsh.googlegroups.com> On Apr 11, 11:35 am, liupeng wrote: > I cut from Sam Python Phrasebook > "Converting Unicode to Local Strings" > > import string locStr = "El " > uniStr = u"Ni\u00F1o" > print uniStr.encode('utf-8') > print uniStr.encode('utf-16') > print uniStr.encode('iso-8859-1') > #Combine local and unicode results > #in new unicode string > newStr = locStr+uniStr > print newStr.encode('iso-8859-1') > #ascii will error because character '\xF1' > #is out of range > asciiStr = newStr.encode('iso-8859-1') > asciiStr =asciiStr.translate(\ > string.maketrans('\xF1','n'), '') > print asciiStr.encode('ascii') > print newStr.encode('ascii') > > unicode_str.py > > Ni??o > ?N|I|?|o > Ni?o > El Ni?o > El Nino > Traceback (most recent call last): > File "C:\books\python\CH2\code\unicode_str.py", > line 19, in ? > print newStr.encode('ascii') > UnicodeEncodeError: 'ascii' codec can't encode > character u'\xf1' in position 5: ordinal not in > range(128) > > On Wed, Apr 11, 2007 at 08:16:07AM -0700, erikcw wrote: > > Hi all, > > > I'm trying to parse an email message, but am running into this > > exception. > > > Traceback (most recent call last): > > File "wa.py", line 336, in ? > > main() > > File "wa.py", line 332, in main > > print out['msg'] > > UnicodeEncodeError: 'ascii' codec can't encode character u'\xd6' in > > position 238: ordinal not in range(128) > > > How can I decode/encode this string to print to stdout and send again > > in another email? Do I have to know what language the email is in? > > > Thanks! > > Erik > > > -- > >http://mail.python.org/mailman/listinfo/python-list > > > > signature.asc > 1KDownload I used the .encode("utf-8") method on the string and it fixed everything! Thanks for your help! From rajshakil at gmail.com Mon Apr 30 06:34:23 2007 From: rajshakil at gmail.com (shakil ahmad) Date: Mon, 30 Apr 2007 16:04:23 +0530 Subject: How do I parse a string to a tuple?? In-Reply-To: References: <1177926452.830059.269230@n59g2000hsh.googlegroups.com> Message-ID: <4482002e0704300334i22b38d0ak58cc64dd7e964fac@mail.gmail.com> > > just do like this: >>>a="text1 \n text2 \n text3 \n text4" >>>g=a.split('\n') >>>g ['text1 ', ' text2 ', ' text3 ', ' text4'] >>> d=tuple(g) >>> d ('text1 ', ' text2 ', ' text3 ', ' text4') by Shakil -------------- next part -------------- An HTML attachment was scrubbed... URL: From aleax at mac.com Fri Apr 20 10:40:00 2007 From: aleax at mac.com (Alex Martelli) Date: Fri, 20 Apr 2007 07:40:00 -0700 Subject: comparison with None References: <3IqdnfRnCNWPC7vbnZ2dnUVZ_jqdnZ2d@rcn.net> <2qzVh.7373$xL6.982@trnddc05> <_JAVh.1700$jR5.897@trnddc08> <1hwu26k.oyynyowsbxvcN%aleax@mac.com> Message-ID: <1hwuyed.1pfg5y31tp64kmN%aleax@mac.com> Tommy Grav wrote: > On Apr 19, 2007, at 11:00 PM, Alex Martelli wrote: > > > Alan Isaac wrote: > > > >> currently documented behavior: > >> "objects of different types always compare unequal". > > > > Where is that documented? URL please? > > > >>>> 1.0 == 1 > > True > >>>> type(1.0), type(1) > > (, ) > > > > Isn't this an example of numerical comparison (= or !=) versus > object comparison (is or is not). I think the documentation needs > to state that there is a difference between the two types. Operator == (TWO equal signs, not just one: that would be an assignment instead) can be applied to arbitrary objects, not just numbers, just like operator 'is'. >>> u'ciao' == 'ciao' True >>> type(u'ciao'), type('ciao') (, ) See, it's not a question of numbers versus other things: the distinction, rather, is between comparison of the values of objects (which can perfectly well be equal even for objects of different types) versus checking object identity (and since an object only has one type at a time, it can't be "the same object" as one with a different type). Why do you think the Python docs don't draw the difference between '==' (equality) and 'is' (identity)? I'm still interested to know where that erroneous quote from Alan Isaac comes from, because if it's in Python's docs, it can be fixed. Alex From ptmcg at austin.rr.com Mon Apr 16 01:06:21 2007 From: ptmcg at austin.rr.com (Paul McGuire) Date: 15 Apr 2007 22:06:21 -0700 Subject: pyparsing Catch-22 In-Reply-To: <1176686782.270354.164630@l77g2000hsb.googlegroups.com> References: <1176686782.270354.164630@l77g2000hsb.googlegroups.com> Message-ID: <1176699981.689781.311720@y5g2000hsa.googlegroups.com> Please take a look at the new page added to the pyparsing wiki. -- Paul From steve at holdenweb.com Mon Apr 2 10:24:29 2007 From: steve at holdenweb.com (Steve Holden) Date: Mon, 02 Apr 2007 10:24:29 -0400 Subject: socket read timeout In-Reply-To: References: <17930.25631.86693.827473@montanaro.dyndns.org> <000e01c771d2$2f3dd240$03000080@hendrik> Message-ID: Bryan Olson wrote: > Steve Holden wrote: >> Hendrik van Rooyen wrote: >>> Are sockets full duplex? >>> >> Yes. But you have to use non-blocking calls in your application to use >> them as full-duplex in your code. > > Hmmm... I'm missing something. Suppose I have one thread (or > process) reading from a blocking-mode socket while another is > writing to it? What stops it from being full duplex? > > Nothing, I guess. I just didn't consider threaded code ... 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 fuzzyman at gmail.com Mon Apr 16 09:42:18 2007 From: fuzzyman at gmail.com (Fuzzyman) Date: 16 Apr 2007 06:42:18 -0700 Subject: newbie question: how to read back the dictionary from a file? In-Reply-To: <1176717819.937015.9890@y80g2000hsf.googlegroups.com> References: <1176717819.937015.9890@y80g2000hsf.googlegroups.com> Message-ID: <1176730938.137608.326630@d57g2000hsg.googlegroups.com> On Apr 16, 11:03 am, "lancered" wrote: > Hi Dear all, > > I have some data here in the form of a dictionary, called "vdic". Then > I write them to a data file "f" using the write function as > f.write(str(vdic)). The keys of this dictionary are integers and > values are float numbers. Something like this: > > { 1: 0.00951486513347, 2: 0.0388123556019, ... ...} > > Now, I want to read these data back in another function. Of course, I > could parse the string little by little, e.g, first read a "{", then > loop read a int, then read a ":", then a float etc etc... Since it is > written out with standard python builtin functions, I guess there may > be some more direct method than this, say a function in some modules? > Could someone give me a hint? ConfigObj and its 'unrepr' mode gives you a useful (and simple) way of preserving and restoring basic Python datatypes. The file format is a very readable 'ini' format - and the basic interface is like a dictionary, for both writing and retrieving values. http://www.voidspace.org.uk/python/configobj.html Fuzzyman From nick at craig-wood.com Wed Apr 25 11:30:04 2007 From: nick at craig-wood.com (Nick Craig-Wood) Date: Wed, 25 Apr 2007 10:30:04 -0500 Subject: trinary operator - if then else References: <1177484290.449378.93720@t38g2000prd.googlegroups.com> <598sgrF2jq0usU1@mid.uni-berlin.de> Message-ID: Diez B. Roggisch wrote: > Michael >> > >> Does Python 2.4 support it? > > > > Not precisely, but you can *usually* get away with: > > > > a and b or c > > This is really bad advice, as long as you don't explain why it "usually" > works (and often enough not). This for example won't work: > > >>> False or '' and 0 > '' You can use this if you want it to be bullet proof (a and [b] or [c])[0] Not exactly elegant though! -- Nick Craig-Wood -- http://www.craig-wood.com/nick From kaoruangel at gmail.com Thu Apr 5 22:46:00 2007 From: kaoruangel at gmail.com (C.L.) Date: Fri, 6 Apr 2007 02:46:00 +0000 (UTC) Subject: "index" method only for mutable sequences?? Message-ID: I was looking for a function or method that would return the index to the first matching element in a list. Coming from a C++ STL background, I thought it might be called "find". My first stop was the Sequence Types page of the Library Reference (http://docs.python.org/lib/typesseq.html); it wasn't there. A search of the Library Reference's index seemed to confirm that the function did not exist. A little later I realized it might be called "index" instead. Voila. My point is that the docs list and describe it as a method that only exists for MUTABLE sequences. Why only for mutables? The class of objects I would expect it to cover would be all ordered sequences, or, to phrase it a little more pointedly, anything that supports ordered INDEXing. My understanding is that dict's don't fall into that class of objects since their ordering is not documented or to be depended on. However, tuple's do support ordered indexing, so why don't tuple's have an index method? P.S.: I know I haven't yet gotten an answer to my "why" question yet, but, assuming it's just an oversight or an example of design without the big picture in mind, an added benefit to fixing that oversight would be that the "index" method's documentation could be moved from the currently odd seeming location on the "Mutable Sequence Types" page to a place someone would look for it logically. P.P.S.: As much as the elementary nature of my question would make it seem, this isn't my first day using Python. I've used it on and off for several years and I LOVE Python. It is only because of my love for the language that I question its ways, so please don't be overly defensive when I guess that the cause for this possible oversight is a lack of design. Corey Lubin From Finger.Octopus at gmail.com Wed Apr 4 15:22:35 2007 From: Finger.Octopus at gmail.com (Finger.Octopus at gmail.com) Date: 4 Apr 2007 12:22:35 -0700 Subject: calling super() Message-ID: <1175714555.413502.77390@o5g2000hsb.googlegroups.com> Hello, I have been trying to call the super constructor from my derived class but its not working as expected. See the code: class HTMLMain: def __init__(self): self.text = ""; print(self.text); def __del__(self): self.text = ""; print(self.text); class NewPage(HTMLMain): def __init__(self): print 'derive2 init' super(NewPage, self).__init__(); N = NewPage(); del N And here's the error message I get: Traceback (most recent call last): File "e:/PyEN/inherit.py", line 16, in N = NewPage(); File "e:/PyEN/inherit.py", line 12, in __init__ super(NewPage, self).__init__(); TypeError: super() argument 1 must be type, not classobj From http Sat Apr 14 22:55:07 2007 From: http (Paul Rubin) Date: 14 Apr 2007 19:55:07 -0700 Subject: Useful decorator References: <7xtzvik417.fsf@ruckus.brouhaha.com> Message-ID: <7xbqhqjqic.fsf@ruckus.brouhaha.com> Steven D'Aprano writes: > if __debug__: > generate_bazillion_items = truncate(20)(generate_bazillion_items) > > Now you don't have to comment/uncomment dozens of lines all over your > application, but only set a single global. The cool thing about organizing the program as a generator pipeline is you only have to comment or uncomment one line ;). From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Fri Apr 20 14:28:51 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Fri, 20 Apr 2007 20:28:51 +0200 Subject: When are immutable tuples *essential*? Why can't you just use lists *everywhere* instead? References: <1177088796.622928.224890@d57g2000hsg.googlegroups.com> <1177089206.550423.288670@q75g2000hsh.googlegroups.com> Message-ID: <58sf33F2b1q8tU1@mid.individual.net> Luis M. Gonz?lez wrote: > I don't remember exactly where I read about it, but Guido said > once that tuples are being kept mainly for historical reasons. Weren't tuples added when lists already existed? Regards, Bj?rn -- BOFH excuse #101: Collapsed Backbone From ptmcg at austin.rr.com Sun Apr 8 02:46:06 2007 From: ptmcg at austin.rr.com (Paul McGuire) Date: 7 Apr 2007 23:46:06 -0700 Subject: RFC: Assignment as expression (pre-PEP) In-Reply-To: <1176000904.832489.72300@o5g2000hsb.googlegroups.com> References: <1175802680.021987.39220@p77g2000hsh.googlegroups.com> <1175807326.466842.219820@p77g2000hsh.googlegroups.com> <1176000904.832489.72300@o5g2000hsb.googlegroups.com> Message-ID: <1176014766.564750.189930@q75g2000hsh.googlegroups.com> On Apr 7, 9:55 pm, "Paul McGuire" wrote: > seriesAndEpnum = Combine( OneOrMore( ~Literal("-") + > Word(alphas) ).setParseAction( capitalizeAll ), > joinString=" ").setResultsName("series") + \ > Word(nums).setResultsName("episodeNum") should be: seriesAndEpnum = Combine( OneOrMore( Word(alphas) ).setParseAction( capitalizeAll ), joinString=" ").setResultsName("series") + \ "-" + Word(nums).setResultsName("episodeNum") (This example is hypothetical based on the limited info in your posted code, the purpose of this element was to try to emulate your case where two "variables" are defined in a single expression.) -- Paul From g.brandl at gmx.net Sun Apr 8 14:21:37 2007 From: g.brandl at gmx.net (Georg Brandl) Date: Sun, 08 Apr 2007 20:21:37 +0200 Subject: How do I get a slice of a string held in a tuple? In-Reply-To: References: <25ine4-rvt.ln1@Hedley.internal.thethurmans.com> <1176050876.835238.68560@d57g2000hsg.googlegroups.com> Message-ID: Lorenzo schrieb: >> > How do I go about it? >> >> Do it correctly. Post your actual example that fails >> and the related error message. Possibnly your indexes >> were out of range. >> >> > I googled this and found a couple >> > of references, but no solution. >> >> Well, there wouldn't be a solution to a non-existent >> problem, would there? >> >> > TIA > > Here's the code: > > elapsedTime = mydata[1] > index = elapsedTime.find("real") > # the index will have a value 0f 110 > totaltime = elapsedTime[index:] > # instead of this returning a shortened html string, i only > # get the left angle bracket '<' May it be that mydata[1] doesn't contain "real" at all? In that case, find() returns -1, and the slice elapsedTime[-1:] always contains at most one character. If you replace "find" by "index", you get a ValueError exception if "real" was not found, if that helps you. Whenever one calls str.find(), one has to check the return value for -1. Georg From bogle at ihug.too.much.spam.co.nz Tue Apr 24 23:33:45 2007 From: bogle at ihug.too.much.spam.co.nz (Gib Bogle) Date: Wed, 25 Apr 2007 15:33:45 +1200 Subject: Video: Professor of Physics Phd at Cal Tech says: 911 Inside Job In-Reply-To: <1177467203.719625.93920@u32g2000prd.googlegroups.com> References: <1177467203.719625.93920@u32g2000prd.googlegroups.com> Message-ID: stj911 at rock.com wrote: > Cal Tech is the ELITE of ELITE in physics. > > If Feynman were alive, he would point his finger straight at the 911 > criminal operators, the yank bastards themselves ....... > > http://www.911blogger.com/node/8101 > > No self-respecting scientist should keep his mouth shut. Its a > fundamental challenge to the method of science, a detective work most > demanding of INTELLECTUAL HONESTY. > When did the University of Iowa (Iowhere?) become CalTech. From chris.cavalaria at free.fr Fri Apr 20 06:08:17 2007 From: chris.cavalaria at free.fr (Christophe) Date: Fri, 20 Apr 2007 12:08:17 +0200 Subject: Do other Python GUI toolkits require this? In-Reply-To: References: <462697A6.6010007@codebykevin.com> Message-ID: <4628913e$0$14534$426a74cc@news.free.fr> Nigel Rowe a ?crit : > On Thu, 19 Apr 2007 19:11, Antoon Pardon wrote in comp.lang.python: >> On 2007-04-19, Michael Bentley wrote: > > > >>> The learning curve is rather steep IMO, but worth it. >> Just a throw in remark, that you may ignore if you wish, but a steep >> learning curve means that the subject is easily familiarized and that >> the learning period is short. >> >> You seem to use it as if it is the opposite. >> > > Who says the axes are labeled "familiarity" and "learning period"? I > just assume they are labeled (y-axis) "Effort" and (x-axis) "Knowledge" > (or "skill" or ....). > > Which means that something with a 'steep learning curve' requires a lot > of effort to achieve a small amount of knowledge (or skill or ...). Funny, I would have placed on the x axis the time, and on the y axis "Knowledge". And Effort = lambda*time where lambda is the amount of effort per minute you are able to produce. Thus I always found it weird to call a steep learning curve something hard to learn. Disclaimer: I have never made any study in that field, never read any reports or anything like that. It just feels much more natural for me to place the time on the x axis. From hlubenow2 at gmx.net Sat Apr 7 19:59:53 2007 From: hlubenow2 at gmx.net (hlubenow) Date: Sun, 08 Apr 2007 01:59:53 +0200 Subject: Can't Get Email Interface Working References: Message-ID: Eric Price wrote: > Good grief! And they call a 722-line program "simple"?! LOL! > I did what I need to do with a __one_line_shell_script__ LOL! > Naw, if I have to go through all that, I'll skip on python this time > around, thank you very much! > Eric Ok, "simplemail.py" is quite long. That's because it enables you to send attachements and deals with character encoding and so on. It is meant as a module (I didn't write it). You can use it just like that: ----------------------------------- from simplemail import Email Email( from_address = "sender at domain.net", to_address = "receiver at domain.net", subject = "Subject", message = "Text of the message" ).send() ----------------------------------- That's not that much longer than a single shell-command (and it's Python :) ). "simplemail.py" has been discussed here: http://www.python-forum.de/topic-3158.html but just in German. H. From dundeemt at gmail.com Wed Apr 11 18:57:24 2007 From: dundeemt at gmail.com (dundeemt) Date: 11 Apr 2007 15:57:24 -0700 Subject: Omaha Python Users Group - Meeting April 12, 2007 Message-ID: Omaha Python Users Group http://www.OmahaPython.org When: April 12, 2007 @ 7:00pm Where: Reboot The User 13416 A Street Omaha, NE 68144 For More Information, please see http://www.omahapython.org/ From mail at timgolden.me.uk Wed Apr 11 07:49:47 2007 From: mail at timgolden.me.uk (Tim Golden) Date: Wed, 11 Apr 2007 12:49:47 +0100 Subject: Shutting down windows using win32api In-Reply-To: <637903.8497.qm@web90304.mail.mud.yahoo.com> References: <637903.8497.qm@web90304.mail.mud.yahoo.com> Message-ID: <461CCB5B.5070906@timgolden.me.uk> On a whim, given the terseness of your post, I cut-and-pasted your subject line into Google, added "python" for good measure, and looked at the results. I suggest you might do the same. Granted, maybe this will raise more questions, but at least it shows willing :) TJG From steve at REMOVE.THIS.cybersource.com.au Sun Apr 8 21:50:41 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Mon, 09 Apr 2007 11:50:41 +1000 Subject: tuples, index method, Python's design References: <1175867771.114540.61810@n76g2000hsh.googlegroups.com> <1175884427.779950.267220@y80g2000hsf.googlegroups.com> <1175953520.316208.241490@o5g2000hsb.googlegroups.com> <7xzm5igbrb.fsf@ruckus.brouhaha.com> <7x8xd2iq53.fsf@ruckus.brouhaha.com> Message-ID: On Sun, 08 Apr 2007 20:10:21 -0400, Carsten Haese wrote: > On Sun, 2007-04-08 at 13:10 -0700, Paul Rubin wrote: >> Carsten Haese writes: >> > > Do you not see the gratuituous inconsistency between tuples and lists >> > > as a useless feature? What is the use case for keeping it? >> > >> > When a new feature is requested, the burden of proof is on the requester >> > to show that it has uses. The use case for not having tuple.index is >> > that there are no use cases for having it. If that answer sounds absurd, >> > it is because your question is absurd. >> >> The use case has already been discussed. Removing the pointless >> inconsistency between lists and tuples means you can stop having to >> remember it, so you can free up brain cells for implementing useful >> things. That increases your programming productivity. > > Will tuples also get a sort method? What about append and extend? pop? > __iadd__? __delslice__? Since tuples are immutable, no. And before you ask, since they aren't strings, they won't get upper, lower, split or strip either. > How many brain cells are actually freed up by not having to remember > that *one* method that you'd never use doesn't exist? 74,972,561. I think the problem is that Python developers are split between those who see tuples as immutable lists, and those who see them as records/structs. Neither of them is wrong -- tuples are multi-use. Guido may or may not have designed them to be used as structs (short and heterogeneous, as opposed to long and homogeneous) but designers are often surprised by the uses people find for their creations, and the designer doesn't get the final say as to what is the "right" usage. If you see tuples as an immutable list, having an index method is quite useful. If you see them as structs, an index method is useless. -- Steven. From w5kh at arrl.net Sun Apr 1 23:18:20 2007 From: w5kh at arrl.net (Barry Newberger) Date: Mon, 02 Apr 2007 03:18:20 GMT Subject: win32con.client.constants error Message-ID: I am working on a Outlook COM project. For some reason win32com.client.constants quit working between runs of one of my test scripts. It's supposed to acquire attributes for all constants defined in loaded COM servers through its __dicts__ attribute,and did for awhile Now it is throwing an AttributeError: PythonWin 2.4.4 (#71, Oct 18 2006, 08:34:43) [MSC v.1310 32 bit (Intel)] on win32. Portions Copyright 1994-2006 Mark Hammond - see 'Help/About PythonWin' for further copyright information. Traceback (most recent call last): File "C:\Python24\Lib\site-packages\pythonwin\pywin\framework\scriptutils.py", line 310, in RunScript exec codeObject in __main__.__dict__ File "C:\Documents and Settings\bnewberg\Desktop\mail_script\mail_move_init_test.py", line 22, in ? msgFolderTypeConsts = {'Rcvd': constants.olFolderInbox, 'Sent': constants.olFolderSentMail} File "C:\Python24\Lib\site-packages\win32com\client\__init__.py", line 168, in __getattr__ raise AttributeError, a AttributeError: olFolderInbox Code snippet: from win32com.client import gencache, constan [SNIP] class MSOutlook(object): def __init__(self): try: self.oOutlookApp = gencache.EnsureDispatch("Outlook.Application") self.outlookFound = True except: print "MSOutlook: unable to load Outlook" self.outlookFound = False if not self.outlookFound: return [SNIP] # Outlook default folder constants msgFolderTypeConsts = {'Rcvd': constants.olFolderInbox, 'Sent': constants.olFolderSentMail} folderSet = [yr, mo, msgType] # Used to loop over folder tree. I am running Python 2.4.4 and pywin32-210. I tried reinstalling pywin without success. Thanks, Barry Newberger From bj_666 at gmx.net Wed Apr 25 01:21:59 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Wed, 25 Apr 2007 07:21:59 +0200 Subject: subprocess.Popen fails, but os.system works References: <1177473554.399696.236450@n35g2000prd.googlegroups.com> Message-ID: In <1177473554.399696.236450 at n35g2000prd.googlegroups.com>, bahoo wrote: > This line of code fails (see error message at the end), > > last_line = subprocess.Popen(["D:/release/win.exe 0.5 1000 100 D:/ > images/img.ppm out.ppm"], stdout=subprocess.PIPE).communicate()[0] > > but using "os.system" works: > os.system('D:/release/win.exe 0.5 1000 100 D:/images/img.ppm out.ppm') > > ---------- > C:/Python25/pythonw.exe -u "D:/run.pyw" > Traceback (most recent call last): > File "D:/run.pyw", line 59, in > process_dir(mydir) > File "D:/run.pyw", line 52, in process_dir > segmentation (dir,f) > File "D:/run.pyw", line 35, in segmentation > last_line = subprocess.Popen(["D:/release/win.exe 0.5 1000 100 D:/ > images/img.ppm out.ppm"], stdout=subprocess.PIPE).communicate()[0] > File "C:\Python25\lib\subprocess.py", line 593, in __init__ > errread, errwrite) > File "C:\Python25\lib\subprocess.py", line 793, in _execute_child > startupinfo) > WindowsError: [Error 22] The filename, directory name, or volume label > syntax is incorrect > ----------- > > Can anyone tell me why? You are trying to execute a program named:: D:/release/win.exe 0.5 1000 100 D:/images/img.ppm out.ppm Such a program does not exist on your computer. ;-) Give `subprocess.Popen()` a list with the program name and the individual arguments as elements instead. Ciao, Marc 'BlackJack' Rintsch From stj911 at rock.com Fri Apr 6 16:06:07 2007 From: stj911 at rock.com (stj911 at rock.com) Date: 6 Apr 2007 13:06:07 -0700 Subject: British Marines Were tortured In Iran According to the Washington Conventions Re: Dr Jeff King, A Jewish MIT Engineer is the LEAD SPEAKER on 911 truth, no Islamics involved http://video.google.com/videoplay?docid=1822764959599063248 In-Reply-To: <1175877828.372962.323450@d57g2000hsg.googlegroups.com> References: <1175713650.228538.165920@p77g2000hsh.googlegroups.com> <5oWdnfYyjuySzonbnZ2dnUVZ_oSnnZ2d@comcast.com> <1175877597.303013.297780@w1g2000hsg.googlegroups.com> <1175877828.372962.323450@d57g2000hsg.googlegroups.com> Message-ID: <1175889966.994800.21660@o5g2000hsb.googlegroups.com> We have just heard the news that the British Marines are ashamed to admit that they were tortured with Electric Wires to their Genitalia and two of them have had their penises bitten while a third ones testicles were eaten by an Iranian dog for the meal. People are now preferring the AbuGharib and Guantanamo style Washington Conventions over the Geneva Conventions. On Apr 6, 9:43 am, therm... at india.com wrote: > See the video with your own EYEBALLS, that is if you have some courage > and shame left: > > http://video.google.com/videoplay?docid=1822764959599063248 > > On Apr 6, 9:39 am, therm... at india.com wrote: > > > On Apr 4, 6:31 pm, "Dr. V I Plankenstein" > > wrote: > > > > The anthrax attack was almost certainly carried out by someone who had > > > access to Gov labs or other secure facilities, but the attack on WTC was an > > > act of Islamic fanaticism, and you're an ass to suggest otherwise without > > > having some very solid proof to back your ridiculous claims - which you > > > lack. > > > You are a LYING SPOOK from the FOOLISH BUREAU OF INCOMPETENCE. > > > If the ODIOUS George W Bush did not inform the American Public (Who > > pays his salary) that Anthrax Attack was by a YANK BASTARD, then it > > must not be so. > > > On the other hand if the Anthrax Attack was produced on such short > > notice and such coordination with the whole 911, then 911 was ALL done > > by yank bastards themselves and George W Bush is a prime suspect with > > all his underlings. > > > ABSENSE OF EVIDENCE IS NOT THE EVIDENCE OF ABSENSE. > > > 911 was a heinous crime done by RACIST and UTTERLY SELFISH yank > > bastards themselves. From sjmachin at lexicon.net Sat Apr 28 06:43:53 2007 From: sjmachin at lexicon.net (John Machin) Date: 28 Apr 2007 03:43:53 -0700 Subject: getting rid of EOL character ? In-Reply-To: References: <268cc$4631f634$83aef404$27224@news1.tudelft.nl> <46327f48$1@news.eftel.com.au> Message-ID: <1177757033.619219.272890@n76g2000hsh.googlegroups.com> On Apr 28, 7:25 pm, Michael Hoffman wrote: > John Machin wrote: > > On 27/04/2007 11:19 PM, Michael Hoffman wrote: > >> stef wrote: > >>> hello, > > >>> In the previous language I used, > >>> when reading a line by readline, the EOL character was removed. > > > Very interesting; how did you distinguish between EOF and an empty line? > > Did you need to call an isEOF() method before each read? > > >>> Now I'm reading a text-file with CR+LF at the end of each line, > >>> Datafile = open(filename,'r') line = Datafile.readline() > > >>> now this gives an extra empty line > >>> print line > > >>> and what I expect that should be correct, remove CR+LF, > >>> gives me one character too much removed > >>> print line[,-2] > > > Stef, that would give you a syntax error. I presume that you meant to > > type line[:-2] > > >>> while this gives what I need ??? > >>> print line[,-1] > > >>> Is it correct that the 2 characters CR+LF are converted to 1 character ? > > > In text mode (the default), whatever is the line ending on your platform > > is converted to a single "newline" '\n' which is the same as LF. > > > Using line[:-1] is NOT recommended, as the last line in your file may > > not be terminated, and in that case you would lose the last data character. > > >>> Is there a more automatic way to remove the EOL from the string ? > > >> line = line.rstrip("\r\n") should take care of it. If you leave out > >> the parameter, it will strip out all whitespace at the end of the > >> line, which is what I do in most cases. > > > If you want *exactly* what is in the line, use line.rstrip('\n') -- this > > will remove only the trailing newline (if it exists). > > > If you want to strip all trailing whitespace, use line.rstrip() as > > Michael suggested. > > > Michael, note carefully that line.rstrip('\r\n') removes instances of > > '\r' OR '\n' -- the arg is a set of characters to be removed, not a > > suffix to be removed. In Stef's situation, it "works" only by accident. > > Using that would not always give you the correct answer -- e.g. if your > > (Windows) file had a line ending in CR CR LF [I've seen stranger]. > > I knew that about line.rstrip, but didn't consider the possibility of > \r\r\n, while still wanting the first \r. Yuck. It would be unusual to want that first \r -- a possibly more likely scenario might be where your text file contains an extract from a database, and you need to check that there are no unwanted (e.g. unprintable) characters in the data (whether at the end of the line, the middle, or the start). In any case I think that you are missing the point that when reading a normal text file on Windows with readline, while the line in the file may be 'foo bar\r\n', what you get from readline is 'foo bar\n' -- so in normal usage, the \r in your line.rstrip('\r\n') is pointless. > > Honestly, I almost always use line.rstrip()--it is seldom that I care > about closing whitespace. Honestly, I almost always split a line into fields and then for each field, strip leading and trailing whitespace, and change runs of 1 or more whitespace characters to a single space -- where "whitespace" includes the pesky U+00A0 aka   which doesn't qualify as whitespace in a str instance. Cheers, John From aleax at mac.com Wed Apr 11 10:40:17 2007 From: aleax at mac.com (Alex Martelli) Date: Wed, 11 Apr 2007 07:40:17 -0700 Subject: passing class by reference does not work?? References: <1176301439.769248.247720@y5g2000hsa.googlegroups.com> Message-ID: <1hweafl.1ddq337v3ylmtN%aleax@mac.com> wswilson wrote: > Here is my code: > > class A(): > val = 0 > > def b(item, a): > a.val = a.val + 1 > return item + a.val > > def c(): > d = [1, 2, 3] > print [b(item, A()) for item in d] > > c() > > I expected this to output [2, 4, 6]. However, it outputs [2, 3, 4] > which is not what I wanted. I thought that if I passed the A() > instance in my list comprehension in c(), then the changes I made to > a.val in b() would be reflected in the A() instance next time the list > comprehension called b(). But, obviously that is not happening. I'm > kinda new at python so I may be missing something obvious here. Yep: a.val = a.val + 1 sets in INSTANCE variable a the value computed on the RHS. A.val (the CLASS variable) is never changed. You're not "passing the class", of course, but rather an instance of the class. To increment A.val, you need to assign to the class variable, or write some method in class A which assigns to the class variable. If you want, you can change class A only, leaving all of the rest of your code untouched, with a property (but then A needs to be newstile), e.g.: class A(object): _val = 0 def getval(self): return A._val def setval(self, value): A._val = value val = property(getval, setval) now your code should work as intended: any read access to a.val returns A._val, and any setting of a.val actually sets A._val, as you appear to desire. Alex From python at hope.cz Tue Apr 24 15:09:54 2007 From: python at hope.cz (Johny) Date: 24 Apr 2007 12:09:54 -0700 Subject: PIL and font colour Message-ID: <1177441794.012794.143680@t38g2000prd.googlegroups.com> I use PIL to write some text to a picture.The text must be seen wery clearly. I write the text to different pictures but to the same position. As pictures maybe different, colour, in the position where I write the text, is also different. Is there a way how to set the font colour so that it will be seen very clearly in the picture? For example, if the picture is bright ( for example yellow), the font colour should be dark( e.g. black) and vice versa. Can anyone help? Thanks L. From cam.ac.uk at mh391.invalid Thu Apr 19 17:28:58 2007 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Thu, 19 Apr 2007 22:28:58 +0100 Subject: Spawn/Exec with asterisk in argument In-Reply-To: <1177010974.882644.159660@d57g2000hsg.googlegroups.com> References: <1176942943.090705.281320@l77g2000hsb.googlegroups.com> <1177010974.882644.159660@d57g2000hsg.googlegroups.com> Message-ID: jeremyfee at gmail.com wrote: > Thanks for the reply Michael. No problem. > I used ls as a simple example, but I'm > using this with scp to transfer files and need shell expansion. It > makes sense since the shell isn't spawning the process, but it's been > a while since I've worked with ipc. I usually don't think of starting new processes as being IPC. I've only ever seen it used to refer to communicating between processes after they have started. -- Michael Hoffman From martin at v.loewis.de Tue Apr 10 17:14:35 2007 From: martin at v.loewis.de (=?ISO-8859-15?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Tue, 10 Apr 2007 23:14:35 +0200 Subject: Custom Python Runtime In-Reply-To: References: <2NudnVn5jsm2QIvbnZ2dnUVZ_vqpnZ2d@comcast.com> Message-ID: <461bfe3c$0$11394$9b622d9e@news.freenet.de> Jack schrieb: > Thanks for all the replies. It would be great to have all customization > related information on one doc page. Please put it into a wiki page, at wiki.python.org > 1. One Windows, it's possible to zip all files in a Python24.zip. I'm not > very clear if it's used in the stardard distribution. What can, > and what can not be put into this file? I suppose zip file will help > reduce the distribution size. I would have to use the source again: if you set PYTHONHOME, you can put the entire library into the zip file. If you don't, I think os.py really needs to exist on disk (if so, that might be a bug, as the intention is that you can put all .py/.pyc into the zip file). > 2. I remember trying the compiler option to strip doc strings didn't > help but maybe I didn't do it right. I had to write some code to compile > selected py files. Is there a way to compile a stripped Python with > compile time options? Sure: -OO. > 3. Some files go to the Windows\system32 directory, including some win32all > files. Can they be in the current directory as python.exe? If you don't need COM, or other dynamic embedding of pythonxy.dll, no. > 4. Are the registry entries necessary? No. Regards, Martin From rehceb at no.spam.plz Sat Apr 7 11:24:50 2007 From: rehceb at no.spam.plz (Rehceb Rotkiv) Date: Sat, 07 Apr 2007 10:24:50 -0500 Subject: Checking whether list element exists Message-ID: I want to check whether, for example, the element myList[-3] exists. So far I did it like this: index = -3 if len(myList) >= abs(index): print myList[index] Another idea I had was to (ab-?)use the try...except structure: index = -3 try: print myList[index] except: print "Does not exist!" Is it ok to use try...except for the test or is it bad coding style? Or is there another, more elegant method than these two? Regards, Rehceb From apardon at forel.vub.ac.be Tue Apr 10 03:42:19 2007 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 10 Apr 2007 07:42:19 GMT Subject: tuples, index method, Python's design References: <1175867771.114540.61810@n76g2000hsh.googlegroups.com> <1175884427.779950.267220@y80g2000hsf.googlegroups.com> <1175953520.316208.241490@o5g2000hsb.googlegroups.com> <7xzm5igbrb.fsf@ruckus.brouhaha.com> <7x8xd2iq53.fsf@ruckus.brouhaha.com> <7xd52e8kgo.fsf@ruckus.brouhaha.com> Message-ID: On 2007-04-09, Georg Brandl wrote: > Paul Rubin schrieb: >> Carsten Haese writes: >>> Will tuples also get a sort method? What about append and extend? pop? >>> __iadd__? __delslice__? >> >> They are immutable so they won't get .sort() etc. sorted(...) already >> works on them. >> >>> How many brain cells are actually freed up by not having to remember >>> that *one* method that you'd never use doesn't exist? >> >> I dunno but I do know that Ruby is attracting a lot of potential Python >> users because it apparently has fewer of these inconsistencies. > > It remains to be proven that it is an inconsistency, rather than a design > decision. The two don't contradict. A design decision can introduce an inconsistency. AFAICS having an index method on tuples seems rather natural. Looking for the index of a particular item in your sequence seems just as usefull independant of the nature of your sequence. So unless there is some rather forcefull argument it seems inconsistent to have some sequences lacking this method. -- Antoon Pardon From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Sat Apr 28 04:46:28 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Sat, 28 Apr 2007 10:46:28 +0200 Subject: if __name__ == 'main': & passing an arg to a class object References: <1177708104.277756.245360@t38g2000prd.googlegroups.com> <1177711182.787219.272900@s33g2000prh.googlegroups.com> Message-ID: <59gfv0F2l1u43U1@mid.individual.net> alisonken1 wrote: [if __name__ == "__main__"] > These are samples to give the programmer an idea of how the code > is supposed to work. No, this belongs into comments or docs. The contents of this block are often used for testing or debugging, or for normally executable code if it makes sense to call the module directly. Regards, Bj?rn -- BOFH excuse #224: Jan 9 16:41:27 huber su: 'su root' succeeded for .... on /dev/pts/1 From oscartheduck at gmail.com Sun Apr 1 20:45:19 2007 From: oscartheduck at gmail.com (oscartheduck) Date: 1 Apr 2007 17:45:19 -0700 Subject: capturing system exit status Message-ID: <1175474718.989364.18900@l77g2000hsb.googlegroups.com> Hi folks, in a program I'm writing I have several commands I pass to the unix OS underneath the code. I want to perform error checking to make sure that the OS commands' exit gracefully, but I'm not seeing a simple python module to do this. The closest I can see is system(), as detailed here: http://www.python.org/doc/2.1.3/lib/os-process.html, but I can't formulate a way to use it. What I want is a simple if statement such that: if ExitStatusIsBad: sys.exit() else: go on to next code chunk From bjourne at gmail.com Sun Apr 29 07:34:36 2007 From: bjourne at gmail.com (=?ISO-8859-1?Q?BJ=F6rn_Lindqvist?=) Date: Sun, 29 Apr 2007 14:34:36 +0300 Subject: While we're talking about annoyances In-Reply-To: References: Message-ID: <740c3aec0704290434j746e83fep2b6b607b361b185c@mail.gmail.com> On 4/29/07, Steven D'Aprano wrote: > To do that, I needed to generate an index table first. In the book > "Numerical Recipes in Pascal" by William Press et al there is a procedure > to generate an index table (46 lines of code) and one for a rank table > (five lines). 51 lines total. > In Python, my index function is four lines of code and my rank function is > five lines. I then wrote three more functions for verifying that my index > and rank tables were calculated correctly (17 more lines) and four more > lines to call doctest, giving a total of 30 lines of code. So 9 lines for Python, excluding tests. > I also have 93 lines of documentation, including doctests, or three > lines of documentation per line of code. Then, without documentation, Python is roughly 560% (51/9) as efficient as Pascal. But with documentation (assuming you need the same amount of documentation for the Python code as the Pascal code), (51 + 93)/(9 + 93) = 1.41 so only 141% as efficient as Pascal. I wonder what that means? Maybe Python the language is approaching the upper bound for how efficient an imperative programming language can be? On the other hand, there seem to be some progress that could be made to reduce the amount of work in writing documentation. Documentation in Esperanto instead of English maybe? -- mvh Bj?rn From mad.vijay at gmail.com Thu Apr 12 05:35:57 2007 From: mad.vijay at gmail.com (SamG) Date: 12 Apr 2007 02:35:57 -0700 Subject: redirecting stdout to a file as well as screen In-Reply-To: <1176363641.493358.62560@y5g2000hsa.googlegroups.com> References: <1176362072.527678.201150@l77g2000hsb.googlegroups.com> <1176363641.493358.62560@y5g2000hsa.googlegroups.com> Message-ID: <1176370557.392734.156530@y80g2000hsf.googlegroups.com> On Apr 12, 12:40 pm, "Ant" wrote: > On Apr 12, 8:14 am, "SamG" wrote: > > > How could i make, from inside the program, to have the stdout and > > stderr to be printed both to a file as well the terminal(as usual). > > One way would be to create a custom class which has the same methods > as the file type, and held a list of file-like objects to write to. > e.g. > > class multicaster(object): > def __init__(self, filelist): > self.filelist = filelist > > def write(self, str): > for f in self.filelist: > f.write(str) > def writelines(self, str_list): > #etc > > Then assign stdout and stderr to a new instance of one of these > objects: > > mc = multicaster([sys.stdout, sys.stderr, log_file]) > sys.stdout = mc > sys.stderr = mc > > HTH I have written this.... import sys class multicaster(object): def __init__(self, filelist): self.filelist = filelist def write(self, str): for f in self.filelist: f.write(str) log_file='out.log' mc = multicaster([sys.stdout, sys.stderr, log_file]) sys.stdout = mc sys.stderr = mc print "Hello" And i get this when i run the porgram. HelloHelloTraceback (most recent call last): Traceback (most recent call last): Kindly advice! From olsonas at gmail.com Tue Apr 24 18:27:08 2007 From: olsonas at gmail.com (Drew) Date: 24 Apr 2007 15:27:08 -0700 Subject: Simple csv read/write Message-ID: <1177453628.474670.301330@t38g2000prd.googlegroups.com> Ok, I'm trying to do the simplest read/write from one csv file to another. For some reason, every other row on the output file is a blank row. What am I doing wrong? import csv reader = csv.reader(open('current.csv')) writer = csv.writer(open('new.csv','w')) for line in reader: writer.writerow(line) From jjl at pobox.com Wed Apr 4 09:48:27 2007 From: jjl at pobox.com (John J. Lee) Date: 04 Apr 2007 14:48:27 +0100 Subject: Question about using urllib2 to load a url References: <1175464332.246623.30090@b75g2000hsg.googlegroups.com> <1175488319.637226.219090@n59g2000hsh.googlegroups.com> Message-ID: "Kushal Kumaran" writes: [...] > If, at any time, an error response fails to reach your machine, the > code will have to wait for a timeout. It should not have to wait > forever. [...] ...but it might have to wait a long time. Even if you use socket.setdefaulttimeout(), DNS lookups can block for a long time. The way around that is to use Python threads (no need to try to "kill" the thread that's doing the urlopen() -- just ignore that thread if it takes too long to finish). Looks like 2.6 will have socket timeouts exposed at the urllib2 level (so no need to call socket.setdefaulttimeout() any more), but the need to use threads with urllib2 to get timeouts will remain in many cases, due to the DNS thing (the same applies to urllib, or any other module that ends up doing DNS lookups). John From martin at v.loewis.de Fri Apr 27 19:00:59 2007 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sat, 28 Apr 2007 01:00:59 +0200 Subject: building _tkinter module with .NET 2005? In-Reply-To: <1177687509.948452.326120@n35g2000prd.googlegroups.com> References: <1177687509.948452.326120@n35g2000prd.googlegroups.com> Message-ID: <463280ab$0$5848$9b622d9e@news.freenet.de> > The instructions contained in both these readme.txt files say that the > Tcl, Tk, and Tix projects must be built from the command line first, > using nmake.exe in conjunction with the corresponding makefile.vc for > each package. I can get this to work using .NET 2003, but not > with .NET 2005. Is there an updated set of instructions somewhere for > doing this with .NET 2005? Is it even possible to get it to work with > the newer version of .NET? I can't help with compiling Tcl - the recommended compiler for Tcl is still VC6, so VS 2005 might not be supported well (or not in the version that we ship with Python). You should ask on a Tcl mailing list for details. However, I'd like to take the opportunity to clarify terminology and naming: The product you are referring to is called "Microsoft Visual Studio", with versions being "Microsoft Visual Studio .NET 2003" and "Microsoft Visual Studio 2005". I.e. the .NET particle was only present with the 2003 release; the common abbreviation is "VS", not ".NET". Indeed "a newer version of .NET" would commonly refer to a version of the Microsoft .NET Framework (whose current version is 3.0). Regards, Martin From rrr at ronadam.com Wed Apr 25 17:55:13 2007 From: rrr at ronadam.com (Ron Adam) Date: Wed, 25 Apr 2007 16:55:13 -0500 Subject: pydoc and imported modules In-Reply-To: <1177080853.261895.224440@q75g2000hsh.googlegroups.com> References: <1177080853.261895.224440@q75g2000hsh.googlegroups.com> Message-ID: <462FCE41.2030400@ronadam.com> schpok at gmail.com wrote: > When I "from foo import *" in my __init__.py, sometimes module foo's > docs will be expanded in the pydocs. It seems to depend in what > language foo was implemented. > > For example, if you "from math import *" in your __init__.py, you will > see math's members will appear in the resulting pydocs, as though it's > part of your module. The behavior is consistent across the C modules I > am writing. > > However, if you "from foo import *" in your __init__.py, and foo is a > python file (not a module written in C), foo's members don't appear in > the resulting pydocs. This also seems to occur in some boost::python > bindings. > > What is expected behavior? How do ensure foo's docs do or don't appear > in help, regardless of their implementation language? > > Thanks, > Schpok Pydoc doesn't check the __module__ attribute of the items imported, it just displays what is in the modules name space as if it was defined in that module. In __init__.py files where an __all__ variable is defined, it won't show items that aren't in __all__. This is probably what you are seeing. I'm currently rewriting pydoc, so what behavior would you like to see? Cheers, Ron From steven.bethard at gmail.com Thu Apr 19 16:35:59 2007 From: steven.bethard at gmail.com (Steven Bethard) Date: Thu, 19 Apr 2007 14:35:59 -0600 Subject: Python un-plugging the Interpreter In-Reply-To: References: Message-ID: S.Mohideen wrote: > I was thinking about the feasbility of adjusting Python as a > compiled language. Python is a compiled language. It's compiled from source code to byte code. That's what the .pyc files are. STeVe From samjnaa at gmail.com Sat Apr 14 06:27:45 2007 From: samjnaa at gmail.com (samjnaa at gmail.com) Date: 14 Apr 2007 03:27:45 -0700 Subject: Python Feature Request: Allow changing base of member indices to 1 Message-ID: <1176546465.632410.52630@w1g2000hsg.googlegroups.com> This is like the previous one. Please check for sanity and approve for posting at python-dev. I would like to have something like "option base" in Visual Basic. IIRC it used to allow me to choose whether 0 or 1 should be used as the base of member indices of arrays. In Python, the same can be used with strings, lists, tuples etc. This would mean: foo = "foo" => foo[1] == 'f' foo = ['foo', 'bar', 'spam' ] => foo[1] == 'foo' foo = ('spam', 'eggs') => foo[1] == 'spam' For convenience it should also affect the range function so that: range(3) = [1, 2, 3] because this is often used where arrays would be used in VB. Finally, when the programmer does not specify his choice of base at the beginning of the program, the current behaviour of using 0 as base should continue so that there is no problem with backward compatibility. From steve at holdenweb.com Fri Apr 6 15:48:05 2007 From: steve at holdenweb.com (Steve Holden) Date: Fri, 06 Apr 2007 15:48:05 -0400 Subject: Newbie Question about sequence multiplication In-Reply-To: References: <6cOdnVFCLMXxuYnbnZ2dnUVZ_rCsnZ2d@comcast.com> <1175726885.373889.23850@y80g2000hsf.googlegroups.com> <1175739226.176472.96280@p77g2000hsh.googlegroups.com> Message-ID: <4616A3F5.4050908@holdenweb.com> Scott wrote: [...] > > Now when suggesting books, keep in mind that, that while I'm new to Python > (and programming in general) I'm able to grasp difficult concepts as long > as I have enough detail as to why it is the way it is. For instance I'm, by > experience and nature, a computer technician and communications specialist. > I've studied, everything from childrens walkie talkie to deep space > satalittes back to how computers talk (which is why I'm here now trying to > learn the language of computers). And all that just because I have a > unquenchable desire to know. SO, with that all said, the more details the > better. If you have a book with 4 chapters on functions......I want to read > it. > > Any help would be greatly appreciated. As I've said, this is something that > I feel I have to know. > "Dive into Python" is probably the best free read about Python for programmers. It takes you in deep much more quickly that the tutorial, but if you can understand it you develop quite a sophisticated understanding of the language in a fairly short time. 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 richardjones at optushome.com.au Sat Apr 14 00:57:36 2007 From: richardjones at optushome.com.au (Richard Jones) Date: Sat, 14 Apr 2007 14:57:36 +1000 Subject: File DB instead of real database? References: <1176524076.446204.70730@w1g2000hsg.googlegroups.com> Message-ID: <46205f3f$0$16553$afc38c87@news.optusnet.com.au> Jia Lu wrote: > I donot want to use a real DB like MySQL ... But I need something to > save about more than 1000 articles. > Is there any good ways? import anydbm Richard From gregcorradini at gmail.com Fri Apr 6 10:41:44 2007 From: gregcorradini at gmail.com (Greg Corradini) Date: Fri, 6 Apr 2007 07:41:44 -0700 (PDT) Subject: Simple mx.ODBC prob seeks simple answer In-Reply-To: References: <9871804.post@talk.nabble.com> Message-ID: <9873176.post@talk.nabble.com> Thanks Steve, Once again your advice solved the problem Greg Steve Holden wrote: > > Greg Corradini wrote: >> Hello all, >> I'm having trouble inserting an SQL selection into a new MS Access table. >> I >> get a parameter error on my insert statement when I try this (see below >> for >> code and error msg). I'm not sure if 'insert' or 'update' is the route I >> should be taking. >> >> CODE: >> #Import Pythond Standard Library Modules >> import win32com.client, sys, os, string, copy, glob >> import mx.ODBC.Windows as odbc >> >> # Create the Geoprocessor Object >> gp = win32com.client.Dispatch("esriGeoprocessing.GpDispatch.1") >> gp.overwriteoutput = 1 >> >> # Variables >> tempspace = "C:\Documents and Settings\corr1gre\Desktop\Workspace\DBFs & >> Shapefiles\TEST.mdb" >> workspace = string.replace(tempspace,"\\","/") >> worksheet1 = "Mower_I" >> worksheet2 = "Mower_II" >> >> #Conection to Access >> driv = 'DRIVER={Microsoft Access Driver (*.mdb)};DBQ='+workspace >> conn = odbc.DriverConnect(driv) >> curse = conn.cursor() >> >> #Drop Tables if they already exist >> try: >> curse.execute('Drop table Table_I') >> curse.execute('Drop table Table_II') >> curse.execute('Drop table Checker') >> except: >> pass >> #Create a New Tables >> curse.execute('Create table Table_I (TISCODE TEXT(12), EXISTSIN >> TEXT(4),STATUS TEXT(3),NOTES TEXT(50))') >> curse.execute('Create table Table_II(TISCODE TEXT(12), EXISTSIN >> TEXT(4))') >> curse.execute('Create table Checker (TISCODE TEXT(12), EXISTSIN >> TEXT(4),STATUS TEXT(3),NOTES TEXT(50))') >> conn.commit() >> >> #Upload DBF 1 as a List of Tuples: Returns tuple as ('1021500000','BMP') >> sql = 'SELECT TISCODE,EXISTSIN from '+worksheet2 >> curse.execute(sql) >> x = curse.fetchall() >> >> #Put the fetched Data into Table_II >> for i in x: >> curse.execute('Insert into Table_II (TISCODE,EXISTSIN) values >> (%s,%s)'%(i[0],i[1])) >> conn.commit() >> conn.close() >> >> TRACEBACK ERROR MSG: >> Traceback (most recent call last): >> File "C:/Documents and >> Settings/corr1gre/Desktop/Workspace/Python/ArcGIS >> Python/ExistenceChecker and Update/Access Double Checker/Access_SQL.py", >> line 40, in ? >> curse.execute('Insert into Table_II (TISCODE,EXISTSIN) values >> (%s,%s)'%(i[0],i[1])) >> ProgrammingError: ('07001', -3010, '[Microsoft][ODBC Microsoft Access >> Driver] Too few parameters. Expected 1.', 4612) > > That error usually occurs when you use a name that isn't defined int he > database (typically I mistype a column name) - the JET engine then > thinks it's missing a value for some parameter. > > In your case it's because you aren't surrounding the string literal > value for TISCODE in your statement with the appropriate '' single > quotes. The engine thus parses it as a name, hence the assumption that a > parameter is missing. > > It's actually good that you have made this error, because it allows me > to expound yet again on the dangers of constructing your own SQL > statements instead of using parameterised statements. In the case of > mxODBC the correct parameter mark to use is a question mark. You should > then supply the data to be substituted for the parameter marks as a > tuple argument to the cursor's execute() method. > > So what you really need is: > > #Put the fetched Data into Table_II > for i in x: > curse.execute("""Insert into Table_II (TISCODE,EXISTSIN) > values (?, ?)""", i) > conn.commit() > conn.close() > > A couple of other points: > > 1. It would actually be better to put the commit() call outside the > loop. This is not only more efficient but it defines the whole set of > changes as a transaction. > > 2. It would be even more efficient not to use a loop at all but to use > the cursor's executemany() method to perform all inserts with a single > call as follows: > > #Put the fetched Data into Table_II > curse.executemany("""Insert into Table_II (TISCODE,EXISTSIN) > values (?, ?)""", x) > conn.commit() > conn.close() > > For more on using the DBI API, including something about the risks of > SQL injection vulnerabilities, take a look at the notes from my PyCon > tutorial at > > http://www.holdenweb.com/PyConTX2007/dbapi.tgz > > 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 > > -- > http://mail.python.org/mailman/listinfo/python-list > > -- View this message in context: http://www.nabble.com/Simple-mx.ODBC-prob-seeks-simple-answer-tf3536661.html#a9873176 Sent from the Python - python-list mailing list archive at Nabble.com. From Peter.Beattie at web.de Wed Apr 25 13:37:03 2007 From: Peter.Beattie at web.de (Peter Beattie) Date: Wed, 25 Apr 2007 19:37:03 +0200 Subject: Controlling gnuplot via subprocess.Popen Message-ID: <599hu0F2k8k1qU1@mid.uni-berlin.de> I am trying to plot something in gnuplot 4.2 using co-ordinates a Python 2.5 program computes. Here's what I'm doing: py> from subprocess import * py> plot = Popen("c:/progs/gp/bin/wgnuplot.exe", stdin=PIPE) py> plot.stdin.write("plot x*x") The first command dutifully opens gnuplot, but the second doesn't do anything. Could someone favour me with an explanation as to the whyness? -- Peter From sjmachin at lexicon.net Thu Apr 5 20:37:47 2007 From: sjmachin at lexicon.net (John Machin) Date: 5 Apr 2007 17:37:47 -0700 Subject: Indentifying the LAST occurrence of an item in a list In-Reply-To: <1175799330.683339.93400@e65g2000hsc.googlegroups.com> References: <1175702329.330032.250750@w1g2000hsg.googlegroups.com> <1175723121.298681.56600@n76g2000hsh.googlegroups.com> <1175799330.683339.93400@e65g2000hsc.googlegroups.com> Message-ID: <1175819867.740913.96430@y80g2000hsf.googlegroups.com> On Apr 6, 4:55 am, "mkPyVS" wrote: > Not sure below is better but it hacks at larger chunks (excuse the 10 > second coding) > m = [2,9,1,5,6,3,1,1,9,2] > f = 1 > temp = m Overwritten 3 statements later > location = m.index(f) > gloc = location > temp = m[location:] > while 1: > print(temp) > try: > location = temp.index(f) + 1 > gloc += location > except: > break > temp = temp[location:] Each time you do that you are copying a chunk of the original list. This could be expensive on a large list. Reminds me of the old joke about how many marines it takes to paint the barracks: 200 to oscillate the barracks, one to hold the brush steady. You don't need to do that. Here's a clue: | >>> help(list.index) Help on method_descriptor: index(...) L.index(value, [start, [stop]]) -> integer -- return first index of value I look forward to your next version. Cheers, John From http Sun Apr 8 12:34:59 2007 From: http (Paul Rubin) Date: 08 Apr 2007 09:34:59 -0700 Subject: itertools, functools, file enhancement ideas References: <7xveg7rhc7.fsf_-_@ruckus.brouhaha.com> <1176049003.872896.7720@d57g2000hsg.googlegroups.com> Message-ID: <7x8xd2rfik.fsf@ruckus.brouhaha.com> rdhettinger at gmail.com writes: > > for block in f.iterchars(n=1024): ... > for block in iter(partial(f.read, 1024), ''): ... Hmm, nice. I keep forgetting about that feature of iter. It also came up in a response to my queue example from another post. > > a) def flip(f): return lambda x,y: f(y,x) > Curious resemblance to: > itemgetter(1,0) Not sure I understand that. From gagsl-py2 at yahoo.com.ar Sun Apr 1 04:20:41 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sun, 01 Apr 2007 05:20:41 -0300 Subject: Converting _node* to a Code object? References: <460F36AF.5030607@christian.net> Message-ID: En Sun, 01 Apr 2007 01:35:59 -0300, Brendon Costa escribi?: > How do i convert a _node* object returned from: > PyParser_SimpleParseStringFlagsFilename() > > into a code object i can use as a module to import with: > PyImport_ExecCodeModule() Using PyNode_Compile. But why don't you use Py_CompileXXX instead? And look into import.c, maybe there is something handy. -- Gabriel Genellina From KDawg44 at gmail.com Fri Apr 20 12:15:09 2007 From: KDawg44 at gmail.com (KDawg44) Date: 20 Apr 2007 09:15:09 -0700 Subject: Expanding tkinter widgets to fill the window Message-ID: <1177085708.955388.119080@o5g2000hsb.googlegroups.com> Hi, I am writing a GUI front end in Python using Tkinter. I have developed the GUI in a grid and specified the size of the window. The widgets are centered into the middle of the window. I would like them to fill the window. I tried using the sticky=E+W+N+S option on the widgets themselves and the window itself. How can I get this? Thanks. From mmanns at gmx.de Thu Apr 5 16:19:39 2007 From: mmanns at gmx.de (Martin Manns) Date: Thu, 5 Apr 2007 16:19:39 -0400 Subject: grandparent method with super Message-ID: <20070405161939.694d51a1@localhost> Hi, I have a class structure as follows and I would like to invoke the method A.m() from D.m class A(object): def m(self): class B(A): def m(self): class C(A): def m(self): class D(B,C): def m(self): # Call A.m with super? I have read http://www.python.org/download/releases/2.2/descrintro/ but I am still stuck. Thanks in advance Martin From adam at atlas.st Sun Apr 29 01:08:49 2007 From: adam at atlas.st (Adam Atlas) Date: 28 Apr 2007 22:08:49 -0700 Subject: Tracebacks for `exec`ed code? Message-ID: <1177823329.567989.281420@c35g2000hsg.googlegroups.com> Is it possible to make more traceback information available for exceptions code dynamically run via `exec`? Normally it just says things like "File '', line 3, in ?", which is not very helpful. I'm looking for a way for it to show the line of source code below it, like it would for an exception in a physical file. Is this possible? From mike.klaas at gmail.com Mon Apr 23 16:52:52 2007 From: mike.klaas at gmail.com (Klaas) Date: 23 Apr 2007 13:52:52 -0700 Subject: No speedup on multi-processor machine? In-Reply-To: <1177200844.134908.192110@q75g2000hsh.googlegroups.com> References: <1177189332.916296.205280@d57g2000hsg.googlegroups.com> <1177197495.821701.140390@b58g2000hsg.googlegroups.com> <1177200844.134908.192110@q75g2000hsh.googlegroups.com> Message-ID: <1177361572.800543.263330@n59g2000hsh.googlegroups.com> On Apr 21, 5:14 pm, Fuzzyman wrote: > Additionally, extending IronPython from C# is orders of magnitude > easier than extending CPython from C. Given the existence of Pyrex, that statement is pretty difficult to substantiate. -Mike From rNOSPAMon at flownet.com Sun Apr 22 02:21:21 2007 From: rNOSPAMon at flownet.com (Ron Garret) Date: Sat, 21 Apr 2007 23:21:21 -0700 Subject: Select weirdness Message-ID: Here's my code. It's a teeny weeny little HTTP server. (I'm not really trying to reinvent the wheel here. What I'm really doing is writing a dispatching proxy server, but this is the shortest way to illustrate the problem I'm having): from SocketServer import * from socket import * from select import select class myHandler(StreamRequestHandler): def handle(self): print '>>>>>>>>>>>' while 1: sl = select([self.rfile],[],[])[0] if sl: l = self.rfile.readline() if len(l)<3: break print l, pass pass print>>self.wfile, 'HTTP/1.0 200 OK' print>>self.wfile, 'Content-type: text/plain' print>>self.wfile print>>self.wfile, 'foo' self.rfile.close() self.wfile.close() print '<<<<<<<<<<<<' pass pass def main(): server = TCPServer(('',8080), myHandler) server.serve_forever() pass if __name__ == '__main__': main() If I telnet into this server and type in an HTTP request manually it works fine. But when I try to access this with a browser (I've tried Firefox and Safari -- both do the same thing) it hangs immediately after reading the first line in the request (i.e. before reading the first header). When I click the "stop" button in the browser it breaks the logjam and the server reads the headers (but then of course it dies trying to write the response to a now-closed socket). The only difference I can discern is that the browser send \r\n for end-of-line while telnet just sends \n. But I don't see why that should make any difference. So I'm stumped. Any clues would be much appreciated. Thanks, rg From acb at uchicago.edu Wed Apr 25 01:38:37 2007 From: acb at uchicago.edu (Aaron Brady) Date: Wed, 25 Apr 2007 00:38:37 -0500 Subject: function object.func_default off the console Message-ID: >>> f.func_defaults[0] [2, 3] >>> f.func_defaults[0]+=[4] Traceback (most recent call last): File "", line 1, in TypeError: 'tuple' object does not support item assignment >>> f.func_defaults[0] [2, 3, 4] V. interesting. Operation succeeds but with a throw. Er, raise. From nogradi at gmail.com Tue Apr 3 05:34:22 2007 From: nogradi at gmail.com (Daniel Nogradi) Date: Tue, 3 Apr 2007 11:34:22 +0200 Subject: Parsing Problems In-Reply-To: <1175591597.120154.240820@q75g2000hsh.googlegroups.com> References: <1175591597.120154.240820@q75g2000hsh.googlegroups.com> Message-ID: <5f56302b0704030234i71cdc6cm9d577e9f3fc1b654@mail.gmail.com> > I have just started learning python.I need to parse an XML file > and present the contents in a particular format.The format is called > as "ini" file.I have written some code.A section of the format needs > the data to be present in format as given below: > > [Services] > supported=0x10,0x1A,0x3B,0x20,0x27,0x28,0x34,0x36,0x3E,0xA2,0xA5,0x2D, > 0x22,0xA9,0x04,0xAA,0xAE > > My code for this section parses the xml file and gives : > [Services] > Supported=['0x3e', '0x28', '0x3b', '0x22', '0x20', '0x27', '0xaa', > '0x10', '0xae', '0x34', '0x36', '0x2d', '0xa9', '0xa5', '0x4', '0xa2', > '0x1a'] > > {forget the numericals matching}.As you can see there > are single quotes around numericals ,which is not desired .I think the > problem lies in me using a list for storing and later printing out > values.I have attached few lines of code,not sure how clear it can be > to you: > > for l in range(0,len(ser_par), > 1): > if > ser_par[l].getAttribute('Semantics')==u'serviceId': > if > tag_exists(ser_par[l].childNodes,'VALUE'): > val = > ser_par[l].getElementsByTagName('VALUE') > value = > str(val[0].getAttribute('value')) > valu = hex(int(value)) > rval.append(valu) > ser_par_num = ser_par_num + 1 > prim_num = prim_num + 1 > > service_num = service_num + 1 > variant_num = variant_num + 1 > ser = list(set(rval)) > > print "\n[Services]" > print "Supported="+str(ser) > > How can i get rid of those single quotes. mylist = ['0x3e', '0x28', '0x3b', '0x22', '0x20', '0x27', '0xaa', '0x10', '0xae', '0x34', '0x36', '0x2d', '0xa9', '0xa5', '0x4', '0xa2', '0x1a'] ','.join( mylist ) This will give you: 0x3e,0x28,0x3b,0x22,0x20,0x27,0xaa,0x10,0xae,0x34,0x36,0x2d,0xa9,0xa5,0x4,0xa2,0x1a Daniel From lobais at gmail.com Tue Apr 17 16:30:32 2007 From: lobais at gmail.com (Thomas Dybdahl Ahle) Date: Tue, 17 Apr 2007 22:30:32 +0200 Subject: Binary file output using python References: <1176833258.851804.63740@p77g2000hsh.googlegroups.com> Message-ID: Den Tue, 17 Apr 2007 11:07:38 -0700 skrev kyosohma: > On Apr 17, 12:41 pm, Chi Yin Cheung wrote: >> Hi, >> Is there a way in python to output binary files? I need to python to >> write out a stream of 5 million floating point numbers, separated by >> some separator, but it seems that all python supports natively is >> string information output, which is extremely space inefficient. I don't understand. To me it seams like there is no space difference: [thomas at localhost ~]$ python Python 2.4.4 (#1, Oct 23 2006, 13:58:00) [GCC 4.1.1 20061011 (Red Hat 4.1.1-30)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> f = open("test2", "w") >>> f.write(str(range(10**7))) >>> f.close() >>> f = open("test", "wb") >>> f.write(str(range(10**7))) >>> f.close() >>> [thomas at localhost ~]$ ls -l test test2 -rw-rw-r-- 1 thomas thomas 88888890 17 apr 22:28 test -rw-rw-r-- 1 thomas thomas 88888890 17 apr 22:27 test2 [thomas at localhost ~]$ From mystilleef at gmail.com Sat Apr 14 14:35:15 2007 From: mystilleef at gmail.com (mystilleef) Date: 14 Apr 2007 11:35:15 -0700 Subject: Python editor/IDE on Linux? In-Reply-To: References: Message-ID: <1176575715.649316.130430@n76g2000hsh.googlegroups.com> On Apr 13, 6:20 pm, "Jack" wrote: > I wonder what everybody uses for Python editor/IDE on Linux? > I use PyScripter on Windows, which is very good. Not sure if > there's something handy like that on Linux. I need to do some > development work on Linux and the distro I am using is Xubuntu. Try Scribes: Flash Demo: http://scribes.sf.net/demo.htm It's writing in Python and can extended with Python plugins. From kyosohma at gmail.com Mon Apr 23 14:44:39 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: 23 Apr 2007 11:44:39 -0700 Subject: Learning Python - First Project In-Reply-To: <1177339942.371167.93970@b75g2000hsg.googlegroups.com> References: <1177339942.371167.93970@b75g2000hsg.googlegroups.com> Message-ID: <1177353879.444542.163020@p77g2000hsh.googlegroups.com> On Apr 23, 9:52 am, KDawg44 wrote: > Hi, > > I am new to Python and am trying to write a little front end to > another application in Python. > > What I want is to have a gui pop up listing some items with several > buttons. The guts of the program I am not having any trouble with but > the GUI part I am (or more accurately, the transition between GUI > pieces). > > The first GUI that pops up lists some groups in a listbox and gives > the user the choice to create a new group, open a group, rename the > group, or delete the group. The new group and rename group buttons > pop up a dialog gui asking for the name/new name. The Open Group is > to open another GUI listing projects within that group in a list with > similar options (New Project, Open Project, Rename Project, Delete > Project). > > My question is, how should I create all these GUIs? Should each GUI > be its own class with its own __init__? Then is the first GUI the > root (how I have it set up now) and all other GUIs using Toplevel()? > > I hope this makes sense (because it only sort of makes sense in my > head). > > THanks for any suggestions. I am assuming you are using Tkinter for your GUI front-end. You should be able to just use standard dialog boxes for your "new group" and "rename group" dialogs and a custom hand-coded dialog for the other one. All three can be called with ShowModal() instead of Toplevel(). And yes, the custom dialog would work best if you made it into a separate class. You could also put that information for the GUI that list projects into a "tree" widget of some sort, maybe with a splitter window. I haven't had much luck with Tkinter's tree widgets though. PMW and Tix both have rather poor docs unless you enjoy man pages. You might check out wxPython instead. It has an excellent demo that is very good at showing you not only what all it can do, but how it is done: www.wxpython.org. Good luck! Mike From per9000 at gmail.com Mon Apr 16 06:39:13 2007 From: per9000 at gmail.com (per9000) Date: 16 Apr 2007 03:39:13 -0700 Subject: ctypes and pointers In-Reply-To: <58ch42F2fnojeU1@mid.uni-berlin.de> References: <58ch42F2fnojeU1@mid.uni-berlin.de> Message-ID: <1176719952.974351.205450@d57g2000hsg.googlegroups.com> [This might be a double posting, if it isn't my previous post was lost] Look up "restype" in the ctypes library - it sets the return type from a function. You may want to set it to c_void_p of something similar, instead of the default int. I made a similar discovery in my blog - http://www.pererikstrandberg.se/blog/index.cgi?page=PythonCansiCombo . This example loads the function find_root from the dll root_find_lib.dll into the variable "find". the restype of find is then set to a c_double. This means that the item returned from C is a C_double and not the default int. root_find_lib = windll.LoadLibrary("root_find_lib.dll") find = root_find_lib.find_root find.restype = c_double You may already know this but 243666016 == 0E860C60 in different bases. HTH, Per [:)]-|--< -- Per Erik Strandberg .NET Architect - Optimization Tomlab Optimization Inc. http://tomopt.com/tomnet/ On 14 Apr, 19:25, "Diez B. Roggisch" wrote: > Hi, > > I'm working under mac os x with the OpenCV-library that I load viactypes. > > From a ObjectiveC-methodcall I get an integer, that "really" is a > pointer to an IplImage-structure. > > I've got a function that takes such a pointer. But I don't find a way to > pass it to that very function. > > These are the relevant parts of my code: > > cvImage = self._f.cvImage() > print "Address of IplImage: %x" % cvImage > cvImage = c_void_p(cvImage) > print cvImage > cvImage2 = macopencv.cvCloneImage(cvImage) > > The output is > > 2007-04-14 19:22:53.910 SequenceGrabberTest[5320] Returning IplImage at > Address of IplImage: e860c60 > e860c60 > c_void_p(243666016) > 2007-04-14 19:22:53.915 SequenceGrabberTest[5320] Exception raised > during posting of notification. Ignored. exception: > exceptions.ValueError: depythonifying 'pointer', got 'int' > > The first line is actually from the ObjectivC-method, a log-statement. > > As one can see, the pointer is passed back as integer. > > But then I'm stuck. > > Any suggestions would be appreciated! > > diez From exarkun at divmod.com Thu Apr 26 14:22:28 2007 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Thu, 26 Apr 2007 14:22:28 -0400 Subject: My python annoyances so far In-Reply-To: Message-ID: <20070426182228.19381.1834169922.divmod.quotient.5561@ohm> On 26 Apr 2007 20:05:45 +0200, Neil Cerutti wrote: >On 2007-04-26, Steven Howe wrote: >> flifus at gmail.com wrote: >>>> Well, why do some things in the library have to be functions, >>>> and other things have to be class methods? >> >> Perhaps because some things are more naturally function like? >> For 'instance' (pardon the pun), functions shouldn't retain >> data. They perform an operation, return data and quit. While >> retaining data is a feature of an class/instance. > >Functions do retain data. Classes and instances are just a >convenient notation. ;) > > [snip] > >Python's scoping rules make certain kinds of functional idioms >hard to use, though. I'm not sure how to get the following to >work in Python using functions: > >>>> def account(s): >... b = s >... def add(a): >... b += a >... def balance(): >... return b >... return add, balance >... >>>> add, balance = account(100) >>>> balance() >100 >>>> add(5) >Traceback (most recent call last): > File "", line 1, in ? > File "", line 4, in add >UnboundLocalError: local variable 'b' referenced before assignment > >Anyhow, it doesn't work, but you can see how closely it resembles >a class definition. Use the outfix closure operator, []: >>> def account(s): ... b = [s] ... def add(a): ... b[0] += a ... def balance(): ... return b[0] ... return add, balance ... >>> add, balance = account(100) >>> add(5) >>> balance() 105 >>> ;) Jean-Paul From grante at visi.com Thu Apr 26 12:27:11 2007 From: grante at visi.com (Grant Edwards) Date: Thu, 26 Apr 2007 16:27:11 -0000 Subject: Access to raw command line? References: <1177571070.229968.155710@t39g2000prd.googlegroups.com> <1177603801.337600.5150@r30g2000prh.googlegroups.com> Message-ID: <1331kmvfdi9ck12@corp.supernews.com> On 2007-04-26, Pieter Edelman wrote: > All your posts pretty much confirmed my own thoughts on this subject. > Every option requires a specific action from the user, and as Bjoern > points out, it would differ from what everybody is used to. I think > there's no trivial and reliable way to do this, so I can better leave > it the way it is (at least for now). Quoting things on the command line that you don't want the shell to expand is trivial and reliable. It's also something than any shell user should know. -- Grant Edwards grante Yow! I wonder if there's at anything GOOD on tonight? visi.com From hlubenow2 at gmx.net Sun Apr 1 15:13:22 2007 From: hlubenow2 at gmx.net (hlubenow) Date: Sun, 01 Apr 2007 21:13:22 +0200 Subject: Pygame Q (linux) beginner References: <460F28F2.D91DB67A@braindead.com> Message-ID: enquiring mind wrote: > Running 2.4.1 Python (learning) > Running SUSE Linux 10 > > At Chapter 5 is where the Pygame module is > introduced so I have a little time before I have to figure out what I > have to download and install. Are you asking for advice how to install pygame on SuSE 10 ? Well, that's easy: python-pygame....rpm comes with SuSE. Just install it with YaST2; the additional packages it needs (like libSDL) are installed automatically then. So you don't have to download any packages from www.pygame.org. Another hint: If sound in pygame doesn't work, try export SDL_AUDIODRIVER=alsa right before starting your script. H. From rw at smsnet.pl Tue Apr 10 16:38:08 2007 From: rw at smsnet.pl (Rob Wolfe) Date: Tue, 10 Apr 2007 22:38:08 +0200 Subject: About Eggs References: <131nspji8t6559b@corp.supernews.com> Message-ID: <87k5wkj77z.fsf@smsnet.pl> Mark Elston writes: > This is probably a *really* stupid question but... > I have looked at all the documentation I have for 2.4.3 > and all the docs I can download for 2.5 and I simply cannot > find anything, anywhere that documents what egg files are. > > I have read posts referring to them and have been able to > deduce that they are some form of zip file for the distribution > of modules but beyond that I cannot find *any* docs for them > anywhere. Start here: http://peak.telecommunity.com/DevCenter/setuptools -- HTH, Rob From python at rcn.com Sun Apr 29 15:12:17 2007 From: python at rcn.com (Raymond Hettinger) Date: 29 Apr 2007 12:12:17 -0700 Subject: While we're talking about annoyances In-Reply-To: References: Message-ID: <1177873937.832484.260050@l77g2000hsb.googlegroups.com> [Steven D'Aprano] > I recently needed to write a function to generate a rank table from a > list. That is, a list of ranks, where the rank of an item is the position > it would be in if the list were sorted: > > alist = list('defabc') > ranks = [3, 4, 5, 0, 1, 2] . . . > def rank(sequence): > table = [None] * len(sequence) > for j, idx in enumerate(index(sequence)): > table[idx] = j > return table FWIW, you can do ranking faster and more succinctly with the sorted() builtin: def rank(seq): return sorted(range(len(seq)), key=seq.__getitem__) Raymond From bbxx789_05ss at yahoo.com Sun Apr 15 23:33:27 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: 15 Apr 2007 20:33:27 -0700 Subject: How to initialize a table of months. In-Reply-To: <1176694257.338172.217660@y80g2000hsf.googlegroups.com> References: <1176694257.338172.217660@y80g2000hsf.googlegroups.com> Message-ID: <1176694407.102613.37460@w1g2000hsg.googlegroups.com> On Apr 15, 9:30 pm, "7stud" wrote: > On Apr 15, 7:30 pm, "Steven W. Orr" wrote: Arrgh. import calendar months = calendar.month_abbr #returns an array with the 0 element empty #so the month names line up with the indexes 1-12 d = {} for i in range(1, 13): d[months[i]] = i print d From martin.laloux at gmail.com Tue Apr 17 04:28:23 2007 From: martin.laloux at gmail.com (martin.laloux at gmail.com) Date: 17 Apr 2007 01:28:23 -0700 Subject: Python + ogr module? In-Reply-To: <1176756787.450645.220310@p77g2000hsh.googlegroups.com> References: <1176756787.450645.220310@p77g2000hsh.googlegroups.com> Message-ID: <1176798503.606319.281100@y5g2000hsa.googlegroups.com> You must seek for python and Open Source GIS or mapserver and you find: http://mapserver.gis.umn.edu/community/conferences/MUM3/workshop/python http://www.archaeoworld.com/classes/osgit/lectures/ with http://www.archaeoworld.com/classes/osgit/lectures/osgit_02_libraries.pdf and you have some examples in http://www.koders.com/python/fid907532DAD536B552A4E6F7328EB863EFB9528C8A.aspx I use the ogr module without problem From samjnaa at gmail.com Sat Apr 14 06:42:52 2007 From: samjnaa at gmail.com (samjnaa at gmail.com) Date: 14 Apr 2007 03:42:52 -0700 Subject: Python Feature Request: Add the "using" keyword which works like "with" in Visual Basic Message-ID: <1176547372.584539.89170@q75g2000hsh.googlegroups.com> Please check for sanity and approve for posting at python-dev. In Visual Basic there is the keyword "with" which allows an object- name to be declared as governing the following statements. For example: with quitCommandButton .enabled = true .default = true end with This is syntactic sugar for: quitCommandButton.enabled=true quitCommandButton.default=true This can be very useful especially in GUI programming when we have to type the same object name in line-after-line. I personally found having to type the word "self" umpteen times inside classes very irritating. Such a beautiful language is Python, she should have this good feature from VB too. Now I hear that the word "with" is being discussed for a different purpose in Py 3 as a result of a PEP and I don't want to conflict with that. So I propose the word "using" as a replacement. This also is similar to the C++ "using" keyword which exposes the members of a namespace to access without specifying the namespace scope for each reference. For example after giving "using namespace std;" I can change all references to "std::cout" to "cout", which is similar to what I am proposing for Python now. Some thoughts about how this "using" statement should behave. The word using should be followed by an object name and a colon indicating the start of a block. The object named after "using" must determine the context (or whatever the technical word is) of the of the statements in that block. self.setFixedSize(200, 120) self.quit = QtGui.QPushButton("Quit", self) self.quit.setGeometry(62, 40, 75, 30) self.quit.setFont(QtGui.QFont("Times", 18, QtGui.QFont.Bold)) self.connect(self.quit, QtCore.SIGNAL("clicked()"), QtGui.qApp, QtCore.SLOT("quit()")) to be rewritten as: using self: __setFixedSize(200,120) __quit = QtGui.QPushButton("Quit", self) __using quit: ____setGeometry(62, 40, 75, 30) ____setFont(QtGui.QFont("Times", 18, QtGui.QFont.Bold)) __connect(self.quit, QtCore.SIGNAL("clicked()"), QtGui.qApp, QtCore.SLOT("quit()")) [I don't know whether usenet will retain my indenting, so I changed the tabs to underscores.] This context governing may need to be limited to the first applicable member - so that in the above example "self" governs setFixedSize, quit, quit and connect only in each sentence and quit (self.quit) governs setGeometry and setFont only. (Point is that the parser should not search for self.QtGui, self.self or self.QtCore in sentences 3 and 7, and self.quit.QtGui in sentence 6.) Due to my absence of professional experience, my request may be somewhat unpolished technical-wise, but I believe that this is a very useful feature for Python and hence request the technically- knowledgeable to reformat it as necessary. Thank you. From bdesth.quelquechose at free.quelquepart.fr Tue Apr 3 17:33:00 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Tue, 03 Apr 2007 23:33:00 +0200 Subject: File Object behavior In-Reply-To: References: Message-ID: <4612bf27$0$29887$426a74cc@news.free.fr> Michael Castleton a ?crit : > When I open a csv or txt file with: > > infile = open(sys.argv[1],'rb').readlines() > or > infile = open(sys.argv[1],'rb').read() > > and then look at the first few lines of the file there is a carriage return > + > line feed at the end of each line - \r\n Is there any reason you open your text files in binary mode ? Unless you're using the csv module (which requires such a mode - but then you don't care since you're not working with the raw data yourself), you should consider opening your files in text mode. This should solve your problem (if not, then you have a problem with universal newlines support in your Python install). HTH From nogradi at gmail.com Wed Apr 25 07:40:35 2007 From: nogradi at gmail.com (Daniel Nogradi) Date: Wed, 25 Apr 2007 13:40:35 +0200 Subject: Now() In-Reply-To: <-857040447710971516@unknownmsgid> References: <-857040447710971516@unknownmsgid> Message-ID: <5f56302b0704250440l548e0c05re38790867e95b50d@mail.gmail.com> > I'm using the following function 'str (now)' to place a date time stamp into > a log file, which works fine, however it writes the stamp like this. > > 2007-04-25 11:06:53.873029 > > But I need to expel those extra decimal places as they're causing problems > with the application that parses the log data, all I need is something like > this: > > 2007-04-25 11:06:53 Please see http://docs.python.org/lib/module-time.html Daniel From martinskou at gmail.com Sat Apr 14 12:48:41 2007 From: martinskou at gmail.com (martinskou at gmail.com) Date: 14 Apr 2007 09:48:41 -0700 Subject: Making a tree out of a 2 column list In-Reply-To: References: Message-ID: <1176569321.762908.293800@o5g2000hsb.googlegroups.com> Hope this helps # list of pairs [child,parent] list=[[2,131],[6,335],[7,6],[8,9],[10,131],[131,99],[5,10]] # list with loop #list=[[2,131],[6,335],[7,6],[8,9],[10,131],[131,99],[5,10],[3,10], [131,3]] # put the pairs in a dictionary, for easy retrieval d={} for c,p in list: # must be able to hold multiple values for each key if not(d.has_key(p)): d[p]=[c] else: d[p].append(c) # function to retrieve children using recursion. max_depth to ensure termination def retrieve_recursive(key,result=[],max_depth=10): if d.has_key(key) and max_depth>0: for i in d[key]: result.append(i) retrieve_recursive(i,result,max_depth-1) return result print retrieve_recursive(131) From antroy at gmail.com Thu Apr 19 06:10:40 2007 From: antroy at gmail.com (Ant) Date: 19 Apr 2007 03:10:40 -0700 Subject: About installing new Python version. In-Reply-To: <1176976568.438207.253120@d57g2000hsg.googlegroups.com> References: <1176973387.967130.27370@y80g2000hsf.googlegroups.com> <1176975545.693682.51870@q75g2000hsh.googlegroups.com> <1176976568.438207.253120@d57g2000hsg.googlegroups.com> Message-ID: <1176977440.265263.186450@n76g2000hsh.googlegroups.com> > checked and everything seems to working fine. But this is an update > release to 2.5, i do not know what is happening when, for example, a > totally new Python version come out, like 2.6 or 2.7 or... Again just install it - it will by default install alongside Python 2.5 in a different directory, and set itself as the default python version. You'll then need to update all your third party extensions to ones compiled against the new version - so if you have a lot of these, it makes sense to wait a while before upgrading. -- Ant. From nogradi at gmail.com Thu Apr 12 19:13:19 2007 From: nogradi at gmail.com (Daniel Nogradi) Date: Fri, 13 Apr 2007 01:13:19 +0200 Subject: Lists and Tuples and Much More In-Reply-To: References: Message-ID: <5f56302b0704121613r6d63f3c7x818c677344bce733@mail.gmail.com> > And the last example brings up another question. What's the deal with a > tupple that has a list in it such as: > > >>>my_tupple = (1, 2, 3, 4, 5, [6, 7, 8, 9]) > > Now I read somewhere that you could change the list inside that tupple. But > I can't find any documentation that describes HOW to do it. The only things > I CAN find on the subject say, "Don't do it because its more trouble than > it's worth." But that doesn't matter to me, because I want to know > everything. You could change the list inside your tuple like this: >>> my_tupple = (1, 2, 3, 4, 5, [6, 7, 8, 9]) >>> my_tupple[5].append(10) >>> my_tupple (1, 2, 3, 4, 5, [6, 7, 8, 9, 10]) > Now there comes append. I read everywhere that append only add's 1 element > to the end of your list. But if you write: > >>> my_list = [1, 2, 3, 4, 5, 6] > >>> my_list.append([7, 8, 9, 10]) > >>> my_list > [1, 2, 3, 4, 5, 6, [7, 8, 9, 10]] > > Is that because list's, no matter what they contain, are counted as 1 > element? Yes. > And how would you sort the list that's in the list? I guess that goes in > conjunction with the section above, but still: > >>> my_list = [6, 4, 3, 5, 2, 1] > >>> my_list.append([7, 9, 8, 10]) > >>> my_list.sort() > >>> my_list > [1, 2, 3, 4, 5, 6, [7, 9, 8, 10]] How about: >>> my_list = [6, 4, 3, 5, 2, 1] >>> my_list.append([7, 9, 8, 10]) >>> my_list[6].sort() >>> my_list [6, 4, 3, 5, 2, 1, [7, 8, 9, 10]] HTH, Daniel From ejensen at visi.com Thu Apr 5 17:42:42 2007 From: ejensen at visi.com (Ed Jensen) Date: Thu, 05 Apr 2007 21:42:42 -0000 Subject: Python and Java References: Message-ID: <131araimq483n27@corp.supernews.com> Steve Holden wrote: > Jython is an implementation of Python that compiles to Java bytecode, > but at the moment there's some version lag so it won't handle the mos > recent language enhancements. Probably worth a look, though. > > http://www.jython.org/ Does Jython compile to Java bytecode, or is Jython a Java implementation of a Python interpreter? From paddy3118 at googlemail.com Fri Apr 13 06:20:42 2007 From: paddy3118 at googlemail.com (Paddy) Date: 13 Apr 2007 03:20:42 -0700 Subject: Problem with algorithm In-Reply-To: <1176448576.047996.12930@d57g2000hsg.googlegroups.com> References: <1176434160.047703.214600@q75g2000hsh.googlegroups.com> <1176434937.258002.162220@p77g2000hsh.googlegroups.com> <1176448576.047996.12930@d57g2000hsg.googlegroups.com> Message-ID: <1176459642.137990.33330@q75g2000hsh.googlegroups.com> On Apr 13, 8:16 am, "Jia Lu" wrote: > > for m in test: > > for n in test: > > for o in test: > > for p in test: > > print m+n+o+p > > Thanx for your anwser. > But if I consider about a combination of over 26 letter's list just > like: > "abcdefssdzxcvzxcvzcv" > "asllxcvxcbbedfgdfgdg" > ..... > > Need I write 26 for loops to do this? > > Thanx > > Jia LU Try this: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/502199 You could then write something like: import string for thiscomb in comb2( *([string.lowercase]*26) ): ... Mind you, it generates a lot of combinations. - Paddy. From howe.steven at gmail.com Thu Apr 5 11:35:12 2007 From: howe.steven at gmail.com (Steven Howe) Date: Thu, 05 Apr 2007 08:35:12 -0700 Subject: Can we make a local variable in a function as global variable??? In-Reply-To: <1175764774.260576.286420@y66g2000hsf.googlegroups.com> References: <1175764774.260576.286420@y66g2000hsf.googlegroups.com> Message-ID: <46151730.5080301@gmail.com> sairam wrote: > I have some local variables defined in one method and Can I make those > variables as global variables? If so , can any one explain me how can > I do that > > > Thanks, > Sairam > > See: http://www.faqs.org/docs/diveintopython/dialect_locals.html When a line of code asks for the value of a variable x, Python will search for that variable in all the available namespaces, in order: 1. local namespace - specific to the current function or class method. If the function defines a local variable x, or has an argument x, Python will use this and stop searching. 2. global namespace - specific to the current module. If the module has defined a variable, function, or class called x, Python will use that and stop searching. 3. built-in namespace - global to all modules. As a last resort, Python will assume that x is the name of built-in function or variable. -------------- next part -------------- An HTML attachment was scrubbed... URL: From nagle at animats.com Tue Apr 3 14:07:03 2007 From: nagle at animats.com (John Nagle) Date: Tue, 03 Apr 2007 11:07:03 -0700 Subject: Numeric compiling problem under QNX 4.25 In-Reply-To: <1175578324.426293.21970@y80g2000hsf.googlegroups.com> References: <1175578324.426293.21970@y80g2000hsf.googlegroups.com> Message-ID: <0IwQh.1146$zC.688@newssvr22.news.prodigy.net> ZMY wrote: > Dear all, > > I am a real newbie for both python and QNX, but I am still trying to > compile Numeric-24.2 under QNX4.25 with python 2.2. If you're new to QNX, why are you running QNX 4? That's for legacy systems only. Move up to QNX 6, which has been out for ten years now. John Nagle From donn at u.washington.edu Fri Apr 27 14:48:58 2007 From: donn at u.washington.edu (Donn Cave) Date: Fri, 27 Apr 2007 11:48:58 -0700 Subject: Access to raw command line? References: <1177571070.229968.155710@t39g2000prd.googlegroups.com> <1331lv4rshck2e@corp.supernews.com> Message-ID: In article <1331lv4rshck2e at corp.supernews.com>, Grant Edwards wrote: > On 2007-04-26, Donn Cave wrote: > > >> One possible way to work around this is to get the raw command line > >> and do the shell expansions ourselves from within Python. Ignoring the > >> question of whether it is worth the trouble, does anybody know if it > >> is possible to obtain the raw (unexpanded) command line? > > > > If you're on VMS (well, you didn't say), you're in luck. > > > > The UNIX shell has already expanded the file globbing by the > > time your program starts up, but VMS leaves it to the application, > > with the help of a handy RMS$ function or two so it gets done in > > a consistent way. This allows the command line interface to > > interact with the user in a little more transparent way, since > > the input seen by the program is congruent with what the user > > typed in. E.g., "rename *.jpeg *.jpg" is trivial on VMS, > > impossible on UNIX. > > Typing rename '*.jpeg' '*.jpg' is impossible? It is not (of course, nor is implementation impossible), but as noted earlier in this thread it isn't idiomatic. You can present an interface like this to a user who has been specially trained to use it, but no one would naturally expect it to work, without prior instruction, so it isn't any more or less interesting than, say, "rename *.jpeg .jpeg". (Oops, now that I think of it, that's what I should have said works on VMS anyway. Been too long.) Donn Cave, donn at u.washington.edu From lew at nospam.lewscanon.com Tue Apr 17 23:27:51 2007 From: lew at nospam.lewscanon.com (Lew) Date: Tue, 17 Apr 2007 23:27:51 -0400 Subject: is laziness a programer's virtue? In-Reply-To: References: <1176757271.282365.319740@n76g2000hsh.googlegroups.com> <1176797558.403629.53140@b75g2000hsg.googlegroups.com> <1176823224.099381.4630@n59g2000hsh.googlegroups.com> Message-ID: "Lew" ranted maniacally: >> Y'know, even in jest, calling for an oppressive regime to suppress even >> wrong-headed and self-serving garbage self-expression is immoral and >> horrible. How dare you? >> >> Free speech, free press and free expression of ideas is not something to >> take so lightly. Bruce C. Baker wrote: > That's right! Momma don't allow no levity around here! > > Off with Markus' head! :-D As they walked off together, Alice heard the King say in a low voice, to the company generally, `You are all pardoned.' `Come, THAT'S a good thing!' she said to herself, for she had felt quite unhappy at the number of executions the Queen had ordered. - /Alice's Adventures in Wonderland/, Lewis Carroll From ptmcg at austin.rr.com Tue Apr 10 16:16:19 2007 From: ptmcg at austin.rr.com (Paul McGuire) Date: 10 Apr 2007 13:16:19 -0700 Subject: Please help!!! In-Reply-To: <1176234239.436463.195870@n33g2000cwc.googlegroups.com> References: <1176234239.436463.195870@n33g2000cwc.googlegroups.com> Message-ID: <1176236179.443346.162070@h3g2000cwc.googlegroups.com> On Apr 10, 2:43 pm, "gslm" wrote: > Hi to all! > I want to do a calendar with pictures near months. > I have designed the form's view.But unfortunately, I am not be able to > save this view as an image file.And so I am not be able to print this > image file too. > Question: > How can I determine the coordinates of a button?Namely How can I use > the comand ImageGrab for this purpose? > > But only I wan to get the button's ares.Because my applicationis on > this. > > Or if it's possible, how can I print the area of this button with the > components on it? > > Thanks... Suggestion 1: "Please help!!!" is just about the worst newsgroup subject line there is (other than those related to government conspiracies or earthquake prediction). You are unlikely to attract the attention of those who really know anything - they are quite busy and must husband their time carefully. Instead, you'll get those who are idly curious, to see what sort of junk is floating about Usenet. Suggestion 2: Consider your audience. What the heck are you talking about?! Your post goes on about calendars and buttons and views. In fact, trying to make sense of your post, it sounds like you've done something truly bizarre, like making the whole view one giant button with lots of images on it, and you want to print it out when the "button" is clicked. Is this even a Python question? Any particular GUI package you are using, such as Tk, wxPython, QT, your own homebrew invention? ImageGrab? Sounds promising, what do the docs say? A more thorough discussion of these suggestions: http://www.catb.org/~esr/faqs/smart-questions.html -- Paul From bignose+hates-spam at benfinney.id.au Thu Apr 12 19:18:01 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Fri, 13 Apr 2007 09:18:01 +1000 Subject: Lists and Tuples and Much More References: Message-ID: <87tzvl5gie.fsf@benfinney.id.au> "Scott" writes: > I'm going to start grouping all my questions in one post as this is > my second today, and sorta makes me feel dumb to keep having to > bother you all with trivial questions. No, please don't do that. Separate questions leading to separate discussions should have separate threads. Post them as separate messages, each with a well-chosen Subject field for the resulting thread. -- \ "Why should I care about posterity? What's posterity ever done | `\ for me?" -- Groucho Marx | _o__) | Ben Finney From shamzz at gmail.com Wed Apr 11 04:02:56 2007 From: shamzz at gmail.com (shamzz at gmail.com) Date: 11 Apr 2007 01:02:56 -0700 Subject: No zlib in Python 2.4.4 Message-ID: <1176278576.196716.104760@p77g2000hsh.googlegroups.com> Hi, I've compiled (configure/make/make install) Python 2.4.4 from source on Suse Linux Enterprise Server 9 (x64). I need Python to be compiled with Zlib so that I can compile and use Zope. After installing Python, zlib doesn't seem to have been compiled with it, I've checked the /usr/local/lib/python2.4/lib-dynload/ folder and there is no zlib.so in there. Shouldn't zlib be compiled as a Python module automatically in Python 2.4.4. I'm guessing Python is doing some kind of check and not compiling zlib for some reason? Any help would be appreciated. Thanks, Shams From flyzone at technologist.com Fri Apr 13 03:59:52 2007 From: flyzone at technologist.com (Flyzone) Date: 13 Apr 2007 00:59:52 -0700 Subject: split and regexp on textfile Message-ID: <1176451192.364949.8260@w1g2000hsg.googlegroups.com> Hi, i have a problem with the split function and regexp. I have a file that i want to split using the date as token. Here a sample: ----- Mon Apr 9 22:30:18 2007 text text Mon Apr 9 22:31:10 2007 text text ---- I'm trying to put all the lines in a one string and then to separate it (could be better to not delete the \n if possible...) while 1: line = ftoparse.readline() if not line: break if line[-1]=='\n': line=line[:-1] file_str += line matchobj=re.compile('[A-Z][a-z][a-z][ ][A-Z][a-z][a-z][ ][0-9| ][0-9] [ ][0-9][0-9][:]') matchobj=matchobj.split(file_str) print matchobj i have tried also matchobj=re.split(r"^[A-Z][a-z][a-z][ ][A-Z][a-z][a-z][ ][0-9| ] [0-9][ ][0-9][0-9][:]",file_str) and reading all with one: file_str=ftoparse.readlines() but the split doesn't work...where i am wronging? From aahz at pythoncraft.com Sat Apr 14 13:25:44 2007 From: aahz at pythoncraft.com (Aahz) Date: 14 Apr 2007 10:25:44 -0700 Subject: Python editor/IDE on Linux? References: <1176488840.672572.101830@y80g2000hsf.googlegroups.com> <461fe88c$0$6420$426a74cc@news.free.fr> Message-ID: In article , Michael Bentley wrote: > >>> >>> Everybody uses vim. >>> >> Except for real programmers... > >Who instead use emacs ;-) "Emacs makes a good OS, but a lousy editor." -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Help a hearing-impaired person: http://rule6.info/hearing.html From openopt at ukr.net Sun Apr 29 13:19:42 2007 From: openopt at ukr.net (dmitrey) Date: 29 Apr 2007 10:19:42 -0700 Subject: howto check is object a func, lambda-func or something else? Message-ID: <1177867182.115406.4640@h2g2000hsg.googlegroups.com> hi all, howto check is object Arg1 - a func, lambda-func - something else? I tried callable(Arg1), but callable(lambda-func) returnes False Thx, D. From jura.grozni at gmail.com Thu Apr 12 19:56:28 2007 From: jura.grozni at gmail.com (azrael) Date: 12 Apr 2007 16:56:28 -0700 Subject: favourite IDE Message-ID: <1176422188.006169.141100@q75g2000hsh.googlegroups.com> Some time ago I posted a question about the favourite IDE. I finally found it. WING IDE i the best I've ever seen for python. Code completition is amazing, automated help, python comand line. evrything i need. Who didnt try, doesnt know what he is missing. just one word: Amazing respect to the developers From steve at holdenweb.com Thu Apr 5 17:55:42 2007 From: steve at holdenweb.com (Steve Holden) Date: Thu, 05 Apr 2007 17:55:42 -0400 Subject: Python and Java In-Reply-To: <131araimq483n27@corp.supernews.com> References: <131araimq483n27@corp.supernews.com> Message-ID: Ed Jensen wrote: > Steve Holden wrote: >> Jython is an implementation of Python that compiles to Java bytecode, >> but at the moment there's some version lag so it won't handle the mos >> recent language enhancements. Probably worth a look, though. >> >> http://www.jython.org/ > > Does Jython compile to Java bytecode, or is Jython a Java > implementation of a Python interpreter? Please read what I wrote again. 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 frankatle at gmail.com Thu Apr 5 10:41:33 2007 From: frankatle at gmail.com (frankatle at gmail.com) Date: 5 Apr 2007 07:41:33 -0700 Subject: snippet manager idea Message-ID: <1175784093.094255.3630@y66g2000hsf.googlegroups.com> Hi. I am writing a opensource code snippet manager in python (pyqt4). The idea is that users can upload their snippets to remote subversion server, (if they choose) and add comments to existing snippets, vote for snippet deletion, add flags to snippets: (tested, working, not working... etc) The snippets are stored locally in a sqlite3 database. So far i have a working application that use a small Soap client/ server to upload snippets to a remote server. The client sends a dict to the server, the server writes the dict as a text file and adds it to the svn server. On the client a local svn repo is downloaded and parsed into the database. The client Ui has syntaxhighlighting(only cplusplus and python at the moment), an "add snippet form", treewidget for snippet listing. My personal conserns are: individual snippet licensing I was wondering if anyone could comment on this idea. And perhaps come with some ideas. From gcmartijn at gmail.com Fri Apr 6 05:52:10 2007 From: gcmartijn at gmail.com (gcmartijn at gmail.com) Date: 6 Apr 2007 02:52:10 -0700 Subject: BaseHTTPRequestHandler reading .html with python code Message-ID: <1175853130.368154.103090@y80g2000hsf.googlegroups.com> H! I was wondering how I can do something like this. file.html --------- hello world print 'hello world' #or display str(time.localtime()[7]) webserver.py --------- def do_GET(self): try: if self.path.endswith(".html"): f = open(curdir + sep + self.path) #self.path has / test.html self.send_response(200) self.send_header('Content-type', 'text/html') self.end_headers() # now display the hello world and run the python code. self.wfile.write(f.read()) f.close() return I saw the mod python for apache and some PSP but I really want to know how they do this. Is there are special module for doing this ? Or is there something like this: --------------------------- 1. a running python program 2. include with write(f.read()) a extra python code inside the already running python program. How they handle this ? From paul at boddie.org.uk Fri Apr 20 09:58:26 2007 From: paul at boddie.org.uk (Paul Boddie) Date: 20 Apr 2007 06:58:26 -0700 Subject: Do other Python GUI toolkits require this? In-Reply-To: References: <462697A6.6010007@codebykevin.com> <465B30B4-5BA0-459A-BE6F-1038874FA74B@jedimindworks.com> <58rq32F2fo980U1@mid.uni-berlin.de> Message-ID: <1177077506.429242.161690@e65g2000hsc.googlegroups.com> On 20 Apr, 15:22, Antoon Pardon wrote: > On 2007-04-20, Diez B. Roggisch wrote: > > > Which is nonsense. The goal is to go from A - ignorance - to B - > > knowledge - which both lie on the X-Axis. > > Well if you want to do it that way, nobody can stop you, but people > in the habit of processing numbers usually put the time on the X-axis > like in time spend learning or exercising and put the other value > on the Y-axis. But time wasn't mentioned. You could have knowledge or accomplishment on the X axis and effort or work on the Y axis. Subjects with more material to learn could be said to have a "long learning curve"; an example of such usage can be found here: http://www.linuxplanet.com/linuxplanet/reviews/3207/5/ But if the nature of the material is not particularly challenging, you could say that a "shallow learning curve" is involved: you don't need to think very hard about the material. Conversely, a "steep learning curve" in the popular sense suggests more effort being expended for a given measure of material. Paul From erikwickstrom at gmail.com Thu Apr 5 13:11:46 2007 From: erikwickstrom at gmail.com (erikcw) Date: 5 Apr 2007 10:11:46 -0700 Subject: AttributeError: 'tuple' object has no attribute 'encode' In-Reply-To: <1175791064.256896.240090@b75g2000hsg.googlegroups.com> References: <1175787095.862712.297480@n76g2000hsh.googlegroups.com> <1175791064.256896.240090@b75g2000hsg.googlegroups.com> Message-ID: <1175793106.373420.39600@w1g2000hsg.googlegroups.com> On Apr 5, 12:37 pm, "Paul Boddie" wrote: > erikcw wrote: > > > I'm trying to build a SQL string > > > sql = """INSERT INTO ag ('cid', 'ag', 'test') VALUES(%i, %s, %d)""", > > (cid, ag, self.data[parent][child]['results']['test']) > > This makes a tuple, though: the first element is the SQL string; the > second element contains a tuple of parameters. > > > It raises this error: AttributeError: 'tuple' object has no attribute > > 'encode' > > What does? I imagine that this error comes from a call to a cursor > object's execute method. In other words, I imagine that you may be > doing something like this: > > cursor.execute(*sql) > > Not that there would be anything obviously wrong with that: you are > keeping the string and its parameters separate, after all. However, > you'd have to show us the full error (a traceback including lines of > code from the database library) for us to really see what's going on. > > > Some of the variables are unicode (test and ag) - is that what is > > causing this error? What do I need to do to make it work? > > Show us more of the error! ;-) > > Paul Here is the full error: (sorry) Traceback (most recent call last): File "/home/erik/Desktop/wa.py", line 178, in ? curHandler.walkData() File "/home/erik/Desktop/wa.py", line 91, in walkData sql = """INSERT INTO ag ('cid', 'ag', 'test') VALUES(%i, %s, %d)""", (cid.encode("utf-8"), ag, self.data[parent][child]['results']['test']) AttributeError: 'long' object has no attribute 'encode' sql = """INSERT INTO ag ('cid', 'ag', 'test') VALUES(%i, %s, %d)""", (cid.encode("utf-8"), ag, self.data[parent][child]['results']['test']) self.cursor.execute(sql) Now, I changed all ofth e %i/%d to %s, and changed self.cursor.execute(sql) to self.cursor.execute(*sql) and it seems to be working now! From clarence1126 at gmail.com Tue Apr 10 14:23:02 2007 From: clarence1126 at gmail.com (Clarence) Date: 10 Apr 2007 11:23:02 -0700 Subject: Mysterious argument count error to __new__ Message-ID: <1176229381.678778.313380@p77g2000hsh.googlegroups.com> I'm having problems with JPype and am trying to change the way it creates Python classes as proxies for Java classes and interfaces. I'm trying to get around "inconsistent mro" problems, but in doing so, I've run into a real mystery. Here's the original code. It first makes a metaclass, then makes a class using that metaclass. ############## metaclass = type.__new__(type, name+"$$Static", tuple(meta_bases), static_fields) members['__metaclass__'] = metaclass result = type.__new__(metaclass, name, tuple(bases), members) ############## I'm getting an error on the first call to __new__, but I want to see if my "bases" list is acceptable, putting aside for the moment that "meta_bases" is having a problem. So I put this line directly ahead of the three quoted above: ############## type.__new__(type, 'aoeu', tuple(bases), members) ############## You can see that this is essentially exactly the same as the first of the three, just using a different name, a diffent bases tuple, and a different dictionary. Whereas the first of the three gets an mro kind of error, when I insert this new line, it gets: type.__new__(type, 'aoeu', tuple(bases), members) TypeError: __new__() takes exactly 2 arguments (4 given) How is it possible that I get a number-of-arguments error when the following line, with the same number of arguments, does not? (This can't even be relevant, really, but I also printed out the value of "type" before the line, and got as it should be.) Thanks for any help. Clarence From mike.klaas at gmail.com Fri Apr 6 20:38:48 2007 From: mike.klaas at gmail.com (Klaas) Date: 6 Apr 2007 17:38:48 -0700 Subject: Problems with os.spawnv In-Reply-To: <1175811935.298942.150620@d57g2000hsg.googlegroups.com> References: <1175807996.524018.146070@n76g2000hsh.googlegroups.com> <1175809984.762401.11020@n59g2000hsh.googlegroups.com> <1175811935.298942.150620@d57g2000hsg.googlegroups.com> Message-ID: <1175906328.793051.262910@b75g2000hsg.googlegroups.com> On Apr 5, 3:25 pm, "Henrik Lied" wrote: > > > I'd still love to get a working example of my problem using the > > > Subprocess module. :-) > > > The same thing: > > p = subprocess.Popen(["mencoder", "/users/...", "-ofps", ...]) > > That example looked great at first, but on a closer look it didn't > quite end up to be what I wanted. In a real environment the user still > had to wait for the command to finish. Then you are not using it correctly. subprocess.Popen() returns immediately. Notice the order of events here: In [2]: subprocess.Popen('sleep 2; echo foo', shell=True); print 'bar' bar foo -Mike From clajo04 at mac.com Wed Apr 4 15:45:34 2007 From: clajo04 at mac.com (John Clark) Date: Wed, 4 Apr 2007 15:45:34 -0400 Subject: New York City Python Users Group Meeting Message-ID: <00c301c776f1$d175e970$fefea8c0@haengma> Greetings! The next New York City Python Users Group meeting is this Tuesday, April 10th, 6:30pm at at the Millennium Partners office at 666 Fifth Avenue (53rd St. and 5th Ave.) on the 8th Floor. We welcome all those in the NYC area who are interested in Python to attend. However, we need a list of first and last names to give to building security to make sure you can gain access to the building. RSVP to clajo04 at mac.com to add your name to the list. More information can be found on the yahoo group page: http://tech.groups.yahoo.com/group/nycpython/ Hope to see you there! -John -------------- next part -------------- An HTML attachment was scrubbed... URL: From soren.skou.nielsen at gmail.com Wed Apr 18 16:21:36 2007 From: soren.skou.nielsen at gmail.com (Soren) Date: 18 Apr 2007 13:21:36 -0700 Subject: Python crash after using weave inline In-Reply-To: <1176926820.627494.13260@o5g2000hsb.googlegroups.com> References: <1176900343.605337.42230@y5g2000hsa.googlegroups.com> <1176926820.627494.13260@o5g2000hsb.googlegroups.com> Message-ID: <1176927696.783635.326940@l77g2000hsb.googlegroups.com> On Apr 18, 10:07 pm, Peter Wang wrote: > Soren, > > For future reference, you might want to direct weave-related questions > to the scipy-u... at scipy.org mailing list. > > > def cartPolFast(xlen, ylen, x_c, y_c): > > > res = zeros((xlen,ylen)) > > > code = """ > > { > > int xlen, ylen, x_c, y_c; > > This line is unnecessary, because weave exposes those variables inside > the local scope of your code. This also makes the braces at the top > and bottom of the code block unnecessary. > > > for( x = 0; x == xlen; x++) > > for( y = 0; y == ylen; y++) > > rel_x = x-x_c; > > rel_y = y_c-y; > > > res(x,y) = rel_y*rel_y; > > } > > Two things: > 1. You need to put curly braces around the three lines of the inner > loop. > 2. You need to change "x == xlen" and "y == ylen" to "x < xlen" and "y > < ylen". > > I made these modifications to your code and it runs fine on my machine > (macbook pro, OS 10.4, scipy 0.5.2.dev2314). > > -peter Thanks alot Peter! I'm a bit rusty on the C! :) Soren From nagle at animats.com Thu Apr 19 11:59:44 2007 From: nagle at animats.com (John Nagle) Date: Thu, 19 Apr 2007 15:59:44 GMT Subject: Python un-plugging the Interpreter In-Reply-To: References: Message-ID: S.Mohideen wrote: > Hi All, > I was thinking about the feasbility of adjusting Python as a > compiled language. Being said that I feel these are the following > advantages of doing so -- > 1) Using the powerful easy-to -use feature of Python programming > language constructs. > 2) Making the program to run at par with the compiled version of C/C++ > program- this is the main benefit which can be derived out of this. > 3) Highly re-use existing Python code for High performance application. > 4) Acheive true parallelism and performance by getting rid of the > middle-man Interpreter and GIL. > > I know this must be appearing like a foolish idea. But I would like to > know the opinion of people who might have thought about it. It's a great idea. Look at ShedSkin, PyPy, and Jython, all of which tried to do it, and none of which really became finished products. John Nagle From ptmcg at austin.rr.com Thu Apr 26 17:48:07 2007 From: ptmcg at austin.rr.com (Paul McGuire) Date: 26 Apr 2007 14:48:07 -0700 Subject: My python annoyances so far In-Reply-To: References: Message-ID: <1177624087.480055.212670@r3g2000prh.googlegroups.com> On Apr 26, 1:22 pm, Jean-Paul Calderone wrote: > On 26 Apr 2007 20:05:45 +0200, Neil Cerutti wrote: > > > > > > >On 2007-04-26, Steven Howe wrote: > >> fli... at gmail.com wrote: > >>>> Well, why do some things in the library have to be functions, > >>>> and other things have to be class methods? > > >> Perhaps because some things are more naturally function like? > >> For 'instance' (pardon the pun), functions shouldn't retain > >> data. They perform an operation, return data and quit. While > >> retaining data is a feature of an class/instance. > > >Functions do retain data. Classes and instances are just a > >convenient notation. ;) > > > [snip] > > >Python's scoping rules make certain kinds of functional idioms > >hard to use, though. I'm not sure how to get the following to > >work in Python using functions: > > >>>> def account(s): > >... b = s > >... def add(a): > >... b += a > >... def balance(): > >... return b > >... return add, balance > >... > >>>> add, balance = account(100) > >>>> balance() > >100 > >>>> add(5) > >Traceback (most recent call last): > > File "", line 1, in ? > > File "", line 4, in add > >UnboundLocalError: local variable 'b' referenced before assignment > > >Anyhow, it doesn't work, but you can see how closely it resembles > >a class definition. > > Use the outfix closure operator, []: > > >>> def account(s): > ... b = [s] > ... def add(a): > ... b[0] += a > ... def balance(): > ... return b[0] > ... return add, balance > ... > >>> add, balance = account(100) > >>> add(5) > >>> balance() > 105 > >>> > > ;) > > Jean-Paul- Hide quoted text - > > - Show quoted text - Check out the Percent class I posted at http://www.programmingforums.org/forum/f43-python/t12461-arithmetic-by-percentage.html#post123290. It allows you to write code like: discount = Percent(20) origprice = 35.00 saleprice = origprice - discount -- Paul From bruno.42.desthuilliers at wtf.websiteburo.oops.com Wed Apr 11 03:09:48 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Wed, 11 Apr 2007 09:09:48 +0200 Subject: Does python have the static function member like C++ In-Reply-To: <1176273559.047449.263710@n76g2000hsh.googlegroups.com> References: <1176260903.362329.59370@o5g2000hsb.googlegroups.com> <1176261542.704649.240350@n76g2000hsh.googlegroups.com> <1176273559.047449.263710@n76g2000hsh.googlegroups.com> Message-ID: <461c895f$0$2128$426a74cc@news.free.fr> goodwolf a ?crit : (snip) > 1. In this case you will prefer a classmethod instead a staticmethod. > 2. If counter is the number of instances of class AAA then you will > incrase counter inside __init__ method. > > class AAA (object): > counter = 0 > def __init__(self): > type(self).counter_increase() You can call a class method on an instance: self.counter_increase() And FWIW, this is probably something I'd put in the constructor (the __new__ method), not in the initializer. > @classmethod > def counter_increase(cls): > cls.counter += 1 > > or > > class AAA (object): > counter = 0 > def __init__(self): > type(self).counter += 1 Instances have a reference to their class, so you can also write this: self.__class__.counter += 1 From martin at v.loewis.de Mon Apr 2 17:00:01 2007 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Mon, 02 Apr 2007 23:00:01 +0200 Subject: curses module In-Reply-To: References: Message-ID: <46116ED1.7030800@v.loewis.de> Kenneth McDonald schrieb: > I know that the curses module has a long-standing bug wherein cursor > visibility can't be set. > > This isn't criticism, I just know that the curses module is the sort of > thing that probably isn't being maintained consistently, and I for one, > have no idea how well all the new terms in common use maintain the sort > of backwards compatibility python curses will need to do its job. This isn't criticism either, but... if you know it has a long-standing bug, why didn't you submit a patch yet? If you had submitted one for Python 2.1 (say), the problem wouldn't be relevant today. If you submit one today, the problem won't be relevant for Python 2.8, or Python 3.0. Regards, Martin From kw at codebykevin.com Wed Apr 18 17:35:05 2007 From: kw at codebykevin.com (Kevin Walzer) Date: Wed, 18 Apr 2007 17:35:05 -0400 Subject: Do other Python GUI toolkits require this? Message-ID: From the introduction to PyObjC, the Python-Objective-C bridge on Mac OS X: "As described in Objective-C for PyObjC users the creation of Objective-C objects is a two-stage process. To initialize objects, first call a class method to allocate the memory (typically alloc), and then call an initializer (typically starts with init). Some classes have class methods which perform this behind the scenes, especially classes that create cached, immutable, or singleton instances." An example: myObject = NSObject.alloc().init() I know Tkinter doesn't require any manual memory allocation of this sort. Does wxPython, PyQt, PyGtk require anything like this when creating objects? -- Kevin Walzer Code by Kevin http://www.codebykevin.com From jeba.ride at gmail.com Thu Apr 19 14:28:03 2007 From: jeba.ride at gmail.com (Clement) Date: 19 Apr 2007 11:28:03 -0700 Subject: Creating search engine in Python Good or Bad [in performance] Message-ID: <1177007283.157437.271230@n76g2000hsh.googlegroups.com> I am now creating IR engine in python which has its own database implementation . For nearly 2GB files it works fast. Can i expect the same speed when my database goes large. Else i have to chose other language[c/c++] for the speed............. Please tell me the solution................................ From dorait at gmail.com Sun Apr 15 10:37:01 2007 From: dorait at gmail.com (Dorai) Date: 15 Apr 2007 07:37:01 -0700 Subject: Getting started with python In-Reply-To: <2enUh.4325$H_5.3894@newssvr23.news.prodigy.net> References: <1176598011.463543.96990@q75g2000hsh.googlegroups.com> <2enUh.4325$H_5.3894@newssvr23.news.prodigy.net> Message-ID: <1176647821.059693.78880@n76g2000hsh.googlegroups.com> On Apr 15, 3:35 am, James Stroud wrote: > Eric wrote: > > Hello, after reading some of the book Programming Python it seems that > > python is something I would like to delve deeper into. The only thing > > is, I have no idea what I should try and write. So I was hoping that > > someone here could help point me to a group/project that would be a > > good starting place for a person with limited python knowledge, but > > that is willing to learn whatever is necessary. I'm hoping that with a > > goal I can start to learn python instead of just playing around with > > it. Thanks. > > Here is a protocol I have used in the past: > > 1. Realize there is a program you really wish you had. > 2. Find out that, upon relentless googling, no > such program exists that meets your needs exactly. > 3. If 2 fails and a program exist s, go back to 1. > 4. Proceed to write this program no matter what it takes--you > may even face some "sitdowns" with your friends, family, > and/or employers. > 5. (Very important) > A. Refer to this list periodically for help but making > sure to properly phrase you questions. > B. Try not to rewrite any libraries by first ascertaining > whether a library doesn't already exist for the > sub-task you are programming. > 6. Enjoy the new program you have written and the new > knowledge you have gained. > > James Start out with something simple and go deeper. For example, here is one progression: 1. A simple program that counts words (wc) - read from a file, tokenize, count 2. A variation of wc that does word frequency count (counts how many times each word occurs) - wfc - In addition to 1, this allows you to use a data structure to store words and search for them to update the count. You may also sort the output. 3. A variation of wfc that reads from a file a set of noise words and stores them in memory. As you are tokenizing, drop the noise words from counting (or count noise words) You could do similar things with database programming (start with something simple and gradually increase the level of complexity or any other area. You can also access Python cookbook, use the examples as a starting point and build variations. This not only allows you to read some well written code but also understand various techniques. Another suggestion is to get hold of a book "Software Tools" and try to code all the examples in Python. I found the best way to learn a language is to read some code, write some code and keep improving it. Many improvements will suggest themselves as you keep coding. Hope this helps. Dorai www.thodla.com From bbxx789_05ss at yahoo.com Wed Apr 11 21:01:50 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: 11 Apr 2007 18:01:50 -0700 Subject: Nested dictionaries trouble In-Reply-To: <461d427e$0$18058$426a74cc@news.free.fr> References: <1176317876.917874.58040@n59g2000hsh.googlegroups.com> <461d427e$0$18058$426a74cc@news.free.fr> Message-ID: <1176339709.998807.32990@e65g2000hsc.googlegroups.com> On Apr 11, 2:57 pm, Bruno Desthuilliers wrote: > IamIan a ?crit : > > yearTotals = dict([(year, dict.fromkeys(months, 0)) for year in years]) > > HTH List comprehensions without a list? What? Where? How? From tjreedy at udel.edu Wed Apr 4 13:34:52 2007 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 4 Apr 2007 13:34:52 -0400 Subject: Indentifying the LAST occurrence of an item in a list References: <1175702329.330032.250750@w1g2000hsg.googlegroups.com> <1175707250.349825.223470@p77g2000hsh.googlegroups.com> Message-ID: "7stud" wrote in message news:1175707250.349825.223470 at p77g2000hsh.googlegroups.com... | How about: | | l = [1, 2, 1, 3, 1, 5] | target = 1 | for index, val in enumerate(l): | if val==1: | lastIndexOf = index | | print lastIndexOf You might want to initialize lastIndexOf (to None, for instance). If len(l) = 1000000, you might prefer to start from the end, as I suggested. tjr From duncan.booth at invalid.invalid Mon Apr 9 10:32:24 2007 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 9 Apr 2007 14:32:24 GMT Subject: how to use the string '\\.\' References: <1176117103.670611.291740@n59g2000hsh.googlegroups.com> Message-ID: "Gabriel Genellina" wrote: > En Mon, 09 Apr 2007 08:21:44 -0300, Duncan Booth > escribi?: > >> wrote: >> >>> print r'\\.\' >> >> See the FAQ: >> http://www.python.org/doc/faq/general/#why-can-t-raw-strings-r-strings >> -end-with-a-backslash > > This form is not included in the FAQ alternatives (should it?): > > print r'\\.' '\\' > > Yes it is. It is just the first of the FAQ suggestions using single quotes instead of double quotes. If you wanted to add another one then I would go for: os.path.normpath("/this/is/my/dos/dir") although it doesn't work with the particular example in question here. From robert.rawlins at thinkbluemedia.co.uk Fri Apr 13 11:57:12 2007 From: robert.rawlins at thinkbluemedia.co.uk (Robert Rawlins - Think Blue) Date: Fri, 13 Apr 2007 16:57:12 +0100 Subject: Class Dependancy Injection Message-ID: <000501c77de4$66b51f30$341f5d90$@rawlins@thinkbluemedia.co.uk> Hey again guys, I'm looking to get an answer about dependency injection in python classes, what is the best way to deal with this? For instance, in my application I have a configuration bean which contains all the applications configuration information. Now in one of other classes I need access to those configuration settings. What I would have done in my ColdFusion/JAVA type applications is create an instance of the configuration bean, and then pass that in as an argument to the constructor for my other class, then have the other class set that as a 'self' variable. Then from within my class I can access the configuration details like self.config.getName() and it would return the name of the application. How is this best handled in python, can I still inject dependencies as a constructor argument like that? If so then is there anything in particular I need to watch out for that may cause me trouble? Thanks, Rob -------------- next part -------------- An HTML attachment was scrubbed... URL: From mangabasi at gmail.com Wed Apr 4 18:40:27 2007 From: mangabasi at gmail.com (Mangabasi) Date: 4 Apr 2007 15:40:27 -0700 Subject: Calling Fortran from Python In-Reply-To: References: <1175640339.648190.207530@y66g2000hsf.googlegroups.com> <1175685841.847487.173440@w1g2000hsg.googlegroups.com> <1175718204.410453.29510@q75g2000hsh.googlegroups.com> Message-ID: <1175726427.114890.7990@y80g2000hsf.googlegroups.com> On Apr 4, 4:39 pm, Robert Kern wrote: > Mangabasi wrote: > > I am using Visual Studio 6.0 and Compaq Visual Fortran 6.6. > > Ah. You can't use VS6 with that version of Python. I believe you need the .NET > SDK 2003. > > You could also use gcc, but I'm not sure if that will work well with Compaq > Visual Fortran; you might have to use gfortran. > > http://www.develer.com/oss/GccWinBinaries > > -- > 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 Would Python 2.5 work with Visual Studio 6.6? From joel.granados at gmail.com Fri Apr 6 07:12:23 2007 From: joel.granados at gmail.com (Joel Andres Granados) Date: Fri, 06 Apr 2007 13:12:23 +0200 Subject: Comments in ConfigParser module Message-ID: <46162B17.8080204@gmail.com> Hi list: I have run across a situation with ConfigParser Module. It refers to the comments in the configuration filed. According to the http://docs.python.org/dev/lib/module-ConfigParser.html it states that lines starting with "#" and ";" are ignored. So lines like: ; comment # comment are considered comments. So far so good. The module also allows the comments to appear in the same line as the "name = value" constructs. The only difference being that this is only possible with ";" and not with "#" character. I did not see this in the documentation but this is how it is behaving. So while the following line takes the comment as a comment. *name = value ; comment* the next line does not result in the same behavior. *name = value # comment* the name element would have "value # comment" as its value, when what I really want is for "comment" to be taken as a comment. QUESTION...So the question is: Can you use "#" and ";" as comment characters? and if so why does the "#" not apply for the same situations as the ";"? I'm working with fc7 (I synced it sometime last week) and python 2.5 (r25:51908, Feb 13 2007, 09:13:20) Any comment greatly appreciated.... Just for reference: On the RFC 822 (a document referenced in the documentation) there is a mention of ";" being used as comment character but not necessarily at the beginning of the line. So anything that comes after the ";" is ignored. name = value ; comment (";comment" would be ignored) From nospam at nospam.com Sat Apr 21 18:13:29 2007 From: nospam at nospam.com (Gilles Ganault) Date: Sun, 22 Apr 2007 00:13:29 +0200 Subject: Building browser-like GET request References: <1177192075.699770.304600@d57g2000hsg.googlegroups.com> Message-ID: On 21 Apr 2007 14:47:55 -0700, Bj?rn Keil wrote: >Well, I am brand new to Python, so it takes me a lot of guessing, but >since it seems you're using urlib2: Thanks. Indeed, it looks like urlib2 is the way to go when going through a proxy. For those interested, here's how to download a page through a proxy: ---------------------------- import sys import urllib import urllib2 import re #set up proxy proxy_info = { 'host' : 'localhost','port' : 8080} proxy_support = urllib2.ProxyHandler({"http" : "http://%(host)s:%(port)d" % proxy_info}) opener = urllib2.build_opener(proxy_support) urllib2.install_opener(opener) #call page with specific headers url = 'http://www.acme.com/cgi-bin/read?code=123' headers = { 'User-Agent' : 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)', 'Accept' : 'text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5', 'Accept-Language' : 'fr-fr,en-us;q=0.7,en;q=0.3', 'Accept-Charset' : 'ISO-8859-1,utf-8;q=0.7,*;q=0.7' } #None = GET; set values to use POST req = urllib2.Request(url, None, headers) response = urllib2.urlopen(req).read() log = open('output.html','w') log.write(response) log.close() ---------------------------- Thanks. From victor.lebrun at gmail.com Sat Apr 28 16:15:46 2007 From: victor.lebrun at gmail.com (vml) Date: 28 Apr 2007 13:15:46 -0700 Subject: how to serialize a COM object ? In-Reply-To: <1%uXh.23478$M.19517@news-server.bigpond.net.au> References: <1177445437.543694.49070@r3g2000prh.googlegroups.com> <1%uXh.23478$M.19517@news-server.bigpond.net.au> Message-ID: <1177791346.249777.145760@n76g2000hsh.googlegroups.com> On 24 avr, 23:53, Neil Hodgson wrote: > vmlwrote: > > I have a COM object. > > > I would like to pass this com object from a server to a client through > > a socket. > > As Diez mentioned, this may be possible through Distributed COM > (DCOM). Its not very popular any more with techniques such as SOAP being > more widely implemented. DCOM is fiddly to set up particularly the > security aspects. IIRC I did get it to work with Python but that was > maybe 8 years ago. Here's an overview of DCOM: > > http://msdn2.microsoft.com/en-us/library/ms809311.aspx > > Neil Thank you for your answers, I think that a DCOM application ... From bdesth.quelquechose at free.quelquepart.fr Thu Apr 5 16:28:32 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Thu, 05 Apr 2007 22:28:32 +0200 Subject: Looping issues In-Reply-To: <1175796069.501575.157410@w1g2000hsg.googlegroups.com> References: <1175796069.501575.157410@w1g2000hsg.googlegroups.com> Message-ID: <461552fb$0$8083$426a74cc@news.free.fr> brochu121 at gmail.com a ?crit : > What I am trying to do is compare two files to each other. > > If the 2nd file contains the same line the first file contains, I want > to print it. I wrote up the following code: > > > > correct_settings = open("C:\Python25\Scripts\Output > \correct_settings.txt","r") > current_settings = open("C:\Python25\Scripts\Output\output.txt","r") > > for line in correct_settings: > for val in current_settings: > if val == line: > print line + " found." > > > correct_settings.close() > current_settings.close() > > > For some reason this only looks at the first line of the > correct_settings.txt file. Not quite. It really go thru the whole file. But it only enter the inner loop for the first line. Then the file iterator is exhausted, and the other iterations are noop. You can verify this by adding a couple print statements - one in the outer loop and one in the inner one. > Any ideas as to how i can loop through each > line of the correct_settings file instead of just looking at the first? > The good question is "how to loop thru the lines of *current_*settings for each line of correct_settings". The answer is : don't use the file iterator here, read the whole file in memory. Cf Larry's post for a howto. From genkuro at gmail.com Wed Apr 18 12:34:56 2007 From: genkuro at gmail.com (genkuro at gmail.com) Date: 18 Apr 2007 09:34:56 -0700 Subject: Newbie: import Message-ID: <1176914096.493758.77120@o5g2000hsb.googlegroups.com> I thought import used relative paths from either the python executable or the script being executed. I have a script pulling in code from an arbitrary directory. How is this happening? It's a RHEL 4 environment by the way. I couldn't find any relevant environment variables. Thanks from a newbie for any insight. From exarkun at divmod.com Tue Apr 10 11:41:36 2007 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Tue, 10 Apr 2007 11:41:36 -0400 Subject: installing pyqt4 on ubuntu 6.06 In-Reply-To: <80628d680704100835y302a575bqe4dd126879f67ec3@mail.gmail.com> Message-ID: <20070410154136.18920.2019160505.divmod.quotient.10073@ohm> On Tue, 10 Apr 2007 21:05:37 +0530, Pradnyesh Sawant wrote: >Hello, >I have a newly installed ubuntu 6.06 system. I am trying to install >pyqt4 on it, but without success. The contents of the >/etc/apt/sources.list file are: >******************************************************************************** >deb http://in.archive.ubuntu.com/ubuntu/ dapper main restricted universe >deb http://in.archive.ubuntu.com/ubuntu/ dapper-backports main >restricted universe multiverse >deb http://security.ubuntu.com/ubuntu dapper-security main universe >deb http://in.archive.ubuntu.com/ubuntu/ dapper-updates main restricted >******************************************************************************** >I've tried installing everything related to python2.4 and qt4, >including sip, pyqt-tools, etc. However, on running a pyqt script, it >gives me the following error: >******************************************************************************** >Traceback (most recent call last): > File "findFiles.py", line 16, in ? > from PyQt4 import QtCore, QtGui >ImportError: No module named PyQt4 >******************************************************************************** > >Any pointers regarding what packages should i install to get the >system into working condition would be very helpful > >Thanks a lot Qt4 Python bindings aren't available in 6.06, afaik. I don't think they were even available at the time it was released. 6.10 has them, though. Jean-Paul From erikwickstrom at gmail.com Wed Apr 11 11:16:07 2007 From: erikwickstrom at gmail.com (erikcw) Date: 11 Apr 2007 08:16:07 -0700 Subject: UnicodeEncodeError - a bit out of my element... Message-ID: <1176304567.142673.69710@y5g2000hsa.googlegroups.com> Hi all, I'm trying to parse an email message, but am running into this exception. Traceback (most recent call last): File "wa.py", line 336, in ? main() File "wa.py", line 332, in main print out['msg'] UnicodeEncodeError: 'ascii' codec can't encode character u'\xd6' in position 238: ordinal not in range(128) How can I decode/encode this string to print to stdout and send again in another email? Do I have to know what language the email is in? Thanks! Erik From Leo.Kislov at gmail.com Sun Apr 8 07:09:05 2007 From: Leo.Kislov at gmail.com (Leo Kislov) Date: 8 Apr 2007 04:09:05 -0700 Subject: iterator interface for Queue? In-Reply-To: <7x64875py2.fsf@ruckus.brouhaha.com> References: <7x64875py2.fsf@ruckus.brouhaha.com> Message-ID: <1176030545.352887.71000@p77g2000hsh.googlegroups.com> On Apr 7, 11:40 pm, Paul Rubin wrote: > Is there any reason Queue shouldn't have an iterator interface? > I.e. instead of > > while True: > item = work_queue.get() > if item is quit_sentinel: > # put sentinel back so other readers can find it > work_queue.put(quit_sentinel) > break > process(item) It's almost equal to: for item in iter(work_queue.get, quit_sentinel): process(item) except that it doesn't keep the quit sentinel in the queue. But that's a personal preference, I usually put as many quit sentinels in a queue as many consumers. -- Leo From ericcoetzee at gmail.com Sun Apr 1 19:50:35 2007 From: ericcoetzee at gmail.com (eC) Date: 1 Apr 2007 16:50:35 -0700 Subject: How can i compare a string which is non null and empty In-Reply-To: <1175469766.979636.65020@e65g2000hsc.googlegroups.com> References: <1175469766.979636.65020@e65g2000hsc.googlegroups.com> Message-ID: <1175471435.593058.84200@n76g2000hsh.googlegroups.com> On Apr 2, 12:22 am, "Plisske... at gmail.com" wrote: > Hi, > > how can i compare a string which is non null and empty? > > i look thru the string methods here, but cant find one which does it? > > http://docs.python.org/lib/string-methods.html#string-methods > > In java,I do this: > if (str != null) && (!str.equals("")) .... > > how can i do that in python? The closest to null in python is None. Do you initialise the string to have a value of None? eg myStr = None if so, you can test with if myStr == None: dosomething... But you might find that you do not need to use None - just initialise the string as empty eg myStr = '' and then test for if myStr != '': or even simpler if myStr: dosomething btw. dont use 'str' - its a built in function of python From aleax at mac.com Wed Apr 18 10:50:46 2007 From: aleax at mac.com (Alex Martelli) Date: Wed, 18 Apr 2007 07:50:46 -0700 Subject: What makes an iterator an iterator? References: Message-ID: <1hwr9pv.13v4ci6106qn0aN%aleax@mac.com> Steven D'Aprano wrote: > I thought that an iterator was any object that follows the iterator > protocol, that is, it has a next() method and an __iter__() method. The special methods need to be on the type -- having attributes of those names on the instance doesn't help (applies to all special methods in the normal, aka newstyle, object model; legacy, aka classic, classes, work by slightly different and not entirely self-consistent semantics). Alex From mike.terrell at earthlink.net Sat Apr 28 13:30:05 2007 From: mike.terrell at earthlink.net (Michael A. Terrell) Date: Sat, 28 Apr 2007 17:30:05 GMT Subject: Video: Professor of Physics Phd at Cal Tech says: 911 Inside Job References: <1177467203.719625.93920@u32g2000prd.googlegroups.com> <1177780530.539758.275660@c35g2000hsg.googlegroups.com> Message-ID: <463384BB.26142112@earthlink.net> Eric Gisse wrote: > > On Apr 24, 6:13 pm, stj... at rock.com wrote: > > Cal Tech is the ELITE of ELITE in physics. > > "INN World Report interviewed Dr. Crockett Grabbe - professor of > physics at the University of Iowa - regarding his thoughts on the > 'collapses' of WTC1, WTC2, & WTC7. In this interview he lists numerous > reasons to suspect controlled demolition and expresses support for > alternative theories." > > A common mistake - I frequently confuse CalTech and U of Iowa. > > http://scholar.google.com/scholar?hl=en&lr=&safe=off&client=firefox-a&q=crockett+grabbe+author%3Ac-grabbe+iowa&btnG=Search > > That's interesting, no publications on any engineering topic. A > professor of physics, not engineering, who claims that explosives were > planted in not only WTC7, but WTC 1 and 2 which were trigged by the > planes impacting the building. > > Why is anyone listening to this loon? The same reason they listen to the even loonier Rosie O'donell? http://www.popularmechanics.com/blogs/911myths/4213805.html -- Service to my country? Been there, Done that, and I've got my DD214 to prove it. Member of DAV #85. Michael A. Terrell Central Florida From rschroev_nospam_ml at fastmail.fm Fri Apr 20 09:46:26 2007 From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven) Date: Fri, 20 Apr 2007 13:46:26 GMT Subject: Do other Python GUI toolkits require this? (OT) In-Reply-To: References: <462697A6.6010007@codebykevin.com> <465B30B4-5BA0-459A-BE6F-1038874FA74B@jedimindworks.com> Message-ID: Hendrik van Rooyen schreef: > "Steve Holden" wrote: > > >> Perhaps in Belgium they prefer climbing mountains over walking up and >> down gentle hills? > > Mountains ? Hills ? In Belgium ?? > > Its not called the battlefield of Europe for nothing... I'm not sure if this adds anything of interest (well actually I'm pretty sure it doesn't), but our king Albert I was a fanatic mountain climber, until he died from a fall in 1934. -- If I have been able to see further, it was only because I stood on the shoulders of giants. -- Isaac Newton Roel Schroeven From max at alcyone.com Sun Apr 22 17:13:10 2007 From: max at alcyone.com (Erik Max Francis) Date: Sun, 22 Apr 2007 14:13:10 -0700 Subject: Bug in select In-Reply-To: References: Message-ID: <1aGdndBf1ON7UrbbnZ2dnUVZ_hjinZ2d@speakeasy.net> Ron Garret wrote: > So this is clearly a bug, but surely I'm not the first person to have > encountered this? Is there a known workaround? It's hard to see how this demonstrates a bug in anything, since you're telnetting to the wrong port in your example. -- 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 Being in love for real / It ain't like a movie screen -- India Arie From bbxx789_05ss at yahoo.com Fri Apr 13 05:01:11 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: 13 Apr 2007 02:01:11 -0700 Subject: reading from sys.stdin In-Reply-To: <1176438754.995753.50190@d57g2000hsg.googlegroups.com> References: <1176366058.261031.111870@p77g2000hsh.googlegroups.com> <1176387908.406115.270630@w1g2000hsg.googlegroups.com> <1176438754.995753.50190@d57g2000hsg.googlegroups.com> Message-ID: <1176454871.538968.176620@n76g2000hsh.googlegroups.com> Hi, Thanks for the responses. My book, Beginning Python: From Novice to Professional(p. 266) says that "sys.stdin is iterable, just like other files", so I thought I would test it out. However, I don't see how it is acting similar to a file in my example. I assume all input is buffered by default, so I'm not sure how it explains things to say that input from sys.stdin is buffered. > I typed many lines, but lst contains only one item, as expected. Same as > your regular file example: the file contains many lines, but only the > first goes into the list. Interesting example--not as I expected! But there is a difference in the two examples isn't there? When you iterate over a file, the whole file isn't put into an internal buffer first, is it? > I don't know if this a python or OS thing, but I know that iterating over a > file is not like applying successive call to readline method. You should try > to use readline instead. I've wondered what the differences were. Thanks for bringing that up. I searched around on google, and PEP 234 has this to say about that: ------------------------------------ - Files implement a tp_iter slot that is equivalent to iter(f.readline, ""). This means that we can write for line in file: ... as a shorthand for for line in iter(file.readline, ""): ... which is equivalent to, but faster than while 1: line = file.readline() if not line: break ... ... Because the file iterator uses an internal buffer, mixing this with other file operations (e.g. file.readline()) doesn't work right. Also, the following code: for line in file: if line == "\n": break for line in file: print line, doesn't work as you might expect, because the iterator created by the second for-loop doesn't take the buffer read-ahead by the first for-loop into account. A correct way to write this is: it = iter(file) for line in it: if line == "\n": break for line in it: print line, -------------------------------------------- > You may want to look at a related issue: > http://www.python.org/sf/1633941 Bad link. >This should be f = iter(raw_input,"") and this will end in a EOFError >and stop on blank line. So you need a wrapper Why a wrapper? This example seems to work without error: lst = [] f = iter(raw_input, "") for line in f: lst.append(line) print lst From buzzard at urubu.freeserve.co.uk Mon Apr 23 23:03:12 2007 From: buzzard at urubu.freeserve.co.uk (Duncan Smith) Date: Tue, 24 Apr 2007 04:03:12 +0100 Subject: numpy migration (also posted to numpy-discussion) In-Reply-To: References: Message-ID: Travis E. Oliphant wrote: > Duncan Smith wrote: > >> Hello, >> Since moving to numpy I've had a few problems with my existing >> code. It basically revolves around the numpy scalar types. e.g. >> > > You will probably get more help on the numpy discussion list: > > numpy-discussion at scipy.org > > > You are encountering problems because numpy scalar types don't raise > errors (unless you have set the appropriate hardware flag using > numpy.seterr). > Aha! > You can get Python scalars out of NumPy arrays if you really want them > using (for example...) > > a.item(0,0) > > >> >> An additional problem involves classes that have e.g. __rmul__ methods >> defined and are sufficiently similar to numpy arrays that my classes' >> __rmul__ methods are not invoked when using numpy scalars. >> > > Could you please post an example showing the problem? > I'll try to post a minimal example tomorrow. But they are classes that have an ndarray as an attribute, and with __getitem__ and __setitem__ methods which simply call the corresponding array methods. Maybe that's enough to account for the behaviour? I'll check tomorrow. >> >> I might (I hope) be missing something obvious; but it seems like, to be >> safe, I'm going to have to do a lot of explicit conversions to Python >> types (or abandon catching zero division errors, and documenting some of >> my classes to highlight that whether scalar * a equals a * scalar >> depends on whether a.__rmul__ is called, which depends on the type of >> scalar). >> > > numpy scalars are try a lot more things before giving up on > multiplication and letting the other class have a stab at it. > > Post your problems to the numpy discussion list for better help and more > discussion. > Yes, I have done. But it's awaiting moderation; presumably because I posted using a different e-mail address than the one I registered with (I wasn't thinking). Thanks for the reply. Duncan From andy.rockford at gmail.com Sun Apr 29 21:26:24 2007 From: andy.rockford at gmail.com (Andy) Date: 29 Apr 2007 18:26:24 -0700 Subject: Counting In-Reply-To: References: <1177873864.502180.283390@u30g2000hsc.googlegroups.com> <1177877775.780666.222080@p77g2000hsh.googlegroups.com> Message-ID: <1177896384.857746.322860@n59g2000hsh.googlegroups.com> James - I pretty doubt about this - "c = line.count(k)" You might wanna recheck on that. ------------------------------------------------ I think it would be obvious how to write this: for i,line in enumerate(linelist): line = line.split() for k in line: if keyword.iskeyword(k): c = line.count(k) total += line.count(k) print "Line #%d has %d keywords." % (i+1, c) break print "Total keyords are: %d" % total > > I think it would be obvious how to write this: > > for i,line in enumerate(linelist): > line = line.split() > for k in line: > if keyword.iskeyword(k): > c = line.count(k) > total += line.count(k) > print "Line #%d has %d keywords." % (i+1, c) > break > > print "Total keyords are: %d" % total From mmanns at gmx.de Thu Apr 5 16:38:45 2007 From: mmanns at gmx.de (Martin Manns) Date: Thu, 5 Apr 2007 16:38:45 -0400 Subject: grandparent method with super References: <20070405161939.694d51a1@localhost> Message-ID: <20070405163845.2ffa8d32@localhost> On Thu, 5 Apr 2007 16:33:37 -0400 "John Clark" wrote: > Pretty sure you can do this: > > class A(object): > def m(self): > class B(A): > def m(self): > class C(A): > def m(self): > class D(B,C): > def m(self): > A.m(self) > > I don't think you want to try to use super() in this case. That works, but when I replace A with something else, I do not get the grandparent anymore without changing all the method calls. Basically, I would like to call the method m in the first grandparent of D. Martin From frankatle at gmail.com Thu Apr 5 10:41:32 2007 From: frankatle at gmail.com (frankatle at gmail.com) Date: 5 Apr 2007 07:41:32 -0700 Subject: snippet manager idea Message-ID: <1175784092.548831.17790@l77g2000hsb.googlegroups.com> Hi. I am writing a opensource code snippet manager in python (pyqt4). The idea is that users can upload their snippets to remote subversion server, (if they choose) and add comments to existing snippets, vote for snippet deletion, add flags to snippets: (tested, working, not working... etc) The snippets are stored locally in a sqlite3 database. So far i have a working application that use a small Soap client/ server to upload snippets to a remote server. The client sends a dict to the server, the server writes the dict as a text file and adds it to the svn server. On the client a local svn repo is downloaded and parsed into the database. The client Ui has syntaxhighlighting(only cplusplus and python at the moment), an "add snippet form", treewidget for snippet listing. My personal conserns are: individual snippet licensing I was wondering if anyone could comment on this idea. And perhaps come with some ideas. From attn.steven.kuo at gmail.com Thu Apr 5 17:17:25 2007 From: attn.steven.kuo at gmail.com (attn.steven.kuo at gmail.com) Date: 5 Apr 2007 14:17:25 -0700 Subject: elementary tuple question. (sorry) In-Reply-To: References: Message-ID: <1175807845.354056.95420@e65g2000hsc.googlegroups.com> On Apr 5, 2:08 pm, "Steven W. Orr" wrote: > I have a tuple that I got from struct.unpack. Now I want to pass the data > from the returned tuple to struct.pack > > >>> fmt > > 'l 10l 11i h 4h c 47c 0l'>>>struct.pack(fmt, tup) > > Traceback (most recent call last): > File "", line 1, in ? > struct.error: required argument is not an integer > > What's the idiom to pass the data in tup? > Try mystring = struct.pack(fmt, *tup) -- Hope this helps, Steven From michael at jedimindworks.com Tue Apr 24 08:14:29 2007 From: michael at jedimindworks.com (Michael Bentley) Date: Tue, 24 Apr 2007 07:14:29 -0500 Subject: Tutorial creates confusion about slices In-Reply-To: References: Message-ID: <5C53191E-20A3-40F7-B48D-13002E683643@jedimindworks.com> On Apr 24, 2007, at 6:35 AM, Antoon Pardon wrote: > On 2007-04-24, Michael Bentley wrote: >> >> On Apr 24, 2007, at 4:47 AM, Antoon Pardon wrote: >> >>> On 2007-04-24, Michael Bentley wrote: >>>> >>>> On Apr 24, 2007, at 1:39 AM, Antoon Pardon wrote: >>>> >>>>> I suspect that if you give this explanation to someone and explain >>>>> that there is also a step parameter, chances are he will answer >>>>> correctly if you ask him, what he thinks the following will result >>>>> in: >>>>> >>>>> >>>>> "This is an example line"[12:19:2] >>>>> >>>>> >>>>> >>>>> If you ask him what the following will result in: >>>>> >>>>> "This is an example line"[19:12:-1] >>>>> >>>>> Chances are he will give the wrong answer. >>>> >>>> To be honest, bro -- I'd expect him to have enough intelligence to >>>> experiment for a second and figure it out. This isn't rocket >>>> science >>>> -- you can plainly see what's happening -- so learn it and move >>>> on. >>> >>> I don't think that the possibility to experiment and see for oneself >>> is a good reason to keep a possible confusing explanation in a >>> tutorial. >> >> It's only potentially confusing if you already know more than has >> been presented and are in fact, *experimenting* with techniques that >> have yet to be presented. > > People don't read tutorials in a strictly linear fashion. They can > continue to later subjects and then come back here to see how things > tie together. So the fact that it is only confusing to those who > know more than is already presented doesn't seem a very good reason > to leave it in. Yet they understand that earlier in the document, there is likely to be a less complete coverage of a given topic. There is in fact, a link on that page that includes a more complete coverage of that topic (which I mentioned to you in an earlier message IIRC). > >>>> Or better yet, quietly submit a patch... >>> >>> Why should I? If the reactions would have been one of agreement that >>> this is confusing and that the explanation should be changed, I >>> would >>> have considered submitting a patch. >>> >>> But most people that reacted seem to defend the current text in some >>> way or another. So if most people seem to feel there is no need for >>> a change why should I then submit a patch? >> >> ... or even continue the thread? > > It is always interresting to see how far people are willing to go to > defend the status quo. > > I bet that if the tutorial was written now, given the possible > confusion, nobody would defend including this section. But now > that it already is in the tutorial it suddenly is worth defending. Submit a patch if you want it changed. I'm sure your valuable insights will greatly improve the quality of the python documentation. From linus at fixedstars.com.au Sat Apr 28 06:19:39 2007 From: linus at fixedstars.com.au (Linus Cohen) Date: 28 Apr 2007 03:19:39 -0700 Subject: Beginner Ping program In-Reply-To: References: <1177739647.737759.32610@u30g2000hsc.googlegroups.com> Message-ID: <1177755579.454423.35590@n59g2000hsh.googlegroups.com> Actually the class ping bit is a placeholder. I'm actually developing a module with python implementations of most standard network/internet tools such as telnet, tracert, whois etc. It will be called inettools, and the ping function is what I'm working on first. It should be a simple enough job to code in the features the Unix and DOS ping programs have(never stop, change size, change timeout). As I am typing this, I'm looking through ping.c to see what I can glean. It probably won't be much. My experience with C is very little. As in, microscopic. Pretty much all the coding I've done up till now has been shell scripting. Cheers, Linus From kw at codebykevin.com Sat Apr 21 11:45:34 2007 From: kw at codebykevin.com (Kevin Walzer) Date: Sat, 21 Apr 2007 11:45:34 -0400 Subject: How To Find Currently Selected Tile.Notebook Tab? In-Reply-To: <1177098709.188440.103610@e65g2000hsc.googlegroups.com> References: <1177035392.983733.68240@n76g2000hsh.googlegroups.com> <315d0$46282bdf$4275d90a$28375@FUSE.NET> <1177098709.188440.103610@e65g2000hsc.googlegroups.com> Message-ID: bcwhite at pobox.com wrote: >>> How can I determine what tab is currently selected in a Tile.Notebook >>> widget? >>> The best suggestion I've been able to find via Google is >>> "mynotebook.index('current')", but that gets an exception from Tcl. >> How about >> >> mynotebook.index.current() > > No good: AttributeError: 'function' object has no attribute 'current' > > I tried "mynotebook.index().current()", too, but get a different > error. > > -- Brian > Not sure what the problem is then--perhaps that function hasn't been mapped into Tkinter. I don't use that feature myself. -- Kevin Walzer Code by Kevin http://www.codebykevin.com From ask at me Wed Apr 4 22:42:11 2007 From: ask at me (alf) Date: Wed, 04 Apr 2007 21:42:11 -0500 Subject: compiling modules with VS 2008 for python 2.4 prepared with Visual Studio 2003 Message-ID: Hi, I want to add some library but it can not be comipled? Here is an output: D:\>cl Microsoft (R) 32-bit C/C++ Optimizing Compiler Version 14.00.50727.42 for 80x86 Copyright (C) Microsoft Corporation. All rights reserved. usage: cl [ option... ] filename... [ /link linkoption... ] D:\> python setup.py install running install running build running build_ext error: Python was built with Visual Studio 2003; extensions must be built with a compiler than can generate compatible binaries. Visual Studio 2003 was not found on this system. If you have Cygwin installed, you can try compiling with MingW32, by passing "-c mingw32" to setup.py. Thx for the help, Andy From kushal.kumaran at gmail.com Thu Apr 12 01:33:15 2007 From: kushal.kumaran at gmail.com (Kushal Kumaran) Date: 11 Apr 2007 22:33:15 -0700 Subject: [OT] Deferred jobs server as backend for web application In-Reply-To: <1176341059.609525.140800@l77g2000hsb.googlegroups.com> References: <1176341059.609525.140800@l77g2000hsb.googlegroups.com> Message-ID: <1176355995.280917.322320@b75g2000hsg.googlegroups.com> On Apr 12, 6:24 am, "Sean Davis" wrote: > In the past, I have put together web applications that process tasks > serially, either with short algorithms to manipulate user-submitted > data or to return database queries. However, now I am faced with the > task of having a long-running process being started by a web > submission. I want to process an uploaded file. One way to do this > is to simply start a process each time someone submits a job and then > email when complete. Instead, I would like to have a way of > submitting the job to a persistent backend queue that can process the > job and answer queries about the status of the job (if it is still > running) or return results. I have looked at threadpool, which seems > fine if I a want to submit jobs from a single process (such as a Qt > application, etc), but it won't work directly for a web platform where > I will likely have multiple threads/processes handling http requests. > Any suggestions on how to go about this? > > Thanks, > Sean I recently discovered this: http://vicerveza.homeunix.net/~viric/soft/ts/ Might be what you need. -- Kushal From anton.vredegoor at gmail.com Wed Apr 25 14:08:27 2007 From: anton.vredegoor at gmail.com (Anton Vredegoor) Date: Wed, 25 Apr 2007 20:08:27 +0200 Subject: Would You Write Python Articles or Screencasts for Money? In-Reply-To: References: <462DCCE6.9060908@taupro.com> <1hx2dvj.10ek1v51noh1otN%aleax@mac.com> Message-ID: Steve Holden wrote: > I'm sorry, but while the PSF is a democratically-run organization its > franchise doesn't extend beyond the membership. I didn't realize this was about an PSF internal affair. Of course a group of people can decide on its internal matters without asking anyone else, as long as its actions do not damage the larger community around it. I'm sorry to have interfered with your private discussions, they took place on an international newsgroup aimed at the global python community at large, you might consider taking it elsewhere, but since there is no moderation, go and spam this group with your posts as much as you like. > You might as well suggest that America isn't being democratic because it > doesn't allow the French to vote for its president. Neither France nor America strike me as being very democratic at the moment, because large parts of their communities have no way of voting on a person or party that represents their specific interests. It's the same way in the Netherlands where I live by he way, so no criticism is intended by me, in any way. I was picturing this thread more in terms like the international court which at least constitutionally *tries* to be democratic in a global community alike manner, albeit unfortunately also failing miserably. It seems current western democracies are preferable over the total chaos that we see in Iraq because its internal legal structure was removed without providing a functional alternative. History shows -to me- that even an evil dictator is better than that. That doesn't mean people shouldn't try to aim higher. Higher than accepting even a benevolent dictator. So in my case the question becomes if I would be willing to promote the interests of some group that doesn't represent me, for a chance that I may comply with their objectives, which I cannot influence. I'd say: No I don't want to do that, although I also wouldn't go out of my way in order to *not* comply. Thanks for clearing it all up. Have a nice life. A. From gagsl-py2 at yahoo.com.ar Mon Apr 23 12:03:42 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 23 Apr 2007 13:03:42 -0300 Subject: When are immutable tuples *essential*? Why can't you just use lists *everywhere* instead? References: <1177088796.622928.224890@d57g2000hsg.googlegroups.com> <1177089206.550423.288670@q75g2000hsh.googlegroups.com> <58sf33F2b1q8tU1@mid.individual.net> <1177103370.022138.110320@n59g2000hsh.googlegroups.com> <1177108560.660288.171890@n76g2000hsh.googlegroups.com> Message-ID: En Mon, 23 Apr 2007 12:46:13 -0300, Neil Cerutti escribi?: > On 2007-04-23, Chris Cioffi wrote: >> On 23 Apr 2007 17:19:15 +0200, Neil Cerutti >> wrote: >>> So the question becomes: Why do Python dictionaries require >>> keys to be of an immutable type? >> >> Or: Because. ;-) > > Heh, heh. I was wondering, if we dig deep enough, wether we'll > end up back at, "just an optimization," as the reason. Fortran guys could make programs for a long time having arrays as their ONLY structured type, so having a built in dictionary is not just an optimization, it's a luxury! :) -- Gabriel Genellina From oliphant.travis at ieee.org Mon Apr 23 22:03:28 2007 From: oliphant.travis at ieee.org (Travis E. Oliphant) Date: Mon, 23 Apr 2007 20:03:28 -0600 Subject: numpy migration (also posted to numpy-discussion) In-Reply-To: References: Message-ID: Duncan Smith wrote: > Hello, > Since moving to numpy I've had a few problems with my existing > code. It basically revolves around the numpy scalar types. e.g. > You will probably get more help on the numpy discussion list: numpy-discussion at scipy.org You are encountering problems because numpy scalar types don't raise errors (unless you have set the appropriate hardware flag using numpy.seterr). You can get Python scalars out of NumPy arrays if you really want them using (for example...) a.item(0,0) > > An additional problem involves classes that have e.g. __rmul__ methods > defined and are sufficiently similar to numpy arrays that my classes' > __rmul__ methods are not invoked when using numpy scalars. > Could you please post an example showing the problem? > > I might (I hope) be missing something obvious; but it seems like, to be > safe, I'm going to have to do a lot of explicit conversions to Python > types (or abandon catching zero division errors, and documenting some of > my classes to highlight that whether scalar * a equals a * scalar > depends on whether a.__rmul__ is called, which depends on the type of > scalar). > numpy scalars are try a lot more things before giving up on multiplication and letting the other class have a stab at it. Post your problems to the numpy discussion list for better help and more discussion. -Travis From http Sun Apr 29 21:12:14 2007 From: http (Paul Rubin) Date: 29 Apr 2007 18:12:14 -0700 Subject: fastest way to find the intersection of n lists of sets References: <1177883328.835058.138990@p77g2000hsh.googlegroups.com> <1177889667.450984.88970@p77g2000hsh.googlegroups.com> <1177894116.018987.250930@c35g2000hsg.googlegroups.com> Message-ID: <7x7iru3btd.fsf@ruckus.brouhaha.com> Prateek writes: > The big set does stay around for a while - I've implemented an LRU > based caching algorithm on the code that does the I/O. Since the db is > transactioned, I keep one copy in the current transaction cache (which > is a simple dictionary) and one in the main read cache (LRU based) > (which obviously survives across transactions). Since the largest sets > also tend to be the most frequently used, this basically solves my I/O > caching issue. The best approach varies from instance to instance. Some big databases often will do stuff like statistically sample the sets from a given query, try a few different strategies on the samples in order to figure out which one works best on them, then use the apparent best strategy on the full sets. From richardjones at optushome.com.au Thu Apr 26 00:15:21 2007 From: richardjones at optushome.com.au (Richard Jones) Date: Thu, 26 Apr 2007 14:15:21 +1000 Subject: Another Python Game Programming Challenge concludes References: <462F7688.2020300@vpcit.ru> <462ffd86$0$5748$afc38c87@news.optusnet.com.au> Message-ID: <46302758$0$9771$afc38c87@news.optusnet.com.au> Richard Jones wrote: > Terry Reedy wrote: >> "???? ???" wrote in message >> news:462F7688.2020300 at vpcit.ru... >> | The fourth Python Game Programming Challenge (PyWeek) has now concluded >> | with >> | judges (PyWeek being peer-judged) declaring the winners: >> | >> | Individual: Which way is up? by Hectigo >> | http://www.pyweek.org/e/Hectic/ >> | >> | Team: Bubble Kong by The Olde Battleaxe >> | http://www.pyweek.org/e/toba4/ >> >> 404 Not found >> >> Ditto for links on rating page. > > Yeah, sorry, terribly bad timing means the site is being migrated to a new > host right at the moment. I hope to have it back up and running ASAP. Site is back now. Richard From mik3l3374 at gmail.com Wed Apr 4 05:16:09 2007 From: mik3l3374 at gmail.com (mik3l3374 at gmail.com) Date: 4 Apr 2007 02:16:09 -0700 Subject: how to remove multiple occurrences of a string within a list? In-Reply-To: <1175673563.212459.322290@y66g2000hsf.googlegroups.com> References: <1175624433.206953.214290@n59g2000hsh.googlegroups.com> <1175626905.957243.301870@w1g2000hsg.googlegroups.com> <1175637235.783612.45980@o5g2000hsb.googlegroups.com> <1175673563.212459.322290@y66g2000hsf.googlegroups.com> Message-ID: <1175678169.140276.161110@n59g2000hsh.googlegroups.com> 7stud wrote: > On Apr 3, 3:53 pm, "bahoo" wrote: > > > target = "0024" > > > l = ["0024", "haha", "0024"] > > > > > > > for index, val in enumerate(l): > > > if val==target: > > > del l[index] > > > > > print l > > > > This latter suggestion (with the for loop) seems to be buggy: if there > > are multiple items in the list "l" equal to "target", then only the > > first one will be removed! > > > > Thanks anyways. > > Prove it. here's something: >>> l = ["0024", "haha", "0024", "0024", "sfs"] >>> target = "0024" >>> for index, val in enumerate(l): ... print "index: " , index , "value: " , val ... del l[index] ... print "after del: " , l ... index: 0 value: 0024 after del: ['haha', '0024', '0024', 'sfs'] index: 1 value: 0024 after del: ['haha', '0024', 'sfs'] index: 2 value: sfs after del: ['haha', '0024'] >>> l ['haha', '0024'] From nitte.sudhir at gmail.com Wed Apr 4 03:31:51 2007 From: nitte.sudhir at gmail.com (kath) Date: 4 Apr 2007 00:31:51 -0700 Subject: how to build a forum? Message-ID: <1175671911.485478.137090@q75g2000hsh.googlegroups.com> Hi everybody, I am planning to build a web portal, which is mainly a discussion forum for our corporate environment. I want to implement it with Python. Because this project is very new to me and I have no idea about how to go about this. I searched in google for getting some tuts/ guidelines about this but ended up in getting tuts for building website. I would like to know some useful links to learn or some usefull guidelines. I would appreciate your help, Thanks in advance, kath. From Graham.Dumpleton at gmail.com Wed Apr 11 00:03:43 2007 From: Graham.Dumpleton at gmail.com (Graham Dumpleton) Date: 10 Apr 2007 21:03:43 -0700 Subject: How to get IP address of client from CGI module? In-Reply-To: References: Message-ID: <1176264223.846507.189200@q75g2000hsh.googlegroups.com> On Apr 11, 12:22 pm, John Nagle wrote: > The documentation for Python's CGI module doesn't seem to say how to get > the IP address of the client. Don't see an obvious way to get that info > from reading the source, either. Ideas? > > John Nagle Read the CGI RFC. http://www.ietf.org/rfc/rfc3875 Specifically section 4.1.8. This value should be supplied by way of variable in os.environ as are all the CGI variables. Graham From aboudouvas at panafonet.gr Tue Apr 10 15:29:36 2007 From: aboudouvas at panafonet.gr (king kikapu) Date: 10 Apr 2007 12:29:36 -0700 Subject: About Trolltech QT OpenSource license. Message-ID: <1176233376.712861.67160@o5g2000hsb.googlegroups.com> Hi to all, i am coming from the Microsoft (.net) world and at the quest of finding the right GUI toolkit that i can use from Python, i have two obvious choices to choose from: wxPython and Qt. Both are looking very good. Qt has Qt designer, a tool that really reminds me of the forms designers that we have in VS.Net.The productivity someone can gain from tools like these can be really astonished. I saw at the forum here that a lot of debate is coming from the "strange" interpretation of it's Open Source Edition lisence. After a lot of reading i was under the impression (and many others with me) that even a stand alone developer working in-house at company cannot use Qt OS Edition and must buy the commercial lisence. I sent an emai to them today and i think their response is interesting, so i appose it here; ##################################################### Thank you for your inquiry regarding the Qt Open Source Edition. The open source edition may be used for either your own private use or for an application used only internally by your company if the application is developed by you on company time. With internal company use under the GPL it is absolutely imperative that the application not be distributed outside of the legal entity. If this happens then the GPL source distribution requirements (as well as all other GPL requirements) will take effect. The internal use by the company falls under the "private modification" exception to the GPL. Please note that if you begin your application development with the GPL version, that application must be GPL licensed and Trolltech does not permit developers to start with the Qt Open Source Edition and later convert to a commercial license. Good luck with your development and please contact sales at trolltech.com if your company wishes to purchase a commercial Qt license at some point in the future. From ptmcg at austin.rr.com Mon Apr 16 08:25:54 2007 From: ptmcg at austin.rr.com (Paul McGuire) Date: 16 Apr 2007 05:25:54 -0700 Subject: pyparsing Catch-22 In-Reply-To: <1176712052.901344.36610@l77g2000hsb.googlegroups.com> References: <1176686782.270354.164630@l77g2000hsb.googlegroups.com> <1176696704.924584.75720@e65g2000hsc.googlegroups.com> <1176711506.989627.282880@o5g2000hsb.googlegroups.com> <1176712052.901344.36610@l77g2000hsb.googlegroups.com> Message-ID: <1176726354.351375.180460@p77g2000hsh.googlegroups.com> On Apr 16, 3:27 am, "7stud" wrote: > > Any tips? 7stud - Here is the modified code, followed by my comments. Oh, one general comment - you mention that you are quite facile with regexp's. pyparsing has a slightly different philosophy from that of regular expressions, especially in the areas of whitespace skipping and backtracking. pyparsing will automatically skip whitespace between parsing expressions, whereas regexp's require explicit '\s*' (unless you specify the magic "whitespace between elements allowed" attribute which I don't remember its magic attribute character at the moment, but I rarely see regexp examples use it). And pyparsing is purely a left-to-right recursive descent parser generator. It wont look ahead to the next element past a repetition operation to see when to stop repeating. There's an FAQ on this on the wiki. ------------------ from pyparsing import Word, alphas, commaSeparatedList, delimitedList, sglQuotedString, removeQuotes name = Word(alphas) lookFor = name + "=" + "[" + commaSeparatedList + "]" # comment #0 my_file = """\ mara = [ 'U2FsdGVkX185IX5PnFbzUYSKg+wMyYg9', 'U2FsdGVkX1+BCxltXVTQ2+mo83Si9oAV0sasmIGHVyk=', 'U2FsdGVkX18iUS8hYBXgyWctqpWPypVz6Fj49KYsB8s=' ]""" my_file = "".join(my_file.splitlines()) # uncomment next line once debugging of grammar is finished # my_file = open("aaa.txt").read() # comment #1 #~ my_file = open("aaa.txt") #~ for line in my_file: for line in [my_file,]: alist = lookFor.parseString(line) globals()[alist[0] ] = [ alist[3].strip("'"), alist[4].strip("'"), alist[5].strip("'") ] # comment #2 def stripSingleQuotes(s): return s.strip("'") globals()[alist[0] ] = map(stripSingleQuotes, alist[3:-1] ) print mara[2] mara = None # comment #3 lookFor = name.setResultsName("var") + "=" + "[" + \ commaSeparatedList.setResultsName("listValues") + "]" alist = lookFor.parseString(my_file) # evaluate parsed assignment globals()[ alist.var ] = map(stripSingleQuotes, alist.listValues ) print len(mara), mara[1] # comment #4 lookFor = name.setResultsName("var") + "=" + "[" + \ delimitedList( sglQuotedString.setParseAction(removeQuotes) )\ .setResultsName("listValues") + "]" alist = lookFor.parseString(my_file) globals()[ alist.var ] = list( alist.listValues ) print len(mara), mara[1] ------------------ Comment #0: When I am debugging a pyparsing application, I find it easier to embed the input text, or a subset of it, into the program itself using a triple-quoted string. Then later, I'll go back and change to reading data from an input file. Purely a matter of taste, but it simplifies posting to mailing lists and newsgroups. Comment #1: Since you are going line by line in reading the input file, be *sure* you have the complete assignment expression on each line. Since pyparsing will read past line breaks for you, and since your input file contains only this one assignment, you might be better off calling parseString with: alist = lookFor.parseString( my_file.read() ) Comment #2: Your assignment of the "mara" global is a bit clunky on two fronts: - the explicit accessing of elements 3,4, and 5 - the repeated calls to strip("'") You can access the pyparsing returned tokens (passed as a ParseResults object) using slices. In your case, you want the elements 3 through n-1, so alist[3:-1] will give you this. It's nice to avoid hard- coding things like list lengths and numbers of list elements. Note that you can also use len to find out the length of the list. As for calling strip("'") for each of these elements, have you learned to use Python's map built-in yet? Define a function or lambda that takes a single element, return from the function what you want done with that element, and then call map with that function, and the list you want to process. This modified version of your call is more resilient than the original. Comment #3: Personally, I am not keen on using too much explicit indexing into the returned results. This is another area where pyparsing goes beyond typical lexing and tokenizing. Just as you can assign names to fields in regexp's, pyparsing allows you to give names to elements within the parsed results. You can then access these by name, using either dict or object attribute syntax. This gets rid of most if not all of the magic numbers from your code, and makes it yet again more resilient in light of changes in the future. (Say for example you decided to suppress the "=", "[", and "]" punctuation from the parsed results. The parsing logic would remain the same, but the returned tokens would contain only the significant content, the variable name and list contents. Using explicit list indexing would force you to renumber the list elements you are extracting, but with results names, no change would be required.) Comment #4: I thought I'd show you an alternative to commaSeparatedList, called delimitedList. delimitedList is a method that gives you more control over the elements you expect to find within the list, and what to do with them when you find them. delimitedList is a constructor method that takes a pyparsing expression 'expr' and expands it to 'expr + ZeroOrMore(Suppress(",") + expr)'. You can also change the delimiter from ',' to some other character, or even to a pyparsing expression. Pyparsing includes predefined expressions for some common text patterns, such as single and double quoted strings, and comments of various forms. Look for a directory called htmldoc in your pyparsing directory tree, and open the index.html file there to look through the classes and methods defined for you in pyparsing. Or just type "help(pyparsing)" in the Python interpreter (after typing "import pyparsing" first, of course). Now that we have access to the expression defined to be matched within the list, we can attach a parse action. A parse action will get run against the matched tokens at parse time, and can be used to modify the matched data before continuing. In this example, we'd like to remove those annoying opening and closing quotation marks. Again, this is such a common task that pyparsing includes a built-in for this, called removeQuotes. It is equivalent to the following: removeQuotes = lambda tokens : tokens[0][1:-1] What?! No verifying that the first and last characters are in fact quotation marks? Nope. Another part of the pyparsing philosophy is that parse actions *know* that they will only be called with text that matches their associated input pattern. removeQuotes is a parse action that *knows* that the string passed to it will have opening and closing "'" or '"' characters. You'll also see this quite often when parsing integers: integer = Word(nums).setParseAction(lambda toks: int(toks[0])) No testing for "are the characters all numeric?" or trapping for ValueError. We *know* that the only time this lambda will be invoked is after having matched a word group composed only of numeric digits. Any way, to wrap up this comment, now that we have attached a parse action to remove the "'" characters as we parse, the listValues field is ready to use as is from the parseString method, without having to clutter our code up with maps, or lambdas, or other post-processing junk. Enjoy! -- Paul From paul at boddie.org.uk Thu Apr 5 14:04:01 2007 From: paul at boddie.org.uk (Paul Boddie) Date: 5 Apr 2007 11:04:01 -0700 Subject: AttributeError: 'tuple' object has no attribute 'encode' In-Reply-To: <1175793106.373420.39600@w1g2000hsg.googlegroups.com> References: <1175787095.862712.297480@n76g2000hsh.googlegroups.com> <1175791064.256896.240090@b75g2000hsg.googlegroups.com> <1175793106.373420.39600@w1g2000hsg.googlegroups.com> Message-ID: <1175796240.919910.187990@y80g2000hsf.googlegroups.com> erikcw wrote: > > Here is the full error: (sorry) No problem! It's easier to comment with these details... > Traceback (most recent call last): > File "/home/erik/Desktop/wa.py", line 178, in ? > curHandler.walkData() > File "/home/erik/Desktop/wa.py", line 91, in walkData > sql = """INSERT INTO ag ('cid', 'ag', 'test') VALUES(%i, %s, %d)""", > (cid.encode("utf-8"), ag, self.data[parent][child]['results']['test']) > AttributeError: 'long' object has no attribute 'encode' If cid is a long, it won't have an encode method, but this is a diversion from the real problem. > sql = """INSERT INTO ag ('cid', 'ag', 'test') VALUES(%i, %s, %d)""", > (cid.encode("utf-8"), ag, self.data[parent][child]['results']['test']) > self.cursor.execute(sql) This won't work because the first parameter of the execute method must be a string (or Unicode object, I guess), but you've provided a tuple. > Now, I changed all ofth e %i/%d to %s, and changed > self.cursor.execute(sql) to self.cursor.execute(*sql) and it seems to > be working now! The first modification may not have been necessary, but you should check the database module documentation to make sure what kinds of parameter markers are permitted. The second modification should, as I suspected, solve your problem. As you may be aware, adding the * unpacks the contents of sql into the parameters for the execute method. Thus, the first element in the tuple gets presented as the first parameter (the SQL statement), and the second element gets presented as the second parameter (a sequence of values which are to be used with the SQL statement). Paul From steve at holdenweb.com Fri Apr 13 09:53:43 2007 From: steve at holdenweb.com (Steve Holden) Date: Fri, 13 Apr 2007 09:53:43 -0400 Subject: Problem with algorithm In-Reply-To: <1176448576.047996.12930@d57g2000hsg.googlegroups.com> References: <1176434160.047703.214600@q75g2000hsh.googlegroups.com> <1176434937.258002.162220@p77g2000hsh.googlegroups.com> <1176448576.047996.12930@d57g2000hsg.googlegroups.com> Message-ID: Jia Lu wrote: >> for m in test: >> for n in test: >> for o in test: >> for p in test: >> print m+n+o+p > > Thanx for your anwser. > But if I consider about a combination of over 26 letter's list just > like: > "abcdefssdzxcvzxcvzcv" > "asllxcvxcbbedfgdfgdg" > ..... > > Need I write 26 for loops to do this? > > Thanx > > Jia LU > Your new example uses 20-byte strings anyway, so to produce those using the specified method you would need 20 nested for loops, not 26. I'm pretty sure you could give a separate name to each atom ont he known universe with a scheme like this. Do you really need 20-byte strings? 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 robert.rawlins at thinkbluemedia.co.uk Thu Apr 26 05:26:23 2007 From: robert.rawlins at thinkbluemedia.co.uk (Robert Rawlins - Think Blue) Date: Thu, 26 Apr 2007 10:26:23 +0100 Subject: Re-ocurring Events Message-ID: <008001c787e5$04efe680$0ecfb380$@rawlins@thinkbluemedia.co.uk> Hello Chaps, A bit more of a complex one this time, and I thought I'd get your opinions on the best way to achieve this. Basically I'm looking for a way to describe a re-occurring event, like a calendar event or appointment I guess. I'm likely to use an XML file for the definition of the events, but imagine I've got an event that looks something like this. Now what I want to do is be able to build a class which has a function like 'getCurrentEvent()' which will return any events that should be occurring at that time. So if the current system time and date is 2007-01-03 13:00:00 then it will return THAT event to me, but if it was say 2007-01-03 16:00:00 then it would not, as the event isn't 'due' to occur at that time. Make sense? What's the best way of handling this? I'm really a little lost as to how I might get started, checking a static date time isn't a problem, it's when it comes to these re-occurring events that I struggle a little. The idea is that I would have 5 core repetitions, none, daily, weekly, monthly and annually. Or perhaps you guys have a more full proof method of describing the event in the XML? Any suggestions are more than welcome guys, thanks again for all your help recently. Rob -------------- next part -------------- An HTML attachment was scrubbed... URL: From robert.kern at gmail.com Wed Apr 4 17:39:20 2007 From: robert.kern at gmail.com (Robert Kern) Date: Wed, 04 Apr 2007 16:39:20 -0500 Subject: Calling Fortran from Python In-Reply-To: <1175718204.410453.29510@q75g2000hsh.googlegroups.com> References: <1175640339.648190.207530@y66g2000hsf.googlegroups.com> <1175685841.847487.173440@w1g2000hsg.googlegroups.com> <1175718204.410453.29510@q75g2000hsh.googlegroups.com> Message-ID: Mangabasi wrote: > I am using Visual Studio 6.0 and Compaq Visual Fortran 6.6. Ah. You can't use VS6 with that version of Python. I believe you need the .NET SDK 2003. You could also use gcc, but I'm not sure if that will work well with Compaq Visual Fortran; you might have to use gfortran. http://www.develer.com/oss/GccWinBinaries -- 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 kw at codebykevin.com Thu Apr 19 22:56:32 2007 From: kw at codebykevin.com (Kevin Walzer) Date: Thu, 19 Apr 2007 22:56:32 -0400 Subject: How To Find Currently Selected Tile.Notebook Tab? In-Reply-To: <1177035392.983733.68240@n76g2000hsh.googlegroups.com> References: <1177035392.983733.68240@n76g2000hsh.googlegroups.com> Message-ID: <315d0$46282bdf$4275d90a$28375@FUSE.NET> bcwhite at pobox.com wrote: > How can I determine what tab is currently selected in a Tile.Notebook > widget? > > The best suggestion I've been able to find via Google is > "mynotebook.index('current')", but that gets an exception from Tcl. > > Any ideas? > > -- Brian > How about mynotebook.index.current() ? -- Kevin Walzer Code by Kevin http://www.codebykevin.com From irstas at gmail.com Tue Apr 3 05:34:23 2007 From: irstas at gmail.com (irstas at gmail.com) Date: 3 Apr 2007 02:34:23 -0700 Subject: Parsing Problems In-Reply-To: <1175591597.120154.240820@q75g2000hsh.googlegroups.com> References: <1175591597.120154.240820@q75g2000hsh.googlegroups.com> Message-ID: <1175592863.362497.286770@q75g2000hsh.googlegroups.com> saif.shakeel at gmail.com wrote: > Hi, > > I have just started learning python.I need to parse an XML file > and present the contents in a particular format.The format is called > as "ini" file.I have written some code.A section of the format needs > the data to be present in format as given below: > > [Services] > supported=0x10,0x1A,0x3B,0x20,0x27,0x28,0x34,0x36,0x3E,0xA2,0xA5,0x2D, > 0x22,0xA9,0x04,0xAA,0xAE > > My code for this section parses the xml file and gives : > [Services] > Supported=['0x3e', '0x28', '0x3b', '0x22', '0x20', '0x27', '0xaa', > '0x10', '0xae', '0x34', '0x36', '0x2d', '0xa9', '0xa5', '0x4', '0xa2', > '0x1a'] > > {forget the numericals matching}.As you can see there > are single quotes around numericals ,which is not desired .I think the > problem lies in me using a list for storing and later printing out > values.I have attached few lines of code,not sure how clear it can be > to you: > > for l in range(0,len(ser_par), > 1): > if > ser_par[l].getAttribute('Semantics')==u'serviceId': > if > tag_exists(ser_par[l].childNodes,'VALUE'): > val = > ser_par[l].getElementsByTagName('VALUE') > value = > str(val[0].getAttribute('value')) > valu = hex(int(value)) > rval.append(valu) > ser_par_num = ser_par_num + 1 > prim_num = prim_num + 1 > > service_num = service_num + 1 > variant_num = variant_num + 1 > ser = list(set(rval)) > > print "\n[Services]" > print "Supported="+str(ser) > > How can i get rid of those single quotes. > > Thanking you > > shakeel Hi, Instead of using str(ser), you should create a string which combines the individual strings in ser, separated by commas. Luckily for you, there's a string method does just that: join. http://docs.python.org/lib/string-methods.html From bbxx789_05ss at yahoo.com Thu Apr 12 19:10:37 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: 12 Apr 2007 16:10:37 -0700 Subject: Lists and Tuples and Much More In-Reply-To: References: Message-ID: <1176419437.278359.52800@q75g2000hsh.googlegroups.com> > Now I read somewhere that you could change the > list inside that tupple. But I can't find any > documentation that describes HOW to do it. t = (1, 2, ["red", "white"]) t[2][1] = "purple" print t t[2] returns the list, so the second line is equivalent to: lst = t[2] lst[1] = "purple" That is exactly how you would access and change a list inside a list, e.g.: [1, 2, ["red", "white"]] > And which is better on resources....I'm guessing a tuple seeing > as it doesn't change. I doubt it matters much unless you have several million lists v. several million tuples. The reason you need to know about tuples is because they are returned by some built in functions. Also, a key in a dictionary can be a tuple, but not a list. But using a tuple as a key in a dictionary is probably something you will never do. > Now there comes append. I read everywhere that append only add's 1 > element to the end of your list. But if you write: >>> my_list = [1, 2, 3, 4, 5, 6] >>> my_list.append([7, 8, 9, 10]) >>> my_list _li [1, 2, 3, 4, 5, 6, [7, 8, 9, 10]] > Is that because list's, no matter what they contain, are counted as > 1 element? Each "element" in a list is associated with an index position. When you append() to a list you are creating one additional index position in the list and assigning the thing you append to that index position. The thing you append becomes one element in the list, i.e. it's associated with one index position in the list. As a result, when you append(), the length of the list only increases by 1: >>> l = [1, 2] >>> len(l) 2 >>> a = ["red", "white"] >>> l.append(a) >>> l [1, 2, ['red', 'white']] >>> len(l) 3 >>> > And how would you sort the list that's in the list? By summoning up the list, and then sorting it: t = (1, 2, ["red", "white", "ZZZ", "abc"]) t[2].sort() print t From buzzard at urubu.freeserve.co.uk Tue Apr 24 21:36:02 2007 From: buzzard at urubu.freeserve.co.uk (Duncan Smith) Date: Wed, 25 Apr 2007 02:36:02 +0100 Subject: numpy migration (also posted to numpy-discussion) In-Reply-To: References: Message-ID: Travis E. Oliphant wrote: > Duncan Smith wrote: > >> Hello, >> Since moving to numpy I've had a few problems with my existing >> code. It basically revolves around the numpy scalar types. e.g. >> > > You will probably get more help on the numpy discussion list: > > numpy-discussion at scipy.org > > > You are encountering problems because numpy scalar types don't raise > errors (unless you have set the appropriate hardware flag using > numpy.seterr). > Unfortunately it seems to raise a FloatingPointError. >>> import numpy as N >>> N.__version__ '1.0.1' >>> a = N.array([[0,1],[2,3]]) >>> a array([[0, 1], [2, 3]]) >>> i = a[0,0] >>> 1/i 0 >>> N.seterr(divide='raise') {'over': 'print', 'divide': 'print', 'invalid': 'print', 'under': 'ignore'} >>> 1/i Traceback (most recent call last): File "", line 1, in 1/i FloatingPointError: divide by zero encountered in long_scalars > You can get Python scalars out of NumPy arrays if you really want them > using (for example...) > > a.item(0,0) > > >> >> An additional problem involves classes that have e.g. __rmul__ methods >> defined and are sufficiently similar to numpy arrays that my classes' >> __rmul__ methods are not invoked when using numpy scalars. >> > > Could you please post an example showing the problem? > [snip] -----------------example.py-------------------- from __future__ import division import numpy class MyClass(object): def __init__(self, arr, labels): self.arr = arr self.labels = labels def __repr__(self): return numpy.array2string(self.arr, separator=', ') + repr(self.labels) def __len__(self): return len(self.labels) def __getitem__(self, key): return self.arr[key] def __setitem__(self, key, item): self.arr[key] = item def __mul__(self, other): return self.__class__(self.arr * other, self.labels) __rmul__ = __mul__ ---------------------------------------------------- >>> import example >>> import numpy as N >>> ex = example.MyClass(N.array([[6,7],[8,9]]), ['axis0', 'axis1']) >>> i = ex.arr[0,0] >>> ex [[6, 7], [8, 9]]['axis0', 'axis1'] >>> ex * i [[36, 42], [48, 54]]['axis0', 'axis1'] >>> i * ex array([[36, 42], [48, 54]]) >>> It seems that it requires having __len__, __setitem__ and __getitem__ defined to get the undesired behaviour. Cheers. Duncan From QncyMI at netscape.net Wed Apr 25 15:11:33 2007 From: QncyMI at netscape.net (Major Quaternion Dirt Quantum) Date: 25 Apr 2007 12:11:33 -0700 Subject: KOREAN MOON revolves around BUSH In-Reply-To: <1176585995.072878.240230@e65g2000hsc.googlegroups.com> References: <1176575332.342215.235820@y80g2000hsf.googlegroups.com> <1176585995.072878.240230@e65g2000hsc.googlegroups.com> Message-ID: <1177528293.204522.59970@s33g2000prh.googlegroups.com> "Global Warning," an *anonymous* article in an old issue of *National Review*, the so-called conservative mag of the grotesque Establishment creature, William Buckley, was a sort of benignly-spun expose of the Mont Pelerin Society, the vehicle of British imperialist "free trade," free beer & free dumb, whose many "rightwing" affiliate foundations are always in the news. the universally-newspaper-lauded-when- he-died founding president, Mitlon Friedman, used Sir Henry of Kiss.Ass. to conduct their first experiment in Chile, with the help of Augusto Pinochet & Dick Nixon. (the fact that it was an awful failure, with the privatization of Chile's social security, was only recently mention, but only before Uncly Milty died.) I realized, much later, since it was anonymous, that it was probably taken from The Holy Spook Economist, but I haven't checked that hypothesis. yes, "Warning" was meant to evoke "warming," although nowhere mentioned in the article, as I recall; can you say, "emmissions trading schemes," Boys and Girl? can you say, "hedge funds on out-of-the-way desert islands?" Just Desserts Island thus: Kucinich is reportedly presenting a bill of impeachment for Trickier Dick Cheeny, today, which may be augmented by some rules of Congress via the state of Vermont. now is the time to make him resign! if you are not a PC Democrat, ask me, How?, in person. if you are not a PC Republican, please, tell the others of the meaning of the word, republic! why do Dick, Borat, Osama, Harry P., Rumsfeld and Tony B. want us to underwrite the 3rd British Invasion of Sudan, so badly? which are really fictional British characters? whwat is the role of the Prime Minister in the Muggles government, and who is he said to be by The Holy Economist? anyway, Bertrand Russel published a jeremyad in the Bulletin of the Atomic Scientists, while the USA was the only thermonukey power, that we should bomb them into the Stone Age; that's your British "pacifist," whether before or after he went nuts because of Godel's proof. thus: if you can't prove that all Fermat numbers are pairwise coprime, again! Darfur 'Mini-Summit' http://www.larouchepub.com/other/1998/rice_2546.html thus: uh yeah; Borat wants you in Sudan, why, Baby?... Harry Potter wants you in Iran -- yeah, Baby; shag'US with a spoon? --DARFURIA CONSISTS OF ARABs & nonARABs; NEWS-ITEM: we are marching to Darfuria, Darfuria, Darfuria! Harry Potter IIX, ?Ordeal @ Oxford//Sudan ^ Aircraft Carrier! http://larouchepub.com/other/2007/3410caymans_hedges.html ALgoreTHEmovieFORpresident.COM: http://larouchepub.com/eirtoc/site_packages/2007/al_gore.html? From iltchevi at gmail.com Sat Apr 21 05:35:57 2007 From: iltchevi at gmail.com (ici) Date: 21 Apr 2007 02:35:57 -0700 Subject: newbie: HTTPS screen scraping In-Reply-To: References: Message-ID: <1177148157.496654.303610@b58g2000hsg.googlegroups.com> On Apr 21, 11:38 am, u... at domain.invalid wrote: > Hi, > Can anyone help me out here. I would like to authenticate myself to > a website which uses HTTPS and then after authentication, I would like > to get the contents of the webpage. How can this be done using python. > I have tried urllib and urllib2 but it has not solved my problem. > > TIA > /varun http://pycurl.sourceforge.net/ From steve at holdenweb.com Tue Apr 10 15:47:52 2007 From: steve at holdenweb.com (Steve Holden) Date: Tue, 10 Apr 2007 15:47:52 -0400 Subject: Parsing log in SQL DB to change IPs to hostnames In-Reply-To: <1176231258.626137.228220@d57g2000hsg.googlegroups.com> References: <1176219463.407804.315560@y80g2000hsf.googlegroups.com> <1176221494.813800.78580@y80g2000hsf.googlegroups.com> <1176231258.626137.228220@d57g2000hsg.googlegroups.com> Message-ID: KDawg44 wrote: > On Apr 10, 11:11 am, "Kushal Kumaran" > wrote: >> On Apr 10, 8:37 pm, "KDawg44" wrote: >> >> >> >>> Hi, >>> I am brand new to Python. In learning anything, I find it useful to >>> actually try to write a useful program to try to tackle an actual >>> problem. >>> I have a syslog server and I would like to parse the syslog messages >>> and try to change any ips to resolved hostnames. Unfortunately, I am >>> not getting any matches on my regular expression. >>> A message will look something like this: >>> Apr 10 2007 00:30:58 DEVICE : %DEVICEINFO: 1.1.1.1 Accessed URL >>> 10.10.10.10:/folder/folder/page.html >>> I would like to change the message to have the hostnames, or even >>> better actually, have it appear as hostname-ip address. So a changed >>> message would look like: >>> Apr 10 2007 00:30:58 DEVICE : %DEVICEINFO: pcname-1.1.1.1 Accessed >>> URLwww.asite.com-10.10.10.10:/folder/folder/page.html >>> or some equivalent. >>> Here is what i have so far. Please be kind as it is my first python >>> program.... :) >>> #! /usr/bin/python >>> import socket >>> import re >>> import string >>> import MySQLdb >>> ipRegExC = r"\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}" >>> ipRegEx = re.compile(ipRegExC) >>> try: >>> conn = MySQLdb.connect(host="REMOVED", user="REMOVED", >>> passwd="REMOVED", db="REMOVED") >>> except MySQLdb.Error, e: >>> print "Error connecting to the database: %d - %s " % >>> (e.args[0], e.args[1]) >>> sys.exit(1) >>> cursor = conn.cursor() >>> cursor.execute("SELECT msg, seq FROM REMOVED WHERE seq = 507702") >>> # one specific message so that it doesn't parse the whole DB during >>> testing... >>> while(1): >>> row = cursor.fetchone() >>> if row == None: >>> break >>> if ipRegEx.match(row[0]): >>> .... >>> >> See the documentation of the re module for the difference between >> matching and searching. >> >> -- >> Kushal > > Thank you very much. I think I have it figured out, except for an > error on the SQL statement: > > > [----- BEGIN ERROR ---] > Traceback (most recent call last): > File "changeLogs.py", line 47, in ? > cursor.execute("""UPDATE logs SET msg = %s WHERE seq = %i""", > (newMsg,seqNum)) > File "/usr/lib/python2.4/site-packages/MySQLdb/cursors.py", line > 148, in execute > query = query % db.literal(args) > TypeError: int argument required > [----- END ERROR ---] > > Here is my code > > [----- BEGIN CODE ---] > #! /usr/bin/python > > import socket > import sys > import re > import string > import MySQLdb > > def resolveHost(ipAdds): > ipDict = {} > for ips in ipAdds: > try: > ipDict[ips] = socket.gethostbyaddr(ips)[0] > except: > ipDict[ips] = "Cannot resolve" > return ipDict > > > ipRegExC = r"\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}" > ipRegEx = re.compile(ipRegExC) > > try: > conn = MySQLdb.connect(host="REMOVED", user="REMOVED", > passwd="REMOVED", db="REMOVED") > > except MySQLdb.Error, e: > print "Error connecting to the database: %d - %s " % > (e.args[0], e.args[1]) > sys.exit(1) > > cursor = conn.cursor() > cursor.execute("SELECT msg, seq FROM `logs` WHERE seq = 507702") > while(1): > row = cursor.fetchone() > ipAddresses = [] > resolvedDict = {} > if row == None: > break > if ipRegEx.search(row[0]): > seqNum = row[1] > ipAddresses = ipRegEx.findall(row[0]) > resolvedDict = resolveHost(ipAddresses) > newMsg = row[0] > for ip in resolvedDict.keys(): > newMsg = newMsg.replace(ip,ip + "-" + > resolvedDict[ip]) > cursor.execute("""UPDATE REMOVED SET msg = %s WHERE > seq = %i""", (newMsg,seqNum)) > > > [----- END CODE ---] > > Thanks again! > > Since the source line that the traceback complains about doesn't appear in the quoted code it's difficult to know what's going wrong. I'd hazard a guess that you have a string in seqNum instead of an integer message number (in which case try using int(seqNum) instead). Otherwise show us the real code, not the one after you modified it to try and make it work, amd we might be able to help more ;-) 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 pippo at pippo.com Fri Apr 6 13:01:47 2007 From: pippo at pippo.com (Lorenzo Mainardi) Date: Fri, 06 Apr 2007 19:01:47 +0200 Subject: Python on MIPS In-Reply-To: References: <46160b35$0$36451$4fafbaef@reader5.news.tin.it> Message-ID: <46167cfc$0$36442$4fafbaef@reader5.news.tin.it> Thomas Kr?ger ha scritto: > Lorenzo Mainardi schrieb: >> I bought a very small embedded card, with a MIPS processor, running >> Linux. So, I would to use Python on that; I checked on python.org, but I >> did'nt find any release for this architecture. Could you help me? > > How about compiling it from source? > > Thomas I did'nt try...I will do that :-) From inq1ltd at verizon.net Fri Apr 20 14:11:26 2007 From: inq1ltd at verizon.net (jim-on-linux) Date: Fri, 20 Apr 2007 14:11:26 -0400 Subject: Expanding tkinter widgets to fill the window In-Reply-To: References: <1177085708.955388.119080@o5g2000hsb.googlegroups.com> Message-ID: <200704201411.26335.inq1ltd@verizon.net> On Friday 20 April 2007 13:56, Anton Vredegoor wrote: > KDawg44 wrote: > > I am writing a GUI front end in Python using > > Tkinter. I have developed the GUI in a grid > > and specified the size of the window. The > > widgets are centered into the middle of the > > window. I would like them to fill the > > window. I tried using the sticky=E+W+N+S > > option on the widgets themselves and the > > window itself. > > > > How can I get this? > > If at all possible post a short, > self-contained, correct, example demonstrating > your question. > > http://homepage1.nifty.com/algafield/sscce.html > > A. try; sticky = NSEW without plus signs headFrame = Frame(win01, bg = 'light grey', bd=10) headFrame.grid(row = 0, column=0, sticky = NSEW) jim-on-linux http://www.inqvista.com From robert.rawlins at thinkbluemedia.co.uk Sat Apr 21 04:46:07 2007 From: robert.rawlins at thinkbluemedia.co.uk (Robert Rawlins - Think Blue) Date: Sat, 21 Apr 2007 09:46:07 +0100 Subject: Class Not Auto-Init On Import Message-ID: <002001c783f1$81084bb0$8318e310$@rawlins@thinkbluemedia.co.uk> Hello Guys, >From my understanding of what I've read, the 'import' is meant to auto Init my class ready for me to access its methods, but it doesn't appear too, I'm having to init them myself before I can access them, like this. import LocationService Location = LocationService.LocationService() LocationService.setIP('192.168.1.1') Why is this the case? Should i not just be able to access the setIP() method by doing LocationService.setIP('192.168.1.1') Without having to create my own inited reference? Thanks, Rob -------------- next part -------------- An HTML attachment was scrubbed... URL: From gagsl-py2 at yahoo.com.ar Mon Apr 9 09:12:37 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 09 Apr 2007 10:12:37 -0300 Subject: how to use the string '\\.\' References: <1176117103.670611.291740@n59g2000hsh.googlegroups.com> Message-ID: En Mon, 09 Apr 2007 08:21:44 -0300, Duncan Booth escribi?: > wrote: > >> print r'\\.\' > > See the FAQ: > http://www.python.org/doc/faq/general/#why-can-t-raw-strings-r-strings-end-with-a-backslash This form is not included in the FAQ alternatives (should it?): print r'\\.' '\\' -- Gabriel Genellina From sbassi at clubdelarazon.org Sun Apr 15 16:06:31 2007 From: sbassi at clubdelarazon.org (Sebastian Bassi) Date: Sun, 15 Apr 2007 17:06:31 -0300 Subject: Making a tree out of a 2 column list In-Reply-To: References: <1176568327.669229.22910@b75g2000hsg.googlegroups.com> Message-ID: <9e2f512b0704151306k5a844d46ucb81a989780cb5d5@mail.gmail.com> On 4/15/07, Peter Otten <__peter__ at web.de> wrote: > Depending on your input data you may need to add some cycle detection. > For example, try it with > tree_path(1, {1:[2], 2:[1]}, []) I guess this should make the program enter into a endless loop. But the data won't have such a redundancy, because it was taken from a philogenetic tree. Best, SB. From mark.dufour at gmail.com Sun Apr 1 14:30:52 2007 From: mark.dufour at gmail.com (mark.dufour at gmail.com) Date: 1 Apr 2007 11:30:52 -0700 Subject: Shed Skin Python-to-C++ Compiler 0.0.21, Help needed In-Reply-To: <7x8xdcrc13.fsf@ruckus.brouhaha.com> 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> <7x8xdcrc13.fsf@ruckus.brouhaha.com> Message-ID: <1175452252.278238.277220@p15g2000hsd.googlegroups.com> > I don't see how that can be--we're talking about a GCC-based compiler, > right? no, Shed Skin is a completely separate entity, that outputs C++ code. it's true I only use GCC to test the output, and I use some GCC- specific extensions (__gnu_cxx::hash_map/hash_set), but people have managed to compile things with Visual Studio or whatever it is called. btw, the windows version of Shed Skin comes with GCC so it's easy to compile things further (two commands, 'ss program' and 'make run' suffice to compile and run some program 'program.py') mark dufour (Shed Skin author). From michele.simionato at gmail.com Mon Apr 9 10:16:37 2007 From: michele.simionato at gmail.com (Michele Simionato) Date: 9 Apr 2007 07:16:37 -0700 Subject: Classes with initialization In-Reply-To: <1176103583.032209.304710@p77g2000hsh.googlegroups.com> References: <1176103583.032209.304710@p77g2000hsh.googlegroups.com> Message-ID: <1176128197.839552.120020@p77g2000hsh.googlegroups.com> On Apr 9, 9:26 am, mariano.suarezalva... at gmail.com wrote: > Hi all, > > I'm currently using code similar to this: > > class ClassWithInitialization(type): > def __init__(cls, name, bases, dict): > type.__init__(name, bases, dict) > dict['__class_init__'](cls) > > class A: > __metaclass__ = ClassWithInitialization > > def __class_init__(cls): > cls.some_attribute = ... > ... > > in order to get class attributes initialized (since the values of > these attributes > need non trivial work to be computed, putting the code that does that > computation in the class scope ends up with the class having extra > attributes---the `local' variables used in the computation of the > values of class attribute; so I'm using __class_init__'s scope to > contain those variables) > > I was wondering: is there a simpler approach to this? Yes, see http://www.phyast.pitt.edu/~micheles/python/classinitializer.html > Also: can someone enlighten me as to when code in class scope is run, > exactly? > if a class A has a metaclass M, then M.__init__ does not seem to get > the code in A's class scope in its arguments AFAICS, so I guess that > code is run before the class is created? > > Cheers, > __init__ is run after class creation. What does not work exactly? Michele Simionato From joshua at eeinternet.com Mon Apr 16 16:37:16 2007 From: joshua at eeinternet.com (Joshua J. Kugler) Date: Mon, 16 Apr 2007 12:37:16 -0800 Subject: Python editor/IDE on Linux? References: Message-ID: <4623d213$0$16346$88260bb3@free.teranews.com> On Friday 13 April 2007 10:20, Jack wrote: > I wonder what everybody uses for Python editor/IDE on Linux? > I use PyScripter on Windows, which is very good. I'm using WingWare's WingIDE. Visual debugger, python-scriptable, projects, code-completion that is second-to-none (I LOVE it.). And a very responsive support team. Yes, it's commercial, but it's cheaper than Komodo, and works a lot better for Python. Plus, it's written in Python, so the developers eat their own dog food. During the development cycle for 3.0 (it's at Alpha 1 right now*), all they used to development was the active code base. *I'm using 3.0a1 right now for my development work, and have not had a single crash or glitch. It's good stuff. 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 nagle at animats.com Fri Apr 27 15:38:22 2007 From: nagle at animats.com (John Nagle) Date: Fri, 27 Apr 2007 19:38:22 GMT Subject: Dedicated CPU core for Python? In-Reply-To: <46323f34$0$16283$88260bb3@free.teranews.com> References: <1177607759.916727.180950@t39g2000prd.googlegroups.com> <4630e90c$0$16272$88260bb3@free.teranews.com> <46323f34$0$16283$88260bb3@free.teranews.com> Message-ID: Joshua J. Kugler wrote: > On Thursday 26 April 2007 14:07, Gabriel Genellina wrote: > > >>En Thu, 26 Apr 2007 15:54:38 -0300, Joshua J. Kugler >> escribi?: >> >> >>>Are you talking about CPU affinity >>>(http://en.wikipedia.org/wiki/Processor_affinity) or an actual CPU that >>>can directory execute Python byte code? If the former, CPython only >>>uses one >>>CPU core right now because it's threads are all internal, and do not >>>spawn system threads (IIRC). >> >>Python threads are OS threads: >>http://docs.python.org/lib/module-thread.html >>"[The thread module] is supported on Windows, Linux, SGI IRIX, Solaris >>2.x, as well as on systems that have a POSIX thread (a.k.a. ``pthread'') >>implementation." > > > Yes, that may be, but they are not true system threads, or at least do not > appear to be. Threads on linux each show up as a separate process. I can > have several threads in my Python program, but no additional processes show > up in ps -A. I don't see how Python threads can be system threads with the > GIL. But, I've been wrong before, and threads are something I have very > light knowledge of. OK. What's going on inside CPython is this: Each Python thread is an operating system thread, managed through the POSIX pthreads interface. On a system with more than one CPU, more than one such thread can run at a time. But, because the CPython system isn't really reentrant, most of the data structures have to be protected against simultaneous access by the Global Interpreter Lock. So, when you have multiple compute-bound threads on multiple CPUs in Python, at any one time, no more than one of them is executing the CPython interpreter. The others are blocked on the Global Interpreter Lock. The lock is unlocked before I/O requests and such, which allows another thread to run while threads are blocked waiting for an I/O operation to complete. That's why having multiple CPUs ("dual core" in marketing jargon) won't improve Python performance. This is an implementation limitation of CPython and its libraries. Jython and Iron Python don't have this issue. John Nagle From joshua at eeinternet.com Tue Apr 3 15:42:14 2007 From: joshua at eeinternet.com (Joshua J. Kugler) Date: Tue, 03 Apr 2007 11:42:14 -0800 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> <1hvqae5.1alie2515sbssfN%aleax@mac.com> <460c01df$0$16410$88260bb3@free.teranews.com> <1hvr2it.jmrhe215gail1N%aleax@mac.com> <461190fe$0$16311$88260bb3@free.teranews.com> Message-ID: <4612a1a2$0$16405$88260bb3@free.teranews.com> On Monday 02 April 2007 16:33, Robert Kern wrote: >>>>>> help(pkgutil.iter_modules) >>> Help on function iter_modules in module pkgutil: >>> >>> iter_modules(path=None, prefix='') >>> Yields (module_loader, name, ispkg) for all submodules on path, >>> or, if path is None, all top-level modules on sys.path. >>> >>> 'path' should be either None or a list of paths to look for >>> modules in. >>> >>> 'prefix' is a string to output on the front of every module name >>> on output. >> >> OK, that looks nice...but what version of Python is that? >> http://docs.python.org/lib/module-pkgutil.html only shows one function >> (and that's 2.5) and my python 2.4 installation is similarly lacking an >> iter_modules() function for the pkgutil module. Is this a 2.6 thing? > > No, 2.5. The documentation is not up to date. Read the source. > Gotcha. Thanks...well, since we're using 2.4, that will have to wait. For the archives, here is what I've come up with. Contents of the __init__.py for a module. import os _myDir = __path__[0] def mod_list(): """ A quick hack that retrieves all the sub modules in a directory that has an __init__.py file. I could use pkgutil.iter_modules, but that is Python 2.5 only, and this should work with several versions of Python. """ modList = [] modHash = {} isModule = False for ii in os.walk(_myDir): if ii[0] == _myDir: for f in ii[2]: # If there is no __init__ file, then the directory # upon which mod_list() is operating is not a module if f[0:8] == '__init__': isModule = True elif f[-3:] == '.py': modHash[f[:-3]] = True elif f[-4:] == '.pyc' or f[-4:] == '.pyo': modHash[f[:-4]] = True if isModule: modList = modHash.keys() modList.sort() return(modList) else: return(None) Hope that helps someone! 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 Thu Apr 19 10:31:59 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Fri, 20 Apr 2007 00:31:59 +1000 Subject: comparison with None References: <3IqdnfRnCNWPC7vbnZ2dnUVZ_jqdnZ2d@rcn.net> Message-ID: On Wed, 18 Apr 2007 15:19:26 -0700, Steven Howe wrote: > I've read and found that 'None' comparisons is not always a good idea. You're probably thinking of testing against None with equality: if x == None: do_something() That can go wrong if x is a class that has an overly-broad concept of equality, e.g.: class FalseKlass: def __eq__(self, other): # equal to anything that is False return not other > Better to: > from types import NoneType > > x = None > if type( x ) == NoneType: > # true > < code > > else: > # false; do something else. > < more code > Not necessary. Since None is a guaranteed singleton, the only test you need to make is "if x is None: ...". But if you wanted to do extra work unnecessarily, a less unnecessary amount of extra work would be: if type(x) == type(None): ... You don't need to look up the type of None in the types module when you can easily get it from the type() function. -- Steven. From rridge at caffeine.csclub.uwaterloo.ca Sun Apr 22 16:46:20 2007 From: rridge at caffeine.csclub.uwaterloo.ca (Ross Ridge) Date: Sun, 22 Apr 2007 16:46:20 -0400 Subject: Python's handling of unicode surrogates References: <1177051493.468698.176740@b75g2000hsg.googlegroups.com> <4629591a$0$13629$9b622d9e@news.freenet.de> <1177122874.524447.85130@p77g2000hsh.googlegroups.com> Message-ID: Rhamphoryncus wrote: >I wish to write software that supports Unicode. Like it or not, >Unicode goes beyond the BMP, so I'd be lying if I said I supported >Unicode if I only handled the BMP. The Unicode standard doesn't require that you support surrogates, or any other kind of character, so no you wouldn't be lying. Also since few Python programs claim to support Unicode, why do you think it's acceptable to break them if they don't support surrogates? Ross Ridge -- l/ // Ross Ridge -- The Great HTMU [oo][oo] rridge at csclub.uwaterloo.ca -()-/()/ http://www.csclub.uwaterloo.ca/~rridge/ db // From rhamph at gmail.com Sun Apr 15 02:29:56 2007 From: rhamph at gmail.com (Rhamphoryncus) Date: 14 Apr 2007 23:29:56 -0700 Subject: tuples, index method, Python's design In-Reply-To: <7xr6qmrg4x.fsf@ruckus.brouhaha.com> References: <1176200361.260546.280510@n76g2000hsh.googlegroups.com> <740c3aec0704100824m132c45fbi5c4c3ec0c0fa3a67@mail.gmail.com> <1176489534.568939.249910@q75g2000hsh.googlegroups.com> <7x3b33k0l9.fsf@ruckus.brouhaha.com> <1176572775.382873.282850@q75g2000hsh.googlegroups.com> <7xr6qmrg4x.fsf@ruckus.brouhaha.com> Message-ID: <1176618596.238855.122000@d57g2000hsg.googlegroups.com> On Apr 14, 11:59 am, Paul Rubin wrote: > "Rhamphoryncus" writes: > > Nope, it's pretty fundamental to working with text, unicode only being > > an extreme example: there's a wide number of ways to break down a > > chunk of text, making the odds of "e" being any particular one fairly > > low. Python's unicode type only makes this slightly worse, not > > promising any particular one is available. > > I don't understand this. I thought that unicode was a character > coding system like ascii, except with an enormous character set > combined with a bunch of different algorithms for encoding unicode > strings as byte sequences. But I've thought of those algorithms > (UTF-8 and so forth) as basically being kludgy data compression > schemes, and unicode strings are still just sequences of code points. Indexing cost, memory efficiency, and canonical representation: pick two. You can't use a canonical representation (scalar values) without some sort of costly search when indexing (O(log n) probably) or by expanding to the worst-case size (UTF-32). Python has taken the approach of always providing efficient indexing (O(1)), but you can compile it with either UTF-16 (better memory efficiency) or UTF-32 (canonical representation). As an aside, I feel the need to clarify the terms "code points" and "scalar values". The only difference is that "code points" includes the surrogates, whereas "scalar values" does not. As the surrogates are just an encoding detail of UTF-16 I feel this makes "scalar values" the more canonical term. It's all quite confusing though x_x. -- Adam Olsen, aka Rhamphoryncus From rw at smsnet.pl Tue Apr 3 05:48:52 2007 From: rw at smsnet.pl (Rob Wolfe) Date: 3 Apr 2007 02:48:52 -0700 Subject: Tkinter <> and bindtags ordering In-Reply-To: <1175589451.633609.216190@e65g2000hsc.googlegroups.com> References: <1175572841.269301.275100@q75g2000hsh.googlegroups.com> <1175584600.221378.143380@n59g2000hsh.googlegroups.com> <1175589451.633609.216190@e65g2000hsc.googlegroups.com> Message-ID: <1175593732.437631.198860@n76g2000hsh.googlegroups.com> bytecolor wrote: > Hey Rob, > I actually started with that event, until I came across the modified > event. I'm working on syntax highlighting. So I need any text change. > Also, colorizing on a key release is annoyingly noticeable to the > user. I tried it :) > > I'm sure there are going to be other perils along the way as this is > my first attempt at syntax highlighing. I can load a file and the > highlighting works very well. I used an elaborate regex with named > groups and re.finditer(). I either use the names directly as edit > tags, or they help me look up other tags in a dict. It's quite fast. > > screenshot with random (ugly) colors: > http://bytecolor.homelinux.org/~bytecolor/vapt_colorizing.png > > That part wasn't bad at all. Now I need to code the text change > logistics but this bindtags ordering has got me perplexed. Have you looked at ColorDelegator.py from idlelib? There has been done such a syntax highlighting based on Tkinter.Text. -- HTH, Rob From bbxx789_05ss at yahoo.com Mon Apr 16 04:27:32 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: 16 Apr 2007 01:27:32 -0700 Subject: pyparsing Catch-22 In-Reply-To: <1176711506.989627.282880@o5g2000hsb.googlegroups.com> References: <1176686782.270354.164630@l77g2000hsb.googlegroups.com> <1176696704.924584.75720@e65g2000hsc.googlegroups.com> <1176711506.989627.282880@o5g2000hsb.googlegroups.com> Message-ID: <1176712052.901344.36610@l77g2000hsb.googlegroups.com> Word("ABC", "def") matches "C", "Added", "Beef" but not "BB", "ACE", "ADD" That is just baffling. There's no explanation that the characters specified in the first string are used to match the first char of a word and that the characters specified in the second string are used to match the rest of the word. It would also help to know that if only one string is specified, then the specified characters will be used to match all the chars in a word. I think you should add a simple example to your wiki that explains all that. Also, I think you should state right up front that alphas is a string made up of the chars a-zA-z and that nums is a string made up of the chars 0-9. That way when someone sees Word(alphas), they will understand exactly what that means. Also since matching any char is a pretty common thing, I think you should mention what printables is as well. In any case this is the example I applied pyparsing to: Given .txt file(all on one line). Requirement--construct a list from the text: ------------- mara = [ 'U2FsdGVkX185IX5PnFbzUYSKg+wMyYg9', 'U2FsdGVkX1+BCxltXVTQ2+mo83Si9oAV0sasmIGHVyk=', 'U2FsdGVkX18iUS8hYBXgyWctqpWPypVz6Fj49KYsB8s=' ] ----------- and this is what I came up with: ---------- from pyparsing import Word, alphas, commaSeparatedList name = Word(alphas) lookFor = name + "=" + "[" + commaSeparatedList + "]" my_file = open("aaa.txt") for line in my_file: alist = lookFor.parseString(line) globals()[alist[0] ] = [ alist[3].strip("'"), alist[4].strip("'"), alist[5].strip("'") ] print mara[2] ---------- Any tips? From stdazi at gmail.com Sun Apr 8 06:52:08 2007 From: stdazi at gmail.com (stdazi) Date: 8 Apr 2007 03:52:08 -0700 Subject: Nice "bug" to loose a contest Message-ID: <1176029528.528010.210230@n59g2000hsh.googlegroups.com> Hello, Yesterday, I was at a programming competition. We programmed on Linux liveCD's and Python was one of the allowed languages (among C and Java). I cared just about the algorithmic approach so I used Python. One of the main rules is, that the code reads its standard input and dumps the result on the standard output. Here happened my bigger programming mistake ever - I used the following approach : ==== import sys print sys.stdout.readlines() # TYPO ! stdin != stdout ==== So the WEIRD issue is, that it worked and, executing the following code I get : ==== azi at magicb0x ~ $ python la.py test test #2 ['test \n', 'test #2\n'] azi at magicb0x ~ $ ==== Ok, as the algorithm worked perfectly, and all the test cases we were given were positive, I've continued with the next problem, copy/ pasting the above idiom... When they tested the code, they used file redirection like : == python la.py < /somefile == And, my code resulted in no output/input (=> 0 points), which can be proved here too : ==== azi at magicb0x ~ $ python la.py < /etc/passwd === Some friend of mine told me that's the Unix way, (stdout can act like stdin) so I tried some C code : === 1 #include 2 3 int main() { 4 char buf[120]; 5 while (fgets(buf, sizeof(buf), stdout) != NULL) { 6 puts(buf); 7 } 8 return 0; 9} === The code returns with no delay, so I'm really wondering where is that nice sys.{stdin,stdout} feature inplemented as pydoc doesn't mention anything. I'd spot the mistake before submitting the problem solutions if it was written in C :) Thanks! From mensanator at aol.com Sat Apr 7 11:52:35 2007 From: mensanator at aol.com (mensanator at aol.com) Date: 7 Apr 2007 08:52:35 -0700 Subject: Checking whether list element exists In-Reply-To: References: Message-ID: <1175961155.790485.156900@e65g2000hsc.googlegroups.com> On Apr 7, 10:37???am, Wojciech Mula wrote: > Rehceb Rotkiv wrote: > > I want to check whether, for example, the element myList[-3] exists. So > > far I did it like this: > > > index = -3 > > if len(myList) >= abs(index): > > ? ?print myList[index] > > IMHO it is good way. > > > Another idea I had was to (ab-?)use the try...except structure: > > > index = -3 > > try: > > ? ?print myList[index] > > except: > > ? ?print "Does not exist!" > > In general case it won't work, because lists accept negative indexes:http://docs.python.org/lib/typesseq.html, 3rd note. Why? What does negative indexes have to do with it? >>> a = [1,2] >>> index = -3 >>> try: print a[index] except: print 'does not exist' does not exist > > w. From stefan.behnel-n05pAM at web.de Sun Apr 15 05:50:02 2007 From: stefan.behnel-n05pAM at web.de (Stefan Behnel) Date: Sun, 15 Apr 2007 11:50:02 +0200 Subject: Python and XML? In-Reply-To: <46217DAE.7040501@ieee.org> References: <46209A55.9070102@web.de> <46217DAE.7040501@ieee.org> Message-ID: <4621F54A.3010008@web.de> Leonard J. Reder wrote: > What I as really after though was other possible solutions > like JAX in the Java world or Gnosis in the Python world. > > Something that can take a Relax NG Schema and compile > it into a bunch of parser/generator objects for handling > an XML format. That's why I was asking why you need this. Validation is provided by RNG itself, so all you would need is some kind of mapping that outputs and parses it for you? What's your target format? Python objects? http://codespeak.net/lxml/objectify.html Stefan From buzzard at urubu.freeserve.co.uk Mon Apr 23 11:53:08 2007 From: buzzard at urubu.freeserve.co.uk (Duncan Smith) Date: Mon, 23 Apr 2007 16:53:08 +0100 Subject: numpy migration (also posted to numpy-discussion) Message-ID: Hello, Since moving to numpy I've had a few problems with my existing code. It basically revolves around the numpy scalar types. e.g. ------------------------------------------------ >>> import Numeric as N >>> a = N.array([[0,1],[2,3]]) >>> a array([[0, 1], [2, 3]]) >>> i = a[0,0] >>> 1/i Traceback (most recent call last): File "", line 1, in -toplevel- 1/i ZeroDivisionError: integer division or modulo by zero >>> b = a * 1.5 >>> b array([[ 0. , 1.5], [ 3. , 4.5]]) >>> N.floor(b) array([[ 0., 1.], [ 3., 4.]]) >>> ================================ RESTART ================================ >>> import numpy as N >>> a = N.array([[0,1],[2,3]]) >>> a array([[0, 1], [2, 3]]) >>> i = a[0,0] >>> 1/i 0 >>> b = a * 1.5 >>> b array([[ 0. , 1.5], [ 3. , 4.5]]) >>> N.floor(b) array([[ 0., 1.], [ 3., 4.]]) >>> a = N.array([[0,1],[2,3]], dtype='O') >>> a array([[0, 1], [2, 3]], dtype=object) >>> i = a[0,0] >>> 1/i Traceback (most recent call last): File "", line 1, in -toplevel- 1/i ZeroDivisionError: integer division or modulo by zero >>> b = a * 1.5 >>> b array([[0.0, 1.5], [3.0, 4.5]], dtype=object) >>> N.floor(b) Traceback (most recent call last): File "", line 1, in -toplevel- N.floor(b) AttributeError: 'float' object has no attribute 'floor' >>> ---------------------------------------------- An additional problem involves classes that have e.g. __rmul__ methods defined and are sufficiently similar to numpy arrays that my classes' __rmul__ methods are not invoked when using numpy scalars. Using the 'O' dtype gives me Python types that raise zero division errors appropriately (for my code) and the desired calls to e.g. __rmul__ methods, but reduced functionality in other repects. I might (I hope) be missing something obvious; but it seems like, to be safe, I'm going to have to do a lot of explicit conversions to Python types (or abandon catching zero division errors, and documenting some of my classes to highlight that whether scalar * a equals a * scalar depends on whether a.__rmul__ is called, which depends on the type of scalar). I suppose I might get round both issues by subclassing existing numpy dtypes. Any ideas? Cheers. TIA. Duncan From see_signature at nospam.nowire.org Tue Apr 24 07:52:44 2007 From: see_signature at nospam.nowire.org (=?ISO-8859-1?Q?Thomas_Kr=FCger?=) Date: Tue, 24 Apr 2007 13:52:44 +0200 Subject: Catching a specific IO error In-Reply-To: References: Message-ID: Tina I schrieb: > Now, this works but of course it catches every IOError, and I can not > figure out how to restrict it to only catch the "[Errno 2]"? There's an example that uses the error number: http://docs.python.org/tut/node10.html#SECTION0010300000000000000000 Thomas -- sinature: http://nospam.nowire.org/signature_usenet.png From michele.simionato at gmail.com Thu Apr 26 11:25:56 2007 From: michele.simionato at gmail.com (Michele Simionato) Date: 26 Apr 2007 08:25:56 -0700 Subject: Access to raw command line? In-Reply-To: <1177571070.229968.155710@t39g2000prd.googlegroups.com> References: <1177571070.229968.155710@t39g2000prd.googlegroups.com> Message-ID: <1177601156.426811.313490@b40g2000prd.googlegroups.com> On Apr 26, 9:04 am, Pieter Edelman wrote: > Hi, > > I'm currently writing a command-line program in Python, which takes > commands in the form of: > ./myprog.py [OPTIONS] ARGS Once you start having too many arguments and options on the command line, you might consider using the cmd module of the standard library instead. Then you could implement your own expansion, and you would have portability for non-Unix system too. Michele Simionato From apardon at forel.vub.ac.be Fri Apr 20 10:34:41 2007 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 20 Apr 2007 14:34:41 GMT Subject: Do other Python GUI toolkits require this? References: <462697A6.6010007@codebykevin.com> <465B30B4-5BA0-459A-BE6F-1038874FA74B@jedimindworks.com> <58rq32F2fo980U1@mid.uni-berlin.de> <1177077506.429242.161690@e65g2000hsc.googlegroups.com> Message-ID: On 2007-04-20, Paul Boddie wrote: > On 20 Apr, 15:22, Antoon Pardon wrote: >> On 2007-04-20, Diez B. Roggisch wrote: >> >> > Which is nonsense. The goal is to go from A - ignorance - to B - >> > knowledge - which both lie on the X-Axis. >> >> Well if you want to do it that way, nobody can stop you, but people >> in the habit of processing numbers usually put the time on the X-axis >> like in time spend learning or exercising and put the other value >> on the Y-axis. > > But time wasn't mentioned. Wel what is the second variable then? > You could have knowledge or accomplishment > on the X axis and effort or work on the Y axis. What else is effort than the time you spent on it? And yes you could do that, but in general it is not done because such an organisation would make your curve no longer a function. Situations could occur where more effort will result in less knowledge; where new material seem to conflict with older material resulting in confusion. With an arrangement of axes like you proposed that would result in an inverted c like curve. So you no longer have the familiar up and down movement but a movement going left and right. -- Antoon Pardon From bdesth.quelquechose at free.quelquepart.fr Wed Apr 11 16:17:54 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Wed, 11 Apr 2007 22:17:54 +0200 Subject: Problem with getting an option value In-Reply-To: <1176237977.075245.324880@8g2000cwh.googlegroups.com> References: <1176237977.075245.324880@8g2000cwh.googlegroups.com> Message-ID: <461d394f$0$6795$426a34cc@news.free.fr> Nanjundi a ?crit : > On Apr 10, 10:23 am, "Lucas Malor" <80xuux... at sneakemail.com> wrote: > >> Thank you. Do you know also if I can do a similar operation with >> functions? I want to select with a string a certain get() function >> of ConfigParser: >> >> if type == "int" : funcname = "getint" elif type == "bool" : >> funcname = "getboolean" etc. >> > >> How can I invoke the funcion with its name in a string? > > Use exec to assign to a variable. Oh, yes, soooo simple !-) > >>>> def testPrint(msg): > > ... print 'Msg: %s' % msg ... > >>>> sfunc = "testPrint" exec("f = %s" % sfunc) f('Hello Python') > > Msg: Hello Python > > & use 'f = self.%s' % name for class methods. > > Hope its not a bad practice! Using exec (or eval) is not a bad practice in itself, but using it when there are much simpler solutions is certainly a WTF. See the other posts in this thread for more idiomatic solutions to the OP's problem (mainly: dict-based dispatch, use of getattr on module objects, and use of the locals() and/or globals() builtins). HTH From steve at holdenweb.com Fri Apr 20 11:11:24 2007 From: steve at holdenweb.com (Steve Holden) Date: Fri, 20 Apr 2007 11:11:24 -0400 Subject: wxPython and how to return text entry to main program? In-Reply-To: <1177078099.337536.79490@q75g2000hsh.googlegroups.com> References: <1177011490.435609.155870@o5g2000hsb.googlegroups.com> <1177030290.529322.56210@p77g2000hsh.googlegroups.com> <1177078099.337536.79490@q75g2000hsh.googlegroups.com> Message-ID: kyosohma at gmail.com wrote: > On Apr 19, 9:05 pm, Steve Holden wrote: >> 7stud wrote: >>> On Apr 19, 1:38 pm, Tyler wrote: >> [after quoting umpteen lines of code] >> >> >> >> >> >>> You can do this: >>> --- >>> class MyFrame(wx.Frame): >>> .. >>> .. >>> .. >>> def OnSubmit(self, event): >>> globals()["userInput"] = self.txtCtrlName.GetValue() >>> self.Close() >>> app = MyApp() >>> app.MainLoop() >>> print userInput >>> ----- >> Please try to limit your quoting to what's relevant. >> >> 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 > > Steve, > > I think Tyler is opening a custom dialog from his main GUI > application. He should have used "ShowModal" if he was using one of > wxPython's standard dialog boxes, but since he was creating his own > custom one he didn't need to, which is why I told him to use the > self.Close(True) method to destroy the dialog. Then again, maybe I am > being "wrong-headed" about the whole thing. > > I was trying to come up with the "instance variable" way of storing > the variables, but I could not think of how to implement it last > night. Here are some other threads on the topic that I thought were > interesting: > > http://mail.python.org/pipermail/tutor/2005-May/038648.html > http://lists.wxwidgets.org/archive/wxPython-users/msg06482.html > http://www.daniweb.com/techtalkforums/thread60439.html > > Well, if the whole application is GUI based then yes, the dialog should inherit from wx.Dialog not wx.Frame, it should be opened using ShowModal either at the click of a button or when the application starts, and everything then becomes easy. The "Run" button event handler should then call EndModal(wx.OK) - there can also then be a cancel button that calls EndModal(wx>CANCEL), I think, but it's been a while. The advantage of this is that the dialog still exists after ShowModal() returns (which is what the call to EndModal() causes to happen). So usually you can do something like this (untested pseudo-code): dlg = MyDialog(args_if_needed) dlg.ShowModal() something = dlg.Control.GetValue() somethingElse = dlg.OtherControl.GetValue() ... repeat at will ... dlg.Destroy() This is the most often-used pattern for returning data from a dialog, but it wasn't easy to see how to adapt that to Tyler's original code. I made the mistake of assuming that Tyler knew a bit more about wxPython that was actually the case, so I am sorry if the advice was off-target. 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 sjmachin at lexicon.net Sat Apr 7 05:29:13 2007 From: sjmachin at lexicon.net (John Machin) Date: 7 Apr 2007 02:29:13 -0700 Subject: os.path.isfile() error In-Reply-To: <1175936167.548551.289600@n76g2000hsh.googlegroups.com> References: <1175936167.548551.289600@n76g2000hsh.googlegroups.com> Message-ID: <1175938153.275420.239070@d57g2000hsg.googlegroups.com> On Apr 7, 6:56 pm, "7stud" wrote: > Here's the code: > ------------ > import os, os.path, pprint > > mydir = "/Users/me/2testing" > > files = [file for file in os.listdir(mydir)] > pprint.pprint(files) > > print os.path.join(mydir, "helloWorld.py") > > files = [file > for file in os.listdir(mydir) > if os.path.isfile(os.path.join(dir, file) ) > ] > > pprint.pprint(files) > ----output:---------------- > > ['.DS_Store', 'cpTest', 'dir1', 'testfile1', 'xmlFile.xml'] > /Users/me/2testing/helloWorld.py > Traceback (most recent call last): > File "test1.py", line 16, in ? > files = [file > File "/System/Library/Frameworks/Python.framework/Versions/2.3/lib/ > python2.3/posixpath.py", line 62, in join > elif path == '' or path.endswith('/'): > AttributeError: 'builtin_function_or_method' object has no attribute > 'endswith' Re your subject: os.path.isfile is nothing to do with the problem. As is evident from the traceback, the error (which is in *your* code) was detected in os.path.join, before os.path.isfile was called. Looking at the source file (posixpath.py), one sees that the offending "path" (the builtin function/method with no endswith attribute) is the first formal arg of os.path.join. You have supplied "dir" as the first actual arg. dir is a builtin function. You meant "mydir" instead. BTW, don't use "file" (or the name of any other builtin function) for your own variables. Use meaningful names -- what you have called "file" is not a file, it is the name of a file. Get pychecker and/or pylint and run them over your source periodically. They'll detect not only shadowing builtins but many other types of actual and potential gotchas. HTH, John From DustanGroups at gmail.com Sat Apr 14 09:24:12 2007 From: DustanGroups at gmail.com (Dustan) Date: 14 Apr 2007 06:24:12 -0700 Subject: Stdout In-Reply-To: References: Message-ID: <1176557052.084680.142070@n76g2000hsh.googlegroups.com> On Apr 14, 2:49 am, gbast... at pasteur.fr wrote: > Dear Users, > > I am trying to recover through the python function > popen3 the stdout,in,err of a launched process. > > I would like also to recover the stdout which you can > get only through the command: command1 >& filename > > Do you know how I can access to that stdout by python? I'm not sure if I understand your entire post, but in python, you get access to stdout through the sys module: >>> print 'hello, world!' hello, world! >>> import sys >>> sys.stdout.write('hello, world!') hello, world! >>> > Thanks > > GIacomo From kw at codebykevin.com Tue Apr 10 16:52:12 2007 From: kw at codebykevin.com (Kevin Walzer) Date: Tue, 10 Apr 2007 16:52:12 -0400 Subject: About Trolltech QT OpenSource license. In-Reply-To: <1176237050.409742.8760@30g2000cwc.googlegroups.com> References: <1176233376.712861.67160@o5g2000hsb.googlegroups.com> <1176237050.409742.8760@30g2000cwc.googlegroups.com> Message-ID: king kikapu wrote: > As i said, i do not fully understand all this license stuff. All i > want to ask is, i can make GPL software and gain money from this ? Yes. Nothing in the GPL prevents you from developing and marketing an application for as high a price as you can get from it. HOWEVER: you will have to distribute the source code to your application to anyone who purchases a binary from you. AND: they will be permitted under the GPL to redistribute your application, source code and all. The GPL would allow them to buy your application from you and then redistribute it at no cost to others. Most commercial shrink-wrap software depends on enforcing restrictions on end users to compel a revenue stream: withholding some of the application's functionality prior to payment, hiding the locking algorithm inside obfuscated source code, and prohibiting modification and redistribution of the application and/or its code. If this is your business model, then the GPL is probably not for you. If you use the GPL, you would have to make your locking alogrithim as plain as day; someone out there would likely have the knowledge to patch your software to work without the locking algorithm, assuming they obtained the binary and source code legally (either by purchasing it from you or obtaining it from someone who purchased it from you); and they would be legally free to redistribute the patched application, with or without cost. Of course, there's no guarantee this will happen; such patching also happens with closed-source software. But many commercial developers look at the GPL and decide that this is a risk they do not want to take. --Kevin -- Kevin Walzer Code by Kevin http://www.codebykevin.com From bruno.42.desthuilliers at wtf.websiteburo.oops.com Wed Apr 4 06:47:46 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Wed, 04 Apr 2007 12:47:46 +0200 Subject: Need help on reading line from file into list In-Reply-To: <1175676774.949776.278150@l77g2000hsb.googlegroups.com> References: <1175630106.220186.107900@y66g2000hsf.googlegroups.com> <4612b8f2$0$28546$426a74cc@news.free.fr> <1175633434.823351.69800@q75g2000hsh.googlegroups.com> <4612c400$0$26325$426a74cc@news.free.fr> <1175676774.949776.278150@l77g2000hsb.googlegroups.com> Message-ID: <46138246$0$15440$426a74cc@news.free.fr> bearophileHUGS at lycos.com a ?crit : > Bruno Desthuilliers: >> result = [line.strip() for line in f.readlines()] > > Probably better, lazily: > result = [line.strip() for line in infile] This is of course better in the general case, but I wanted to stay consistant with the other examples... From steve1791 at REMOVETHISNOWgmail.com Mon Apr 2 21:34:28 2007 From: steve1791 at REMOVETHISNOWgmail.com (Steve) Date: Tue, 3 Apr 2007 11:34:28 +1000 Subject: Question about text in Python In-Reply-To: <57cbejF2cataiU1@mid.individual.net> References: <4610c366$0$15022$5a62ac22@per-qv1-newsreader-01.iinet.net.au> <57cbejF2cataiU1@mid.individual.net> Message-ID: <4611af55$0$15038$5a62ac22@per-qv1-newsreader-01.iinet.net.au> Yes it is. Where else to ask for help but here. Thanks for your help everyone. I figured it out. "Bjoern Schliessmann" wrote in message news:57cbejF2cataiU1 at mid.individual.net... > Steve wrote: > >> What I want to add to the program is the abilty to rerun this >> process (where the user enteres another line of text) until the >> user has had enough and enters a blank line which would then end >> the program. > > Homework? > > Regards, > > > Bj?rn > > -- > BOFH excuse #106: > > The electrician didn't know what the yellow cable was so he yanked > the ethernet out. > From jeremyfee at gmail.com Thu Apr 19 15:29:35 2007 From: jeremyfee at gmail.com (jeremyfee at gmail.com) Date: 19 Apr 2007 12:29:35 -0700 Subject: Spawn/Exec with asterisk in argument In-Reply-To: References: <1176942943.090705.281320@l77g2000hsb.googlegroups.com> Message-ID: <1177010974.882644.159660@d57g2000hsg.googlegroups.com> On Apr 18, 7:24 pm, Michael Hoffman wrote: > If you want to process asterisk the way the shell does, you can pass > things through the shell. os.system is one way of doing that. Probably > better is: > > subprocess.check_call("ls -l *", shell=True) Thanks for the reply Michael. I used ls as a simple example, but I'm using this with scp to transfer files and need shell expansion. It makes sense since the shell isn't spawning the process, but it's been a while since I've worked with ipc. I had converted to os.system before posting, but subprocess gives me more control than I originally hoped for Thanks again From mike at uk.maibaum.org Thu Apr 19 06:06:14 2007 From: mike at uk.maibaum.org (Michael Maibaum) Date: Thu, 19 Apr 2007 11:06:14 +0100 Subject: Do other Python GUI toolkits require this? In-Reply-To: <462697A6.6010007@codebykevin.com> References: <462697A6.6010007@codebykevin.com> Message-ID: On 18/04/07, Kevin Walzer wrote: > > James Stroud wrote: > > > This appears more or less unique to Objective C. It looks that with > > PyObjC, you have to interact with the Objective C runtime to manage > > memory. This is not required, thankfully, with any other GUI tookits > > I've seen. > > > > I think the main difference is that PyObjC is not a GUI toolkit per se, > > but is simply a means to make the Objective C runtime (and hence Cocoa) > > available via a python layer. > > > > James > > That's kind of what I thought. Memory management? In Python? *shudder* I'm wondering if this might go away with the arrival of garbage collection in ObjectiveC? Michael -------------- next part -------------- An HTML attachment was scrubbed... URL: From peter.mosley at talk21.com Thu Apr 19 17:22:14 2007 From: peter.mosley at talk21.com (peter) Date: 19 Apr 2007 14:22:14 -0700 Subject: Screen Control in WinXP and Linux In-Reply-To: References: <1176847598.832345.220270@b75g2000hsg.googlegroups.com> Message-ID: <1177017734.463725.278890@e65g2000hsc.googlegroups.com> Thanks for these replies. Clearly what I'm looking for does not exist - yet! I've started by looking at Frederik Lundh's Console module. It looks promising, although on basis of ten minutes experience I can't yet figure out how to use it properly. Perhaps I should study Frederik's examples .... Peter From kyosohma at gmail.com Fri Apr 27 11:24:50 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: 27 Apr 2007 08:24:50 -0700 Subject: Accessing SQL View with Python Message-ID: <1177687490.404875.170650@s33g2000prh.googlegroups.com> Hi All, I need to access a Microsoft SQL database View. Is there a way to do this with Python? I have done a fair share of "googling" and found nothing on accessing Views, just executing SQL, which I already know how to do. I am running Windows XP, Python 2.4. Thanks a lot! Mike From martin.laloux at gmail.com Thu Apr 12 07:04:59 2007 From: martin.laloux at gmail.com (martin.laloux at gmail.com) Date: 12 Apr 2007 04:04:59 -0700 Subject: SQLite problems In-Reply-To: <1176371562.110295.217360@l77g2000hsb.googlegroups.com> References: <1176371562.110295.217360@l77g2000hsb.googlegroups.com> Message-ID: <1176375899.401083.216620@e65g2000hsc.googlegroups.com> > I run Python 2.5 on a Mac OS X system with SQLite 3.2.8 installed via > fink. Why fink ?, it is very easy to make sqlite. download the source, configure, make and install from terminal From bbxx789_05ss at yahoo.com Sun Apr 1 23:24:43 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: 1 Apr 2007 20:24:43 -0700 Subject: can a method access/set another's variables? In-Reply-To: References: <1175477764.549115.159410@n59g2000hsh.googlegroups.com> Message-ID: <1175484283.702475.76740@b75g2000hsg.googlegroups.com> On Apr 1, 7:43 pm, Michael Hoffman wrote: > asdf1234234 wrote: > > -a.py- > > import b > > > class A: > > def __init__(self): > > pass > > def my_method(self): > > var = 1 > > self.var = 2 > > b.set_var(self) > > print var > > print self.var > > > my_a = A() > > my_a.my_method() > > > -b.py- > > def set_var(self): > > var = 2 > > self.var = 2 > > > I want both var and self.var to be 2 at the end. Is there anything I > > can pass to set_var() that will give it access to the variables in > > my_method() like I can use self for the variables in the class A? > > I hope there isn't a way to do this that simply. :) Why do you want to > do this, or is it idle curiosity? There is almost surely a better way to > solve your underlying problem. > > You can *read* your caller's local variables (either pass locals() as an > argument or use inspect to get the frame locals), but writing to this > dictionary has undefined behavior. > -- > Michael Hoffman class A(object): def early_parse(self): self.result1 = eval("10+5") def later_parse(A_obj): A_obj.result2 = eval("20*2") a = A() a.early_parse() later_parse(a) print a.result1 print a.result2 From Leo.Kislov at gmail.com Sun Apr 1 17:24:17 2007 From: Leo.Kislov at gmail.com (Leo Kislov) Date: 1 Apr 2007 14:24:17 -0700 Subject: I18n issue with optik In-Reply-To: References: Message-ID: <1175462657.413779.286590@l77g2000hsb.googlegroups.com> On Apr 1, 8:47 am, Thorsten Kampe wrote: > I guess the culprit is this snippet from optparse.py: > > # used by test suite > def _get_encoding(self, file): > encoding = getattr(file, "encoding", None) > if not encoding: > encoding = sys.getdefaultencoding() > return encoding > > def print_help(self, file=None): > """print_help(file : file = stdout) > > Print an extended help message, listing all options and any > help text provided with them, to 'file' (default stdout). > """ > if file is None: > file = sys.stdout > encoding = self._get_encoding(file) > file.write(self.format_help().encode(encoding, "replace")) > > So this means: when the encoding of sys.stdout is US-ASCII, Optparse > sets the encoding to of the help text to ASCII, too. .encode() method doesn't set an encoding. It encodes unicode text into bytes according to specified encoding. That means optparse needs ascii or unicode (at least) for help text. In other words you'd better use unicode throughout your program. > But that's > nonsense because the Encoding is declared in the Po (localisation) > file. For backward compatibility gettext is working with bytes by default, so the PO file encoding is not even involved. You need to use unicode gettext. > How can I set the encoding of sys.stdout to another encoding? What are you going to set it to? As I understand you're going to distribute your program to some users. How are you going to find out the encoding of the terminal of your users? -- Leo From bjourne at gmail.com Sat Apr 14 13:49:51 2007 From: bjourne at gmail.com (=?ISO-8859-1?Q?BJ=F6rn_Lindqvist?=) Date: Sat, 14 Apr 2007 19:49:51 +0200 Subject: Python Feature Request: Add the "using" keyword which works like "with" in Visual Basic In-Reply-To: <740c3aec0704141046x7bcb2ac0qb924a04440633124@mail.gmail.com> References: <1176547372.584539.89170@q75g2000hsh.googlegroups.com> <1176560672.108264.44890@p77g2000hsh.googlegroups.com> <740c3aec0704141046x7bcb2ac0qb924a04440633124@mail.gmail.com> Message-ID: <740c3aec0704141049n7ad0b988m69f739c91a573493@mail.gmail.com> On 4/14/07, BJ?rn Lindqvist wrote: > On 14 Apr 2007 07:24:32 -0700, jamadagni wrote: > > > You already can emulate the using statement like this: > > > > You can emulate only assignments like this. How would you emulate > > function calls, like the ones in my example? > > You can't, of course. But using the with statement: > > using self.q: > .doit() > > becomes: > > with self.quit as q: > q.doit() Er.. I guess there are some details you need to work out for that. But in principle, it works fine. -- mvh Bj?rn From krisbee1983 at gmail.com Wed Apr 4 14:17:40 2007 From: krisbee1983 at gmail.com (krisbee1983 at gmail.com) Date: 4 Apr 2007 11:17:40 -0700 Subject: Getting word frequencies from files which are in folder. Message-ID: <1175710660.753453.205000@n76g2000hsh.googlegroups.com> Hello to all, I'm beginer in learning Python I wish somebody help me with solving this problem. I would like to read all text files wchich are in some folder. For this text files I need to make some word frequencies using defined words like "buy", "red", "good". If some file don't have that word will get "0" for this frequency. It shoud be stored in array. If I have alredy got frequencies for every file in folder, my array wrote to text file. I will be very gratefully for receiving any help. From nagle at animats.com Fri Apr 27 13:42:07 2007 From: nagle at animats.com (John Nagle) Date: Fri, 27 Apr 2007 10:42:07 -0700 Subject: My newbie annoyances so far In-Reply-To: References: <1177688082.758043.133920@r30g2000prh.googlegroups.com> Message-ID: <3zqYh.1800$uJ6.1494@newssvr17.news.prodigy.net> Dennis Lee Bieber wrote: > On 27 Apr 2007 08:34:42 -0700, Paul McGuire > declaimed the following in comp.lang.python: > > >>deficient - ternary expressions are now part of the language after >>years of refugees from C and C++ asking how to write "a = b ? c : d", >>and now they'll get to puzzle/gripe over mapping this to "a = c if b >>else d". But as a newbie, you need to invest a little more time and > > > And I'll probably ignore those expressions whenever I do get around > to 2.5+... That syntax, in my mind, just... stinks... ALGOL used "expression IF"; you could write x := (IF a > b THEN a ELSE b); but that doesn't map well to an indentation-based language. A syntax suitable for Python, now that there's a bool type, might be to define ".if()" for "bool". Then one could write (a > b).if(a,b) which is better than adding an operator. Such things are useful in formatting expressions. msg = 'Unit is %s' % (unitstatus.if("on","off"),) but not really essential. John Nagle From plutoinchina at gmail.com Wed Apr 4 06:36:12 2007 From: plutoinchina at gmail.com (autin) Date: 4 Apr 2007 03:36:12 -0700 Subject: bool value 'False' no memory address? Message-ID: <1175682972.507206.29000@n76g2000hsh.googlegroups.com> such as: >>>b = False >>>id(b) Traceback (most recent call last): File "", line 1, in ? TypeError: 'bool' object is not callable --- how to desc it? From shandy.b at gmail.com Wed Apr 11 13:20:13 2007 From: shandy.b at gmail.com (shandy.b at gmail.com) Date: 11 Apr 2007 10:20:13 -0700 Subject: ValueError: too many values to unpack In-Reply-To: <1176311618.617765.120560@p77g2000hsh.googlegroups.com> References: <1176311618.617765.120560@p77g2000hsh.googlegroups.com> Message-ID: <1176312013.590991.294520@l77g2000hsb.googlegroups.com> That happens when you try something like this: a,b,c = [1,2,3,4] It means there are more items on the right side than the left. You probably have < 11 variables on the left side. On Apr 11, 10:13 am, "fscked" wrote: > Trying to use CSV to read in a line with 11 fields and I keep getting > this error. I have googled a bit and have been unable to figure it out. From bbxx789_05ss at yahoo.com Tue Apr 3 01:06:12 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: 2 Apr 2007 22:06:12 -0700 Subject: getattr/setattr q. In-Reply-To: <1175573213.682671@jubilee.claranet.pt> References: <1175573213.682671@jubilee.claranet.pt> Message-ID: <1175576772.241573.256980@b75g2000hsg.googlegroups.com> On Apr 2, 10:08 pm, Paulo da Silva wrote: > Is it possible to use getattr/setattr for variables not inside > classes...? What does the python documentation say about the definition of setattr()? From ask at me Wed Apr 4 07:30:35 2007 From: ask at me (alf) Date: Wed, 04 Apr 2007 06:30:35 -0500 Subject: SNMP agent In-Reply-To: <1175680387.575097.4590@e65g2000hsc.googlegroups.com> References: <1175680387.575097.4590@e65g2000hsc.googlegroups.com> Message-ID: alain wrote: > Hi, > > I have a Python app and i would like to add some SNMP agent > functionality to it. > I know it's possible to write a sub-agent with netsnmp but it is in C > and quite complicated. > I know of YAPSNMP (a wrapper around NETSNMP) but it doesn't seem to > support agent writing. > Any suggestion ? > > Thanks to all in advance > > Alain > twistedmatrix.org? From tjreedy at udel.edu Fri Apr 6 16:38:19 2007 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 6 Apr 2007 16:38:19 -0400 Subject: Basic Serialization - a design decision question References: <5d2e4d280704060940s3fa1defdl874c8c4e7fa92266@mail.gmail.com> Message-ID: "Gizmo" wrote in message news:5d2e4d280704060940s3fa1defdl874c8c4e7fa92266 at mail.gmail.com... | Hello | I am a relative newcomer to Python, and I am studying it to understand its | design. It intrigues me. | I recently studied Serialization of classes via the pickle/cPickle library, | and I have a question. | | Why is Serialization handled by a separate library (ie, pickle). Is it | possible, by design, to have serialization "internally" implemented via an | implicit ___serialize___ method? Ofcourse, you have to make this method not | overrideable (sp?). For example, the __repr__ method gives us the string | representation of a class... similarly, the __serialize__ method would give | us the "serial norm" representation of the class. Pickle has the factored-out code common to all classes. It uses .__reduce__() for each, which has the class-specific code. | This would allow me to do something like this, | conn.send(serial(myClass)); // or something like that? I believe pickle does more than just that. tjr From larry.bates at websafe.com Thu Apr 19 14:46:26 2007 From: larry.bates at websafe.com (Larry Bates) Date: Thu, 19 Apr 2007 13:46:26 -0500 Subject: Creating search engine in Python Good or Bad [in performance] In-Reply-To: <1177007283.157437.271230@n76g2000hsh.googlegroups.com> References: <1177007283.157437.271230@n76g2000hsh.googlegroups.com> Message-ID: Clement wrote: > I am now creating IR engine in python which has its own database > implementation . For nearly 2GB files it works fast. Can i expect the > same speed when my database goes large. Else i have to chose other > language[c/c++] for the speed............. > Please tell me the solution................................ > Your speed will be good if your database design is good. We don't have a crystal ball out here to see into your database design. It is also not clear what the bottlenecks to "speed" would be for you. If it is disk I/O or LAN bandwidth C won't help at all. -Larry From samjnaa at gmail.com Sat Apr 14 09:35:34 2007 From: samjnaa at gmail.com (jamadagni) Date: 14 Apr 2007 06:35:34 -0700 Subject: Python Feature Request: Explicit variable declarations In-Reply-To: References: <1176546078.934340.253810@y5g2000hsa.googlegroups.com> Message-ID: <1176557734.456820.275780@p77g2000hsh.googlegroups.com> > Languages like Perl and VB need a strict mode because they will > auto-vivify variable for you. I.e. they will bring variables to life > with defined or undefined values if you use them in a l-value (left hand > side of an assignment) without having declared them prior. If you do > that in Python you get an exception. I don't comprehend. I can just type a = 5 in a new Python session and I get no exception. Python currently does not require variables to be declared before they are used on the LHS. From Robert.Katic at gmail.com Wed Apr 11 02:39:19 2007 From: Robert.Katic at gmail.com (goodwolf) Date: 10 Apr 2007 23:39:19 -0700 Subject: Does python have the static function member like C++ In-Reply-To: <1176261542.704649.240350@n76g2000hsh.googlegroups.com> References: <1176260903.362329.59370@o5g2000hsb.googlegroups.com> <1176261542.704649.240350@n76g2000hsh.googlegroups.com> Message-ID: <1176273559.047449.263710@n76g2000hsh.googlegroups.com> On Apr 11, 5:19 am, "7stud" wrote: > On Apr 10, 9:08 pm, "???????????????" wrote: > > > I define the class like this: > > class AAA: > > counter = 0 > > def __init__(self): > > pass > > def counter_increase(): > > AAA.counter += 1 > > print "couter now :", AAA.counter > > > But how could I call the function "counter_incrrease" ? > > > Thanks ! > > 1) > class AAA: > counter = 0 > def __init__(self): > pass > @staticmethod > def counter_increase(): > AAA.counter += 1 > print "couter now :", AAA.counter > > AAA.counter_increase() > > 2) > class AAA: > counter = 0 > def __init__(self): > pass > def counter_increase(): > AAA.counter += 1 > print "couter now :", AAA.counter > counter_increase = staticmethod(counter_increase) > > AAA.counter_increase() > > 3) > class AAA: > counter = 0 > def __init__(self): > pass > def counter_increase(self): > AAA.counter += 1 > print "couter now :", AAA.counter > aaa = AAA() > AAA.counter_increase(aaa) 1. In this case you will prefer a classmethod instead a staticmethod. 2. If counter is the number of instances of class AAA then you will incrase counter inside __init__ method. class AAA (object): counter = 0 def __init__(self): type(self).counter_increase() @classmethod def counter_increase(cls): cls.counter += 1 or class AAA (object): counter = 0 def __init__(self): type(self).counter += 1 From jorgen.maillist at gmail.com Thu Apr 19 12:54:50 2007 From: jorgen.maillist at gmail.com (Jorgen Bodde) Date: Thu, 19 Apr 2007 18:54:50 +0200 Subject: Relative import problem Message-ID: <11e49df10704190954y100a2dd3s3879d9cb5f262ebd@mail.gmail.com> Hi all, I want to structure my app so that I have two dirs like; obj/{object files} gui/{gui files} Here comes the catch. From the GUI dir, I would like to access the obj submodule path. I need to go one dir back.. I read there was something like from .. import x in python 2.5 so that I could access my obj dir from a lower level, but I have problems getting this to work. Example; In the main dir I have; main.py: -------- import gui gui.gui.startme() -------- In the obj dir I have; obj/obj.py --------- def start(): print 'Started OBJ' --------- In the GUI dir I have gui/gui.py --------- from .. import obj def start(): obj.obj.start() --------- This does not work. It gives me; D:\personal\src\GuitarPortfolio\tmp>python start.py Traceback (most recent call last): File "start.py", line 4, in gui.gui.start() AttributeError: 'module' object has no attribute 'gui' Am I shooting myself in the foot by trying to structure? Or are there better more elegant ways? Regards, - Jorgen From bj_666 at gmx.net Wed Apr 18 15:37:47 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Wed, 18 Apr 2007 21:37:47 +0200 Subject: Nested dictionaries trouble References: <1176317876.917874.58040@n59g2000hsh.googlegroups.com> <1176325715.951076.4790@w1g2000hsg.googlegroups.com> <1176923772.011976.116190@p77g2000hsh.googlegroups.com> Message-ID: In <1176923772.011976.116190 at p77g2000hsh.googlegroups.com>, IamIan wrote: > years = ["199%s" % x for x in range(0,10)] > years += ["200%s" % x for x in range(0,10)] > > I haven't had any luck doing this in one line though. Is it possible? In [48]: years = map(str, xrange(1999, 2011)) In [49]: years Out[49]: ['1999', '2000', '2001', '2002', '2003', '2004', '2005', '2006', '2007', '2008', '2009', '2010'] Ciao, Marc 'BlackJack' Rintsch From paddy3118 at googlemail.com Sat Apr 14 06:48:28 2007 From: paddy3118 at googlemail.com (Paddy) Date: 14 Apr 2007 03:48:28 -0700 Subject: Python editor/IDE on Linux? In-Reply-To: References: Message-ID: <1176547708.418058.300940@y5g2000hsa.googlegroups.com> On Apr 13, 7:20 pm, "Jack" wrote: > I wonder what everybody uses for Python editor/IDE on Linux? > I use PyScripter on Windows, which is very good. Not sure if > there's something handy like that on Linux. I need to do some > development work on Linux and the distro I am using is Xubuntu. When the Linux distros wanted an editor, they did not choose Emacs or emaacs vi mode. They chose vim. Emacs users: Margaret Thatcher, Nixon, The Joker. Max Wall. Vim users: Nelson Mandella, Ghandi, Isambard Kingdom Brunel, Batman. The Silver Surfer. Edison. Max Planck Notepad user: G.W. Bush. See, it's clear! - Paddy ;-) From http Sun Apr 29 12:33:41 2007 From: http (Paul Rubin) Date: 29 Apr 2007 09:33:41 -0700 Subject: While we're talking about annoyances References: Message-ID: <7x1wi3dtsq.fsf@ruckus.brouhaha.com> Steven D'Aprano writes: > I recently needed to write a function to generate a rank table from a > list. That is, a list of ranks, where the rank of an item is the position > it would be in if the list were sorted: > > alist = list('defabc') > ranks = [3, 4, 5, 0, 1, 2] fst = operator.itemgetter(0) # these should be builtins... snd = operator.itemgetter(1) ranks=map(fst, sorted(enumerate(alist), key=snd)) From jim.hefferon at gmail.com Fri Apr 27 09:59:04 2007 From: jim.hefferon at gmail.com (Jim) Date: 27 Apr 2007 06:59:04 -0700 Subject: getting rid of EOL character ? In-Reply-To: <268cc$4631f634$83aef404$27224@news1.tudelft.nl> References: <268cc$4631f634$83aef404$27224@news1.tudelft.nl> Message-ID: <1177682344.810546.51990@n35g2000prd.googlegroups.com> If you have a recent Python, see the documentation for open on the library page for built-in functions. http://docs.python.org/lib/built-in-funcs.html Jim From larry.bates at websafe.com Mon Apr 2 18:26:04 2007 From: larry.bates at websafe.com (Larry Bates) Date: Mon, 02 Apr 2007 17:26:04 -0500 Subject: doing standart window icons unvisible in python In-Reply-To: <1175549454.378661.93570@y66g2000hsf.googlegroups.com> References: <1175549454.378661.93570@y66g2000hsf.googlegroups.com> Message-ID: gslm wrote: > Hi! > I want to do close-minimize icons unvisible in python.How can I do > this?I want to do this especially for printing. > And is it possible to provide .exe file for any program in python or > only we can change the file as .pyw? > I don't understand what you mean by close-minimize icons unvisible, but I can answer the .exe question. Take a look at py2exe which allows you to bundle up python program as .exe for distribution. You can see it a www.py2exe.org. -Larry From s_broscious at comcast.net Thu Apr 12 18:38:55 2007 From: s_broscious at comcast.net (Scott) Date: Thu, 12 Apr 2007 18:38:55 -0400 Subject: Lists and Tuples and Much More Message-ID: I'm going to start grouping all my questions in one post as this is my second today, and sorta makes me feel dumb to keep having to bother you all with trivial questions. I'll just seperate my questions with: ------------------------------------------------------------------------------------------- Now onto the issue: List's and Tuple's I don't see the distinction between the two. I mean, I understand that a list is mutable and a tuple is immutable. The thing that I dont understand about them is what, besides that, seperates the two. I did a little experimentation to try to understand it better, but only confused myelf more. A list looks like this: >>>my_list = [1, 2, 3, 4, 5, 6] and a tuple looks like this: >>>my_tuple = (1, 2, 3, 4, 5, 6) Now you can add to a list, but not a tuple so: >>>my_list.append(my_tuple) #or extend for that matter right? [1, 2, 3, 4, 5, 6, (1, 2, 3, 4, 5, 6)] Is that pretty much accurate? And which is better on resources....I'm guessing a tuple seeing as it doesn't change. And the last example brings up another question. What's the deal with a tupple that has a list in it such as: >>>my_tupple = (1, 2, 3, 4, 5, [6, 7, 8, 9]) Now I read somewhere that you could change the list inside that tupple. But I can't find any documentation that describes HOW to do it. The only things I CAN find on the subject say, "Don't do it because its more trouble than it's worth." But that doesn't matter to me, because I want to know everything. --------------------------------------------------------------------------------------------- Now there comes append. I read everywhere that append only add's 1 element to the end of your list. But if you write: >>> my_list = [1, 2, 3, 4, 5, 6] >>> my_list.append([7, 8, 9, 10]) >>> my_list [1, 2, 3, 4, 5, 6, [7, 8, 9, 10]] Is that because list's, no matter what they contain, are counted as 1 element? And how would you sort the list that's in the list? I guess that goes in conjunction with the section above, but still: >>> my_list = [6, 4, 3, 5, 2, 1] >>> my_list.append([7, 9, 8, 10]) >>> my_list.sort() >>> my_list [1, 2, 3, 4, 5, 6, [7, 9, 8, 10]] This is, again, something I'm finding nothing on. --------------------------------------------------------------------------------------------- Maybe I'm just not looking in the right spots. The only things I have as learning aids are: this newsgroup ;p, http://diveintopython.org, http://python.org/, Beggining Python: From Novice to Professional, and (now don't laugh) Python for Dummies. From elguavas at users.sourceforge.net Sat Apr 21 23:08:11 2007 From: elguavas at users.sourceforge.net (Stephen M. Gava) Date: Sun, 22 Apr 2007 03:08:11 -0000 Subject: using tkinter to display html References: <1176988173.015892.273660@e65g2000hsc.googlegroups.com> <1177064902.230394.133830@d57g2000hsg.googlegroups.com> <462A1835.5090005@codebykevin.com> Message-ID: On Sat, 21 Apr 2007 09:57:09 -0400, Kevin Walzer wrote: > Stephen M. Gava wrote: >> On Fri, 20 Apr 2007 03:28:22 -0700, Rob Wolfe wrote: >>>>> The following thread has various ideas in it: >>>>> http://mail.python.org/pipermail/python-list/2001- October/107989.html >>>> thanks mike, i found that thread before i posted here, it doesn'rt >>>> answer my question though. >>> Why not? Did you try to use tkhtml [1]_ with python wrapper [2]_. IMHO >>> it works pretty nice. >> >> i found the tkhtml page but it hasn't been updated since 2002 and the >> mailing list doesn't even exist anymore. so unsure of the future on >> that. >> >>> .. [1] http://www.hwaci.com/sw/tkhtml/ .. [2] >> >> didn't find these bindings though, so thanks, i'll have a play. >> >> stephen. >> >>> http://tix.sourceforge.net/Tixapps/src/Python/TkHtml.py >>> >>> > TkHTML: > > http://tkhtml.tcl.tk ah ok, thanks. i did find this but thought it was unrelated to the widget metionned on the old hwaci.com page and that there weren't any existing tkinter bindings for this project. so the tix.sourceforge.net bindings are for this up to date widget, including the current V3 that supports css and such? (thinking aloud, i'll check that out myself.) thanks mate, stephen. > From ask at me Sat Apr 14 11:59:46 2007 From: ask at me (alf) Date: Sat, 14 Apr 2007 10:59:46 -0500 Subject: compiling modules with VS 2008 for python 2.4 prepared with Visual Studio 2003 In-Reply-To: <461f1a5a$0$996$9b622d9e@news.freenet.de> References: <1hw2ak4.1cxnvt81nzd971N%aleax@mac.com> <461f1a5a$0$996$9b622d9e@news.freenet.de> Message-ID: Martin v. L?wis wrote: >>well, instructions were clear enough for me. What is hard to get why it >>could not use free M$ compiler which is presumably produces compatible >>objects and libraries. > > > This presumption is incorrect. The compiler does *not* create compatible > objects and libraries. It links with msvcr8.dll, whereas Python is > linked with mscvr71.dll; Microsoft does not support mixing CRTs. > complier is just a compiler. perhaps final linking could be somehow tweaked to include msvcrt71 instad of 80. From http Sat Apr 7 17:43:20 2007 From: http (Paul Rubin) Date: 07 Apr 2007 14:43:20 -0700 Subject: itertools, functools, file enhancement ideas Message-ID: <7xveg7rhc7.fsf_-_@ruckus.brouhaha.com> I just had to write some programs that crunched a lot of large files, both text and binary. As I use iterators more I find myself wishing for some maybe-obvious enhancements: 1. File iterator for blocks of chars: f = open('foo') for block in f.iterchars(n=1024): ... iterates through 1024-character blocks from the file. The default iterator which loops through lines is not always a good choice since each line can use an unbounded amount of memory. Default n in the above should be 1 char. 2. wrapped file openers: There should be functions (either in itertools, builtins, the sys module, or whereever) that open a file, expose one of the above iterators, then close the file, i.e. def file_lines(filename): with f as open(filename): for line in f: yield line so you can say for line in file_lines(filename): crunch(line) The current bogus idiom is to say "for line in open(filename)" but that does not promise to close the file once the file is exhausted (part of the motivation of the new "with" statement). There should similarly be "file_chars" which uses the n-chars iterator instead of the line iterator. 3. itertools.ichain: yields the contents of each of a sequence of iterators, i.e.: def ichain(seq): for s in seq: for t in s: yield t this is different from itertools.chain because it lazy-evaluates its input sequence. Example application: all_filenames = ['file1', 'file2', 'file3'] # loop through all the files crunching all lines in each one for line in (ichain(file_lines(x) for x in all_filenames)): crunch(x) 4. functools enhancements (Haskell-inspired): Let f be a function with 2 inputs. Then: a) def flip(f): return lambda x,y: f(y,x) b) def lsect(x,f): return partial(f,x) c) def rsect(f,x): return partial(flip(f), x) lsect and rsect allow making what Haskell calls "sections". Example: # sequence of all squares less than 100 from operator import lt s100 = takewhile(rsect(lt, 100), (x*x for x in count())) From steve at holdenweb.com Thu Apr 19 21:58:26 2007 From: steve at holdenweb.com (Steve Holden) Date: Thu, 19 Apr 2007 21:58:26 -0400 Subject: PythonD 2.4.2 for older Windows / DOS / DJGPP In-Reply-To: <4628183d$0$4606$61c65585@un-2park-reader-01.sydney.pipenetworks.com.au> References: <46279af8$0$4610$61c65585@un-2park-reader-01.sydney.pipenetworks.com.au> <4628183d$0$4606$61c65585@un-2park-reader-01.sydney.pipenetworks.com.au> Message-ID: <46281E42.8060202@holdenweb.com> caddit wrote: > Steve Holden wrote: > >> caddit wrote: >>> Hello. >>> >>> There has been some confusion as to the current version of the python >>> programming language available for DOS. >>> >>> This is partially due to incorrect information kept on python.org, that >>> says "python2.2.1 available for DOS". The actual version is currently >>> 2.4.2. >>> >>> I am also happy to announce that a second release of PythonD. >>> Additionally, there are many fine module libraries hat have been made >>> available including Python-opengl and curses. >>> >>> The URL for PythonD has moved. >>> It is now http://www.caddit.net/pythond >>> >>> not that this is NOT the same as http://www.caddit.net/pythond.php, which >>> it was formerly. Please update your bookmarks. It would also be nice if >>> someone else could raise a ticket to have python.org website updated. >>> >> Submitted as >> >> http://pydotorg.python.org/pydotorg/ticket/423 >> >> Please note: it would have been helpful if you'd given the URL of the >> offending page! There is a "report website bug" link on each page of the >> python.org web site, though at present you have to email someone to get >> posting privileges (this is an anti-spam measure). >> >> regards >> Steve > > > Thanks for this Steve. > > I notice the ticket is already closed. When should I see the changes appear? > Dashed if I know - there must be a bug in the build system, normally changes appear within an hour of being made. Real soon now? I'm copying Andrew Kuchling, who made the changes, on this. He may be able to shed more light on the matter. Probably it will just happen. 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 mail at microcorp.co.za Sun Apr 1 11:19:01 2007 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Sun, 1 Apr 2007 17:19:01 +0200 Subject: socket read timeout References: <17930.25631.86693.827473@montanaro.dyndns.org><000e01c771d2$2f3dd240$03000080@hendrik> Message-ID: <000401c77471$5ee152a0$03000080@hendrik> "Steve Holden" > 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? > > > Yes. But you have to use non-blocking calls in your application to use > them as full-duplex in your code. This seems to bear out the scenario I have described elsewhere in this thread - I think its caused by the file handlers, but I don't _know_ it. > > > I know Ethernet isn't. > > > Don't know much, then, do you? ;-) No not really - I easily get confused by such things as collisions... : - ) - Hendrik From KDawg44 at gmail.com Mon Apr 23 16:02:50 2007 From: KDawg44 at gmail.com (KDawg44) Date: 23 Apr 2007 13:02:50 -0700 Subject: Launch another application Message-ID: <1177358570.341152.171670@n76g2000hsh.googlegroups.com> Hi, I would like to launch another application and pass some arguments to it from python. WHen the user clicks on the button, i want it to execute: binaryApplication fileName Is there a way to do this as if I was doing it from a shell in python? Would it be using something like popen? this app does not need to return anything to the python app i am writing and the python app does not need to wait for it (to close or do anyting else). Thanks. From jorgen.maillist at gmail.com Fri Apr 13 08:38:47 2007 From: jorgen.maillist at gmail.com (Jorgen Bodde) Date: Fri, 13 Apr 2007 14:38:47 +0200 Subject: sqlite3 question In-Reply-To: <1176382582.4220.13.camel@dot.uniqsys.com> References: <1176382582.4220.13.camel@dot.uniqsys.com> Message-ID: <11e49df10704130538s73618ec3n168807ca0cb400cc@mail.gmail.com> Thanks, This is how I did it in the end as well. Yes i use the connection object, abbreviated as 'c' for ease of typing. In my real app the connection is kept inside a singleton object and I use the DB like result = GuitarDB().connection.execute('select * from song where id = 1').fetchone() if result: print 'Found a song' else: print 'Found nothing' I know there will always be a cursor object back from connection.execute, so for ease of use and sparing a temp var, I put the .fetchone() behind the connection.execute() Thanks everyone for their help! - Jorgen On 4/12/07, Carsten Haese wrote: > On Thu, 2007-04-12 at 13:43 +0200, Marc 'BlackJack' Rintsch wrote: > > In , Jorgen Bodde > > wrote: > > > > >>>> r = c.execute('select * from song where id = 1') > > >>>> for s in r: > > > ... print s > > > ... > > > (1, u'Spikedrivers Blues', u'Mississippi John Hurt') > > > > > > That works. But when I can't restore the row by e.g. an ID that does > > > not exist, I cannot see any method in 'r' (which is a SQLite.Cursor) > > > that can tell me if I have rows. As explained in the help, r.rowcount > > > does not give a valid result because it can't determine how many rows > > > are restored in advance. > > > > This should not work because `r` should not be a `Cursor` object. The > > `execute()`-Method returns an integer with the number of "affected rows". > > It does work if 'c' is a connection object with a poorly chosen name. > According to > http://docs.python.org/lib/sqlite3-Connection-Objects.html , sqlite3 > connection objects have a non-standard execute method that creates a > cursor, executes a query on that cursor, and returns that cursor. > > Anyway, if you expect a query to return at most one row, such as when > you're filtering on the table's primary key, this is how I would do it: > > cur.execute("select * from song where id = ?", (wanted_id,) ) > song_row = cur.fetchone() > if song_row: > # Do something with song_row > else: > # Song not found > > HTH, > > Carsten. > > > -- > http://mail.python.org/mailman/listinfo/python-list > On 4/12/07, Carsten Haese wrote: > On Thu, 2007-04-12 at 13:43 +0200, Marc 'BlackJack' Rintsch wrote: > > In , Jorgen Bodde > > wrote: > > > > >>>> r = c.execute('select * from song where id = 1') > > >>>> for s in r: > > > ... print s > > > ... > > > (1, u'Spikedrivers Blues', u'Mississippi John Hurt') > > > > > > That works. But when I can't restore the row by e.g. an ID that does > > > not exist, I cannot see any method in 'r' (which is a SQLite.Cursor) > > > that can tell me if I have rows. As explained in the help, r.rowcount > > > does not give a valid result because it can't determine how many rows > > > are restored in advance. > > > > This should not work because `r` should not be a `Cursor` object. The > > `execute()`-Method returns an integer with the number of "affected rows". > > It does work if 'c' is a connection object with a poorly chosen name. > According to > http://docs.python.org/lib/sqlite3-Connection-Objects.html , sqlite3 > connection objects have a non-standard execute method that creates a > cursor, executes a query on that cursor, and returns that cursor. > > Anyway, if you expect a query to return at most one row, such as when > you're filtering on the table's primary key, this is how I would do it: > > cur.execute("select * from song where id = ?", (wanted_id,) ) > song_row = cur.fetchone() > if song_row: > # Do something with song_row > else: > # Song not found > > HTH, > > Carsten. > > > -- > http://mail.python.org/mailman/listinfo/python-list > From gagsl-py2 at yahoo.com.ar Mon Apr 9 18:42:29 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 09 Apr 2007 19:42:29 -0300 Subject: Comments in ConfigParser module References: <1175977146.653832.245350@p77g2000hsh.googlegroups.com> <7ad76b520704080217q5b35efc3jcec4751d9d84654c@mail.gmail.com> Message-ID: En Sun, 08 Apr 2007 06:17:46 -0300, Joel Granados escribi?: > On 7 Apr 2007 13:19:06 -0700, Gabriel Genellina > wrote: >> >> Joel Andres Granados wrote: >> >> > The module also allows the comments to appear in the same line as the >> > "name = value" constructs. The only difference being that this is >> only >> > possible with ";" and not with "#" character. I did not see this in >> the >> > documentation but this is how it is behaving. >> >> Yes, it's not documented. There is only a comment in the source code: >> >> # ';' is a comment delimiter only if it >> follows >> # a spacing character >> >> I think it's either a bug in the code or in the documentation. > > Yep, IMO its a weirdness in the behavior that is not documented. It was a bit hard, but I finally found the original Windows ini-file specification at where you can see ; used as comment delimiter. ConfigParser tries to handle both RFC822-like headers (with name: value, including continuation lines, but ignoring almost everything else in the syntax) and ini files (with ; as comments), plus some unique features like # comments and "rem" lines removal (?). That is, it tries to cover a lot of formats without a clear specification. Add wrong defaults usage, and the need for SafeConfigParser, and some other gotchas... then switch to use alternative implementations like ConfigObj -- Gabriel Genellina From spamtrap at dot-app.org Thu Apr 5 07:11:35 2007 From: spamtrap at dot-app.org (Sherm Pendley) Date: Thu, 05 Apr 2007 07:11:35 -0400 Subject: Why NOT only one class per file? References: <1175721799.714907.52770@o5g2000hsb.googlegroups.com> <46142acc$0$7532$426a34cc@news.free.fr> <4614b40e$0$26843$426a74cc@news.free.fr> Message-ID: Bruno Desthuilliers writes: > Sherm Pendley a ?crit : > >> It's a stylistic thing, nothing more. > > A bit more than just 'stylistic' IMHO. It's a matter of > convenience. Having to manage hundreds of files each with a dozen > lines of code is a PITA. Yes, but the pain in that case comes from having hundreds of trivial classes, not from the way in which the source for them is organized. > Having to retype the same import statements > in hundreds of files is a PITA - and a good way to waste time and > forget something when one has to fix these import statements (yes, > even with the appropriate tediting tools). I wouldn't call such > considerations "nothing more than stylistic". Neither would I. But then, I would describe the existence of all those files as just the symptom - the real problem being the design that needs all of those hundreds of trivial classes in the first place. Granted, I know very little of Python. It may be the case that Python encourages the use of hundreds of "little classes" - and if that is the case, then I agree, storing each one in its own file would be rather absurd. I'm more accustomed to writing classes that tend to be larger - hundreds if not thousands of lines each, or more - and in that case, storing them one per file is a reasonable way to organize one's sources. sherm-- -- Web Hosting by West Virginians, for West Virginians: http://wv-www.net Cocoa programming in Perl: http://camelbones.sourceforge.net From steve at REMOVE.THIS.cybersource.com.au Wed Apr 11 08:49:22 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Wed, 11 Apr 2007 22:49:22 +1000 Subject: tuples, index method, Python's design References: <1175867771.114540.61810@n76g2000hsh.googlegroups.com> <1175884427.779950.267220@y80g2000hsf.googlegroups.com> <1175953520.316208.241490@o5g2000hsb.googlegroups.com> <7xzm5igbrb.fsf@ruckus.brouhaha.com> <1176200361.260546.280510@n76g2000hsh.googlegroups.com> <1176214831.3430.49.camel@dot.uniqsys.com> Message-ID: On Wed, 11 Apr 2007 08:57:43 +0200, Hendrik van Rooyen wrote: > I can write: > > L = [a,b,c,d,e,f] > T= (a,b,c,d,e,f) > > The difference between the two things is that I can add to > and change L, but not T. No, that's *one* difference between the two things. There are other differences, e.g. the obvious is that they are different types (and therefore different string representations), but also some not so obvious: >>> hash((1,2,3)) -378539185 >>> hash([1,2,3]) Traceback (most recent call last): File "", line 1, in TypeError: list objects are unhashable > Now it seems to me that whatever argument is used to justify the > existence of: > > n = L.index(d) > > can be used to justify the existence of: > > n = T.index(d) > > and vice versa. That depends on what you the purpose of lists and tuples are. Yes, they are both sequences, but they have different uses. Ball-peen hammers and tack hammers are both hammers, but they have different purposes and therefore different functionality. Likewise for tuples and lists: Lists are designed for sequences of homogeneous items, e.g.: L = [1, 2, 4, 8, 16, 32] while tuples are designed to be more like structs or records, with heterogeneous items, e.g.: T = ("Fred", 32, 12.789, {}, None, '\t') So according to these intended usages, it makes sense to ask for L.index(32) because in an application you have no way of telling which item (if any) 32 would be in. But T.index(32) is seen as meaningless, because you know that either 32 is in the second slot or it isn't -- you're never going to find yourself in a situation knowing that 32 is *somewhere* in the tuple without knowing where the one place it *could* be. (There is one other option: you care that 32 is somewhere in the tuple, but you don't care where. That's when you use the "in" operator.) Anyway, that was the original design. When you see tuple, think struct. If you have a struct, it doesn't make a whole lot of sense to ask "which field contains 32?", and so according to this intended usage, giving tuples index and count methods would be a Bad Idea: it just makes extra work for the Python Dev team, for no benefit. Personally, I think that tuples do double-duty as *both* immutable lists and structs/records. So even though index and count methods don't make sense for a struct, it does make sense for an immutable list, and I for one would not object to seeing tuples grow those two methods. [snip] > And I would heretically go even further, and argue that it should be > possible to write stuff like: > > T = T.append(x) > > And get back a new tuple bound to the old name... That's a design decision, and one that's not likely to be accepted because it's so easy to do: T = T + (x,) # like T.append() T = T + (x, y, z) # like T.extend() T = tuple(sorted(T)) # like T.sort() T = T[:4] + T[4:] # like del T[4] etc. It makes sense for lists to have these methods because lists can make the changes in place, but tuples can't. -- Steven. From michele.simionato at gmail.com Thu Apr 26 01:23:09 2007 From: michele.simionato at gmail.com (Michele Simionato) Date: 25 Apr 2007 22:23:09 -0700 Subject: Would You Write Python Articles or Screencasts for Money? In-Reply-To: References: Message-ID: <1177564989.359400.74160@c18g2000prb.googlegroups.com> On Apr 24, 11:24 am, Jeff Rush wrote: > There is discussion by the Python Software Foundation of offering cash > bounties or perhaps periodic awards to the "best of" for magazine articles, > video/screencast clips and such. > I would be +1 for offering symbolic prices (i.e. Python T-shirts or even silver plates) and -1 for cash. You could use the cash to fund other kind of initiatives (perhaps the forthcoming Italian Python conference? http://www.pycon.it ;) Michele Simionato From wswilson at gmail.com Wed Apr 11 10:42:14 2007 From: wswilson at gmail.com (wswilson) Date: 11 Apr 2007 07:42:14 -0700 Subject: passing class by reference does not work?? In-Reply-To: <1176302210.632948.38590@p77g2000hsh.googlegroups.com> References: <1176301439.769248.247720@y5g2000hsa.googlegroups.com> <1176302210.632948.38590@p77g2000hsh.googlegroups.com> Message-ID: <1176302534.649563.299740@y5g2000hsa.googlegroups.com> On Apr 11, 10:36 am, "antred" wrote: > > def b(item, a): > > a.val = a.val + 1 > > return item + a.val > > This is where the problem lies, specifically the line a.val = a.val + > 1 > What happens here is that the 1st a.val refers to a member of the > class instance a, called val ... which does not yet exist and is > therefore created as the result of taking the val member of the class > A and adding 1 to it. In other words, a.val is not the same variable > as A.val. Are you following? If not, change your b() method to this: > > def b(item, a): > a.val = a.val + 1 > assert a.val is A.val > return item + a.val > > and see what happens. OK, I see that. I thought I was creating an instance of the class A() when I called the list comprehension and that the a parameter in b() was then a reference to that instance. What can I do instead? From 12cc104 at gmail.com Fri Apr 27 11:17:51 2007 From: 12cc104 at gmail.com (proctor) Date: 27 Apr 2007 08:17:51 -0700 Subject: regex question In-Reply-To: References: <1177655637.717863.93920@o40g2000prh.googlegroups.com> <1177659238.159411.40640@c18g2000prb.googlegroups.com> <1177683018.566343.105620@c18g2000prb.googlegroups.com> Message-ID: <1177687071.378607.285070@t38g2000prd.googlegroups.com> On Apr 27, 8:37 am, Duncan Booth wrote: > proctor <12cc... at gmail.com> wrote: > > so my question remains, why doesn't the star quantifier seem to grab > > all the data. isn't findall() intended to return all matches? i > > would expect either 'abc' or 'a', 'b', 'c' or at least just > > 'a' (because that would be the first match). why does it give only > > one letter, and at that, the /last/ letter in the sequence?? > > findall returns the matched groups. You get one group for each > parenthesised sub-expression, and (the important bit) if a single > parenthesised expression matches more than once the group only contains > the last string which matched it. > > Putting a star after a subexpression means that subexpression can match > zero or more times, but each time it only matches a single character > which is why your findall only returned the last character it matched. > > You need to move the * inside the parentheses used to define the group, > then the group will match only once but will include everything that it > matched. > > Consider: > > >>> re.findall('(.)', 'abc') > ['a', 'b', 'c'] > >>> re.findall('(.)*', 'abc') > ['c', ''] > >>> re.findall('(.*)', 'abc') > > ['abc', ''] > > The first pattern finds a single character which findall manages to > match 3 times. > > The second pattern finds a group with a single character zero or more > times in the pattern, so the first time it matches each of a,b,c in turn > and returns the c, and then next time around we get an empty string when > group matched zero times. > > In the third pattern we are looking for a group with any number of > characters in it. First time we get all of the string, then we get > another empty match. thank you this is interesting. in the second example, where does the 'nothingness' match, at the end? why does the regex 'run again' when it has already matched everything? and if it reports an empty match along with a non-empty match, why only the two? sincerely, proctor From aleax at mac.com Sat Apr 7 22:09:50 2007 From: aleax at mac.com (Alex Martelli) Date: Sat, 7 Apr 2007 19:09:50 -0700 Subject: block scope? References: <7xr6qwal50.fsf@ruckus.brouhaha.com> <7xtzvseqzo.fsf@ruckus.brouhaha.com> <1hw72cg.115yokgarr9enN%aleax@mac.com> <1hw7kzo.1hepj3c1who5zhN%aleax@mac.com> <1hw7lxn.18itayl1fua6w0N%aleax@mac.com> <7xodlzofw2.fsf@ruckus.brouhaha.com> Message-ID: <1hw7rf0.1p2nwloex6vupN%aleax@mac.com> Paul Rubin wrote: > aleax at mac.com (Alex Martelli) writes: > > > exec? > > option 1: that just runs the compiler a bit later ... > > Besides exec, there's also locals(), i.e. > locals['x'] = 5 > can shadow a variable. Any bad results are probably deserved ;) >>> locals['x']=5 Traceback (most recent call last): File "", line 1, in TypeError: 'builtin_function_or_method' object does not support item assignment I suspect you want to index the results of calling locals(), rather than the builtin function itself. However: >>> def f(): ... locals()['x'] = 5 ... return x ... >>> f() Traceback (most recent call last): File "", line 1, in File "", line 3, in f NameError: global name 'x' is not defined No "shadowing", as you see: the compiler knows that x is NOT local, because it's not assigned to (the indexing of locals() does not count: the compiler's not expected to detect that), so it's going to look it up as a global variable (and not find it in this case). I think that ideally there should be a runtime error when assigning an item of locals() with a key that's not a local variable name (possibly excepting functions containing exec, which are kind of screwy anyway). Alex From gagsl-py2 at yahoo.com.ar Thu Apr 5 18:09:05 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 05 Apr 2007 19:09:05 -0300 Subject: Problems with os.spawnv References: <1175807996.524018.146070@n76g2000hsh.googlegroups.com> <1175809984.762401.11020@n59g2000hsh.googlegroups.com> Message-ID: En Thu, 05 Apr 2007 18:53:04 -0300, Henrik Lied escribi?: > On Apr 5, 11:39 pm, "Gabriel Genellina" > wrote: >> v = os.spawnl(os.P_NOWAIT, "mencoder", "mencoder", >> "/Users/henriklied/test.mov", "-ofps", "25", "-o", "...") >> > Thanks for your reply - but I'm afraid to tell you that spawnl didn't > do the trick either. > Here's the full command I used: http://dpaste.com/hold/7982/ What means "didnt do the trick"? Do you get an exception? what's the returned value? Does the command work OK from the console? Try from the python interpreter, using P_WAIT, and inspect the returned value. > I'd still love to get a working example of my problem using the > Subprocess module. :-) The same thing: p = subprocess.Popen(["mencoder", "/users/...", "-ofps", ...]) -- Gabriel Genellina From nguser3552 at comcast.net Sun Apr 1 20:32:28 2007 From: nguser3552 at comcast.net (nguser3552) Date: Sun, 1 Apr 2007 18:32:28 -0600 Subject: In beloved Iraq, blood flows between brothers in the shadow of illegitimate foreign occupation Re: +++ Russia Watched 9/11 In REAL TIME on SATELLITE +++ References: <1174284614.170100.264620@b75g2000hsg.googlegroups.com> <1175449765.840268.148700@b75g2000hsg.googlegroups.com> Message-ID: You posting in the wrong group, I'm sure to don't give a rats ass and that's why no one will ever, in your life, take you seriously. I have my own feelings on President Bush but I spend the time to get the facts (months and sometimes years) and find a publisher. Get an education, quit shouting at people and if you believe in heaven and hell, well, then truly I'm sorry. You Fundamentalist Fascist. From bj_666 at gmx.net Sat Apr 21 09:18:10 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Sat, 21 Apr 2007 15:18:10 +0200 Subject: Suggestion: str.itersplit() References: <1177160280.784224.53460@b58g2000hsg.googlegroups.com> Message-ID: In <1177160280.784224.53460 at b58g2000hsg.googlegroups.com>, Dustan wrote: > From my searches here, there is no equivalent to java's > StringTokenizer in python, which seems like a real shame to me. > > However, str.split() works just as well, except for the fact that it > creates it all at one go. I suggest an itersplit be introduced for > lazy evaluation, if you don't want to take up recourses, and it could > be used just like java's StringTokenizer. > > Comments? Does it really make such a difference? Ciao, Marc 'BlackJack' Rintsch From steve at holdenweb.com Thu Apr 26 13:22:55 2007 From: steve at holdenweb.com (Steve Holden) Date: Thu, 26 Apr 2007 13:22:55 -0400 Subject: EuroPython vs PyconUK In-Reply-To: References: <4630D480.7050308@gmail.com> Message-ID: Steve Holden wrote: > EuGeNe Van den Bulke wrote: [...] > > Diversity is good, so it isn't one vs. the other. And the UK really *is* > part of Europe (no matter how its politicians behave) :P > > regards > Steve PS: Have you seen the new "[PyCon Uno Italy] Call For Papers" post? I hope you are going to rap their knuckles too :P ;-) regards Steve -- Steve Holden +1 571 484 6266 +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 holdenweb.com Tue Apr 24 11:04:37 2007 From: steve at holdenweb.com (Steve Holden) Date: Tue, 24 Apr 2007 11:04:37 -0400 Subject: Would You Write Python Articles or Screencasts for Money? In-Reply-To: <1hx2dvj.10ek1v51noh1otN%aleax@mac.com> References: <462DCCE6.9060908@taupro.com> <1hx2dvj.10ek1v51noh1otN%aleax@mac.com> Message-ID: Alex Martelli wrote: > Steve Holden wrote: > ... >> used to provide incentives to improve the available information about >> Python, and possibly even the software that's available in Python. I >> have undertaken to make a proposal to the PSF Board for an incentive >> scheme. So please let me have your ideas. > > My main suggestion here is to declare PSF members to be "not eligible" > for these cash awards (although it would be perfectly fine to award > ourselves nice pieces of parchment, or PSF hats or other schwag, in > recognition of such good work, I'd suggest giving cash awards only to > non-members). When cash is involved, it's important to avoid even the > slightest hint of a suggestion of a suspicion of a conflict of interest; > that, I guess, is why firms that run contests with cash prizes always > declare employees and their families "not eligible", and why I think the > PSF should do likewise in this case. > That's a good point, and also a valid reason for restricting the voting community to PSF members. Thanks, Alex. regards Steve -- Steve Holden +1 571 484 6266 +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 steven.bethard at gmail.com Mon Apr 2 10:06:47 2007 From: steven.bethard at gmail.com (Steven Bethard) Date: Mon, 02 Apr 2007 08:06:47 -0600 Subject: Sorting a multidimensional array by multiple keys In-Reply-To: References: <1hvww1d.1k8ozo312a7yazN%aleax@mac.com> Message-ID: <4vydnSCXtPBrkIzbnZ2dnUVZ_szinZ2d@comcast.com> Thomas Kr?ger wrote: > Alex Martelli schrieb: >> Thomas Kr?ger wrote: >>> def sorter(a, b): >>> return cmp(a.id, b.id) >>> >>> obj_lst.sort(sorter) >> A MUCH better way to obtain exactly the same semantics would be: >> >> def getid(a): >> return a.id >> >> obj_list.sort(key=getid) > > Frankly speaking the purpose of the example was to show how to pass a > function as argument for the sort method. > Your code may be more efficient but it explains something different. Yes, but there's almost never a reason to use the cmp= argument to sort() anymore. It's almost always better to use the key= argument. STeVe From kelvin.you at gmail.com Sun Apr 29 08:16:37 2007 From: kelvin.you at gmail.com (=?utf-8?B?5Lq66KiA6JC95pel5piv5aSp5rav77yM5pyb5p6B5aSp5rav5LiN6KeB5a62?=) Date: 29 Apr 2007 05:16:37 -0700 Subject: Could zipfile module process the zip data in memory? In-Reply-To: References: <1177845313.798239.71580@o5g2000hsb.googlegroups.com> Message-ID: <1177848997.653302.43770@l77g2000hsb.googlegroups.com> On Apr 29, 7:37?pm, "Daniel Nogradi" wrote: > > I made a C/S network program, the client receive the zip file from the > > server, and read the data into a variable. how could I process the > > zipfile directly without saving it into file. > > In the document of the zipfile module, I note that it mentions the > > file-like object? what does it mean? > > > class ZipFile( file[, mode[, compression[, allowZip64]]]) > > ? ? ? ? ?Open a ZIP file, where file can be either a path to a file (a > > string) or a file-like object. > > Yes it is possible to process the content of the zipfile without > saving every file: > > [untested] > > ? ? ? ? from zipfile import ZipFile > ? ? ? ? from StringIO import StringIO > > ? ? ? ? zipp = ZipFile( this_is_the_zip_file_from_your_server, 'r' ) > ? ? ? ? for name in zipp.namelist( ): > ? ? ? ? ? ? ? ? content = zipp.read( name ) > ? ? ? ? ? ? ? ? s = StringIO( ) > ? ? ? ? ? ? ? ? s.write( content ) > ? ? ? ? ? ? ? ? # now the file 'name' is in 's' (in memory) > ? ? ? ? ? ? ? ? # you can process it further > ? ? ? ? ? ? ? ? # ............ > ? ? ? ? ? ? ? ? s.close( ) > ? ? ? ? zipp.close( ) > > HTH, > Daniel OK, I see, thank you! From s.mientki at id.umcn.nl Thu Apr 26 05:21:42 2007 From: s.mientki at id.umcn.nl (stef) Date: Thu, 26 Apr 2007 11:21:42 +0200 Subject: simplest install procedure for Python + packages under winXP ? Message-ID: <617df$46306f26$83aef404$8949@news2.tudelft.nl> hello, I'm still in the transition of going from MatLab to Scipy, and installed previous week a SciPy on a PC twice, through the new "Enstaller". It's a pitty that there will be no old installer versions anymore (although I can understand why). Although I succeeded, the behavior of the Enstaller was different both times, and you can clearly see it's an alpha version. (I already wrote my experiences with the first install, the second install had the weird phenomena that none of the succesful installed packages was detected). As a spoiled windows user, which by the way are most people in my surrounding, I'm used to a "one-button-install", so I wonder if it's possible to make a much simpler install procedure. I don't know anything about what's required for a good install, what kind of things things should be stored in the windows registry, but as Python is an interpretor, I would expect there should be a very easy procedure: - Install it on one machine, - copy the complete subdirectory to another computer Does this work for Python + Scipy ? (If so, I can use Inno, which I'm familiar with) Though the above question might seem a lot of fuzz about nearly nothing, it's very essential for my plan, in which I want to convince the other people at our university to move from MatLab to Python. For windows users, the "one-button-install" is essential, otherwise most windows users, will not even try a new package. Sorry for the long post, about "nothing" for non-windows users ;-) thanks, Stef Mientki From gagsl-py2 at yahoo.com.ar Mon Apr 23 03:51:52 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 23 Apr 2007 04:51:52 -0300 Subject: Select weirdness References: <462b3e47$0$326$e4fe514c@news.xs4all.nl> <462c54cb$0$336$e4fe514c@news.xs4all.nl> Message-ID: En Mon, 23 Apr 2007 04:33:22 -0300, Ron Garret escribi?: > I have not been able to find a proxy server that can proxy to unix > sockets, so I need to write my own. Conceptually its a very simple > thing: read the first line of an HTTP request, parse it with a regexp to > extract the sandbox name, connect to the appropriate unix server socket, > and then bidirectionally pipe bytes back and forth. But it has to do > this for multiple connections simultaneously, which is why I need select. No. This is what the *server* should do, not the *handler*. The server listens on incoming requests, and creates a new handler for each one. Inside a handler, you don't have to worry about multiple connections. If you want to process simultaneous connections, inherit your server from ThreadingMixIn or ForkingMixIn (or use one of the predefined server classes). -- Gabriel Genellina From oliver at obeattie.com Tue Apr 3 09:28:39 2007 From: oliver at obeattie.com (oliver at obeattie.com) Date: 3 Apr 2007 06:28:39 -0700 Subject: Finding and copying files with python. In-Reply-To: <1175606497.896681.119490@l77g2000hsb.googlegroups.com> References: <1175606497.896681.119490@l77g2000hsb.googlegroups.com> Message-ID: <1175606919.195392.309840@d57g2000hsg.googlegroups.com> Just sort them and then select the bottom one from a list by using a negative indices. I.e.: list[-1] Would return the bottom result out of a list On Apr 3, 2:21 pm, "gtb" wrote: > I wish to copy the highest version number of a file from directory \ > \ > \fileserver\D:\scripts to C:\scripts where the file names are of the > form > > filename_MM.NN.SS.zip, where MM, NN, and SS can be one to three > digits. > > Example directory: > other.zip > dx_ver_1.1.63.zip > dx_ver_1.2.01.zip > dx_ver_1.12.7.zip > temp.txt > > Does python have string matching routines that would find the bottom > listed zip file and/or file copying routines? > > A little pointer or two would be much appreciated. > > Thanks, > > jh From martin at v.loewis.de Sat Apr 7 04:44:00 2007 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sat, 07 Apr 2007 10:44:00 +0200 Subject: SWIG, Python, C++, and Coca-Cola In-Reply-To: <1175886932.067217.17700@w1g2000hsg.googlegroups.com> References: <1175886932.067217.17700@w1g2000hsg.googlegroups.com> Message-ID: <461759D0.7030003@v.loewis.de> > Any clues as to what is happening here or what to do next? Apparently, it tries to wrap the main() function. It should not do that: main should not be callable from Python. Most likely, you have a declaration of main somewhere so it thinks it should wrap it. You should not have a declaration of main, anyway, so you should be safely able to drop that. Regards, Martin From quiettechblue at yahoo.com Wed Apr 25 03:36:57 2007 From: quiettechblue at yahoo.com (joseph2k) Date: Wed, 25 Apr 2007 00:36:57 -0700 Subject: *** Watch BOMBSHELL video of Senator John Kerry admitting 911 was in INSIDE JOB ??? References: <1177387965.127809.175390@l77g2000hsb.googlegroups.com> Message-ID: Jon Slaughter wrote: > > wrote in message > news:1177387965.127809.175390 at l77g2000hsb.googlegroups.com... >> http://www.911blogger.com/node/8053 >> >> Senator John Kerry was questioned concerning 9/11 during an appearance >> at Book People in Austin, Texas. Members of Austin 9/11 Truth Now >> asked Kerry about the officially unexplained collapse of WTC Building >> 7." >> >> Kerry responded: >> >> "I do know that that wall, I remember, was in danger and I think >> they made the decision based on the danger that it had in destroying >> other things-- that they did it in a controlled fashion." >> >> http://www.jonesreport.com/articles/220407_kerry_wtc7.html >> >> Thanks to the dozen or so people who submitted this as a blog entry :) >> >> "Mr. Kerry?!?" >> >> "Just a follow-up or two... >> >> WHAT THE HELL|?| Are you saying that building was wired that day? Or >> well in advance? 'Splain, please. >> >> Does your fellow Bonesman George Walker Bush appreciate you letting >> the cat out of the bag on this? Is that your cell phone I hear >> ringing? >> >> Why is your wife squirming like that? Stop it, Theresa! Stop it!" >> > > So what your saying is that the democrates are behind 9/11? So they tried > to frame Bush? Whats new? Doesn't this then mean that the democrates and > alqaeda are working together? I always that pelosie looked like she had a > little arabic in her(probably in more ways than one). Naw, the Repuglicans were fully in power then, it had to be them. -- JosephKK Gegen dummheit kampfen die Gotter Selbst, vergebens.?? --Schiller From jjl at pobox.com Sun Apr 29 19:38:18 2007 From: jjl at pobox.com (John J. Lee) Date: Sun, 29 Apr 2007 23:38:18 GMT Subject: http pipelining References: Message-ID: <87ps5m7nuz.fsf@pobox.com> Steve Holden writes: > swq22 at yahoo.com wrote: > > Which python module is capable of pipelining http requests? > > (I know httplib can send mulitple requests per tcp connection, but in > > a strictly serial way. ) > > > Oops, sorry, you meant sending requests in parallel, right? > > You'll need to use either urllib or urllib2 for the web, and the > threading module is one way to run parallel requests. It's fairly easy > to use as long as you keep your tasks properly isolated form each > other. No, he means "HTTP pipelining", which means sending multiple requests down a single TCP connection, without waiting for the first response. httplib's module-level docstring says (reformatted here): """ ... The HTTPResponse class does not enforce this state machine, which implies sophisticated clients may accelerate the request/response pipeline. Caution should be taken, though: accelerating the states beyond the above pattern may imply knowledge of the server's connection-close behavior for certain requests. For example, it is impossible to tell whether the server will close the connection UNTIL the response headers have been read; this means that further requests cannot be placed into the pipeline until it is known that the server will NOT be closing the connection. """ So, sort-of-yes, if you know what you're doing and you're lucky. Certainly urllib and urllib2 don't support pipelining. There were plans for a new HTTP client in Twisted with pipelining support, but I don't know if that ever came about. AFAIK not many libraries (in any language) support it -- e.g. none of "Jakarta commons HTTPClient", libwww-perl, and libcurl currently support it. libwww (without the "-perl") does claim to support it (I say "claim" merely because I haven't used it or read the source -- no FUD intended). Side note: As the OP mentions in a followup, by default firefox does NOT do pipelining (to the disbelief of the people I told about this when it came up in a previous job -- but I just tried running tcpdump and indeed about:config seems to be telling the truth; fortunately, in response to the limitations imposed by RFC 2616, somebody has thoughtfully arranged for the speed of light to be fast enough for this not to be a major problem when using websites on the other side of the planet). The firefox people say: http://www.mozilla.org/support/firefox/tips#oth_pipelining """ Pipelining is an experimental feature, designed to improve page-load performance, that is unfortunately not well supported by some web servers and proxies. """ Instead of pipelining, it uses multiple connections (2 when I tried it, which is the maximum RFC 2616 says SHOULD be used by a "single-user client"). I didn't try IE, but apparently it has the same behaviour (2 connections, no pipelining): http://blogs.msdn.com/ie/archive/2005/04/11/407189.aspx I wonder if the right economic pressures are there for SCTP ever to get used for everyday web HTTP stuff... John From mariano.suarezalvarez at gmail.com Mon Apr 9 03:26:23 2007 From: mariano.suarezalvarez at gmail.com (mariano.suarezalvarez at gmail.com) Date: 9 Apr 2007 00:26:23 -0700 Subject: Classes with initialization Message-ID: <1176103583.032209.304710@p77g2000hsh.googlegroups.com> Hi all, I'm currently using code similar to this: class ClassWithInitialization(type): def __init__(cls, name, bases, dict): type.__init__(name, bases, dict) dict['__class_init__'](cls) class A: __metaclass__ = ClassWithInitialization def __class_init__(cls): cls.some_attribute = ... ... in order to get class attributes initialized (since the values of these attributes need non trivial work to be computed, putting the code that does that computation in the class scope ends up with the class having extra attributes---the `local' variables used in the computation of the values of class attribute; so I'm using __class_init__'s scope to contain those variables) I was wondering: is there a simpler approach to this? Also: can someone enlighten me as to when code in class scope is run, exactly? if a class A has a metaclass M, then M.__init__ does not seem to get the code in A's class scope in its arguments AFAICS, so I guess that code is run before the class is created? Cheers, -- m From ceball at gmail.com Wed Apr 18 05:12:10 2007 From: ceball at gmail.com (Chris) Date: 18 Apr 2007 02:12:10 -0700 Subject: Strange terminal behavior after quitting Tkinter application In-Reply-To: References: <1176881604.574369.77230@b58g2000hsg.googlegroups.com> Message-ID: <1176887530.377648.115510@n59g2000hsh.googlegroups.com> > What happens if you type 'stty sane' (and of course, a carriage > return) afterwards? The terminal returns to normal, thanks! But does anyone know why the Tkinter program is doing this to the terminal in the first place? I don't want to have to tell users of my program that they must recover their terminal's sanity each time after running my program. From steve at holdenweb.com Tue Apr 3 12:17:52 2007 From: steve at holdenweb.com (Steve Holden) Date: Tue, 03 Apr 2007 12:17:52 -0400 Subject: Stack experiment In-Reply-To: <5QuQh.152$9L1.108@read3.inet.fi> References: <5QuQh.152$9L1.108@read3.inet.fi> Message-ID: tom at finland.com wrote: > Hi! Im new to Python and doing exercise found from internet. It is > supposed to evaluate expression given with postfix operator using > Stack() class. > > class Stack: > def __init__(self): > self.items = [] > > def push(self, item): > self.items.append(item) > > def pop(self): > return self.items.pop() > > def isEmpty(self): > return (self.items == []) > > def evaluatePostfix(expr): > import re > tokenList = re.split(" ([^0-9])", expr) If you add a print statement here I think you will find that the tokenisation here isn't really what you want: >>> expr = "56 47 + 2 *" >>> re.split(" ([^0-9])", expr) ['56 47', '+', ' 2', '*', ''] > stack = Stack() > for token in tokenList: > if token == '' or token == ' ': > continue > if token == '+': > sum = stack.pop() + stack.pop() > stack.push(sum) > elif token == '*': > product = stack.pop() * stack.pop() > stack.push(product) > else: > stack.push(int(token)) > return stack.pop() > > print evaluatePostfix("56 47 + 2 *") > > Errormsg: > Traceback (most recent call last): > File "C:\*\postfix1.py", line 31, in > print evaluatePostfix("56 47 + 2 *") > File "C:\*\postfix1.py", line 28, in evaluatePostfix > stack.push(int(token)) > ValueError: invalid literal for int() with base 10: '56 47' > > How can I avoid the error and get desired result? I'd try using tokenList = split(expr) instead - this has the added benefit of removing the spaces, so you can simplify your code by removing the case that handles empty tokens and sapaces, I suspect. 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 Mon Apr 23 04:29:39 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 23 Apr 2007 05:29:39 -0300 Subject: serializable object references References: <1242622.P0zHLAfcMH@beaureve.gmx.net> <25065059.0D4t2YsirZ@beaureve.gmx.net> <2082235.4RuV3RCOoU@beaureve.gmx.net> Message-ID: En Mon, 23 Apr 2007 03:35:42 -0300, Martin Drautzburg escribi?: > Gabriel Genellina wrote: > >> En Sun, 22 Apr 2007 12:47:10 -0300, Martin Drautzburg >> escribi?: >> >>> I was thinking that it would be nice if a web application could talk >>> to real objects. The client side does not need to know the internals >>> of an object, it acts as a "view" for server-side models. All it has >>> to be able to do is invoke methods on "its" model. So a view could >>> just store "its" object-reference in an instance variable and pass it >>> to the server, where my problem of looking it up comes in. >> >> This is more or less what several web frameworks do. You publish >> objects; URLs are mapped to method objects; URL parameters become >> method parameters. See http://wiki.python.org/moin/WebFrameworks > > Okay will look. I have checked out cherrypy, but it does not seem to > support direct object references, i.e. the server-side objects are > really stateless and all calls to an object method will see the same > state unless you do something about it youself. The description I wrote above aplies exactly to ZOPE: URLs map exactly to object methods and those objects can (and should) maintain state. (Zope uses an OO database, ZODB, to hold those objects). But Zope is a big framework and not easy to grasp, so I would not recomend it for a small site or web application. Using CherryPy you can keep state across requests, if you use some sort of session machinery; at least you could build a mapping SessionID-State (the state being as complex as you want). I think TurboGears has something built in for managing sessions, but I'm not sure. > I have also looked at the wonderful qooxdoo javascript framework and in > the examples they have, the data I receive on a published object method > on my cherrypy server is: Never used qooxdoo... -- Gabriel Genellina From marcpp at gmail.com Thu Apr 12 09:55:20 2007 From: marcpp at gmail.com (Marcpp) Date: 12 Apr 2007 06:55:20 -0700 Subject: Pyqt calling custom dialog Message-ID: <1176386120.486374.195960@n59g2000hsh.googlegroups.com> I need to call a custom dialog from a program, and return parameters. Any idea or example? From mangabasi at gmail.com Thu Apr 5 10:33:12 2007 From: mangabasi at gmail.com (Mangabasi) Date: 5 Apr 2007 07:33:12 -0700 Subject: Calling Fortran from Python In-Reply-To: References: <1175640339.648190.207530@y66g2000hsf.googlegroups.com> <1175685841.847487.173440@w1g2000hsg.googlegroups.com> <1175718204.410453.29510@q75g2000hsh.googlegroups.com> <1175726427.114890.7990@y80g2000hsf.googlegroups.com> <1175729338.287712.305870@e65g2000hsc.googlegroups.com> Message-ID: <1175783592.931018.318850@l77g2000hsb.googlegroups.com> On Apr 4, 10:10 pm, Lenard Lindstrom wrote: > Mangabasi wrote: > > On Apr 4, 5:48 pm, Robert Kern wrote: > >> Mangabasi wrote: > >>> Would Python 2.5 work with Visual Studio 6.6? > >> No. > > >> -- > >> 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 > > > I will try the GCC then. It is a shame that I could not get calldll > > to work. It was very simple to use. I think I am making a mistake > > with the argument types but not sure. > > > Thanks for your help, it is greatly appreciated. > > Did you try ctypes? > > >>> from ctypes import * > >>> sample=cdll.sample.sample_ > >>> sample.restype=None > >>> sample.argtypes=[POINTER(c_int), POINTER(c_int), POINTER(c_double), > POINTER(c_double)] > >>> e1 = c_int(0) > >>> e2 = c_int(0) > >>> ain = (c_double*3)(2.0, 3.0, 4.0) > >>> aout = (c_double*4)() > >>> sample(e1, e2, ain, aout) > >>> aout[:] > [6.0, 9.0, 8.0, 12.0] > >>> e1.value > 0 > >>> e2.value > 0 > > I compile the SAMPLE example with mingw g77 3.4.5: > > g77 -shared -o sample.dll sample.for > > I had to take out the "INTENT(OUT)"s because g77 didn't like them. And > "SAMPLE" became "sample_" in the dll. Also note that argument passing to > Fortran subroutines is strictly pass-by-reference. Thus the ain pointer. > > Lenard Lindstrom- Hide quoted text - > > - Show quoted text - A little bit of googling solved the problem. instead of >>> sample = cdll.sample_dll.SAMPLE I used >>> sample = windll.sample_dll.SAMPLE and now it seems to be working without error messages. Thanks a lot. From mike.klaas at gmail.com Tue Apr 10 15:26:29 2007 From: mike.klaas at gmail.com (Klaas) Date: 10 Apr 2007 12:26:29 -0700 Subject: itertools, functools, file enhancement ideas In-Reply-To: <7x8xd2rfik.fsf@ruckus.brouhaha.com> References: <7xveg7rhc7.fsf_-_@ruckus.brouhaha.com> <1176049003.872896.7720@d57g2000hsg.googlegroups.com> <7x8xd2rfik.fsf@ruckus.brouhaha.com> Message-ID: <1176233189.570853.27830@o5g2000hsb.googlegroups.com> On Apr 8, 9:34 am, Paul Rubin wrote: > rdhettin... at gmail.com writes: > > > a) def flip(f): return lambda x,y: f(y,x) > > Curious resemblance to: > > itemgetter(1,0) > > Not sure I understand that. I think he read it as lambda (x, y): (y, x) More interesting would be functools.rshift/lshift, that would rotate the positional arguments (with wrapping) def f(a, b, c, d, e): ... rshift(f, 3) --> g, where g(c, d, e, a, b) == f(a, b, c, d, e) Still don't see much advantage over writing a lambda (except perhaps speed). -Mike From leuchte at gmail.com Wed Apr 25 15:12:48 2007 From: leuchte at gmail.com (TimC) Date: 25 Apr 2007 19:12:48 GMT Subject: Python not giving free memory back to the os get's me in real problems ... References: <1177510121.882503.145560@n15g2000prd.googlegroups.com> Message-ID: <599nhgF2jlkssU1@mid.dfncis.de> Donald 'Paddy' McCarthy wrote > Could you split the program into one handling the outer loop and > calling another program, with data transfer, to handle the inner > loops? > > - Paddy. I'm afraid this isn't possible, because the python macro is called and started from within our commercial tool which leads to the cirumstance that this tool eats up more and more memory. Due to the fact that there is no way we can start the tool via commandline giving an argument that tells the tool it has to start macroXY.py after startup I don't see a way to lower the memory usage by splitting it up in two loops. thanks for all your help so far, tim From superflit at gmail.com Wed Apr 4 19:30:03 2007 From: superflit at gmail.com (flit) Date: 4 Apr 2007 16:30:03 -0700 Subject: way to extract only the message from pop3 In-Reply-To: References: <1175628970.874615.127020@y80g2000hsf.googlegroups.com> Message-ID: <1175729403.429741.86820@w1g2000hsg.googlegroups.com> Yep you are right.. I made an filter to get the data in the message I want.. So it?s not the most beatiful code, but works. :) On Apr 4, 4:11 am, Tim Roberts wrote: > "flit" wrote: > > >Using poplib in python I can extract only the headers using the .top, > >there is a way to extract only the message text without the headers? > > Only by using Python code. The other responses gave you good pointers > toward that path, but I thought I would point out the reason why. > > The POP3 protocol is surprisingly primitive. There are only two commands > to fetch a message: RETR, which fetches the headers and the entire message, > and TOP, which fetches the headers and the first N lines of the message. > The key point is that both commands fetch the headers. > -- > Tim Roberts, t... at probo.com > Providenza & Boekelheide, Inc. From gagsl-py2 at yahoo.com.ar Fri Apr 20 17:10:59 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 20 Apr 2007 18:10:59 -0300 Subject: getting from command line options to file References: <1176748372.685762.169820@w1g2000hsg.googlegroups.com> <1177102090.716465.133610@d57g2000hsg.googlegroups.com> Message-ID: En Fri, 20 Apr 2007 17:48:10 -0300, CSUIDL PROGRAMMEr escribi?: > On Apr 16, 1:08 pm, Michael Hoffman wrote: >> CSUIDL PROGRAMMEr wrote: >> > hi folks >> > I am new to python. I have a module does call a os.command(cmd) where >> > cmd is a rpm command. >> > Instead of using os.command and getting the results on command line , >> > i would like to dump the output in a file. Is os.command(cmd > >> > filename) the most efficient command?? >> >> I think the best thing to do would be something like this (Python 2.5): >> >> from __future__ import with_statement >> import subprocess >> >> with file("test.out", "w") as outfile: >> subprocess.check_call(["ls", "/etc"], stdout=outfile) >> -- >> Michael Hoffman > > > but what if i have python which is 2.4?? Omit the with statement: import subprocess outfile = open("test.out", "w") try: subprocess.check_call(["ls", "/etc"], stdout=outfile) finally: outfile.close() -- Gabriel Genellina From steve at REMOVEME.cybersource.com.au Wed Apr 18 04:09:34 2007 From: steve at REMOVEME.cybersource.com.au (Steven D'Aprano) Date: Wed, 18 Apr 2007 18:09:34 +1000 Subject: The smallest and largest values of numeric types References: <1176825226.633555.85860@d57g2000hsg.googlegroups.com> Message-ID: On Wed, 18 Apr 2007 07:15:11 +0200, Hendrik van Rooyen wrote: > I once made a thing that tried to find the limit of longs and stopped > when I had two or three screenfulls of numbers. You should find that converting longs to strings (say, for printing them) is *very* slow. E.g. the following code big = 10L**100 # one google, a big number while True: print big # so we can see the last value before it fails big *= 10 will run terribly slow and should be written as: big = 10L**100 # one google, a big number try: while True: big *= 10 except: # don't know what exception will be raised, so catch ANYTHING print len(str(big))-1 # the number of digits only does the slow conversion to string once, instead of every time around the loop. However, once your machine starts paging, it will still slow down a lot. > I came to the conclusion that for "integer" arithmetic like this, the > limit is either your memory size, or some other number that is so big > that in practice you don't have to worry about it.. Yes, longs are limited only by the amount of memory accessible. -- Steven D'Aprano From mail at microcorp.co.za Wed Apr 4 01:24:48 2007 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Wed, 4 Apr 2007 07:24:48 +0200 Subject: Question about text in Python References: <4610c366$0$15022$5a62ac22@per-qv1-newsreader-01.iinet.net.au><57cbejF2cataiU1@mid.individual.net><4611af55$0$15038$5a62ac22@per-qv1-newsreader-01.iinet.net.au><87wt0ugplk.fsf@benfinney.id.au> Message-ID: <002b01c77679$912cc820$03000080@hendrik> "Steven D'Aprano" wrote: 8< -------- > This is not a call to turn a blind eye for plagiarism, or to do students > homework for them. It's a plea for common-sense. We're not bound by > university guidelines, or universities' over-broad definition of > plagiarism, and we don't have to live by them. We are ethically bound not > to do student's homework for them -- but that doesn't mean we're bound to > refuse to answer their reasonable questions, or to treat those who are > looking for help as frauds _just because they are a student_. I agree - It is not fraud if the OP says he is a student, and asks for help on something that puzzles him. It would be fraud if he gets a "full answer" here, and represents it as "his own work". It would also be stupid, as its a sure fire way of failing your examinations. Getting clarification on some point here is no different from looking it up in a library, except that its more risky - some wag may lie to the poor bugger... - Hendrik From mwilson at the-wire.com Mon Apr 23 23:38:45 2007 From: mwilson at the-wire.com (Mel Wilson) Date: Mon, 23 Apr 2007 23:38:45 -0400 Subject: When are immutable tuples *essential*? Why can't you just use lists *everywhere* instead? In-Reply-To: References: <1177088796.622928.224890@d57g2000hsg.googlegroups.com> <1177089206.550423.288670@q75g2000hsh.googlegroups.com> <58sf33F2b1q8tU1@mid.individual.net> <1177103370.022138.110320@n59g2000hsh.googlegroups.com> <1177108560.660288.171890@n76g2000hsh.googlegroups.com> Message-ID: Neil Cerutti wrote: > The interpreter explains it: "A list is not a hashable object." > Choosing a hash table instead of some kind of balanced tree seems > to be just an optimization. ;) Even with a balanced tree, if a key in a node changes value, you may have to re-balance the tree. Nothing in a Python list says that a dictionary tree would have to be re-balanced if you changed that particular list. Mel. From surekap at gmail.com Mon Apr 30 04:19:34 2007 From: surekap at gmail.com (Prateek) Date: 30 Apr 2007 01:19:34 -0700 Subject: fastest way to find the intersection of n lists of sets In-Reply-To: <1177918661.205983.280140@e65g2000hsc.googlegroups.com> References: <1177883328.835058.138990@p77g2000hsh.googlegroups.com> <1177890102.708578.70460@y5g2000hsa.googlegroups.com> <1177918661.205983.280140@e65g2000hsc.googlegroups.com> Message-ID: <1177921174.934386.214520@o5g2000hsb.googlegroups.com> On Apr 30, 12:37 pm, Raymond Hettinger wrote: > [Prateek] > > > The reason why I'm casting to a list first is because I found that > > creating a long list which I convert to a set in a single operation is > > faster (although probably less memory efficient - which I can deal > > with) than doing all the unions. > > That would be a surprising result because set-to-set operations do > not have to recompute hash values. Also, underneath-the-hood, > both approaches share the exact same implementation for inserting > new values one the hash value is known. > > If you've seen an unfavorable speed comparison, then you most likely > had code that built new intermediate sets between step: > > common = s1 | s2 | s3 | s4 | s5 | s6 | s7 | s8 | s9 > > Instead, it is faster to build-up a single result set: > > common = set() > for s in s1, s2, s3, s4, s5, s6, s7, s8, s9: > common |= s > > Raymond Hettinger Thanks Raymond, This was my old code: self.lv is a dictionary which retrieves data from the disk or cache v_r = reduce(operator.or_, [self.lv[x.id] for x in v], set()) This code ran faster: v_r = reduce(operator.add, [list(self.lv.get(x.id, [])) for x in v], []) v_r = set(v_r) I was doing 3 of these and then intersecting them. Now, I'm doing... v_r = set() _efs = frozenset() for y in [self.lv.get(x.id, _efs) for x in v]: v_r |= y Since the number of sets is always 2 or 3, I just do the intersections explicitly like so: if len(list_of_unioned_sets) == 3: result = list_of_unioned_sets[0] result &= list_of_unioned_sets[1] result &= list_of_unioned_sets[2] elif len(list_of_unioned_sets) == 2: result = list_of_unioned_sets[0] result &= list_of_unioned_sets[1] else: # Do something else... Sorry for the relatively non-descript variable names. Prateek From elguavas at users.sourceforge.net Thu Apr 19 07:29:20 2007 From: elguavas at users.sourceforge.net (Stephen M. Gava) Date: Thu, 19 Apr 2007 11:29:20 -0000 Subject: using tkinter to display html Message-ID: Hi all, I prefer using tkinter to wxpython (so sue me :) and i need to display a lot of html in a particular app. does anyone know if one of the existing add on tk html widgets have been wrapped for tkinter already? TIA for any reply, Stephen From steve at REMOVEME.cybersource.com.au Wed Apr 4 05:25:56 2007 From: steve at REMOVEME.cybersource.com.au (Steven D'Aprano) Date: Wed, 04 Apr 2007 19:25:56 +1000 Subject: optparse option prefix References: Message-ID: On Wed, 04 Apr 2007 08:52:48 +0000, Mathias Waack wrote: > We've integrated python into a legacy application. Everything works fine (of > course because its python;). There's only one small problem: the > application reads the commandline and consumes all arguments prefixed with > a '-' sign. Thus its not possible to call a python module from the > commandline with a parameter list containing options prefixed by '-' > or '--' signs. Thats not a major problem, but it prevents us from using th > optparse module. Is there a way to change to prefix, so one could use a '+' > (for instance) to mark command line options for optparse? You have the source code. Does it look like the "-" is hard-coded in the module? Some solutions: (1) Fork the code. It's open source, you should be able to copy the code into a new module while still obeying the licence. (Note: open source does not mean "I can do anything I want". There is still a licence, but it is a very user-friendly licence. Read it and obey it.) Duplicate the file and change all the relevant "-" signs to "+" signs. (2) Are you sure you need to be using optparse? It sounds like an very non-standard use of the module to me. Perhaps there is a simpler alternative. (3) Create a filter module that reads sys.argv, replaces leading "+" signs with "-" signs, and then stuffs it back into sys.argv before optparse gets to see it. -- Steven D'Aprano From livibetter at gmail.com Tue Apr 17 12:38:53 2007 From: livibetter at gmail.com (livibetter) Date: 17 Apr 2007 09:38:53 -0700 Subject: UpdateLayeredWindow in pywin32 In-Reply-To: <1176766638.627412.240750@o5g2000hsb.googlegroups.com> References: <1176766638.627412.240750@o5g2000hsb.googlegroups.com> Message-ID: <1176827933.590708.193820@q75g2000hsh.googlegroups.com> I have found the cause "Please note that after SetLayeredWindowAttributes has been called, subsequent UpdateLayeredWindow calls will fail until the layering style bit is cleared and set again." from http://msdn2.microsoft.com/en-us/library/ms632599.aspx#layered But I still can't use winxpgui.UpdateLayeredWindow, Now I am using ctypes to enable calling UpdateLayeredWindow, and this works. From michael at jedimindworks.com Fri Apr 13 11:22:45 2007 From: michael at jedimindworks.com (Michael Bentley) Date: Fri, 13 Apr 2007 10:22:45 -0500 Subject: Problem with algorithm In-Reply-To: <1176473989.420067.190970@l77g2000hsb.googlegroups.com> References: <1176434160.047703.214600@q75g2000hsh.googlegroups.com> <1176434937.258002.162220@p77g2000hsh.googlegroups.com> <1176448576.047996.12930@d57g2000hsg.googlegroups.com> <1176473989.420067.190970@l77g2000hsb.googlegroups.com> Message-ID: On Apr 13, 2007, at 9:19 AM, Paul McGuire wrote: > If you just expand the length to five million* or so, one of those > strings will contain all the works of Shakespeare. Not likely, even with a tiny sampling of the works of Shakespeare: # :-) import string import random def main(bardText, maxTries=5000000): tries = 0 while tries < maxTries: tries += 1 attempt = [] for letter in bardText.lower(): if random.choice( string.lowercase[:26] + string.punctuation + ' ' ) == letter: attempt.append(letter) else: break if len(attempt) >= 4: print '%d: %s' % ( tries, ''.join(attempt) ) if __name__ == "__main__": main("Alas, poor Yorick!") From Gregory.Bloom at gmail.com Fri Apr 27 16:09:31 2007 From: Gregory.Bloom at gmail.com (Gregory Bloom) Date: 27 Apr 2007 13:09:31 -0700 Subject: webbrowser.open works in IDLE and cmd shell but not from cygwin prompt In-Reply-To: References: <1177646975.285805.106920@b40g2000prd.googlegroups.com> Message-ID: <1177704571.370848.101970@r3g2000prh.googlegroups.com> On Apr 27, 3:12 am, Michael Hoffman wrote: > > And, more to the point, how can I use webbrowser from scripts launched under > > > cygwin? > > If you're using native Windows Python as you seem to be, try > webbrowser.get("windows-default").open_new(url) > > If you want to use Cygwin Python instead, I submitted a patch more than > 1.5 years ago to allow it, but it hasn't been reviewed: > > http://python.org/sf/1244861 > -- > Michael Hoffman Awesome! That works perfectly. Thanks. From maxerickson at gmail.com Fri Apr 20 11:37:50 2007 From: maxerickson at gmail.com (Max Erickson) Date: Fri, 20 Apr 2007 15:37:50 +0000 (UTC) Subject: Do other Python GUI toolkits require this? References: <462697A6.6010007@codebykevin.com> <1177014799.004875.262060@y80g2000hsf.googlegroups.com> Message-ID: Antoon Pardon wrote: > On 2007-04-20, Max Erickson wrote: >> >> If we are being pedantic about describing a curve that shows the >> progress of a person in learning a topic, there is no arguing >> with you, a steep curve describes fast uptake and is a good >> thing. >> >> If we are being pedantic about what a learning curve describes, >> it seems possible that it describes the rate of knowledge uptake >> required to master a given topic, and that such a learning curve >> could exclude people that were unable to take in knowledge at >> that rate(for whatever reason) from mastering that topic, making >> it reasonable to describe such a topic as both 'hard' and >> 'having a steep learning curve'. > > I must confess I don't follow you here. A rate is a single > number. Now some second variable can be a function of this rate > or vice versa but I can't make out what this second variable is > supposed to be from your explanation. > I'm stopping after this because it is offtopic noise, but take a graph of position vs time for an object; the slope of that graph happens to be related to the velocity of the object, so you can 'see' the velocity of the object even though the graph is of position and time. The slope of the graph can be said to describe a rate. (and a graph that showed the movement of the world around that object would be quite different, and similar lines on those different graphs would thus elecit rather different descriptions, which is the point, pretending that all graphs of learning curves only describe what you assume they describe and then being pedantic about what information can be inferred from the graphs isn't going to get you anywhere, hence this thread) My english is full of colloquialisms and idioms and I am not interested in learning "Antoon Pardon's Dictionary of Exact Usage", so I fear that further explanation will be fruitless. max From bbxx789_05ss at yahoo.com Sat Apr 21 18:24:09 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: 21 Apr 2007 15:24:09 -0700 Subject: Returning a date as string In-Reply-To: <1177189171.147254.35920@n76g2000hsh.googlegroups.com> References: <1177189171.147254.35920@n76g2000hsh.googlegroups.com> Message-ID: <1177194249.516456.220250@p77g2000hsh.googlegroups.com> On Apr 21, 2:59 pm, Bj?rn Keil wrote: > Hello pythons, > > I have little problem with understanding conversions in python. I've > written a little class - nothing much, just to try out Python a little > - containing the following method: > > def __repr__(self): > """Serializes the note. > > Currently the format of notes isn't decided upon. XML output > is > projected.""" > return "Due: " + str(self.dateDue) + \ > "\nDate: " + str(self.dateCreated) + \ > "\nSubject: " + self.subject + \ > "\n" + self.content > > The fields "dateDue" and "dateCreated" contain datetime.date objects. > Now when I try to serialize the whole thing: > > >>> myNote > > Traceback (most recent call last): > File "", line 1, in ? > File "notes.py", line 81, in __repr__ > return "Due: " + str(self.dateDue) + \ > TypeError: cannot concatenate 'str' and 'datetime.date' objects > > I tryed different variant before I wrapped "self.dateDue" in a str() > constructor: > I tried to put it in brackets, or call its .isoformat() method. > Nothing works. It still complains that I was trying to concatenate a > string with a date, but I really wanna concatenate a string with a > string! > > Could anyone please tell me what I am doing wrong? > > Greetings, > Bj?rn This works for me: import datetime class MyDate(object): def __init__(self, date): self.d = date def __repr__(self): return str(self.d) md = MyDate(datetime.date.today()) print "the result is: " + repr(md) ##output: the result is: 2007-04-21 From aleax at mac.com Fri Apr 6 02:08:49 2007 From: aleax at mac.com (Alex Martelli) Date: Thu, 5 Apr 2007 23:08:49 -0700 Subject: Why NOT only one class per file? References: <1175721799.714907.52770@o5g2000hsb.googlegroups.com> <46142acc$0$7532$426a34cc@news.free.fr> <4614b40e$0$26843$426a74cc@news.free.fr> <1175778276.603838.86500@l77g2000hsb.googlegroups.com> <2O9Rh.24647$uo3.24013@newssvr14.news.prodigy.net> Message-ID: <1hw4dl8.tyjlpo1qryou6N%aleax@mac.com> John Nagle wrote: > systems that didn't work that way, in which the program source was > manipulated within the language environment, in a more structured > fashion. Smalltalk, LISP, and (wierdly) Forth environments have been > built that way. But it never really caught on. APL was that way, too. And now the ACM wants to dissolve the APL SIG -- there just isn't anything much happening there any more:-( Alex From steve at holdenweb.com Mon Apr 9 12:47:47 2007 From: steve at holdenweb.com (Steve Holden) Date: Mon, 09 Apr 2007 12:47:47 -0400 Subject: Threads aren't distinguished by titles and they don't belong to anyone [was: Re: shelve error] In-Reply-To: <1176095310.492686.78880@p77g2000hsh.googlegroups.com> References: <1175746456.995618.186190@e65g2000hsc.googlegroups.com> <1175746966.023613.178830@n76g2000hsh.googlegroups.com> <1175756092.643182.142420@n76g2000hsh.googlegroups.com> <1hw9lxy.ldrc541w507xyN%aleax@mac.com> <1176095310.492686.78880@p77g2000hsh.googlegroups.com> Message-ID: 7stud wrote: >> Discussion subject changed to "Python universal build, OSX 10.3.9 and undefined symbols when >> linking" by David Pratt > > What gives? How come you can change the title of my thread? > > > On Apr 8, 8:14 pm, a... at mac.com (Alex Martelli) wrote: >> But if you open an errata for the missing explanation for the different >> default value of the flag argument (use URL >> ), I'll be glad to >> fix it for the next printing... > > In my opinion, the most valuable thing you could do for a next > printing would be to expand the index to 3 times its current length. > As it is now, I think the index is woefully inadequate, which I find > surprising for a reference book. I haven't been able to find 3/4 of > the things I have looked up in the index. For instance __get__(), > __set__(), and sorted() are nowhere to be found in the index. > > Also, the book is brand new, yet the cover has completely separated > from the spine of the book, and now the cover is only attached to the > first and last pages with a bit of glue. > That's not something an author can do much about ... 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 piyali.de.bis at gmail.com Mon Apr 16 03:01:56 2007 From: piyali.de.bis at gmail.com (piyali biswas) Date: Mon, 16 Apr 2007 12:31:56 +0530 Subject: plz sort this out Message-ID: <75c5d9400704160001m26218750ubaa4285fd12fb2d1@mail.gmail.com> Hi, I am using networkx and pylab for creating a graph using a python script abc.py. I have saved the networkx folder in "C:/Python24/Lib/site-packages". When I run the script from command prompt, it creates the graph and saves it to the place I want to but when I write a python-cgi script and run it as os.system('python abc.py') it doesn't gives me any result. I have included the path of my system using os.environ['PATH'] = ".........". I also appended the path of networkx directory using sys.path.append('C:/Python24/Lib/site-packages') as it seems to me that it is a path related problem and the cgi result page shows error (1) networkx *undefined* (2)* *drawing undefined (3) nx_pylab *undefined* (4) matplotlib *undefined* *(5) raise RuntimeError("'%s' is not a writable dir; you must set environment variable HOME to be * * a writable dir "%h)* Can you please tell me how to enable cgi to run this program on runtime. I have kept both the cgi script as well as python script in Apache/cgi-bin folder. Thanks, Piyali -------------- next part -------------- An HTML attachment was scrubbed... URL: From mik3l3374 at gmail.com Fri Apr 6 08:51:07 2007 From: mik3l3374 at gmail.com (mik3l3374 at gmail.com) Date: 6 Apr 2007 05:51:07 -0700 Subject: elementary tuple question. (sorry) In-Reply-To: <1175808663.261249.175970@n76g2000hsh.googlegroups.com> References: <1175808663.261249.175970@n76g2000hsh.googlegroups.com> Message-ID: <1175863867.087571.251330@y66g2000hsf.googlegroups.com> On Apr 6, 5:31 am, "7stud" wrote: > On Apr 5, 3:08 pm, "Steven W. Orr" wrote: > > > I have a tuple that I got from struct.unpack. Now I want to pass the data > > from the returned tuple to struct.pack > > > >>> fmt > > > 'l 10l 11i h 4h c 47c 0l'>>>struct.pack(fmt, tup) > > > Traceback (most recent call last): > > File "", line 1, in ? > > struct.error: required argument is not an integer > > > What's the idiom to pass the data in tup? > > > TIA > > import struct > > fmt = "l l" > result = struct.pack(fmt, 12, 4) > > t = (12, 4) > result = struct.pack(fmt, *t) > --------- > > The * unpacks the tuple. there's an unpack(). >>> struct.unpack(fmt,result) From ocollioud at gmail.com Tue Apr 3 08:38:46 2007 From: ocollioud at gmail.com (olive) Date: 3 Apr 2007 05:38:46 -0700 Subject: XML DTD analysis, diffing ... Message-ID: <1175603926.371027.69390@e65g2000hsc.googlegroups.com> Hi, I have a bunch of similar DTDs written by different coders. I would like to normalize, sort elements and attributes by name and compare those files. Do you know any XML DTD parser/normalizer written in Python ? If not, how would you perform that task in Python language ? Please, Olive. From bdesth.quelquechose at free.quelquepart.fr Fri Apr 13 17:02:07 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Fri, 13 Apr 2007 23:02:07 +0200 Subject: attribute save restore In-Reply-To: <7_ydnZt7B8WqSILbnZ2dnUVZ_uOmnZ2d@comcast.com> References: <7_ydnZt7B8WqSILbnZ2dnUVZ_uOmnZ2d@comcast.com> Message-ID: <461fe69b$0$6318$426a74cc@news.free.fr> Carl K a ?crit : > Is there a more elegant way of coding this: > > x=o.p # save .p > o.p=0 > o.m() > o.p=x # restore .p > > seems very push/pop to me - like there should be a way that doesn't need > a var (x) or the save/set lines should be done in one command. > > (personally I think .m would better be implemented by passing in a > parameter, but that isn't my choice.) I was about to comment on this. It looks like o.m is wanting to take an optional arg defaulting to o.p, and you should probably propose a patch to the author. My 2 cents From olsonas at gmail.com Wed Apr 11 22:41:16 2007 From: olsonas at gmail.com (Drew) Date: 11 Apr 2007 19:41:16 -0700 Subject: Code Explaination: Spelling correction code Message-ID: <1176345676.300560.78020@n59g2000hsh.googlegroups.com> I recently saw this website: http://www.norvig.com/spell-correct.html All the code makes sense to me save one line: def known_edits2(word): return set(e2 for e1 in edits1(word) for e2 in edits1(e1) if e2 in NWORDS) I understand (from seeing a ruby version of the code) that the goal here is to rerun the edits1 method on each member of the set returned by running edits1 on the initial word. However, I'm confused how the for within a for works. Can anyone help shed some light on this for me? From steve at REMOVE.THIS.cybersource.com.au Fri Apr 6 22:15:56 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Sat, 07 Apr 2007 12:15:56 +1000 Subject: Hide the python-script from user References: <8ktie4-0i9.ln1@athlon.my> Message-ID: On Sat, 07 Apr 2007 00:19:20 +0200, hlubenow wrote: > Hi, > > recently there was a thread about hiding the python-script from the user. > The OP could use > > http://freshmeat.net/projects/pyobfuscate/ Wearing my developer hat, I can tell you that there's nothing I love more than getting error reports from my users that look like this: Traceback (most recent call last): File "myapp.py", line 36, in ? print i1I1Iiii1111 ( ) File "myapp.py", line 33, in i1I1Iiii1111 return IiiIII111iI ( ) File "myapp.py", line 24, in IiiIII111iI O0oo0OO0 = IiII + I1i1iiI1 ( iI1Ii11111iIi ) + i1i1II [ 2 ] - Oo ( ) File "myapp.py", line 18, in Oo raise iI1 ( "a problem happened" ) __main__.iI1: a problem happened I love a challenge! -- Steven. From gagsl-py2 at yahoo.com.ar Mon Apr 23 21:00:35 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 23 Apr 2007 22:00:35 -0300 Subject: script for seconds in given month? References: <1176740556.859125.221980@l77g2000hsb.googlegroups.com> <1hwokmz.1ropcwj17pg55dN%aleax@mac.com> <1176796031.889407.323950@b75g2000hsg.googlegroups.com> <1177360091.516469.77830@l77g2000hsb.googlegroups.com> Message-ID: En Mon, 23 Apr 2007 17:28:11 -0300, edfialk escribi?: > Alex, very nice. That should be good enough for me. > The rest of you as well, thanks for all the help. > > I, unfortunately, failed to realize the actual platform the script is > for is IronPython. When trying to import calendar in IronPython, I > get: > > SyntaxError: future feature is not defined: with_statement (c: > \Python25\Lib\calendar.py, line 8) You could download and use the calendar.py from the 2.4 installation. -- Gabriel Genellina From surekap at gmail.com Sun Apr 29 19:51:35 2007 From: surekap at gmail.com (Prateek) Date: 29 Apr 2007 16:51:35 -0700 Subject: Launching an independent Python program in a cross-platform way (including mac) In-Reply-To: <1177889540.489960.176380@u30g2000hsc.googlegroups.com> References: <1177889540.489960.176380@u30g2000hsc.googlegroups.com> Message-ID: <1177890695.308785.165580@l77g2000hsb.googlegroups.com> On Apr 30, 4:32 am, Andr? wrote: > I would like to find out how I can launch an independent Python > program from existing one in a cross-platform way. The result I am > after is that a new terminal window should open (for io independent of > the original script). > > The following seems to work correctly under Ubuntu and Windows ... but > I haven't been able to find a way to make it work under Mac OS. > > def exec_external(code, path): > """execute code in an external process > currently works under: > * Windows NT (tested) > * GNOME (tested) [January 2nd and 15th change untested] > This also needs to be implemented for OS X, KDE > and some form of linux fallback (xterm?) > """ > if os.name == 'nt': > current_dir = os.getcwd() > target_dir, fname = os.path.split(path) > > filename = open(path, 'w') > filename.write(code) > filename.close() > > if os.name == 'nt': > os.chdir(target_dir) # change dir so as to deal with paths > that > # include spaces > Popen(["cmd.exe", ('/c start python %s'%fname)]) > os.chdir(current_dir) > elif os.name == 'posix': > try: > os.spawnlp(os.P_NOWAIT, 'gnome-terminal', 'gnome- > terminal', > '-x', 'python', '%s'%path) > except: > raise NotImplementedError > else: > raise NotImplementedError > ========================== > Any help would be greatly appreciated. > > Andr? Well, You need to check sys.platform on the Mac instead of os.name. os.name returns 'posix' on all *nix based systems. sys.platform helpfully returns "darwin" on the Mac. Not sure how to start Terminal. Here's what I got when I tried it: >>> if sys.platform == "darwin": os.spawnlp(os.P_NOWAIT, '/Applications/Utilities/Terminal.app/Contents/MacOS/Terminal') 9460 >>> 2007-04-30 05:19:59.255 [9460] No Info.plist file in application bundle or no NSPrincipalClass in the Info.plist file, exiting Maybe I'm just calling it wrong and you'll have more luck. Prateek From gagsl-py2 at yahoo.com.ar Sun Apr 29 19:15:12 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sun, 29 Apr 2007 20:15:12 -0300 Subject: exclusive shelve open References: <1177873921.270358.259310@l77g2000hsb.googlegroups.com> <1177877622.660437.299810@y5g2000hsa.googlegroups.com> Message-ID: En Sun, 29 Apr 2007 17:13:42 -0300, escribi?: > On Apr 29, 2:12 pm, castiro... at gmail.com wrote: >> I'm trying to be safe and make sure only one python instance opens the >> shelf. Any ideas? > Using Windows. Use the locking function in the msvcrt module to lock/unlock the file. Locking just the first byte is enough. -- Gabriel Genellina From gagsl-py2 at yahoo.com.ar Fri Apr 20 16:52:09 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 20 Apr 2007 17:52:09 -0300 Subject: When are immutable tuples *essential*? Why can't you just use lists *everywhere* instead? References: <1177088796.622928.224890@d57g2000hsg.googlegroups.com> <1177089206.550423.288670@q75g2000hsh.googlegroups.com> <58sf33F2b1q8tU1@mid.individual.net> Message-ID: En Fri, 20 Apr 2007 15:28:51 -0300, Bjoern Schliessmann escribi?: > Luis M. Gonz?lez wrote: > >> I don't remember exactly where I read about it, but Guido said >> once that tuples are being kept mainly for historical reasons. > > Weren't tuples added when lists already existed? Both listobject.c and tupleobject.c appear to had been checked in at the same time: Revision 2167 - (view) (download) (as text) - [select for diffs] Added Sun Oct 14 12:07:46 1990 UTC (16 years, 6 months ago) by guido File length: 4965 byte(s) Initial revision And that's before the earliest tagged release I could find on svn, Python 0.98 -- Gabriel Genellina From martin at v.loewis.de Fri Apr 27 18:46:09 2007 From: martin at v.loewis.de (=?ISO-8859-15?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sat, 28 Apr 2007 00:46:09 +0200 Subject: Command-line option equiv of PYTHONPATH In-Reply-To: References: <1177648804.947472.112830@s33g2000prh.googlegroups.com> Message-ID: <46327D31.9070208@v.loewis.de> >> Why not just modify sys.path within the actual script? > > Maybe because he has multiple versions of modules he wants to test his > script against. See the original post: 'I can use it as "#!/usr/bin/perl -I"' so clearly his intention is modify the script. Martin From bbxx789_05ss at yahoo.com Tue Apr 3 15:01:46 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: 3 Apr 2007 12:01:46 -0700 Subject: how to remove multiple occurrences of a string within a list? In-Reply-To: <1175624433.206953.214290@n59g2000hsh.googlegroups.com> References: <1175624433.206953.214290@n59g2000hsh.googlegroups.com> Message-ID: <1175626905.957243.301870@w1g2000hsg.googlegroups.com> On Apr 3, 12:20 pm, "bahoo" wrote: > Hi, > > I have a list like ['0024', 'haha', '0024'] > and as output I want ['haha'] > > If I > myList.remove('0024') > > then only the first instance of '0024' is removed. > > It seems like regular expressions is the rescue, but I couldn't find > the right tool. > > Thanks! > bahoo Here are a couple of ways: target = "0024" l = ["0024", "haha", "0024"] ------------------------------------ while(True): try: l.remove(target) except ValueError: break print l ------------------------------------- for index, val in enumerate(l): if val==target: del l[index] print l From jkn_gg at nicorp.f9.co.uk Wed Apr 18 14:42:34 2007 From: jkn_gg at nicorp.f9.co.uk (jkn) Date: 18 Apr 2007 11:42:34 -0700 Subject: How to communicate via USB "port" In-Reply-To: <1176875664.555559.259840@y80g2000hsf.googlegroups.com> References: <1176875664.555559.259840@y80g2000hsf.googlegroups.com> Message-ID: <1176921754.758115.58380@l77g2000hsb.googlegroups.com> Have a look for PyUSB - there are (confusingly) two different packages called pyUSB. one interfaces to FTDI chips connected to a USB port: http://bleyer.org/pyusb/ The other uses libusb to interface to devices generally under windows: http://pyusb.berlios.de/ HTH jon N From phil at riverbankcomputing.co.uk Thu Apr 26 14:15:51 2007 From: phil at riverbankcomputing.co.uk (Phil Thompson) Date: Thu, 26 Apr 2007 19:15:51 +0100 Subject: passing tuple with pyqt4 signal/slot mechanism In-Reply-To: <80628d680704261034u2632a1ackb9b40cf4175a1fd2@mail.gmail.com> References: <80628d680704261034u2632a1ackb9b40cf4175a1fd2@mail.gmail.com> Message-ID: <200704261915.51985.phil@riverbankcomputing.co.uk> On Thursday 26 April 2007 6:34 pm, Pradnyesh Sawant wrote: > > > Also, in the modified code, why aint the method setLabel getting > > > called? > > > > Works for me, > > Does the "setLabel" method get called in your case? In your previous > reply, you mentioned that it doesn't. Can you tell me the reason why? In the first version it didn't. In the second version it did. > > and I still don't know what versions you are using and on > > which > > platform. Whatever they are, try the latest release. > > Python 2.4.4c1 (#2, Oct 11 2006, 21:51:02) > [GCC 4.1.2 20060928 (prerelease) (Ubuntu 4.1.1-13ubuntu5)] on linux2 The version of PyQt? The version of SIP? The version of Qt? Phil From aleax at mac.com Fri Apr 20 10:39:59 2007 From: aleax at mac.com (Alex Martelli) Date: Fri, 20 Apr 2007 07:39:59 -0700 Subject: Calling private base methods References: <1176374675.347453.89340@n76g2000hsh.googlegroups.com> <1176404325.211501.26610@w1g2000hsg.googlegroups.com> <1176435087.708516.66470@o5g2000hsb.googlegroups.com> <1176650850.211487.294690@y80g2000hsf.googlegroups.com> <1hwmmq4.n76p2d1k88mz5N%aleax@mac.com> <1176902245.845880.308870@b75g2000hsg.googlegroups.com> <1176995820.855309.304040@e65g2000hsc.googlegroups.com> Message-ID: <1hwuy84.brlpwzny8zwgN%aleax@mac.com> Marc 'BlackJack' Rintsch wrote: > In <1176995820.855309.304040 at e65g2000hsc.googlegroups.com>, Isaac > Rodriguez wrote: > > > But the truth is that C++ and Java made a decision to do that for a > > reason, and the times when you have to work around those language > > features come once in a blue moon; they are the exception, not the > > rule, and you don't implement features in a language, or for that > > matter in an application, to simplify the exceptions; you try to > > implement the most common scenarios. > > So the most common scenario is that programmers try to poke around all the > time in the internals of classes even if the need to do so is > very rare? Otherwise it would not be necessary to have and use a > mechanism to declare everything private. ;-) Historically, say in the '70s, it was probably the case that experienced programmers, trained in a very different environment, had to be nearly coerced to respect encapsulation; so the enforced encapsulation mechanisms of languages born at that time may well have been warranted. Nowadays, I agree with your thesis that having extra mechanisms to enforce encapsulation is probably supererogatory. Alex From cam.ac.uk at mh391.invalid Tue Apr 24 05:22:32 2007 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Tue, 24 Apr 2007 10:22:32 +0100 Subject: I/O Error In-Reply-To: <1177402242.614113.289570@r30g2000prh.googlegroups.com> References: <1177402242.614113.289570@r30g2000prh.googlegroups.com> Message-ID: saif.shakeel at gmail.com wrote: > file_input = raw_input("Enter The ODX File Path:") > odx_file_output = raw_input("Enter the output file path : ") > log_file_output = raw_input("Enter the path for LogFile : ") > > saveout = sys.stdout > try: > f_open=open(odx_file_output, 'w') > except: > print "cant open file" > sys.exit() > sys.stdout = f_open > > try: > input_xml = open(file_input,'r') > except: > print "The File Cannot Be Opened" > sys.exit() > > if input_xml.read(5)!=' print "Invalid File" > input_xml.close() > sys.exit() > else: > xmldoc = minidom.parse(input_xml) > input_xml.close() > > if xmldoc.childNodes[1].getAttribute("DtdVers") == u'1.1.4' or > xmldoc.childNodes[1].getAttribute("DtdVers")== u'1.1.5': > pass > else: > print "Invalid Version" > sys.exit() > > After this some more code follows,but i have > pasted only the i/o part . In the future, it is best to be able to produce a short and complete test case. Doing so may help you find your error, without assistance. > Traceback (most recent call last): > File "C:\Projects\ODX Import\code_ini\odxparse.py", line 250, in > > file_input = raw_input("Enter The ODX File Path:") > ValueError: I/O operation on closed file Well, you set sys.stdout to f_open, and you probably closed it without setting it back. Can't tell because you didn't include the whole script (and you shouldn't do that either--make a test case). Here are some general comments: 1) Redirecting sys.stdout does not seem advisable in this case, and seems to be causing some confusion. It's far better to make a new file handle for your output. You can print to it using: print >>filehandle, "message" 2) Interactively asking for filenames like this will cause irritation for yourself, and possibly your users if they ever want to automate things. My personal preference would be to accept the arguments on the command line. If your users don't know how to use a command line, then you should really be getting the filenames through some sort of GUI instead of raw_input(). 3) I try to name my file-related variables consistently so I know where they are. Naming the file name variable and the file handle variable something completely different is confusing. 4) If you have some abnormal exit condition, you should exit with sys.exit(1) or really any number besides 0. Exiting with sys.exit() or sys.exit(0) means everything is fine. 5) If an exception occurs that will result in the end of the program, there's no point in catching it just to print a less descriptive error message and quit. It makes your code harder to understand with all the exception catching, and it makes it harder to debug because you lose crucial details of where the exception occurred and what its calling stack was. 6) Further, I'm not sure how much sense it makes to double-check that the file begins with " References: Message-ID: <1176530119.547420.286150@n76g2000hsh.googlegroups.com> On Apr 13, 11:39 pm, Tina I wrote: > Hello group, > > Say I have the following dictionary: > > ListDict = { > 'one' : ['oneone' , 'onetwo' , 'onethree'], > 'two' : ['twoone' , 'twotwo', 'twothree'], > 'three' : ['threeone' , 'threetwo', threethree']} > > Now I want to append 'twofour' to the list of the 'two' key but I can't > figure out how to that? > Some pointers would be greatly appreciated. > > Thanks > Tina ListDict["two"] returns the list. So you can do this: lst = listDict["two"] lst.append("twofour") or you can do it directly like this: ListDict["two"].append("twofour") From steve at holdenweb.com Fri Apr 20 15:05:38 2007 From: steve at holdenweb.com (Steve Holden) Date: Fri, 20 Apr 2007 15:05:38 -0400 Subject: Beautiful Soup iterator question.... In-Reply-To: <1177094168.548423.115730@y80g2000hsf.googlegroups.com> References: <1177094168.548423.115730@y80g2000hsf.googlegroups.com> Message-ID: cjl wrote: > P: > > I am screen-scraping a table. The table has an unknown number of rows, > but each row has exactly 8 cells. I would like to extract the data > from the cells, but the first three cells in each row have their data > nested inside other tags. > > So I have the following code: > > for row in table.findAll("tr"): > for cell in row.findAll("td"): > print cell.contents[0] > > This code prints out all the data, but of course the first three cells > still contain their unwanted tags. > > I would like to do something like this: > > for cell1, cell2, cell3, cell4, cell5, cell6, cell7, cell8 in > row.findAll("td"): > > Then treat each cell differently. > > I can't figure this out. Can anyone point me in the right direction? > did you try something like (untested) cell1, cell2, cell3, cell4, cell5, \ cell6, cell7, cell8 = row.findAll("td") No need for the "for" if you want to handle each cell differently, you won;t be iterating over htem . And, as you saw, it doesn't work unless row.findAll(...) returns a sequence of eight-item containers. 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 Fri Apr 27 17:44:37 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 27 Apr 2007 18:44:37 -0300 Subject: what python technology for my app? References: <4631dc06$0$15457$426a74cc@news.free.fr> Message-ID: En Fri, 27 Apr 2007 08:38:57 -0300, Robert Rawlins - Think Blue escribi?: >> The application is for in-house use only and not likely to have more >> than a few users at any one time. I've managed to hack out enough > If you're looking for a web based server side solution, then you can't go > wrong with Adobe ColdFusion. Its and incredibly powerful and scalable > development platform and yet supports a simple tag based language which > makes life very easy when getting started, and yet will support much more > complex OOP methodology with a whole myriad of frameworks, orm's and > object > factories. For a small in-house application, U$S 6000 per server (Coldfusion MX 7 Enterprise) or even U$S 1300 (Standard Edition) might be too much, depending on the OP budget... -- Gabriel Genellina From steven.bethard at gmail.com Tue Apr 3 01:00:14 2007 From: steven.bethard at gmail.com (Steven Bethard) Date: Mon, 02 Apr 2007 23:00:14 -0600 Subject: getattr/setattr q. In-Reply-To: <1175573213.682671@jubilee.claranet.pt> References: <1175573213.682671@jubilee.claranet.pt> Message-ID: Paulo da Silva wrote: > In a class C, I may do setattr(C,'x',10). > > Is it possible to use getattr/setattr for variables not inside > classes or something equivalent? I mean with the same result as > exec("x=10"). If you're at the module level, you can do:: globals()['x'] = 10 If you're inside a function, you probably want to look for another way of doing what you're doing. What's the actual task you're trying to accomplish here? STeVe From bj_666 at gmx.net Sun Apr 29 16:03:52 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Sun, 29 Apr 2007 22:03:52 +0200 Subject: I can't inherit from "compiled" classes ? References: Message-ID: In , Maxim Veksler wrote: > Hello list, > > I'm trying to subclass socket and select, for both I get: > """ TypeError: Error when calling the metaclass bases > module.__init__() takes at most 2 arguments (3 given) """, I don't > understand this error. Why would python try to pass 3 arguments (what > are they) ? > > Googling for this error gave random results talking about try to > inherit a "Package" but socket is definitely a class, > (/usr/lib/python2.4/socket.py). Not sure about select thought. > > I've did the following to receive the error: > """ > In [1]: import socket > > In [2]: class PollingSocket(socket): > ...: pass > ...: > --------------------------------------------------------------------------- > exceptions.TypeError Traceback (most > recent call last) > > /home/hq4ever/ > > TypeError: Error when calling the metaclass bases > module.__init__() takes at most 2 arguments (3 given) > """ > > > What am I breaking wrong? You are trying to subclass a module here, just like the error message says. The module contains a `socket` type: In [3]: import socket In [4]: type(socket) Out[4]: In [5]: type(socket.socket) Out[5]: `select.select()` is a function: In [6]: import select In [7]: type(select.select) Out[7]: Ciao, Marc 'BlackJack' Rintsch From bj_666 at gmx.net Fri Apr 20 04:35:02 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Fri, 20 Apr 2007 10:35:02 +0200 Subject: Calling private base methods References: <1176374675.347453.89340@n76g2000hsh.googlegroups.com> <1176404325.211501.26610@w1g2000hsg.googlegroups.com> <1176435087.708516.66470@o5g2000hsb.googlegroups.com> <1176650850.211487.294690@y80g2000hsf.googlegroups.com> <1hwmmq4.n76p2d1k88mz5N%aleax@mac.com> <1176902245.845880.308870@b75g2000hsg.googlegroups.com> <1176995820.855309.304040@e65g2000hsc.googlegroups.com> Message-ID: In <1176995820.855309.304040 at e65g2000hsc.googlegroups.com>, Isaac Rodriguez wrote: > But the truth is that C++ and Java made a decision to do that for a > reason, and the times when you have to work around those language > features come once in a blue moon; they are the exception, not the > rule, and you don't implement features in a language, or for that > matter in an application, to simplify the exceptions; you try to > implement the most common scenarios. So the most common scenario is that programmers try to poke around all the time in the internals of classes even if the need to do so is very rare? Otherwise it would not be necessary to have and use a mechanism to declare everything private. ;-) Ciao, Marc 'BlackJack' Rintsch From grante at visi.com Tue Apr 24 11:55:31 2007 From: grante at visi.com (Grant Edwards) Date: Tue, 24 Apr 2007 15:55:31 -0000 Subject: Generate report containing pdf or ps figures? References: <132pnp6r4qg0lc2@corp.supernews.com> Message-ID: <132sa3jkr5uv0a9@corp.supernews.com> On 2007-04-24, Cameron Laird wrote: [...] >>I've looked at ReportLab's documentation, but although it >>appears to be able to use bitmap images (e.g jpeg) it doesn't >>appear to be able to use vector images (EPS/PDF/SVG). >> >>Is there a PDF generation library that can place EPS or >>PDF figures on a page? > . > . > . > You're stuck. > > If I understand what you're after, you're probably going to > end up finding a way to leverage Ghostscript. There are a > lot of ways to move forward in this area, but GS has most of > 'em beat, despite all its liabilities. Yup, GS is what I'm using now, and it's working fine. I was hoping there would be something that'd be easier to bundle as part of a Win32 application. You can pretty much except a Linux platform to have ghostscript available, but for Win32 users it'll have to be bundled. :/ > That's my summary. I've done quite a bit in this area, and > am happy to talk about specifics. > > I have two recommendations: see if anything in http://phaseit.net/claird/comp.text.pdf/PDF_converters.html > > resonates with you; and e-mail the nice folks at http://www.pdf-tools.com/ >. Thanks. I'll take a look at those. It's too bad that ReportLab can't use vector image formats such as PDF or SVG. I would have thought that sticking a PDF image into a PDF document would be a pretty straight-forward thing to do, but it must not be something in high demand. > I've taken the liberty of cross-posting to c.t.p. Python > alone isn't big enough (yet) to solve your problem. -- Grant Edwards grante Yow! Did I do an INCORRECT at THING?? visi.com From bbxx789_05ss at yahoo.com Thu Apr 12 18:38:55 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: 12 Apr 2007 15:38:55 -0700 Subject: wxPython, mac, wx.HSCROLL not working In-Reply-To: <587i0iF2fu57fU1@mid.individual.net> References: <1176364597.741079.25840@n59g2000hsh.googlegroups.com> <586qvsF2fbq3rU1@mid.individual.net> <1176392605.298630.8210@y5g2000hsa.googlegroups.com> <1176404918.079527.148440@d57g2000hsg.googlegroups.com> <587i0iF2fu57fU1@mid.individual.net> Message-ID: <1176417535.246590.158780@y80g2000hsf.googlegroups.com> On Apr 12, 2:09 pm, Bjoern Schliessmann wrote: > 7stud wrote: > > Where is that list? > > Argh! > > http://www.wxpython.org/maillist.php > > Regards, > > Bj?rn > > -- > BOFH excuse #330: > > quantum decoherence Thanks. It looks like someone asked the same question yesterday. From deets at nospam.web.de Sun Apr 15 16:54:47 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sun, 15 Apr 2007 22:54:47 +0200 Subject: Qt4 in ubuntu In-Reply-To: <1176668662.770066.208350@n76g2000hsh.googlegroups.com> References: <1176668662.770066.208350@n76g2000hsh.googlegroups.com> Message-ID: <58fhooF2finkjU1@mid.uni-berlin.de> Marcpp schrieb: > Is possible install Qt4 pyqt4 under kubuntu? > Few times ago i tried to run pyqt in ubuntu (gnome) but i can't > do it. It's certainly possible. On ubuntu as well as on kubuntu. You can install all KDE and Qt stuff on ubuntu as well. But unless you are more specific what your actual problems were, you can't better help. Diez From erikwickstrom at gmail.com Fri Apr 6 10:31:13 2007 From: erikwickstrom at gmail.com (erikcw) Date: 6 Apr 2007 07:31:13 -0700 Subject: Extract zip file from email attachment In-Reply-To: <1175835107.288163.139050@b75g2000hsg.googlegroups.com> References: <1175815907.434721.274190@w1g2000hsg.googlegroups.com> <65fge4-j15.ln1@athlon.my> <1175821421.265541.120440@w1g2000hsg.googlegroups.com> <1175835107.288163.139050@b75g2000hsg.googlegroups.com> Message-ID: <1175869873.747758.278050@b75g2000hsg.googlegroups.com> On Apr 6, 12:51 am, "Gabriel Genellina" wrote: > erikcw wrote: > > resp = p.retr(msg_num) > > if resp[0].startswith('+OK'): > > You don't have to check this; errors are transformed into exceptions. > > > fileObj = StringIO.StringIO() > > cStringIO is faster > > > fileObj.write( part.get_payload() ) > > You have to reset the file pointer to the beginning: fileObj.seek(0), > else ZipFile will not be able to read the contents. > > -- > Gabriel Genellina Hi Gabriel, I added fileObj.seek(0) on the line directly after fileObj.write( part.get_payload() ) and I'm still getting the following error. Traceback (most recent call last): File "wa.py", line 209, in attachment = zipfile.ZipFile(fileObj) File "/usr/lib/python2.5/zipfile.py", line 346, in __init__ self._GetContents() File "/usr/lib/python2.5/zipfile.py", line 366, in _GetContents self._RealGetContents() File "/usr/lib/python2.5/zipfile.py", line 378, in _RealGetContents raise BadZipfile, "File is not a zip file" zipfile.BadZipfile: File is not a zip file Could the file like object still be encoded in MIME or something? Thanks! Erik From nospam at invalid.com Fri Apr 13 16:35:55 2007 From: nospam at invalid.com (Jack) Date: Fri, 13 Apr 2007 13:35:55 -0700 Subject: Python editor/IDE on Linux? References: Message-ID: > We should do a weekly poll. :) Seriously - this question is coming up > very frequently and everybody has their preference. Maybe a web page, something like pythonidepoll.com :) I apologize for bringing up this FAQ once again ;-p > My (current) favorite: > pida (exists as a ready package on Debian as derivates like Xubuntu) > > pida because it embeds the 'vim' editor which I love and adds useful > features without really getting in my way. And it's the only IDE I found > that supports bazaar-ng (bzr) repositories. pida screenshots look neat. It's not in xubuntu's repository though. Not even in universe. I installed from the source. When running it, I get an error "Service not found. Tried to access non-existing service filemanager" From jstroud at mbi.ucla.edu Sat Apr 14 06:48:49 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Sat, 14 Apr 2007 10:48:49 GMT Subject: Python Feature Request: Explicit variable declarations In-Reply-To: <1176546078.934340.253810@y5g2000hsa.googlegroups.com> References: <1176546078.934340.253810@y5g2000hsa.googlegroups.com> Message-ID: samjnaa at gmail.com wrote: > Hello. Please tell me whether this feature request is sane (and not > done before) for python so it can be posted to the python-dev mailing > list. I should say first that I am not a professional programmer with > too much technical knowledge. > > I would like to have something like the "option explicit" statement in > Visual Basic which turns on C-like checking for declaration of > variables. This is highly helpful for people who are coming from C/C+ > +, for people who are learning programming using Python, and even > professionals, since this helps prevent typo errors like: > > sunlognitude = sunlongitude + 180.0 > > where the user has inadvertantly typed "g" before "n" and will later > wonder why his application is not working as expected. > I have no formal training in programming and thus have had to shake off all of the worst habits afflicting amateurs on my path to the modest proficiency I enjoy now. So let me assure you that this is something I can honestly say is just about the least of your worries and consequently has no place clogging up a language like python. But, if you have masochistic tendencies and want a lot of overhead in your programming, you can always bind yourself mercilessly to classes: class C(object): declared = ['bob', 'carol', 'ted', 'alice'] def __setattr__(self, anattr, aval): if anattr not in C.declared: raise TypeError, "Just can't hook you up, bro." else: self.__dict__[anattr] = aval E.g.: py> class C(object): ... declared = ['bob', 'carol', 'ted', 'alice'] ... def __setattr__(self, anattr, aval): ... if anattr not in C.declared: ... raise TypeError, "Just can't hook you up, bro." ... else: ... self.__dict__[anattr] = aval ... py> c = C() py> c.bob = 42 py> c.bob 42 py> c.x = 69 Traceback (most recent call last): File "", line 1, in File "", line 5, in __setattr__ TypeError: Just can't hook you up, bro. Extending this ugliness to type-checking is left as an exercise for the reader. Using metaclasses for such nonsense is left as an exercise for metaclass maniacs. James From hugonz at h-lab.net Thu Apr 12 03:41:26 2007 From: hugonz at h-lab.net (=?ISO-8859-1?Q?Hugo_Gonz=E1lez_Monteverde?=) Date: Thu, 12 Apr 2007 02:41:26 -0500 Subject: Any Pythonistas in Mexico? Message-ID: <461DE2A6.8070700@h-lab.net> Hola, Le? este mail viej?simo en una lista. Yo uso Python y tambi?n quer?a saber qui?n pythoneaba en M?xico. Todav?a est?s por ah?? Saludos, Hugo G. From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Sun Apr 22 06:34:31 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Sun, 22 Apr 2007 12:34:31 +0200 Subject: Select weirdness References: Message-ID: <590s1nF2ibkeqU1@mid.individual.net> Ron Garret wrote: > print>>self.wfile, 'HTTP/1.0 200 OK' > print>>self.wfile, 'Content-type: text/plain' > print>>self.wfile > print>>self.wfile, 'foo' > [...] > If I telnet into this server and type in an HTTP request manually > it works fine. But when I try to access this with a browser (I've > tried Firefox and Safari -- both do the same thing) it hangs > immediately after reading the first line in the request (i.e. > before reading the first header). Could the problem be that print ends lines with "\r\n" not on all platforms? Try doing it explicitly. > The only difference I can discern is that the browser send \r\n > for end-of-line while telnet just sends \n. Then, I think, your telnet client is broken. I've seem multiple applications relying on telnet or similar protocols which required "\r\n" as end-of-line. E. g. I needed to hack twisted.protocols.basic.LineReceiverFactory since it showed the exact behaviour you described for browsers. It showed up because busybox' telnet only sends \n as EOL. > But I don't see why that should make any difference. Easy. If you only accept "\r\n" as EOL, you'll wait forever unless you really receive it. Regards, Bj?rn -- BOFH excuse #81: Please excuse me, I have to circuit an AC line through my head to get this database working. From cam.ac.uk at mh391.invalid Mon Apr 2 14:54:59 2007 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Mon, 02 Apr 2007 19:54:59 +0100 Subject: Launch script on Linux using Putty In-Reply-To: <1312jhhpbll3ta7@corp.supernews.com> References: <1175467029.572354.138930@y66g2000hsf.googlegroups.com> <1175536278.510176.183360@l77g2000hsb.googlegroups.com> <1312jhhpbll3ta7@corp.supernews.com> Message-ID: [Michael Hoffman] >> If you are running bash, you can do this: [Grant Edwards] > He's not running bash. He's running busybox's shell. There's a nohup applet for busybox. > [He'd be far better off asking his question in an OpenWRT or > Busybox forum, since it's got absolutely nothing to do with > Python.] I was going to say that originally, but then I realized that the daemon solution is on-topic. So is masking SIGHUP. -- Michael Hoffman From mangabasi at gmail.com Mon Apr 23 17:48:53 2007 From: mangabasi at gmail.com (Mangabasi) Date: 23 Apr 2007 14:48:53 -0700 Subject: Establishing socket connections to Synthesis Toolkit Message-ID: <1177364933.924820.108620@o5g2000hsb.googlegroups.com> Howdy, I would like to use the Synthesis Toolkit for a demo. I downloaded the STK from http://ccrma.stanford.edu/software/stk/index.html. It seems very powerful and user friendly. There are bindings for socket connections and TCL gui examples. I would like to get one of the demo samples work with Python/wxPython. I am including the TCL code for the drums demo (this was the shortest one). Has anybody converted this to wxPython? If yes, would you be kind enough to share the code? If not, How do I establish a socket connection for localhost and port 2001 in Python? And how do I send commands to this connection once it is established? Thank you in advance, Mangabasi # Tcl/Tk Drum GUI for the Synthesis Toolkit (STK) # Set initial control values set press 127 set outID "stdout" set commtype "stdout" # Turn down the reverb puts $outID "ControlChange 0.0 1 44.0 0.0" # Configure main window wm title . "STK Drum Controller" wm iconname . "drum" . config -bg black # Configure "communications" menu menu .menu -tearoff 0 menu .menu.communication -tearoff 0 .menu add cascade -label "Communication" -menu .menu.communication \ -underline 0 .menu.communication add radio -label "Console" -variable commtype \ -value "stdout" -command { setComm } .menu.communication add radio -label "Socket" -variable commtype \ -value "socket" -command { setComm } . configure -menu .menu # Configure slider scale .bPressure -from 0 -to 128 -length 100 \ -command {changePress } -variable press\ -orient horizontal -label "Velocity" \ -tickinterval 64 -showvalue true -bg grey66 pack .bPressure -pady 5 -padx 5 # Configure buttons frame .buttons -bg black frame .buttons.left -bg black frame .buttons.right -bg black button .buttons.left.bass -text Bass -bg grey66 \ -command { playDrum 36 } -width 7 button .buttons.left.snare -text Snare -bg grey66 \ -command { playDrum 38 } -width 7 button .buttons.left.tomlo -text LoTom -bg grey66 \ -command { playDrum 41 } -width 7 button .buttons.left.tommid -text MidTom -bg grey66 \ -command { playDrum 45 } -width 7 button .buttons.left.tomhi -text HiTom -bg grey66 \ -command { playDrum 50 } -width 7 button .buttons.left.homer -text Homer -bg grey66 \ -command { playDrum 90 } -width 7 button .buttons.right.hat -text Hat -bg grey66 \ -command { playDrum 42 } -width 7 button .buttons.right.ride -text Ride -bg grey66 \ -command { playDrum 46 } -width 7 button .buttons.right.crash -text Crash -bg grey66 \ -command { playDrum 49 } -width 7 button .buttons.right.cowbel -text CowBel -bg grey66 \ -command { playDrum 56 } -width 7 button .buttons.right.tamb -text Tamb -bg grey66 \ -command { playDrum 54 } -width 7 button .buttons.right.homer -text Homer -bg grey66 \ -command { playDrum 90 } -width 7 pack .buttons.left.bass -pady 5 pack .buttons.left.snare -pady 5 pack .buttons.left.tomlo -pady 5 pack .buttons.left.tommid -pady 5 pack .buttons.left.tomhi -pady 5 pack .buttons.left.homer -pady 5 pack .buttons.right.hat -pady 5 pack .buttons.right.ride -pady 5 pack .buttons.right.crash -pady 5 pack .buttons.right.cowbel -pady 5 pack .buttons.right.tamb -pady 5 pack .buttons.right.homer -pady 5 pack .buttons.left -side left -pady 5 -padx 5 pack .buttons.right -side right -pady 5 -padx 5 pack .buttons -pady 5 -padx 5 # Configure exit button button .exit -text "Exit Program" -bg grey66 -command myExit pack .exit -side bottom -pady 20 #bind all { bind . { noteOn $pitch $press } # Bind an X windows "close" event with the Exit routine bind . +myExit proc myExit {} { global outID puts $outID [format "ExitProgram"] flush $outID close $outID exit } proc playDrum {value} { global press global outID puts $outID [format "NoteOn 0.0 1 %i %f" $value $press] flush $outID } proc changePress {value} { global press set press $value } # Socket connection procedure set d .socketdialog proc setComm {} { global outID global commtype global d if {$commtype == "stdout"} { if { [string compare "stdout" $outID] } { set i [tk_dialog .dialog "Break Socket Connection?" {You are about to break an existing socket connection ... is this what you want to do?} "" 0 Cancel OK] switch $i { 0 {set commtype "socket"} 1 {close $outID set outID "stdout"} } } } elseif { ![string compare "stdout" $outID] } { set sockport 2001 set sockhost localhost toplevel $d wm title $d "STK Client Socket Connection" wm resizable $d 0 0 grab $d label $d.message -text "Specify a socket host and port number below (if different than the STK defaults shown) and then click the \"Connect\" button to invoke a socket-client connection attempt to the STK socket server." \ -background white -font {Helvetica 10 bold} \ -wraplength 3i -justify left frame $d.sockhost entry $d.sockhost.entry -width 15 label $d.sockhost.text -text "Socket Host:" \ -font {Helvetica 10 bold} frame $d.sockport entry $d.sockport.entry -width 15 label $d.sockport.text -text "Socket Port:" \ -font {Helvetica 10 bold} pack $d.message -side top -padx 5 -pady 10 pack $d.sockhost.text -side left -padx 1 -pady 2 pack $d.sockhost.entry -side right -padx 5 -pady 2 pack $d.sockhost -side top -padx 5 -pady 2 pack $d.sockport.text -side left -padx 1 -pady 2 pack $d.sockport.entry -side right -padx 5 -pady 2 pack $d.sockport -side top -padx 5 -pady 2 $d.sockhost.entry insert 0 $sockhost $d.sockport.entry insert 0 $sockport frame $d.buttons button $d.buttons.cancel -text "Cancel" -bg grey66 \ -command { set commtype "stdout" set outID "stdout" destroy $d } button $d.buttons.connect -text "Connect" -bg grey66 \ -command { set sockhost [$d.sockhost.entry get] set sockport [$d.sockport.entry get] set err [catch {socket $sockhost $sockport} outID] if {$err == 0} { destroy $d } else { tk_dialog $d.error "Socket Error" {Error: Unable to make socket connection. Make sure the STK socket server is first running and that the port number is correct.} "" 0 OK } } pack $d.buttons.cancel -side left -padx 5 -pady 10 pack $d.buttons.connect -side right -padx 5 -pady 10 pack $d.buttons -side bottom -padx 5 -pady 10 } } From mcPas.De.Spam at mclaveauPas.De.Spam.com Sun Apr 22 00:02:01 2007 From: mcPas.De.Spam at mclaveauPas.De.Spam.com (Michel Claveau) Date: Sun, 22 Apr 2007 06:02:01 +0200 Subject: Problem redefining __getitem__ for str subclass References: <1177212972.973086.319990@b58g2000hsg.googlegroups.com> Message-ID: Hi! Same result, with Python 2.5.1 on win-XP; I have compassion with you. -- @-salutations Michel Claveau From bdesth.quelquechose at free.quelquepart.fr Tue Apr 3 15:37:47 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Tue, 03 Apr 2007 21:37:47 +0200 Subject: How to have a list of lists (or array of lists) In-Reply-To: <1175616750.744309.156580@n76g2000hsh.googlegroups.com> References: <1175616750.744309.156580@n76g2000hsh.googlegroups.com> Message-ID: <4612a426$0$14561$426a74cc@news.free.fr> bahoo a ?crit : > Hi, > > I want to have many lists, such as list0, list1, list2, ..., each one > holding different number of items. > Is there something like > list[0] > list[1] > list[2] > > so that I can iterate through this list of lists? listoflists = [ [1, 2, 3], ["foo", "bar", "baaz", "quux"], ["A", "B", "C", "D", "E"] ] for alist in listoflists: for item in alist: print item From anton.vredegoor at gmail.com Wed Apr 18 18:51:59 2007 From: anton.vredegoor at gmail.com (Anton Vredegoor) Date: Thu, 19 Apr 2007 00:51:59 +0200 Subject: multirember&co In-Reply-To: <1176925857.535835.130010@b58g2000hsg.googlegroups.com> References: <1176768854.720234.23320@w1g2000hsg.googlegroups.com> <1176790588.024371.119360@n76g2000hsh.googlegroups.com> <1176850352.999231.79260@n59g2000hsh.googlegroups.com> <1176921030.330467.76860@o5g2000hsb.googlegroups.com> <1176925857.535835.130010@b58g2000hsg.googlegroups.com> Message-ID: attn.steven.kuo at gmail.com wrote: > Try it with > > def test(): > L = 'a', 1, 2, 'a' > it1, it2 = xsplitter(L, lambda x: x == 'a') > print it1.next() > print it2.next() > print it1.next() > print it2.next() > > > The last print statement raises StopIteration... > We, however, expected each iterator to contain > two elements (one yielding 'a' then 'a', and > the other yielding 1 then 2). Ouch! I never understood much about generators anyway. A. From anton.vredegoor at gmail.com Sun Apr 15 17:16:21 2007 From: anton.vredegoor at gmail.com (Anton Vredegoor) Date: Sun, 15 Apr 2007 23:16:21 +0200 Subject: combination function in python In-Reply-To: <1176669548.436118.176300@e65g2000hsc.googlegroups.com> References: <1176615838.830315.160210@b75g2000hsg.googlegroups.com> <1176629911.409257.149780@l77g2000hsb.googlegroups.com> <1176669548.436118.176300@e65g2000hsc.googlegroups.com> Message-ID: mensanator at aol.com wrote: >> We're getting closer and closer to something I already posted a few >> times here. This implementation was unfortunate because I consistently >> used an uncommon name for it so people couldn't easily find it > > But then, who's looking for it? The OP was trying to find it in the docs, assuming it was some kind of builtin function. I can see the logic of that and I can also see the logic of including some other smallish functions like for example fac. Failing that, the next recourse would be the Internet, or a Usenet search but that would imply well named Usenet posts and function names. >> (mea culpa), and maybe also because it uses the despised reduce builtin. >> >> def noverk(n,k): >> ? ? ?return reduce(lambda a,b: a*(n-b)/(b+1),xrange(k),1) This is a rather concise function which has the added advantage that it returns 0 when k>n. >> BTW I hereby give up the strange name for this and request a better name >> that everybody will use so there will be no confusion anymore. Maybe >> comb(n,k) ? > > No, that name's already used by gmpy. And a single > function doesn't replace all of gmpy's other > functionality, many of which are needed in the > same applications where comb() is used, so there's > really no need for your function. Actually, by proposing comb I am *honoring* gmpy and I'm also complying with it. In Python we use namespaces to differentiate between such things. You might want to read the documentation about it some time. > Your time is better spent applying the tools provided > by gmpy rather than trying to re-invent the wheel. Please let me be the judge of how to spend my time. In this case it seems rather unjustified to introduce dependencies on external modules when only a few functions are needed. Since I'm also interested in the functions themselves -in this case- I'd rather have a few lines of code in my source than importing an optimized code library. There *are* situations where such things are completely justified, but I don't think this is one of them. You could take it up with the gmpy author and induce him to get gmpy included in the standard distro if you are so inclined. A. From jon_d_r at msn.com Wed Apr 4 13:32:52 2007 From: jon_d_r at msn.com (jon) Date: 4 Apr 2007 10:32:52 -0700 Subject: Requirements For A Visualization Software System For 2010 In-Reply-To: <1175628186.459945.290750@d57g2000hsg.googlegroups.com> References: <1175628186.459945.290750@d57g2000hsg.googlegroups.com> Message-ID: <1175707972.733728.176500@n59g2000hsh.googlegroups.com> Go for it! I can see immediate application in displaying and exploring multivariate projections. e.g., factor analyses and components analysis, multivariate groupings superimposed on projected hyperspaces... This is stuff some of us have been dreaming about for a couple of decades, and getting there from primitives has been (ahem) "fun." To be able to express this and see results using a higher level language would be really important to a lot of research exploration. -- jondr From clarence1126 at gmail.com Wed Apr 11 14:58:49 2007 From: clarence1126 at gmail.com (Clarence) Date: 11 Apr 2007 11:58:49 -0700 Subject: MRO theory Message-ID: <1176317929.068559.263330@o5g2000hsb.googlegroups.com> I'm having problems creating classes because of "can't create a consistent mro" problems. I noticed, in a test program, that if the base class list that I pass to type.__new__ is sorted (using default keys, so presumably sorting by the id's of the class objects), that the problem goes away. Now in this test, the id's (memory addresses) of the class objects are presumably in the same order as the chronological order that the classes were created in (since the program is simple and doesn't delete any objects or make any temporaries). This may sound weird, but I don't actually care what order the base classes appear in as long as they're all there. This makes me wonder, since I can't say I understand the theory (I read the paper referenced in typeobject.c source, my brain didn't _quite_ melt) behind mro creation, if it is the case that there cannot be a consistency problem if each class in the base list was created after all classes that precede it in the base list. Can any genius weigh in on this question? From bbxx789_05ss at yahoo.com Tue Apr 3 01:00:55 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: 2 Apr 2007 22:00:55 -0700 Subject: python on mac os 10.4.x Message-ID: <1175576455.471249.58740@q75g2000hsh.googlegroups.com> Hi, Python 2.3.5 comes pre-installed on mac os 10.4.7, and I've looked around in /System/Library/Frameworks/Python.framework/ and under .../ Versions/2.3/bin/, there is an exec file named 'idle'. I assume that is the Python IDLE I've read about, but I can't figure out what I need to do to use IDLE to edit a file. Any help would be appreciated. I know it's recommended to install the latest version of python, which would then come with the IDLE, but I want to learn wxPython as well, and from what I understand you need a "framework" build of python on a Mac to use wxPython. And I don't have any idea how to install a python framework build Thanks. From john106henry at hotmail.com Fri Apr 6 17:29:42 2007 From: john106henry at hotmail.com (John Henry) Date: 6 Apr 2007 14:29:42 -0700 Subject: Debugging multithreaded program using Eclipse/Pydev In-Reply-To: References: <1175887942.192837.187600@n76g2000hsh.googlegroups.com> Message-ID: <1175894982.467720.309810@w1g2000hsg.googlegroups.com> On Apr 6, 1:33 pm, Michael Bentley wrote: > On Apr 6, 2007, at 2:32 PM, John Henry wrote: > > > I am back against the wall trying to migrate my multithreaded > > application from Python 2.3 to 2.5. The part of the code that's > > failing has to do with queues (2.3 queues and 2.5 queues are not the > > same). Since WingIDE doesn't support multithread debugging (they've > > been saying that one day they might support that - and that was 2003), > > I am starting to look for alternatives. > > The alpha release of Wing IDE (3.0.0-a1) does in fact, support > multithread debugging. It is an alpha release but so far, I'm quite > satisfied with it. > > hth, > Michael That's nice to know. May be I can get on their alpha list. Thanks, From bruno.42.desthuilliers at wtf.websiteburo.oops.com Wed Apr 4 06:55:32 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Wed, 04 Apr 2007 12:55:32 +0200 Subject: how to remove multiple occurrences of a string within a list? In-Reply-To: <1175624433.206953.214290@n59g2000hsh.googlegroups.com> References: <1175624433.206953.214290@n59g2000hsh.googlegroups.com> Message-ID: <46138418$0$3275$426a74cc@news.free.fr> bahoo a ?crit : > Hi, > > I have a list like ['0024', 'haha', '0024'] > and as output I want ['haha'] > > If I > myList.remove('0024') > > then only the first instance of '0024' is removed. > > It seems like regular expressions is the rescue, Nope. re wouldn't help here - it works on strings, not on lists (you need to understand that in Python, strings are *not* 'lists of chars'). Use list comps: mylist = [item for item in mylist if item != '0024'] or filter() : mylist = filter(lambda item: item != '0024', mylist) > but I couldn't find > the right tool. May I second Grant Edward's suggestion in previous thread ? You'd really do yourself a favor by following a couple Python tutorials. I'd say the one in the official doc, and Dive into Python. From wswilson at gmail.com Wed Apr 18 14:39:02 2007 From: wswilson at gmail.com (wswilson) Date: 18 Apr 2007 11:39:02 -0700 Subject: Iterate through a dictionary of lists one "line" at a time Message-ID: <1176921542.567121.248820@b58g2000hsg.googlegroups.com> Here is my code: listing = {'id': ['a', 'b', 'c'], 'name': ['Joe', 'Jane', 'Bob']} I need to output: id name a Joe b Jane c Bob I could do: print 'id', 'name' for id, name in zip(listing['id'], listing['name']): print id, name but that only works if there are two entries in the dictionary, id and name, and I know what they are. My problem is I don't know how many of these entries there will be. Thanks for any help you can give! From http Sat Apr 7 20:42:53 2007 From: http (Paul Rubin) Date: 07 Apr 2007 17:42:53 -0700 Subject: block scope? References: <7xr6qwal50.fsf@ruckus.brouhaha.com> <7xtzvseqzo.fsf@ruckus.brouhaha.com> <1hw72cg.115yokgarr9enN%aleax@mac.com> <1hw7kzo.1hepj3c1who5zhN%aleax@mac.com> <1hw7lxn.18itayl1fua6w0N%aleax@mac.com> Message-ID: <7xodlzofw2.fsf@ruckus.brouhaha.com> aleax at mac.com (Alex Martelli) writes: > > exec? > option 1: that just runs the compiler a bit later ... Besides exec, there's also locals(), i.e. locals['x'] = 5 can shadow a variable. Any bad results are probably deserved ;) From python.leojay at gmail.com Mon Apr 30 05:25:47 2007 From: python.leojay at gmail.com (Leo Jay) Date: Mon, 30 Apr 2007 17:25:47 +0800 Subject: anyone has experience on cross-compile python 2.5.1? Message-ID: <4e307e0f0704300225t691e1ba3g436af126de63cef3@mail.gmail.com> i have a development board based on s3c2410 arm cpu. and i want to port python on it. after googling some threads, i successfully cross compiled python. but i still encountered a weird issue that when i ran /lib/python2.5/test/testall.py, the process stuck at test_asynchat.py, i located the stuck point here: def test_numeric_terminator(self): # Try reading a fixed number of bytes s = echo_server() s.start()?????????# <----- stuck here !!! time.sleep(1) # Give server time to initialize c = echo_client(6L) c.push("hello ") c.push("world\n") asyncore.loop() s.join() but the weirdest thing is, if i run python test_asynchat.py directly, everything is ok. anybody could help me? thanks in advance. ps, my linux box is an ubuntu 6.10. -- Best Regards, Leo Jay From apardon at forel.vub.ac.be Thu Apr 26 06:58:12 2007 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 26 Apr 2007 10:58:12 GMT Subject: Feedback on Until recipe References: <1177430903.027128.86480@o40g2000prh.googlegroups.com> Message-ID: On 2007-04-24, Thomas Nelson wrote: > Occasionally someone posts to this group complaining about the lack of > "repeat ... until" in python. I too have occasionally wished for such > a construct, and after some thinking, I came up with the class below. > I'm hoping to get some feedback here, and if people besides me think > they might use it someday, I can put it on the python cookbook. I'm > pretty happy with it, the only ugly thing is you have to use a > lambda. Ideally i'd like to just see > while Until(i<3) > but that doesn't work. > Please tell me what you think, and thanks for your time. Maybe we should try to get the developers revive PEP 315. This PEP whould introduce a do-while statement that looks like the folowing: do statements while condition statements this would be equivallent to: while 1: statements if not condition: break statements Those wanting something like: repeat statements until condition Could then write something like: do statements while not condition pass Still not the most elegant but a vast improvement IMO. -- Antoon Pardon From paddy3118 at googlemail.com Fri Apr 13 15:03:24 2007 From: paddy3118 at googlemail.com (Paddy) Date: 13 Apr 2007 12:03:24 -0700 Subject: Python editor/IDE on Linux? In-Reply-To: <1176488840.672572.101830@y80g2000hsf.googlegroups.com> References: <1176488840.672572.101830@y80g2000hsf.googlegroups.com> Message-ID: <1176491004.834877.281810@w1g2000hsg.googlegroups.com> On Apr 13, 7:27 pm, "7stud" wrote: > Jack wrote: > > I wonder what everybody uses for Python editor/IDE on Linux? > > I use PyScripter on Windows, which is very good. Not sure if > > there's something handy like that on Linux. I need to do some > > development work on Linux and the distro I am using is Xubuntu. > > Everybody uses vim. Vim! (Oh great its been seconds since the last editor war). - Paddy ;-), From irstas at gmail.com Tue Apr 3 12:20:29 2007 From: irstas at gmail.com (irstas at gmail.com) Date: 3 Apr 2007 09:20:29 -0700 Subject: Stack experiment In-Reply-To: References: <5QuQh.152$9L1.108@read3.inet.fi> <1175616703.386553.147830@w1g2000hsg.googlegroups.com> Message-ID: <1175617229.555905.175790@w1g2000hsg.googlegroups.com> On Apr 3, 7:14 pm, "Richard Brodie" wrote: > wrote in message > >There may be something wrong with the "re" code in your example, > >but I don't know enough about that to help in that area. > > There is a stray leading space in it. Nah, I'd say there's a stray ([^0-9]) after the space. With just space in it (same as basic split) one would get the tokens 56, 47, +, 2 and *. Without the space one would get: ['56', ' ', '47', ' + ', '2', ' *', ''] From joshbloom at gmail.com Tue Apr 10 18:38:36 2007 From: joshbloom at gmail.com (Josh Bloom) Date: Tue, 10 Apr 2007 15:38:36 -0700 Subject: grabbing Pictures from the web In-Reply-To: <5dbef1c10704101018w13a13ca7i53be4564cec4784@mail.gmail.com> References: <5dbef1c10704101018w13a13ca7i53be4564cec4784@mail.gmail.com> Message-ID: I don't have any experience with TK so I can't comment on that but for getting pics from the web, you will need to do the following: 1) Work with the flickr API or flickr feeds to get the url for each picture that you want to work with. 2) Either download the image to disk or read it into memory to work with. Here's some sample code to open a url and save it to disk. (This is expecting that the url points to a .jpg) import urllib picture = urllib.urlopen(pathToTheImageThatYouWant).readlines() newPic = open('YourNewFile.jpg', 'wb') #Use wb as you're writing a binary file. newPic.writelines(picture) newPic.close() -Josh On 4/10/07, Juan Vazquez < juanvazquez at gmail.com> wrote: > > I am new to python (2 weeks old) and I would like to write a script that > grabs pictures from the web (specifically flickr) and put them on a Tk > Canvas for a slide show/editing program. my 2 questions are > 1) How do I grab a picture from the web > 2) is the use of the Tk canvas for working with the picture the best > approach? > > Any help or references to resources that point me in the right direction > would be greatly appreciated. Thanks in Advance. > -Juan > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From len-l at telus.net Wed Apr 4 19:59:49 2007 From: len-l at telus.net (Lenard Lindstrom) Date: Wed, 04 Apr 2007 23:59:49 GMT Subject: operator overloading In-Reply-To: <1175679412.741899.45990@l77g2000hsb.googlegroups.com> References: <1175679412.741899.45990@l77g2000hsb.googlegroups.com> Message-ID: looping wrote: > Hi, > for the fun I try operator overloading experiences and I didn't > exactly understand how it works. > > Here is my try: >>>> class myint(int): > def __pow__(self, value): > return self.__add__(value) > >>>> a = myint(3) >>>> a ** 3 > 6 > > OK, it works. Now I try different way to achieve the same result but > without much luck: > >>>> class myint(int): > pass >>>> myint.__pow__ = myint.__add__ > > or: >>>> class myint(int): > __pow__ = int.__add__ > > or: >>>> class myint(int): > pass >>>> a.__pow__ = a.__add__ > > but for every try the result was the same: >>>> a = myint(3) >>>> a ** 3 > 27 > > Why it doesn't works ? > This may, or may not be a bug, depending on ones interpretation. int.__pow__ is a ternary operation while int.__add__ is binary. For a Python function, like def __pow__(self, ...), the interpreter can't properly check if the method takes the correct number of arguments, so accepts it without question. But since int.__add__ is a slot wrapper the interpreter can tell, and chokes. So it just falls back to using int.__pow__. Now for a more detailed explanation. Each Python type, and class, has a vtable of C function pointers for all the operations the interpreter understands. A type only defines functions for those operations it supports. The remaining pointer are null. These functions are known as slot functions, a slot being a C structure field in a Python object instance (Types are instances too!). The int type has slot functions for binary + and ternary ** for instance, but none for container []. To make the slot mechanism visible to Python, allowing operator overloading, generic wrapper slot functions and slot wrapper methods are used. When a special method, such as __add__ or __pow__, is added to a class, either in the class declaration or later by attribute assignment, the corresponding slot is set to point to a generic wrapper that will actually call the special method. When a builin type, like int, has a type specific slot function for a particular operation, a corresponding slot wrapper is added to the type that can call the slot function. So not only can one define addition for a class by having an __add__ method (via generic wrappers), but one can call the __add__ method on an int (via slot wrappers). Now for the specific case of myint. Not all slot functions are created equal. The binary + slot function takes two arguments, the ternary ** slot function three. So int's corresponding __add__ and __pow__ slot wrapper methods also differ. When subclassing int all goes well: class myint(int): pass The myint class inherits int's slot functions for arithmetic, and those functions can be called by int's slot wrappers, such as __add__ and __pow__. But the following is unexpected: myint.__pow__ = myint.__add__ Here __pow__ calls a slot function taking three arguments, __add__ calls one taking two. What follows is probably unplanned, no exception is raised. myint's ** slot function is not replaced with a generic wrapper that will call the __pow__ method. Instead myint keeps the slot function inherited from int. So myint may have a __pow__ method that adds, but it is never called when doing a **. Curiously C PyPy does what was expected: >pypy-c.exe Python 2.4.1 (pypy 1.0.0 build 41438) on win32 Type "help", "copyright", "credits" or "license" for more information. >>>> class MyInt(int): .... pass .... >>>> MyInt.__pow__ = MyInt.__add__ >>>> mi=MyInt(12) >>>> mi**2 14 >>>> Lenard Lindstrom From kelvin.you at gmail.com Mon Apr 30 05:42:00 2007 From: kelvin.you at gmail.com (=?utf-8?B?5Lq66KiA6JC95pel5piv5aSp5rav77yM5pyb5p6B5aSp5rav5LiN6KeB5a62?=) Date: 30 Apr 2007 02:42:00 -0700 Subject: What's the life time of the variable defined in a class function? In-Reply-To: <59lqmnF2lr5nkU1@mid.uni-berlin.de> References: <1177924115.659293.185880@q75g2000hsh.googlegroups.com> <59lqmnF2lr5nkU1@mid.uni-berlin.de> Message-ID: <1177926120.843837.259170@u30g2000hsc.googlegroups.com> On Apr 30, 5:20?pm, "Diez B. Roggisch" wrote: > ??????????????? wrote: > > Please see the followed example: > > class A: > > ? ? def __init__(self): > > ? ? ? ? pass > > > class X: > > ? ? def __init__(self): > > ? ? ? ? n = 200 > > ? ? ? ? if True: > > ? ? ? ? ? ? j = 200 > > ? ? ? ? m = j > > ? ? ? ? k = A() > > ? ? ? ? print m, j > > > a = X() > > # ?? what about the m, n and j? is it still alive? > > del a > > > -------------------------- > > In C/C++, the life time of m,n and j was the nearest block. ?but > > obviously, python doen't have this syntax, but I would like to know > > that whether the life time of ?m, n, j ?is base on function range or > > the object range. > > > We can not access the m, n, and j from the outside of class X. Now I'm > > writing a program base on the wxpython. In the __init__ function of > > wx.Panel, I use normal varable(just like the m,n and j) created some > > widgets. It could be show in the window. ?Does it indicated the life > > time of varable m,n,j is base on the object range? > > Python has no variables. It has objects, which can be bound to names. Each > binding to a name will increase a reference counter. Each unbinding will > decrease it. so > > a = SomeObject() > b = a > del a > > will result in the SomeObject-instance still be alive. But when you add > > del b > > it will be garbage collected. > > Now in your example A() bound to k will not survive the exit of the method, > as that means that k goes out of scope, and the object is bound to - the > A-instance - gets its reference-counter decreased, resulting in it being > freed. > > The wxwidgets example though is a different thing. If the panel stores a > reference to the object, e.g. via a list (being part of a list or dict also > increases the reference count), it will be kept around. > > Diez- Hide quoted text - > > - Show quoted text - Yes, I see. Many thanks for you ! From kyosohma at gmail.com Thu Apr 19 17:40:20 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: 19 Apr 2007 14:40:20 -0700 Subject: wxPython and how to return text entry to main program? In-Reply-To: <1177011490.435609.155870@o5g2000hsb.googlegroups.com> References: <1177011490.435609.155870@o5g2000hsb.googlegroups.com> Message-ID: <1177018820.445401.131420@n59g2000hsh.googlegroups.com> On Apr 19, 2:38 pm, Tyler wrote: > Hello All: > > I am currently working on a project to create an FEM model for school. > I was thinking about using wxPython to gather the 12 input variables > from the user, then, after pressing the "Run" button, the GUI would > close, and the 12 input variables would then be available for the rest > of the program. > > So far, what I have been able to do is mostly a reverse engineering > job to get the frame to look right and return the text variable to a > dialog box. > > I have read about a "redirect" that could be used to send the values > to a file. But, then I would have to open the file and read in the > data from there. This seems crude and lacking elegance. > > Any help on how to get the program to output the data back to the main > python program and close when I press submit? My apologies if this is > something of a simple question, but I have only started in on wxPython > about a week ago, and Python this term. > > The codes I am using are below. > > Any help (or suggested reading material) is greatly appreciated. > > Cheers, > > t. > > MY MAIN PROGRAM > > #!/usr/bin/env python > import femGUI > app = femGUI.MyApp(False) > dlg = femGUI.FemInput() > dlg.Destroy() > app.MainLoop() > > # Then do something with inputs here.... > > THE FEMINPUT GUI CLASS > > import wx > > class FemInput(wx.Frame): > def __init__(self): > wx.Frame.__init__(self, None, -1, "Options Input Interface") > panel = wx.Panel(self) > > # First create the controls > > # Title > topLbl = wx.StaticText(panel, -1, "FEM 2D Basket Put Option > ",size=(420,-1)) > topLbl.SetFont(wx.Font(18, wx.SWISS, wx.NORMAL, wx.BOLD)) > > # S1 lower and upper bounds for grid > s1label = wx.StaticText(panel, -1, "S1 Low , S2 Low: ", > size=(220,-1)) > self.s1lower = wx.TextCtrl(panel, -1, "", size=(100,-1)); > self.s2lower = wx.TextCtrl(panel, -1, "", size=(100,-1)); > > # S2 lower and upper bounds for grid > s2label = wx.StaticText(panel, -1, "S1 High, S2 High: ", > size=(220,-1)) > self.s1upper = wx.TextCtrl(panel, -1, "", size=(100,-1)); > self.s2upper = wx.TextCtrl(panel, -1, "", size=(100,-1)); > > # S1 and S2 volatility > vlabel = wx.StaticText(panel, -1, "S1 Volatility, S2 > Volatility: ", size=(220,-1)) > self.v1vol = wx.TextCtrl(panel, -1, "", size=(100,-1)); > self.v2vol = wx.TextCtrl(panel, -1, "", size=(100,-1)); > > # Risk free rate and correlation > prlabel = wx.StaticText(panel, -1, "Interest Rate, > Correlation: ", size=(220,-1)) > self.risk = wx.TextCtrl(panel, -1, "", size=(100,-1)); > self.corr = wx.TextCtrl(panel, -1, "", size=(100,-1)); > > # Strike and Exercise Date > kTlabel = wx.StaticText(panel, -1, "Srike Price, Exercise > Date: ", size=(220,-1)) > self.strike = wx.TextCtrl(panel, -1, "", size=(100,-1)); > self.finalT = wx.TextCtrl(panel, -1, "", size=(100,-1)); > > # deltaT and deltaX > dTXlabel = wx.StaticText(panel, -1, "delta T, delta X: ", > size=(220,-1)) > self.deltaT = wx.TextCtrl(panel, -1, "", size=(100,-1)); > self.deltaX = wx.TextCtrl(panel, -1, "", size=(100,-1)); > > # Execute program > runBtn = wx.Button(panel, -1, "Run") > self.Bind(wx.EVT_BUTTON, self.OnSubmit, runBtn) > > # Now do the layout. > > # mainSizer is the top-level one that manages everything > mainSizer = wx.BoxSizer(wx.VERTICAL) > mainSizer.Add(topLbl, 0, wx.ALL, 5) > mainSizer.Add(wx.StaticLine(panel), 0, > wx.EXPAND|wx.TOP|wx.BOTTOM, 5) > > # femSizer is a grid that holds all of the address info > femSizer = wx.FlexGridSizer(cols=2, hgap=5, vgap=5) > femSizer.AddGrowableCol(1) > > # S1 and S2 LOWER label > femSizer.Add(s1label, 0, > wx.ALIGN_RIGHT|wx.ALIGN_CENTER_VERTICAL) > # the lower and upper S1 bounds are in a sub-sizer > s1Sizer = wx.BoxSizer(wx.HORIZONTAL) > s1Sizer.Add(self.s1lower, 1) > s1Sizer.Add((10,10)) # some empty space > s1Sizer.Add(self.s2lower, 1, wx.LEFT|wx.RIGHT, 5) > femSizer.Add(s1Sizer, 1, wx.EXPAND) > > # S1 and S2 HIGH label > femSizer.Add(s2label, 0, > wx.ALIGN_RIGHT|wx.ALIGN_CENTER_VERTICAL) > # the lower and upper S1 bounds are in a sub-sizer > s2Sizer = wx.BoxSizer(wx.HORIZONTAL) > s2Sizer.Add(self.s1upper, 1) > s2Sizer.Add((10,10)) # some empty space > s2Sizer.Add(self.s2upper, 1, wx.LEFT|wx.RIGHT, 5) > femSizer.Add(s2Sizer, 1, wx.EXPAND) > > # Volatility label > femSizer.Add(vlabel, 0, > wx.ALIGN_RIGHT|wx.ALIGN_CENTER_VERTICAL) > # the lower and upper S1 bounds are in a sub-sizer > volSizer = wx.BoxSizer(wx.HORIZONTAL) > volSizer.Add(self.v1vol, 1) > volSizer.Add((10,10)) # some empty space > volSizer.Add(self.v2vol, 1, wx.LEFT|wx.RIGHT, 5) > femSizer.Add(volSizer, 1, wx.EXPAND) > > # Risk free Rate and corelation > femSizer.Add(prlabel, 0, > wx.ALIGN_RIGHT|wx.ALIGN_CENTER_VERTICAL) > # the lower and upper S1 bounds are in a sub-sizer > rcSizer = wx.BoxSizer(wx.HORIZONTAL) > rcSizer.Add(self.risk, 1) > rcSizer.Add((10,10)) # some empty space > rcSizer.Add(self.corr, 1, wx.LEFT|wx.RIGHT, 5) > femSizer.Add(rcSizer, 1, wx.EXPAND) > > # Strike and Exercise Date > femSizer.Add(kTlabel, 0, > wx.ALIGN_RIGHT|wx.ALIGN_CENTER_VERTICAL) > # the lower and upper S1 bounds are in a sub-sizer > ktSizer = wx.BoxSizer(wx.HORIZONTAL) > ktSizer.Add(self.strike, 1) > ktSizer.Add((10,10)) # some empty space > ktSizer.Add(self.finalT, 1, wx.LEFT|wx.RIGHT, 5) > femSizer.Add(ktSizer, 1, wx.EXPAND) > > # deltaT and deltaX > femSizer.Add(dTXlabel, 0, > wx.ALIGN_RIGHT|wx.ALIGN_CENTER_VERTICAL) > # the lower and upper S1 bounds are in a sub-sizer > dtxSizer = wx.BoxSizer(wx.HORIZONTAL) > dtxSizer.Add(self.deltaT, 1) > dtxSizer.Add((10,10)) # some empty space > dtxSizer.Add(self.deltaX, 1, wx.LEFT|wx.RIGHT, 5) > femSizer.Add(dtxSizer, 1, wx.EXPAND) > > # now add the femSizer to the mainSizer > mainSizer.Add(femSizer, 0, wx.EXPAND|wx.ALL, 10) > > # The buttons sizer will put them in a row with resizeable > # gaps between and on either side of the buttons > btnSizer = wx.BoxSizer(wx.HORIZONTAL) > btnSizer.Add((10,10)) # some empty space > btnSizer.Add(runBtn) > btnSizer.Add((10,10)) # some empty space > mainSizer.Add(btnSizer, 0, wx.EXPAND|wx.BOTTOM, 10) > > panel.SetSizer(mainSizer) > > # Fit the frame to the needs of the sizer. The frame will > # automatically resize the panel as needed. Also prevent the > # frame from getting smaller than this size. > mainSizer.Fit(self) > mainSizer.SetSizeHints(self) > > def OnSubmit(self, evt): > s1low = self.s1lower.GetValue() > s2low = self.s2lower.GetValue() > s1high = self.s1upper.GetValue() > s2high = self.s2upper.GetValue() > s1vol = self.v1vol.GetValue() > s2vol = self.v2vol.GetValue() > irate = self.risk.GetValue() > pcorr = self.corr.GetValue() > kprice = self.strike.GetValue() > totalT = self.finalT.GetValue() > delT = self.deltaT.GetValue() > delX = self.deltaX.GetValue() > wx.MessageBox('You chose: \n %s \n %s \n %s \n %s \ > \n %s \n %s \n %s' % > (s1low,s2low,s1high,s2high,s1vol,s2vol,irate)) > # I want to do something like this below.... > # return s1low,s2low,s1high,s2high,s1vol,s2vol,irate > > class MyApp(wx.App): > > def OnInit(self): > frame = FemInput() > self.SetTopWindow(frame) > frame.Show() > return True > > # Needed if called as a module > if __name__ == '__main__': > app = MyApp(False) > app.MainLoop() Right now I can't figure it out...but you can close it by sticking the following code as the last line in the OnSubmit method: self.Close(True) Also, I highly recommend the wxPython in Action book by Robin Dunn. You might also submit wxPython questions to the wxPython mailing group at http://wxpython.org/maillist.php Sorry I wasn't of more help. Mike From kelvin.you at gmail.com Tue Apr 10 23:34:42 2007 From: kelvin.you at gmail.com (=?utf-8?B?5Lq66KiA6JC95pel5piv5aSp5rav77yM5pyb5p6B5aSp5rav5LiN6KeB5a62?=) Date: 10 Apr 2007 20:34:42 -0700 Subject: Does python have the static function member like C++ In-Reply-To: <1176261542.704649.240350@n76g2000hsh.googlegroups.com> References: <1176260903.362329.59370@o5g2000hsb.googlegroups.com> <1176261542.704649.240350@n76g2000hsh.googlegroups.com> Message-ID: <1176262482.839148.276940@d57g2000hsg.googlegroups.com> On Apr 11, 11:19?am, "7stud" wrote: > On Apr 10, 9:08?pm, "???????????????" wrote: > > > I define the class like this: > > class AAA: > > ? ? counter = 0 > > ? ? def __init__(self): > > ? ? ? ? pass > > ? ? def counter_increase(): > > ? ? ? ? AAA.counter += 1 > > ? ? ? ? print "couter now :", AAA.counter > > > But how could I call the function "counter_incrrease" ? > > > Thanks ! > > 1) > class AAA: > ? ? counter = 0 > ? ? def __init__(self): > ? ? ? ? pass > ? ? @staticmethod > ? ? def counter_increase(): > ? ? ? ? AAA.counter += 1 > ? ? ? ? print "couter now :", AAA.counter > > AAA.counter_increase() > > 2) > class AAA: > ? ? counter = 0 > ? ? def __init__(self): > ? ? ? ? pass > ? ? def counter_increase(): > ? ? ? ? AAA.counter += 1 > ? ? ? ? print "couter now :", AAA.counter > ? ? counter_increase = staticmethod(counter_increase) > > AAA.counter_increase() > > 3) > class AAA: > ? ? counter = 0 > ? ? def __init__(self): > ? ? ? ? pass > ? ? def counter_increase(self): > ? ? ? ? AAA.counter += 1 > ? ? ? ? print "couter now :", AAA.counter > aaa = AAA() > AAA.counter_increase(aaa) Many thanks for you! I've never heard of the "staticmethod" , that's great! From steve at holdenweb.com Wed Apr 11 13:12:18 2007 From: steve at holdenweb.com (Steve Holden) Date: Wed, 11 Apr 2007 13:12:18 -0400 Subject: Parsing log in SQL DB to change IPs to hostnames In-Reply-To: <1176310842.511437.241560@l77g2000hsb.googlegroups.com> References: <1176219463.407804.315560@y80g2000hsf.googlegroups.com> <1176221494.813800.78580@y80g2000hsf.googlegroups.com> <1176231258.626137.228220@d57g2000hsg.googlegroups.com> <92%Sh.21541$tD2.14028@newsread1.news.pas.earthlink.net> <1176295161.448113.253650@w1g2000hsg.googlegroups.com> <1176310842.511437.241560@l77g2000hsb.googlegroups.com> Message-ID: KDawg44 wrote: > On Apr 11, 11:58 am, Dennis Lee Bieber wrote: >> On 11 Apr 2007 05:39:21 -0700, "KDawg44" declaimed >> the following in comp.lang.python: >> >>> ohhh okay. thanks so much. I knew that it came out as strings, i >>> guess it makes sense that I would have to send it back IN as a >>> string. Changed that and now it works! THanks so much. >> I'd be interested in the schema definition -- my experience has been >> that numeric fields come out of MySQLdb as numerics... >> >>>>> import MySQLdb >>>>> cn = MySQLdb.connect(host="localhost", user="BestiariaCP", db="bestiaria") >>>>> cr = cn.cursor() >>>>> cr.execute("select * from comics where banner is not Null") >> 35L >>>>> cr.fetchone() >> (2L, 'Anxiety Cafe', 'Anxiety Cafe', >> 'http://rockerbot.artistrealm.org/', 'images/ronandrockerbutton.jpg', >> 234L, 60L, 'Platitudes from a platypus.', 'On hiatus - site rebuild', >> 'N', 'Y') >> >> >> >> Note the first field there -- a Python long integer (the schema >> defines that as an integer auto_increment field). Also the "234L, 60L," >> (image width/height) -- all returned as numeric. >> >> If your data is coming out as a string, I'd suspect the schema >> defined it as a character type. >> >>>>> cr.description >> (('ID', 3, 2, 11, 11, 0, 0), ('name', 253, 33, 100, 100, 0, 0), >> ('sortname', 253, 33, 100, 100, 0, 0), ('URL', 253, 56, 75, 75, 0, 0), >> ('banner', 253, 29, 75, 75, 0, 1), ('width', 3, 3, 11, 11, 0, 1), >> ('height', 3, 3, 11, 11, 0, 1), ('description', 252, 170, 65535, 65535, >> 0, 0), ('occurs', 253, 58, 125, 125, 0, 1), ('isactive', 254, 1, 1, 1, >> 0, 0), ('isonline', 254, 1, 1, 1, 0, 0)) >> >> >> >> CREATE TABLE `comics` ( >> `ID` int(11) NOT NULL auto_increment, >> `name` varchar(100) NOT NULL default '', >> `sortname` varchar(100) NOT NULL default '', >> `URL` varchar(75) NOT NULL default '', >> `banner` varchar(75) default NULL, >> `width` int(11) default NULL, >> `height` int(11) default NULL, >> `description` text NOT NULL, >> `occurs` varchar(125) default NULL, >> `isactive` enum('N','Y') NOT NULL default 'Y', >> `isonline` enum('N','Y') NOT NULL default 'Y', >> PRIMARY KEY (`ID`), >> KEY `namesort` (`sortname`) >> ) ENGINE=MyISAM AUTO_INCREMENT=92 DEFAULT CHARSET=latin1; >> -- >> 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/ > > I see your point. Somewhere in my head I must have mixed them up. It > goes in as a string but comes out as whatever data type. > > Thanks. > No, it doesn't even go *in* as a string (though a lot of database modules will convert data of the wrong type if they reasonably can). "%s" is just what's known as a "parameter marker" - each parameter marker is substituted by suceeding values form the data tuple provided as the second argument to cursor.execute(). Some database modules use "?" as a parameter marker. 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 saif.shakeel at gmail.com Mon Apr 23 08:29:40 2007 From: saif.shakeel at gmail.com (saif.shakeel at gmail.com) Date: 23 Apr 2007 05:29:40 -0700 Subject: redirect ouput Message-ID: <1177331380.838772.240200@b58g2000hsg.googlegroups.com> Hi, I am working on parsing an xml file using python.How can i redirect the output to 2 files,say,for some portion of code the output has to go to one file and for some part the o/p be directed to another file. From steve at holdenweb.com Thu Apr 19 22:04:36 2007 From: steve at holdenweb.com (Steve Holden) Date: Thu, 19 Apr 2007 22:04:36 -0400 Subject: What makes an iterator an iterator? In-Reply-To: <1177017151.900443.71450@o5g2000hsb.googlegroups.com> References: <1hwr9pv.13v4ci6106qn0aN%aleax@mac.com> <1176936067.315082.17970@y80g2000hsf.googlegroups.com> <1hws6rd.u0a6hd78fhhpN%aleax@mac.com> <1176961515.450458.189530@p77g2000hsh.googlegroups.com> <1177017151.900443.71450@o5g2000hsb.googlegroups.com> Message-ID: 7stud wrote: > On Apr 19, 5:37 am, Steve Holden wrote: >> It's nothing to do with the name lookup. Alex mentioned that to remind >> us that the magic "double-under" names are looked up on the type rather >> than the instance... > > P.next() > > vs. > > type(P).next() > > Where is the "double-under" name? > Try and stick with the main party. Here is the exact exchange (between Steven D'Aprano and Alex) to which I referred: > Steven D'Aprano wrote: > >> > I thought that an iterator was any object that follows the iterator >> > protocol, that is, it has a next() method and an __iter__() method. > > The special methods need to be on the type -- having attributes of those > names on the instance doesn't help (applies to all special methods in > the normal, aka newstyle, object model; legacy, aka classic, classes, > work by slightly different and not entirely self-consistent semantics). So if you have a beef, it would appear to be with Alex? 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 robert.kern at gmail.com Wed Apr 4 16:55:21 2007 From: robert.kern at gmail.com (Robert Kern) Date: Wed, 04 Apr 2007 15:55:21 -0500 Subject: BeautifulSoup vs. real-world HTML comments In-Reply-To: <1175717833.872281.6300@l77g2000hsb.googlegroups.com> References: <1175711322.448629.20300@y80g2000hsf.googlegroups.com> <1175717833.872281.6300@l77g2000hsb.googlegroups.com> Message-ID: Carl Banks wrote: > On Apr 4, 2:43 pm, Robert Kern wrote: >> Carl Banks wrote: >>> On Apr 4, 2:08 pm, John Nagle wrote: >>>> BeautifulSoup can't parse this page usefully at all. >>>> It treats the entire page as a text chunk. It's actually >>>> HTMLParser that parses comments, so this is really an HTMLParser >>>> level problem. >>> Google for a program called "tidy". Install it, and run it as a >>> filter on any HTML you download. "tidy" has invested in it quite a >>> bit of work understanding common bad HTML and how browsers deal with >>> it. It would be pointless to duplicate that work in the Python >>> standard library; let HTMLParser be small and tight, and outsource the >>> handling of floozy input to a dedicated program. >> Well, BeautifulSoup is just such a dedicated library. > > No, not really. Yes, it is. Whether it succeeds in all particulars is besides the point. The only mission of BeautifulSoup is to handle bad HTML. That tidy doesn't successfully handle some other subset of bad HTML doesn't mean it's not a dedicated program for handling bad HTML. >> However, it defers its >> handling of comments to HTMLParser. That's the problem. > > Well, it's up to the writers of Beautiful Soup to decide how much bad > HTML they want to accept. ISTM they're happy to live with the > limitations of HTMLParser, meaning that they do not consider Beautiful > Soup to be a library dedicated to reading every piece of bad HTML out > there. Sorry, let me be clearer: The problem is that they haven't overridden the handling of comments of SGMLParser (not HTMLParser, sorry) like it has many other parts of SGMLParser. Yes, any fix should go into BeautifulSoup and not SGMLParser. All it takes is someone to code up their desired behavior for these perverse comments and submit it to Leonard Richardson. -- 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 aisaac at american.edu Sun Apr 29 14:54:32 2007 From: aisaac at american.edu (Alan Isaac) Date: Sun, 29 Apr 2007 18:54:32 GMT Subject: relative import broken? References: <1hxa9x3.c0unyd1jw7vu9N%aleax@mac.com> Message-ID: "Alex Martelli" wrote in message news:1hxa9x3.c0unyd1jw7vu9N%aleax at mac.com... > If you're running test1.py as your main module, then it's not part of a > package, so the relative import should indeed fail as you mention. So if I understand you, in a package, any module that I wish to make available for execution as a script (in the usual way, with a main function) cannot have any relative imports. Is this right? What is the reason for this restriction? (And where is it documented?) Thank you, Alan Isaac From adam at atlas.st Tue Apr 24 07:59:42 2007 From: adam at atlas.st (Adam Atlas) Date: 24 Apr 2007 04:59:42 -0700 Subject: Python for Vcard Parsing in UTF16 In-Reply-To: <132l7inssigkted@corp.supernews.com> References: <132l7inssigkted@corp.supernews.com> Message-ID: <1177415982.837015.121400@n15g2000prd.googlegroups.com> On Apr 21, 7:28 pm, R Wood wrote: > To me this was a natural task for Perl. Turns out however, there's a catch. > Apple exports the file in UTF-16 to ensure anyone with Chinese characters in > their addressbook gets a legitimate Vcard file. Here's a function that, given a `str` containing a vcard in some encoding, guesses the encoding and returns a canonical representation as a `unicode` object. def fix_encoding(s): m = u'BEGIN:VCARD' for c in ('ascii', 'utf_16_be', 'utf_16_le', 'utf_8'): try: u = unicode(s, c) except UnicodeDecodeError: continue if m in u: return u return None From anton.vredegoor at gmail.com Sun Apr 15 04:23:33 2007 From: anton.vredegoor at gmail.com (Anton Vredegoor) Date: Sun, 15 Apr 2007 10:23:33 +0200 Subject: proposed PEP: iterator splicing In-Reply-To: <7xirbyi5d7.fsf_-_@ruckus.brouhaha.com> References: <7xirbyi5d7.fsf_-_@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > def some_gen(): > ... > yield *some_other_gen() > > comes to mind. Less clutter, and avoids yet another temp variable > polluting the namespace. > > Thoughts? Well, not directly related to your question, but maybe these are some ideas that would help determine what we think generators are and what we would like them to become. I'm currently also fascinated by the new generator possibilities, for example sending back a value to the generator by making yield return a value. What I would like to use it for is when I have a very long generator and I need just a slice of the values. That would mean running through a loop, discarding all the values until the generator is in the desired state and only then start doing something with the output. Instead I would like to directly set or 'wind' -like a file- a generator into some specific state. That would mean having some convention for generators signaling their length (like xrange): >>> it = xrange(100) >>> len(it) 100 >>> Note: xrange didn't create a list, but it has a length! Also we would need some convention for a generator to signal that it can jump to a certain state without computing all previous values. That means the computations are independent and could for example be distributed across different processors or threads. >>> it = range(100) >>> it[50:] [50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99] >>> But currently this doesn't work for xrange: >>> it = xrange(100) >>> it[50:] Traceback (most recent call last): File "", line 1, in ? TypeError: sequence index must be integer >>> Even though xrange *could* know somehow what its slice would look like. Another problem I have is with the itertools module: >>> itertools.islice(g(),10000000000000000) Traceback (most recent call last): File "", line 1, in ? ValueError: Stop argument must be a non-negative integer or None. >>> I want islice and related functions to use long integers for indexing. But of course this only makes sense when there already are generator slices possible, else there would be no practical way to reach such big numbers by silently looping through the parts of the sequence until one reaches the point one is interested in. I also have thought about the thing you are proposing, there is itertools.chain of course but that only works when one can call it from 'outside' the generator. Suppose one wants to generate all unique permutations of something. One idea would be to sort the sequence and then start generating successors until one reaches the point the sequence is completely reversed. But what if one wants to start with the actual state the sequence is in? One could generate successors until one reaches the 'end' and then continue by generating successors from the 'beginning' until one reaches the original state. Note that by changing the cmp function this generator could also iterate in reverse from any point. There only would need to be a way to change the cmp function of a running generator instance. from operator import ge,le from itertools import chain def mutate(R,i,j): a,b,c,d,e = R[:i],R[i:i+1],R[i+1:j],R[j:j+1],R[j+1:] return a+d+(c+b+e)[::-1] def _pgen(L, cmpf = ge): R = L[:] yield R n = len(R) if n >= 2: while True: i,j = n-2,n-1 while cmpf(R[i],R[i+1]): i -= 1 if i == -1: return while cmpf(R[i],R[j]): j -= 1 R = mutate(R,i,j) yield R def perm(L): F = _pgen(L) B = _pgen(L,le) B.next() return chain(F,B) def test(): P = '12124' g = perm(P) for i,x in enumerate(g): print '%4i) %s' %(i, x) if __name__ == '__main__': test() A. From jura.grozni at gmail.com Fri Apr 13 09:39:33 2007 From: jura.grozni at gmail.com (azrael) Date: 13 Apr 2007 06:39:33 -0700 Subject: Problem with algorithm In-Reply-To: References: <1176434160.047703.214600@q75g2000hsh.googlegroups.com> <1176434937.258002.162220@p77g2000hsh.googlegroups.com> <1176448576.047996.12930@d57g2000hsg.googlegroups.com> <1176452247.231807.65060@e65g2000hsc.googlegroups.com> Message-ID: <1176471573.759192.95130@e65g2000hsc.googlegroups.com> sorry for the bad grammar. I didn't investigate the StackLess Python, but as I have been reading about it (so if it was correct), the recursionlimit should not be the problem using StackLess Python. >From my expirience with python and recursions, it works well to the depth of about 200 to 500 (depending od algorithm and purpose). I think that in this case it should work well with about 500. If you need a bigger string, then lett it repeat and merge the different strings. You could also generate multidimensional hash. Best Regards On Apr 13, 2:24 pm, Michael Hoffman wrote: > azrael wrote: > > I think that this would be very silly to do. bad kung foo. The > > recoursion technique would be more satisfying. You sholud consider > > that this would take about 4 lines to write. Also be avare of the > > default recoursion depth in python wich is 1000. you can get and set > > the recoursion limit hrough importing the "sys" module and using > > getrecoursionlimit() and setrecoursionlimit(). > > Well, you'd have to spell sys.getrecursionlimit() correctly, but yes ;) > > At least in the past, raising the recursion limit past a certain point > would result in the CPython interpreter crashing, so it's not completely > scalable. > -- > Michael Hoffman From gigs at hi.t-com.hr Sat Apr 28 09:50:57 2007 From: gigs at hi.t-com.hr (Gigs_) Date: Sat, 28 Apr 2007 15:50:57 +0200 Subject: tkinter undo Message-ID: Hi I dont have idea how to write tkinter undo/redo function form my text editor and my paint program. Could someone help? I'm not asking for code, just for some guidelines to get me in the right way. thanks From grante at visi.com Mon Apr 30 19:40:35 2007 From: grante at visi.com (Grant Edwards) Date: Mon, 30 Apr 2007 23:40:35 -0000 Subject: Master's Thesis Help Needed References: <1177898031.790447.253360@n76g2000hsh.googlegroups.com> <1hxcqfn.11m7qp91766nc4N%aleax@mac.com> <1177975197.557114.46700@o5g2000hsb.googlegroups.com> Message-ID: <133cvjjrs13mh6f@corp.supernews.com> On 2007-04-30, RobJ wrote: >> Things start on a pretty bad note when I'm asked to select my >> OS: Ubuntu Linux Windows XP >> >> I'm running MacOSX. What now? Why is there no choice "none >> of the above"...?! > Sorry about that. I'll add on to the front page what 2 OSs are > available.. During my pre-work for my project I did a survey and > WindowsWP and Ubuntu Linux came up as the top two OSs. So if we're not running one of those two, you don't want our input? -- Grant Edwards grante Yow! Jesuit priests are at DATING CAREER DIPLOMATS!! visi.com From attn.steven.kuo at gmail.com Wed Apr 18 14:30:30 2007 From: attn.steven.kuo at gmail.com (attn.steven.kuo at gmail.com) Date: 18 Apr 2007 11:30:30 -0700 Subject: multirember&co In-Reply-To: <1176850352.999231.79260@n59g2000hsh.googlegroups.com> References: <1176768854.720234.23320@w1g2000hsg.googlegroups.com> <1176790588.024371.119360@n76g2000hsh.googlegroups.com> <1176850352.999231.79260@n59g2000hsh.googlegroups.com> Message-ID: <1176921030.330467.76860@o5g2000hsb.googlegroups.com> On Apr 17, 3:52 pm, bearophileH... at lycos.com wrote: (snipped) > > So far I haven't succed using the coroutine Python 2.5 allows using > the generators, and I think still that xsplitter can be done with two > coroutines instead of two It objects. Despite Steven's code I am > unable still to write a working code with coroutines (probably because > I haven't understood how they work yet). This time I take a breath and > I show my wrong code: > > import collections > > def xsplitter(iseq, pred): > def it(parity): > queue = collections.deque() > while True: > received = (yield) > if received is not None: > queue.append(received) > if queue: > yield queue.popleft() > else: > try: > el = iseq.next() > if pred(el) == parity: > yield el > else: > its[not parity].send(el) > except StopIteration: > raise > > its = [it(False), it(True)] > return its[True], its[False] > > idata = iter([1, 'a', 3, 'a', 4, 5, 6, 'a']) > it1, it2 = xsplitter(idata, lambda x: x == 'a') > > from itertools import izip > for el1, el2 in izip(it1, it2): > print el1, el2 > > It prints: > None None > None None > a 3 > None None > a 4 > None None > None None > None None > > Can it be fixed? Are you able to fix it for me? (If you want you can > think of it as an exercise to understand Python coroutines :-) ). I don't think coroutine are what's needed here. In particular, using 'send' will *deplete* the iterator -- the very iterator to which one is trying to add an element. If you don't wish to use objects, you can replace them with a closure: import collections def xsplitter(iseq, pred): queue = [ collections.deque(), collections.deque() ] def it(parity): while True: if queue[parity]: yield queue[parity].popleft() else: try: el = iseq.next() if pred(el) == parity: yield el else: queue[not parity].append(el) except StopIteration: raise its = [ it(False), it(True) ] return its[True], its[False] idata = iter([1, 'a', 3, 'a', 4, 5, 6, 'a']) it1, it2 = xsplitter(idata, lambda x: x == 'a') from itertools import izip for el1, el2 in izip(it1, it2): print el1, el2 Oh, I and do like your rewrite; it's much less repetitive and cleaner than my original version. -- Regards, Steven From andrew.jefferies at gmail.com Thu Apr 26 15:23:12 2007 From: andrew.jefferies at gmail.com (andrew.jefferies at gmail.com) Date: 26 Apr 2007 12:23:12 -0700 Subject: File not read to end In-Reply-To: References: <1177522730.327454.121120@s33g2000prh.googlegroups.com> <-LWdnRS04OCCCLLbnZ2dnUVZ_uSgnZ2d@comcast.com> <1177589949.885985.164380@c18g2000prb.googlegroups.com> Message-ID: <1177615392.285747.212600@r35g2000prh.googlegroups.com> On Apr 26, 9:48 am, Facundo Batista wrote: > andrew.jeffer... at gmail.com wrote: > > I've attached the whole script. Thanks again for your help. > > > --Andrew > > Andrew, tip: > > If you attach the whole script, what you get is that a lot of people > goes away from the thread. Me for example. I won't read 100 lines of > code to see where is the problem, and then try to solve. > > The best way to handle this, and effectively getting more help from the > community, is start to trim your code. So, you take those 20 lines away, > and the problem persist. You cut off another 15, and the problem > persist. > > After ten minutes of work, you get a 15 lines code, which still shows > your problem. You send that to the community, and surely you'll get more > help. > > As a fantastic side effect of that process, normally you actually *find* > the problem by yourself, which is always better, :) > > Regards, > > -- > . Facundo > . > Blog:http://www.taniquetil.com.ar/plog/ > PyAr:http://www.python.org/ar/ Thanks for the input Facundo. I'm not a frequent poster so I'm not up on the etiquette and do appreciate the feedback. I'll better control code spews in future posts! From tenax.raccoon at gmail.com Mon Apr 16 11:36:02 2007 From: tenax.raccoon at gmail.com (Jason) Date: 16 Apr 2007 08:36:02 -0700 Subject: yield, curry, mix-in, new.function, global, closure, .... what will work? In-Reply-To: <1176730099.467774.212440@q75g2000hsh.googlegroups.com> References: <1176657848.944538.169780@p77g2000hsh.googlegroups.com> <7xy7ktmrzn.fsf@ruckus.brouhaha.com> <1176684145.537202.68090@p77g2000hsh.googlegroups.com> <7xbqhp6sdu.fsf@ruckus.brouhaha.com> <1176730099.467774.212440@q75g2000hsh.googlegroups.com> Message-ID: <1176737762.629412.189270@y80g2000hsf.googlegroups.com> On Apr 16, 7:28 am, ecir.h... at gmail.com wrote: > On Apr 16, 3:05 am, Paul Rubin wrote: > > > ecir.h... at gmail.com writes: > > > > Please, can you elaborate further, I'm not sure if I understood. > > > Should I lock global variables i, j during the execution of run()? In > > > that case I have to apologize, I showed rather simplified version of > > > the actual problem I have - in fact changer() and run() will be a bit > > > more complex thus executing a bit longer and perhaps causing a dead-lock. > > > Put both variables into one shared object with a lock (see the docs for > > threading.RLock()). Acquire the lock before modifying or reading the > > variables, and release it afterwards. That is the traditional way. > > Thanks for the reply! And at the same time, please bear with me. > > If I understand correctly: when one thread acquires the lock, every > other thread has to wait. If so, this is not exacly what I would like > to have since the thread might take a bit longer to finish. > > The reason why I try so hard to use local variables is that they are > inherently thread-safe. So I don't even mind to copy changer() every > time run() is called - run() has it's own local variables i, j, no one > has to touch them except it's ("local") function changer(). But the > problem is, I don't know how to propagate run()'s variables into > changer() without declarating them as changer()'s arguments (it would > be ok to append the declaration during run-time, though, if I only > knew how). In Python, names are bound to objects. The parameter names passed to a function *are not inherently thread safe*! Python parameters are not passed-by-value. To show you what I mean: >>> spam = ["delicious"] >>> def test(meal): ... global spam ... if spam is meal: ... print "Spam is the same object as meal" ... >>> test(spam) Spam is the same object as meal (While the "global spam" statement is optional in this case, I wanted to make it painfully obvious where the "spam" name in function test is coming from.) It is thread-safe to rebind the name "meal" in the function test (ie, meal = "Green eggs"). It is not thread-safe to mutate or modify the object that meal is bound to. In the example given above, appending data to the list, removing data, changing elements, and other operations will cause potential race conditions across multiple threads. Follow Paul's advice and get acquainted with the issues of concurrent and threaded programming. Judicious locking will help avoid most race conditions. If you don't want to keep other threads waiting, make a copy of your data then release the data lock. Depending on the data, you can usually have multiple threads "reading" the data, as long as no other threads write to the data while there are any readers. A writer can be allowed to change the data, but only if there are no readers and no other writers. (This is commonly known as a read/write lock.) I didn't see a read/write lock in the Python documentation with some casual browsing, but one can be implemented from the existing thread locking mechanisms. Your description of what you want to do is rather vague, so I can't get too specific. You've described how you want to do things, but I don't know what you're trying to accomplish. Where possible, simplify your design. --Jason From 12cc104 at gmail.com Fri Apr 27 11:49:16 2007 From: 12cc104 at gmail.com (proctor) Date: 27 Apr 2007 08:49:16 -0700 Subject: regex question In-Reply-To: <1177685415.648222.281100@o40g2000prh.googlegroups.com> References: <1177655637.717863.93920@o40g2000prh.googlegroups.com> <1177659238.159411.40640@c18g2000prb.googlegroups.com> <1177683018.566343.105620@c18g2000prb.googlegroups.com> <1177685415.648222.281100@o40g2000prh.googlegroups.com> Message-ID: <1177688956.768796.89550@c18g2000prb.googlegroups.com> On Apr 27, 8:50 am, Paul McGuire wrote: > On Apr 27, 9:10 am, proctor <12cc... at gmail.com> wrote: > > > > > On Apr 27, 1:33 am, Paul McGuire wrote: > > > > On Apr 27, 1:33 am, proctor <12cc... at gmail.com> wrote: > > > > > hello, > > > > > i have a regex: rx_test = re.compile('/x([^x])*x/') > > > > > which is part of this test program: > > > > > ============ > > > > > import re > > > > > rx_test = re.compile('/x([^x])*x/') > > > > > s = '/xabcx/' > > > > > if rx_test.findall(s): > > > > print rx_test.findall(s) > > > > > ============ > > > > > i expect the output to be ['abc'] however it gives me only the last > > > > single character in the group: ['c'] > > > > > C:\test>python retest.py > > > > ['c'] > > > > > can anyone point out why this is occurring? i can capture the entire > > > > group by doing this: > > > > > rx_test = re.compile('/x([^x]+)*x/') > > > > but why isn't the 'star' grabbing the whole group? and why isn't each > > > > letter 'a', 'b', and 'c' present, either individually, or as a group > > > > (group is expected)? > > > > > any clarification is appreciated! > > > > > sincerely, > > > > proctor > > > > As Josiah already pointed out, the * needs to be inside the grouping > > > parens. > > > > Since re's do lookahead/backtracking, you can also write: > > > > rx_test = re.compile('/x(.*?)x/') > > > > The '?' is there to make sure the .* repetition stops at the first > > > occurrence of x/. > > > > -- Paul > > > i am working through an example from the oreilly book mastering > > regular expressions (2nd edition) by jeffrey friedl. my post was a > > snippet from a regex to match C comments. every 'x' in the regex > > represents a 'star' in actual usage, so that backslash escaping is not > > needed in the example (on page 275). it looks like this: > > > =========== > > > /x([^x]|x+[^/x])*x+/ > > > it is supposed to match '/x', the opening delimiter, then > > > ( > > either anything that is 'not x', > > > or, > > > 'x' one or more times, 'not followed by a slash or an x' > > ) any number of times (the 'star') > > > followed finally by the closing delimiter. > > > =========== > > > this does not seem to work in python the way i understand it should > > from the book, and i simplified the example in my first post to > > concentrate on just one part of the alternation that i felt was not > > acting as expected. > > > so my question remains, why doesn't the star quantifier seem to grab > > all the data. isn't findall() intended to return all matches? i > > would expect either 'abc' or 'a', 'b', 'c' or at least just > > 'a' (because that would be the first match). why does it give only > > one letter, and at that, the /last/ letter in the sequence?? > > > thanks again for replying! > > > sincerely, > > proctor- Hide quoted text - > > > - Show quoted text - > > Again, I'll repeat some earlier advice: you need to move the '*' > inside the parens - you are still leaving it outside. Also, get in > the habit of using raw literal notation (that is r"slkjdfljf" instead > of "lsjdlfkjs") when defining re strings - you don't have backslash > issues yet, but you will as soon as you start putting real '*' > characters in your expression. > > However, when I test this, > > restr = r'/x(([^x]|x+[^/])*)x+/' > re_ = re.compile(restr) > print re_.findall("/xabxxcx/ /x123xxx/") > > findall now starts to give a tuple for each "comment", > > [('abxxc', 'xxc'), ('123xx', 'xx')] > > so you have gone beyond my limited re skill, and will need help from > someone else. > > But I suggest you add some tests with multiple consecutive 'x' > characters in the middle of your comment, and multiple consecutive 'x' > characters before the trailing comment. In fact, from my > recollections of trying to implement this type of comment recognizer > by hand a long time ago in a job far, far away, test with both even > and odd numbers of 'x' characters. > > -- Paul thanks paul, the reason the regex now give tuples is that there are now 2 groups, the inner and outer parens. so group 1 matches with the star, and group 2 matches without the star. sincerely, proctor From deets at nospam.web.de Mon Apr 2 04:25:38 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 02 Apr 2007 10:25:38 +0200 Subject: Clean "Durty" strings References: <1175463083.135907.128480@y80g2000hsf.googlegroups.com> Message-ID: <57bt02F2c9fpuU2@mid.uni-berlin.de> Ulysse wrote: > Hello, > > I need to clean the string like this : > > string = > """ > bonne mentalité mec!:) \n
bon pour > info moi je suis un serial posteur arceleur dictateur ^^* > \n
mais pour avoir des resultats probant il > faut pas faire les mariolles, comme le "fondateur" de bvs > krew \n > mais pour avoir des resultats probant il faut pas faire les mariolles, > comme le "fondateur" de bvs krew \n > """ > > into : > bonne mentalit? mec!:) bon pour info moi je suis un serial posteur > arceleur dictateur ^^* mais pour avoir des resultats probant il faut > pas faire les mariolles, comme le "fondateur" de bvs krew > mais pour avoir des resultats probant il faut pas faire les mariolles, > comme le "fondateur" de bvs krew The obvious way that has been suggested to you at other places is to use BeautifulSoup. > To do this I wold like to use only strandard librairies. Then you need to reprogram what BeautifulSoup does. Happy hacking! Diez From n.pontikos at laconic.com Sat Apr 14 14:20:10 2007 From: n.pontikos at laconic.com (nikolas pontikos) Date: Sat, 14 Apr 2007 19:20:10 +0100 Subject: Python Feature Request: Explicit variable declarations In-Reply-To: References: <1176546078.934340.253810@y5g2000hsa.googlegroups.com> <1176557734.456820.275780@p77g2000hsh.googlegroups.com> Message-ID: Army1987 wrote: > "jamadagni" ha scritto nel messaggio > news:1176557734.456820.275780 at p77g2000hsh.googlegroups.com... >>> Languages like Perl and VB need a strict mode because they will >>> auto-vivify variable for you. I.e. they will bring variables to life >>> with defined or undefined values if you use them in a l-value (left hand >>> side of an assignment) without having declared them prior. If you do >>> that in Python you get an exception. >> I don't comprehend. I can just type a = 5 in a new Python session and >> I get no exception. Python currently does not require variables to be >> declared before they are used on the LHS. > > I think (s)he meant right hand. > > Yes I did sorry about that. If an assignment had hands then I would have been right ;). From bdesth.quelquechose at free.quelquepart.fr Sun Apr 22 12:32:48 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sun, 22 Apr 2007 18:32:48 +0200 Subject: Dictionaries and dot notation In-Reply-To: <462b842e$0$28548$426a74cc@news.free.fr> References: <23087554.X5dcTmlj7P@beaureve.gmx.net> <462b842e$0$28548$426a74cc@news.free.fr> Message-ID: <462b84b6$0$28548$426a74cc@news.free.fr> Bruno Desthuilliers a ?crit : > Martin Drautzburg a ?crit : > >> This may be pretty obvious for most of you: >> >> When I have an object (an instance of a class "Foo") I can access >> attributes via dot notation: >> >> aFoo.bar >> >> however when I have a dictionary >> aDict = {"bar":"something"} >> >> I have to write >> >> aDict["bar"] >> >> What if I want to create a datastructure that can be used in dot >> notation without having to create a class, i.e. because those objects >> have no behavior at all? > > > A class inheriting from dict and implementing __getattr__ and > __setattr__ should do the trick... Oh, yes, if you don't care about dict-like behaviour, you can also just: class Data(object): def __init__(self, **kw): self.__dict__.update(kw) From mark.dufour at gmail.com Sun Apr 1 11:05:41 2007 From: mark.dufour at gmail.com (mark.dufour at gmail.com) Date: 1 Apr 2007 08:05:41 -0700 Subject: Shed Skin Python-to-C++ Compiler 0.0.21, Help needed In-Reply-To: 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> <7x8xdcrc13.fsf@ruckus.brouhaha.com> Message-ID: <1175439941.446661.260670@y80g2000hsf.googlegroups.com> > Anyway, the only real point is that if there is a concern about the > copyright and licensing of the output of ShedSkin, then we merely need > to ask the author of it to clarify matters and move on with life. With > the exception of GNAT, to date no GPL'd compiler has ever placed a GPL > restriction on its output. Whether this is explicit or implicit doesn't > matter, so long as it's there. it's fine if people want to create non-GPL software with Shed Skin. it is at least my intention to only have the compiler proper be GPL (LICENSE states that the run-time libraries are BSD..) mark dufour (Shed Skin author). From larry.bates at websafe.com Thu Apr 26 10:49:42 2007 From: larry.bates at websafe.com (Larry Bates) Date: Thu, 26 Apr 2007 09:49:42 -0500 Subject: Interrupting ftplib.storbinary() In-Reply-To: <1177597797.296812.226620@t39g2000prd.googlegroups.com> References: <1177597797.296812.226620@t39g2000prd.googlegroups.com> Message-ID: Florian Demmer wrote: > Hi! > > I have a number of ftp uploads running in parallel using > ftplib.storbinary and threading and in case one of them fails I need > to interrupt all the others (but not exit the program completely)... > do you guys have an idea how i could implement the interruption as > cleanly as possible? > > thanks! > I suspect that you would make a file-like object that has a read method and pass it to storbinary instead of your normal fp argument. Then you can signal it to stop gracefully. Haven't tested, but it should be easy to test. -Larry From andre.ditador9999 at gmail.com Thu Apr 5 14:38:47 2007 From: andre.ditador9999 at gmail.com (Andre P.S Duarte) Date: 5 Apr 2007 11:38:47 -0700 Subject: defining functions Message-ID: <1175798327.249407.129860@o5g2000hsb.googlegroups.com> How do I define a function, then import it, without having to save it in lib; like "C:\python25\lib". ? From anton.vredegoor at gmail.com Sun Apr 15 12:34:18 2007 From: anton.vredegoor at gmail.com (Anton Vredegoor) Date: Sun, 15 Apr 2007 18:34:18 +0200 Subject: combination function in python In-Reply-To: References: <1176615838.830315.160210@b75g2000hsg.googlegroups.com> <1176629911.409257.149780@l77g2000hsb.googlegroups.com> Message-ID: Jussi Piitulainen wrote: >> There's probably even a really clever way to avoid that final >> division, but I suspect that would cost more in time and memory than >> it would save. We're getting closer and closer to something I already posted a few times here. This implementation was unfortunate because I consistently used an uncommon name for it so people couldn't easily find it (mea culpa), and maybe also because it uses the despised reduce builtin. def noverk(n,k): return reduce(lambda a,b: a*(n-b)/(b+1),xrange(k),1) BTW I hereby give up the strange name for this and request a better name that everybody will use so there will be no confusion anymore. Maybe comb(n,k) ? > Here's one non-clever one for integers n, k that uses n^k / k^k > (falling powers) with the smaller of k and n - k as lower index: > > def choose(n, k): > if 0 <= k <= n: > ntok = 1 > ktok = 1 > for t in xrange(1, min(k, n - k) + 1): > ntok *= n > ktok *= t > n -= 1 > return ntok // ktok > else: > return 0 Ha, my function uses smaller subproducts :-) A. From ptmcg at austin.rr.com Sun Apr 8 20:09:43 2007 From: ptmcg at austin.rr.com (Paul McGuire) Date: 8 Apr 2007 17:09:43 -0700 Subject: how to remove multiple occurrences of a string within a list? In-Reply-To: <1175633278.370582.175940@p77g2000hsh.googlegroups.com> References: <1175624433.206953.214290@n59g2000hsh.googlegroups.com> <1175625098.269660.184790@o5g2000hsb.googlegroups.com> <1175627593.307674.11280@w1g2000hsg.googlegroups.com> <1175633278.370582.175940@p77g2000hsh.googlegroups.com> Message-ID: <1176077383.318641.209340@p77g2000hsh.googlegroups.com> On Apr 3, 3:47 pm, irs... at gmail.com wrote: > Beware that converting a list to set and then back to list won't > preserve the order of the items, because the set-type loses the order. Also beware that this conversion will remove duplicates, so that if 'haha' is in the original list multiple times, there will only be one after converting to a set and then back to a list. Only you can tell us whether this behavior is desirable or not. -- Paul From s_broscious at comcast.net Fri Apr 13 07:09:44 2007 From: s_broscious at comcast.net (Scott) Date: Fri, 13 Apr 2007 07:09:44 -0400 Subject: Lists and Tuples and Much More References: <1176422546.385731.172910@d57g2000hsg.googlegroups.com> Message-ID: "7stud" wrote in message news:1176422546.385731.172910 at d57g2000hsg.googlegroups.com... >> Yes. Tuples are immutable - once created, they can't change. > > Just to explain that statement a little better. If you do this: > > > t = (1, 2, ["red", "white"]) > t[2].append("purple") > print t #(1, 2, ['red', 'white', 'purple']) > > > It sure looks like t changed, and therefore t is NOT immutable--and > the whole "tuples are immutable" mantra is a lie. However, the list > itself isn't actually stored inside t. What's stored inside t is > python's internal id for the list. So suppose python gave the list > the internal id: 10008. The tuple really looks like this: > > t = (1, 2, <10008>) > > And no matter what you do to the list: append() to it, sort() it, > etc., the list's id remains the same. In that sense, the tuple is > immutable because the id stored in the tuple never changes. > > In actuality, the numbers 1 and 2 aren't stored in the list either-- > python has internal id's for them too, so the tuple actually looks > like this: > > t = (<56687>, <93413>, <10008>) > | | | > | | | > | | | > V V V > 1 2 ["red", "white", "purple"] > > > Because of that structure, you can create situations like this: > >>>> lst = ["red", "white"] >>>> t1 = (1, 2, lst) >>>> t2 = (15, 16, lst) >>>> print t1 > (1, 2, ['red', 'white']) >>>> print t2 > (15, 16, ['red', 'white']) >>>> lst.append("purple") >>>> print lst > ['red', 'white', 'purple'] >>>> print t1 > (1, 2, ['red', 'white', 'purple']) >>>> print t2 > (15, 16, ['red', 'white', 'purple']) >>>> > > lst, t1, and t2 all refer to the same list, so when you change the > list, they all "see" that change. In other words, the names lst, > t1[2], and t2[2] all were assigned the same python id for the original > list ["red", "white"]. Since all those names refer to the same list, > any of those names can be used to change the list. ********************************************************************* This is exactly the type of explaination I'm looking for. Thank you much!!! From sjdevnull at yahoo.com Thu Apr 19 16:33:19 2007 From: sjdevnull at yahoo.com (sjdevnull at yahoo.com) Date: 19 Apr 2007 13:33:19 -0700 Subject: Do other Python GUI toolkits require this? In-Reply-To: References: <462697A6.6010007@codebykevin.com> Message-ID: <1177014799.004875.262060@y80g2000hsf.googlegroups.com> On Apr 19, 6:54 am, Antoon Pardon wrote: > I don't know how you come to the conclusion that it is a mathematical > absurdity but consider this: If you find that common usage propagates > something that is incorrect, should we just shrug it off or should we > attemp a correction? a) In English, "learning curve" is not restricted to a mathematical plot--Webster's also defines it as "the course of progress made in learning something". In that context, adding the adjective steep ("extremely or excessively high...STEEP implies such sharpness of pitch that ascent or descent is very difficult") makes sense. Trying to apply a mathematical definition to an English-language phrase is prone to incorrect outcomes. b) The purpose of language is to communicate. In English, if a phrase now means something in common usage, then that is (one of) its current definition(s)--this is possibly different from some other languages where there is an attempt to have an "officially sanctioned" set of definitions and spellings that may differ from common usage. If you find that everyone else means something when they say a phrase, you'd best learn what they mean if you want to be speaking the same language (and hence be able to communicate with them). From brzrkr0 at gmail.com Mon Apr 30 13:01:28 2007 From: brzrkr0 at gmail.com (brzrkr0 at gmail.com) Date: 30 Apr 2007 10:01:28 -0700 Subject: Tracebacks for `exec`ed code? In-Reply-To: <46346816.3040201@v.loewis.de> References: <1177823329.567989.281420@c35g2000hsg.googlegroups.com> <46346816.3040201@v.loewis.de> Message-ID: <1177952488.617288.105430@p77g2000hsh.googlegroups.com> On Apr 29, 2:40 am, "Martin v. L?wis" wrote: > Adam Atlas schrieb: > > > Is it possible to make more traceback information available for > > exceptions code dynamically run via `exec`? Normally it just says > > things like "File '', line 3, in ?", which is not very > > helpful. I'm looking for a way for it to show the line of source code > > below it, like it would for an exception in a physical file. Is this > > possible? > > Yes. You will need to print the traceback yourself; see > traceback.print_tb for an example. > > Regards > Martin You could also write the code you want to execute to a temporary file, then use execfile() on that file. -Casey From krisbee1983 at gmail.com Wed Apr 4 16:07:26 2007 From: krisbee1983 at gmail.com (krisbee1983 at gmail.com) Date: 4 Apr 2007 13:07:26 -0700 Subject: Getting word frequencies from files which are in folder. In-Reply-To: <4613f24f$0$327$e4fe514c@news.xs4all.nl> References: <1175710660.753453.205000@n76g2000hsh.googlegroups.com> <4613f24f$0$327$e4fe514c@news.xs4all.nl> Message-ID: <1175717246.781352.178090@e65g2000hsc.googlegroups.com> > This sounds suspiciously like a homework assignment. > I don't think you'll get much help for this one, unless > you show some code you wrote yourself already with a specific > question about problems you're having.... Well you have some right. I will make it more specific. I have got something like that: import os, os.path def wyswietlanie_drzewa(dir_path): #function is reading folders and sub folders until it gets to a file. for name in os.listdir(dir_path): full_path = os.path.join(dir_path, name) print full_path if os.path.isdir(full_path): wyswietlanie_drzewa(full_path) My question is how to get word frequencies from this files? I will be glad to get any help. Krisbee From bbxx789_05ss at yahoo.com Mon Apr 23 18:25:05 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: 23 Apr 2007 15:25:05 -0700 Subject: Learning Python - First Project In-Reply-To: <1177352775.828143.9910@y5g2000hsa.googlegroups.com> References: <1177339942.371167.93970@b75g2000hsg.googlegroups.com> <1177352775.828143.9910@y5g2000hsa.googlegroups.com> Message-ID: <1177367105.564414.312320@y5g2000hsa.googlegroups.com> On Apr 23, 12:26 pm, kyoso... at gmail.com wrote: > I am assuming you are using Tkinter for your front-end GUI. You might > also take a gander at wxPython. It has an excellent demo you could > download and it might give you some additional ideas for > implementation:www.wxpython.org. > > Mike Hi, I've heard about that excellent demo, but I downloaded wxPython, and I don't even know where to look for it. Any pointers? From jeba.ride at gmail.com Wed Apr 18 09:19:56 2007 From: jeba.ride at gmail.com (Clement) Date: 18 Apr 2007 06:19:56 -0700 Subject: Help on Shelve.... In-Reply-To: References: <1176810739.765433.47470@n59g2000hsh.googlegroups.com> Message-ID: <1176902396.364403.134210@o5g2000hsb.googlegroups.com> On Apr 17, 5:52 pm, Michael Bentley wrote: > On Apr 17, 2007, at 6:52 AM, Clement wrote: > > > Can i useShelvefor storing large amount of data around 6GB.. Is it > > stable...? if any problems come, can i retrive the document.. > > Do you know for sure your filesystem handles files that big? I am using NTFS filesystem that can handle more than 500GB files From nagle at animats.com Thu Apr 5 12:51:10 2007 From: nagle at animats.com (John Nagle) Date: Thu, 05 Apr 2007 16:51:10 GMT Subject: Why NOT only one class per file? In-Reply-To: <1175778276.603838.86500@l77g2000hsb.googlegroups.com> References: <1175721799.714907.52770@o5g2000hsb.googlegroups.com> <46142acc$0$7532$426a34cc@news.free.fr> <4614b40e$0$26843$426a74cc@news.free.fr> <1175778276.603838.86500@l77g2000hsb.googlegroups.com> Message-ID: <2O9Rh.24647$uo3.24013@newssvr14.news.prodigy.net> Nate Finch wrote: > I think you're all going about this the wrong way. There's no reason > to *always* have one class per file. However, there's also no reason > to have 1600 lines of code and 50 classes in one file either. It's really an operating system thing. We think of programs as living in text files, manipulated by programs which are basically text editors. Python has that implicit assumption. There have been systems that didn't work that way, in which the program source was manipulated within the language environment, in a more structured fashion. Smalltalk, LISP, and (wierdly) Forth environments have been built that way. But it never really caught on. The assumption that programs are text files is deeply embedded in programming culture, so deeply that it's seldom questioned. Programs are the last refuge of non-rich media. You can't even embed an image in your program; it has to be in some completely separate file. Interestingly, PHP breaks this model; PHP programs are web pages. They may be on to something. John Nagle From bbxx789_05ss at yahoo.com Tue Apr 3 14:06:47 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: 3 Apr 2007 11:06:47 -0700 Subject: How to have a list of lists (or array of lists) In-Reply-To: <1175616750.744309.156580@n76g2000hsh.googlegroups.com> References: <1175616750.744309.156580@n76g2000hsh.googlegroups.com> Message-ID: <1175623607.559541.178450@n59g2000hsh.googlegroups.com> On Apr 3, 10:12 am, "bahoo" wrote: > Hi, > > I want to have many lists, such as list0, list1, list2, ..., each one > holding different number of items. > Is there something like > list[0] > list[1] > list[2] > > so that I can iterate through this list of lists? > > Thanks! > bahoo list0 = [1] list1 = [2,3,4,5] list2 = [6,7,8] allLists = [list0, list1, list2] print allLists[1][3] print allLists[0][0] From steve at holdenweb.com Fri Apr 13 11:46:10 2007 From: steve at holdenweb.com (Steve Holden) Date: Fri, 13 Apr 2007 11:46:10 -0400 Subject: tuples, index method, Python's design In-Reply-To: <461F974B.6060508@cc.umanitoba.ca> References: <1176210960.3430.20.camel@dot.uniqsys.com> <740c3aec0704100810g5f962e8eu614fbaedecf3608e@mail.gmail.com> <1176219856.3430.76.camel@dot.uniqsys.com> <740c3aec0704101021i1fd79ef2l99eac4ced1e252d9@mail.gmail.com> <1176226682.3430.86.camel@dot.uniqsys.com> <4866bea60704101104r4600d281h135286b66378f4d4@mail.gmail.com> <740c3aec0704101534y3c65f5a7je382f97e1f6301b7@mail.gmail.com> <1176305859.581010.199600@n76g2000hsh.googlegroups.com> <461F974B.6060508@cc.umanitoba.ca> Message-ID: Brian van den Broek wrote: > Antoon Pardon said unto the world upon 04/13/2007 02:46 AM: >> On 2007-04-12, Steven D'Aprano wrote: > > > >>> So much fuss over such a little thing... yes it would be nice if tuples >>> grew an index method, but it isn't hard to work around the lack. >> Yes it is a little thing. But if it is such a little thing why do >> the developers don't simply add it? > > It's wafer thin! > Quite. [The Python language adds an index() method to tuples and promptly EXPLODES]. Thank you, Mr. Creosote. 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 Emile.Boudreau at cognos.com Tue Apr 3 10:52:07 2007 From: Emile.Boudreau at cognos.com (Boudreau, Emile) Date: Tue, 3 Apr 2007 10:52:07 -0400 Subject: Problem with filter() Message-ID: <09042D621CD4AA479C678463F3A646D0F73D1A@sottemail1.ent.ad.cognos.com> Hey all, So I'm trying to filter a list with the built-in function filter(). My list looks something like this: ['logs', 'rqp-8.2.104.0.dep', 'rqp-8.2.93.0.dep', 'rqp-win32-app-8.2.96.0-inst.tar.gz', 'rqp-win32-app-8.2.96.0-inst.tar.gz'] Calling filter like this: compFiles = filter(is_Dev, compFiles) compFiles is my list and is_dev is the following def is_Dev(stringy): print stringy stringx = stringy.split('-') if stringx[1] == r'win32': if stringx[2] == r'app': if stringx[4] == r'dev.tar.gz': return 1 For some reason I only get 'logs' printed when is_Dev is called. (ie. It's only going through is_dev once) Does anyone see something wrong that I'm not seeing?? Thanks, 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 kyosohma at gmail.com Fri Apr 6 15:22:10 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: 6 Apr 2007 12:22:10 -0700 Subject: real time updating of popen, bufsize=0 problems In-Reply-To: <1175885074.694737.261430@e65g2000hsc.googlegroups.com> References: <1175885074.694737.261430@e65g2000hsc.googlegroups.com> Message-ID: <1175887330.532994.30840@d57g2000hsg.googlegroups.com> On Apr 6, 1:44 pm, "ianar?" wrote: > hey all, I'm trying to get real time updates of batch file output. > > Here is my batch file: > @echo off > echo 1 > @ping 127.0.0.1 -n 2 -w 1500 > nul > echo 2 > @ping 127.0.0.1 -n 2 -w 1500 > nul > echo 3 > > If I run it in cmd.exe it will print "1", wait 15sec, print "2", wait > 15sec, print "3". > > I tried doing it like this: > > r, w, e = popen2.popen3('"C:/path/to/test.bat"',bufsize=0) > for line in r: > self.display.WriteText(line) > > ... but get: ValueError: popen3() arg 3 must be -1 > > If I use -1, then it waits for the batch file to complete, and prints > out all 3 lines at once. > > So I tried subprocess: > proc = subprocess.Popen('"C:/path/to/test.bat"', bufsize=0, > stdout=subprocess.PIPE) > for line in proc.stdout: > self.display.WriteText(line) > > No error message, but no real time printing either. > > info: > self.display is a wx.TextCtrl - not that it should matter,as > 'WriteText()' behaves basically like 'print' > winXP pro SP2, python 2.5, wxPython 2.6.3.3 > > You help is appreciated. Hi, I think this script on another post will help: http://groups.google.com/group/comp.lang.python/msg/9fa3a3c287e8e2a3?hl=en& The 4 line code example (from Daniel) in one of the posts at this link worked with your batch file: http://www.velocityreviews.com/forums/t350573-redirect-ossystem-output.html Mike From rridge at caffeine.csclub.uwaterloo.ca Fri Apr 20 19:49:09 2007 From: rridge at caffeine.csclub.uwaterloo.ca (Ross Ridge) Date: Fri, 20 Apr 2007 19:49:09 -0400 Subject: Python's handling of unicode surrogates References: <4628532B.5060104@v.loewis.de> <1177051493.468698.176740@b75g2000hsg.googlegroups.com> Message-ID: Rhamphoryncus wrote: >The only code that will be changed is that which doesn't handle >surrogates properly. Some will start working properly. Some (ie >random.choice(u'\U00100000\uFFFF')) will fail explicitly (rather than >silently). You're falsely assuming that any code that doesn't support surrogates is broken. Supporting surrogates is no more required than supporting combining characters, right-to-left languages or lower case letters. Ross Ridge -- l/ // Ross Ridge -- The Great HTMU [oo][oo] rridge at csclub.uwaterloo.ca -()-/()/ http://www.csclub.uwaterloo.ca/~rridge/ db // From jjcrump at myuw.net Thu Apr 12 12:24:05 2007 From: jjcrump at myuw.net (Jon Crump) Date: Thu, 12 Apr 2007 09:24:05 -0700 Subject: python newbie beautifulSoup question In-Reply-To: <1176346264.708905.245820@e65g2000hsc.googlegroups.com> References: <1176346264.708905.245820@e65g2000hsc.googlegroups.com> Message-ID: Justin, Wow! I thought there might be a 'simple' way! thanks so much, you've given me a lot to chew on. Jon __________ J.J. Crump Dept. of History 353560 University of Washington Seattle, WA. 98195 On Wed, 11 Apr 2007, Justin Ezequiel wrote: > On Apr 12, 4:15 am, Jon Crump wrote: > >> Is it possible to feed findAll() a list of tags WITH attributes? > >>>> BeautifulSoup.__version__ > '3.0.3' >>>> s = '''\nboo\nhello\nboo\nhi\n''' >>>> soup = BeautifulSoup.BeautifulSoup(s) >>>> def func(tag): > ... if tag.name not in ('y', 'z'): return False > ... if tag.name=='y': return tag.get('a')=='foo' > ... return tag.get('a')=='foo' and tag.get('b')=='bar' > ... >>>> soup.findAll(func) > [hello, hi] >>>> def get_func(lst): > ... def func(tag): > ... for name, attrs in lst: > ... if tag.name==name: > ... for k, v in attrs.items(): > ... if tag.get(k, None)==v: continue > ... else: return False > ... else: return True > ... else: return False > ... return func > ... >>>> func2 = get_func([('y', {'a': 'foo'}), ('z', {'b': 'bar', 'a': 'foo'})]) >>>> soup.findAll(func2) > [hello, hi] >>>> > > > -- > http://mail.python.org/mailman/listinfo/python-list > From aleax at mac.com Sun Apr 22 22:33:02 2007 From: aleax at mac.com (Alex Martelli) Date: Sun, 22 Apr 2007 19:33:02 -0700 Subject: Namespaces/introspection: collecting sql strings for validation References: <1921780.hifcbgjtIO@beaureve.gmx.net> Message-ID: <1hwzkoo.118nt2f1htv72tN%aleax@mac.com> Martin Drautzburg wrote: ... > The problem is the first part: how can I lookup the callers module and > the classobjs defined in there? Or finding any constant strings in the > caller's module would also be just fine. Or is there a completely > different way to do such a thing? Don't do black magic in production code. For just hacking around, see sys._getframe -- it can give you a frame object from where you can introspect into your caller's globals -- and the inspect module of the standard Python library. But don't put such black magic in production. The completely different way is: just don't. Alex From soren.skou.nielsen at gmail.com Mon Apr 16 06:35:40 2007 From: soren.skou.nielsen at gmail.com (Soren) Date: 16 Apr 2007 03:35:40 -0700 Subject: Boost Problem! Boost.Build not found Message-ID: <1176719740.525832.132610@e65g2000hsc.googlegroups.com> Hi! I'm trying to extend my python program with some C++ code. Right now I've spent hours just trying to get boost to work! I'm trying to get the example hello.cpp to work. Using Windows XP and Visual Studio 8 (.NET 2005) I've set BOOST_BUILD_PATH = C:\boost\boost_1_33_1 (where i installed boost) I've changed the jamrules in C:\boost\boost_1_33_1\libs\python\example \tutorial to path-global BOOST_ROOT : C:\boost\boost_1_33_1 ; No matter what I do i always get: C:\boost\boost_1_33_1\libs\python\example\tutorial>bjam -sTOOLS=vc-8_0 Unable to load Boost.Build: could not find "boost-build.jam" --------------------------------------------------------------- Attempted search from C:\boost\boost_1_33_1\libs\python\example \tutorial up to t he root and in these directories from BOOST_BUILD_PATH and BOOST_ROOT: C:\boost\boost_1_ 33_1. Please consult the documentation at 'http://www.boost.org'. Can anyone please tell me what I am doing wrong?? Theres no tutorial on how to make a boost-build.jam file.. and as I understand I don't need one as long as I set BOOST_BUILD_PATH .. Any help is apprecieated!! Thanks!, Soren From aboudouvas at panafonet.gr Thu Apr 19 05:56:08 2007 From: aboudouvas at panafonet.gr (king kikapu) Date: 19 Apr 2007 02:56:08 -0700 Subject: About installing new Python version. In-Reply-To: <1176975545.693682.51870@q75g2000hsh.googlegroups.com> References: <1176973387.967130.27370@y80g2000hsf.googlegroups.com> <1176975545.693682.51870@q75g2000hsh.googlegroups.com> Message-ID: <1176976568.438207.253120@d57g2000hsg.googlegroups.com> On Apr 19, 11:39 am, half.ital... at gmail.com wrote: > On Apr 19, 2:03 am, king kikapu wrote: > > > Hi to all, > > > i started with Python at v2.5 and now i see that a new version is > > released. > > As i already have a lot of stuff for Python installed in the site- > > packages directory, which is the correct way to install a new Python > > version without do any damage ? > > > Remove Python and ALL Python related software and install them all > > over again (painful)? > > Remove Python and do not touch anything else and install new version > > on top of them at the same directory ? > > Any other choice available ? > > > Thanks a lot for any help! > > Just install the new version. It should link everything back up so the > new version is active, but the old versions are intact. > > ~Sean I installed 2.5.1 and as the installer said, it have replaced my old installation with the new one, something like i wanted to do! So i checked and everything seems to working fine. But this is an update release to 2.5, i do not know what is happening when, for example, a totally new Python version come out, like 2.6 or 2.7 or... From samjnaa at gmail.com Sat Apr 14 23:19:14 2007 From: samjnaa at gmail.com (jamadagni) Date: 14 Apr 2007 20:19:14 -0700 Subject: Python Feature Request: Add the "using" keyword which works like "with" in Visual Basic In-Reply-To: <58ctpvF2gtuo3U1@mid.individual.net> References: <1176547372.584539.89170@q75g2000hsh.googlegroups.com> <58buojF2e7nifU1@mid.individual.net> <1176557659.625615.138080@d57g2000hsg.googlegroups.com> <58ctpvF2gtuo3U1@mid.individual.net> Message-ID: <1176607154.855811.257880@b75g2000hsg.googlegroups.com> On Apr 15, 2:01 am, Bjoern Schliessmann wrote: > > self.myVar -- something lost, something gained, IMHO. > > So, the gain is the loss of something different? If you say so. My mistake - I should have said "no pain, no gain". > IMHO, the ability to find something quickly weighs much stronger > than needing to write 5 characters more. Five characters more how many times? From cam.ac.uk at mh391.invalid Fri Apr 13 05:13:58 2007 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Fri, 13 Apr 2007 10:13:58 +0100 Subject: reading from sys.stdin In-Reply-To: <1176454871.538968.176620@n76g2000hsh.googlegroups.com> References: <1176366058.261031.111870@p77g2000hsh.googlegroups.com> <1176387908.406115.270630@w1g2000hsg.googlegroups.com> <1176438754.995753.50190@d57g2000hsg.googlegroups.com> <1176454871.538968.176620@n76g2000hsh.googlegroups.com> Message-ID: 7stud wrote: > I assume all input is buffered by default, so I'm not sure how it > explains things to say that input from sys.stdin is buffered. The difference with sys.stdin is that it has indeterminate length until you signal EOF. I believe you'd get the same problem reading from, say, a named pipe. >> I typed many lines, but lst contains only one item, as expected. Same as >> your regular file example: the file contains many lines, but only the >> first goes into the list. > > Interesting example--not as I expected! But there is a difference in > the two examples isn't there? When you iterate over a file, the whole > file isn't put into an internal buffer first, is it? It is if the file is smaller than the buffer size. >> This should be f = iter(raw_input,"") and this will end in a EOFError >> and stop on blank line. So you need a wrapper > > Why a wrapper? Because without a wrapper you'll get EOFError, while the file iterator would ordinarily give you StopIteration. -- Michael Hoffman From kyosohma at gmail.com Mon Apr 16 16:53:07 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: 16 Apr 2007 13:53:07 -0700 Subject: Python + ogr module? In-Reply-To: References: Message-ID: <1176756787.450645.220310@p77g2000hsh.googlegroups.com> On Apr 16, 11:36 am, Szkandera.Karel wrote: > Hi, > I need to do web service, which will be convert vector formats, like shapefile, dgn, mapinfo..(and other formats, which are supported in gdal - ogr2ogr). I want to do it with using ogr2ogr in the ogr python module, but i am newbie in python, so here is my questions. Is here anybody, who wrote any similar scripts and can give it me? If not, can at least anyone point me to few examples of using ogr2ogr in the ogr > python module? > > Thank you for every answer, K.Szkandera Not much info is out there. Sheesh! Here's an example I found: http://postgis.refractions.net/support/wiki/index.php?OGR%20Examples And here's some more: http://zcologia.com/news/16/graticule-hacking-with-ogr/ http://www.perrygeo.net/wordpress/?p=4 Sorry I couldn't find more. I know nothing about this module. Good luck! Mike From gagsl-py2 at yahoo.com.ar Sat Apr 7 01:43:44 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: 6 Apr 2007 22:43:44 -0700 Subject: Extract zip file from email attachment In-Reply-To: <1175922270.358349.64630@b75g2000hsg.googlegroups.com> References: <1175815907.434721.274190@w1g2000hsg.googlegroups.com> <65fge4-j15.ln1@athlon.my> <1175821421.265541.120440@w1g2000hsg.googlegroups.com> <1175835107.288163.139050@b75g2000hsg.googlegroups.com> <1175869873.747758.278050@b75g2000hsg.googlegroups.com> <1175922270.358349.64630@b75g2000hsg.googlegroups.com> Message-ID: <1175924624.054337.31880@q75g2000hsh.googlegroups.com> Basilisk96 wrote: > > > > Could the file like object still be encoded in MIME or something? > > > > Yes it is. You don't need to seek(0). > Try this: > > decoded = email.base64mime.decode(part.get_payload()) > fileObj.write(decoded) > > > -Basilisk96 From hugonz at gmail.com Fri Apr 13 04:04:27 2007 From: hugonz at gmail.com (hugonz at gmail.com) Date: 13 Apr 2007 01:04:27 -0700 Subject: Databases with python In-Reply-To: References: Message-ID: <1176451467.062640.323650@p77g2000hsh.googlegroups.com> On Apr 13, 1:02 am, Anthony Irwin wrote: > Hi All, > > I am interested in playing with python some more and am looking at > writing an app with data stored in a database. I have experience with > mysql but thought that their may be other better databases that can be > more easily distributed with the program does anyone have any > suggestions here? Specially if your program is going to be multi plattform, check out BuzHug http://buzhug.sourceforge.net/ It is a pure python database. Its performance may not be that high, but it will be very easily distributed with your program. The interface is pythonic, with no SQL to write. From malkarouri at gmail.com Wed Apr 11 15:30:31 2007 From: malkarouri at gmail.com (malkarouri at gmail.com) Date: 11 Apr 2007 12:30:31 -0700 Subject: run function in separate process In-Reply-To: <1176305800.824643.28810@e65g2000hsc.googlegroups.com> References: <1176301427.183706.321920@n76g2000hsh.googlegroups.com> <1hweao8.1t99a5vdqygvbN%aleax@mac.com> <1176305800.824643.28810@e65g2000hsc.googlegroups.com> Message-ID: <1176319831.333206.109710@q75g2000hsh.googlegroups.com> On Apr 11, 4:36 pm, malkaro... at gmail.com wrote: [...] > .. And I avoided pickle at the time > because I had a structure that was unpicklable (grown by me using a > mixture of python, C, ctypes and pyrex at the time). The structure is > improved now, and I will go for the more standard approach.. Sorry, I was speaking about an older version of my code. The code is already using pickle, and yes, cPickle is better. Still trying the code. So far, after modifying the line: cPickle.dump(f, -1) to: cPickle.dump(result, f, -1) it is working. Regards, Muhammad From Bulkan at gmail.com Mon Apr 23 04:00:59 2007 From: Bulkan at gmail.com (placid) Date: 23 Apr 2007 01:00:59 -0700 Subject: python cgi problem with textarea In-Reply-To: <1177254110.057238.315240@o5g2000hsb.googlegroups.com> References: <1177222084.696307.128620@n59g2000hsh.googlegroups.com> <1177247362.014926.12500@n76g2000hsh.googlegroups.com> <1177254110.057238.315240@o5g2000hsb.googlegroups.com> Message-ID: <1177315259.401721.62040@l77g2000hsb.googlegroups.com> On Apr 23, 1:01 am, Adrian Smith wrote: > On Apr 22, 10:09 pm, placid wrote: > > > i just tried it and its working. here it is > > >http://yallara.cs.rmit.edu.au/~bevcimen/form.html > > > maybe the internal server error is because mod_python isn't installed > > assuming your using Apache as your web server > > Yeah, but it wouldn't work *at all* in that case, would it? ATM it > seems to work as long as the textarea input has no spaces. it doest work because the "space" character isnt interpreted correctly, you need to change the space characters too   Cheers From bignose+hates-spam at benfinney.id.au Tue Apr 24 22:31:13 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Wed, 25 Apr 2007 12:31:13 +1000 Subject: Where's the source code for __builtin__? References: <1177457545.075398.204990@r3g2000prh.googlegroups.com> <462EA63C.6080805@lexicon.net> Message-ID: <87lkghgp72.fsf@benfinney.id.au> John Machin writes: > On 25/04/2007 9:32 AM, Dustan wrote: > > I've been paging through the source code for various C modules in > > python, and wanted to find the source of some of the builtin > > functions. > > What's the 2nd file (in alphabetical order) in the Python folder? What is "the Python folder"? Assuming you mean "the folder for the Python standard library modules": $ ls -1 /usr/lib/python2.4/ | head -n 10 aifc.py aifc.pyc anydbm.py anydbm.pyc asynchat.py asynchat.pyc asyncore.py asyncore.pyc atexit.py atexit.pyc There are no files in that folder with 'builtin' in their name. I'm don't know what point you're driving at. -- \ "Oh, I love your magazine. My favorite section is 'How To | `\ Increase Your Word Power'. That thing is really, really, | _o__) really... good." -- Homer, _The Simpsons_ | Ben Finney From bcwhite at pobox.com Wed Apr 18 20:09:10 2007 From: bcwhite at pobox.com (bcwhite at pobox.com) Date: 18 Apr 2007 17:09:10 -0700 Subject: Future Python Gui? In-Reply-To: References: <1176859699.906386.326720@b75g2000hsg.googlegroups.com> <1176863948.526051.186210@n76g2000hsh.googlegroups.com> <1176909848.455264.174730@e65g2000hsc.googlegroups.com> Message-ID: <1176941350.215908.310760@n59g2000hsh.googlegroups.com> > "Tile" has already been mentioned in this thread, and I know > there'll be at least one more follow-up on the subject. Tile > includes a ("native"!) notebook, as well as a combobox, tree- > view, ... . It seems that Tile does include a "notebook" widget but it's pure Tcl code and so isn't available via the Python wrapper. -- Brian From usenet.jan at jboecker.de Sat Apr 21 13:06:05 2007 From: usenet.jan at jboecker.de (=?ISO-8859-15?Q?Jan_B=F6cker?=) Date: Sat, 21 Apr 2007 19:06:05 +0200 Subject: pyHook equivalent for WH_SHELL hooks? Message-ID: Hi, i want to write an app which has to log various user activity, such as opening folders and office documents, to help the user keep an overview about what open windows are related to one task he/she is currently doing. I thought of using a windows shell hook, which notifies the program similar to a keyboard hook when a top-level window is created or destroyed. The pyHook extension shows that this is possible, but only supports keyboard and mouse hooks. My own experiments have not succeeded, as I never have programmed in C/C++ before, let alone a python extension, but I am willing to learn. (I managed to do a test extension without any useful functionality). I have difficulties understanding how my hook will cope with multithreading. As far as I understand, a windows hook dll is loaded into the address space of every running program. How does a hook handle concurrency and how exactly does it call the python function? Will the python function run on another thread? How do I call a python function on another thread? pyHook claims to be open source, but I could only find the python part of the source, the C part seems to be missing on sourceforge.net (correct me if I am wrong). Is there already something like pyHook for WH_SHELL hooks? If not, how does pyHook work internally and is its C source available? I would be glad if anybody could help or point me in the right direction. I already tried the de.comp.lang.python and a web forum full of nerds ;) Regards, Jan B?cker From attn.steven.kuo at gmail.com Thu Apr 12 20:19:12 2007 From: attn.steven.kuo at gmail.com (attn.steven.kuo at gmail.com) Date: 12 Apr 2007 17:19:12 -0700 Subject: "Cloning" file attributes and permissions In-Reply-To: <1176419326.395692@jubilee.claranet.pt> References: <1176394818.428367@jubilee.claranet.pt> <1176406707.711609.211110@q75g2000hsh.googlegroups.com> <1176419326.395692@jubilee.claranet.pt> Message-ID: <1176423552.199317.129400@n59g2000hsh.googlegroups.com> On Apr 12, 4:09 pm, Paulo da Silva wrote: > attn.steven.... at gmail.com escreveu: > > > > > On Apr 12, 9:20 am, Paulo da Silva wrote: > >> Hi! > > >> I need to process a file to produce another file that *must* have > >> *exactly* the same attributes and permissions of the former. What is the > >> best way to do this? The file must not exist with contents (it may exist > >> empty) unless it has the same attributes and permissions. > >> I know how to do this using, let me call it, "C type code" (stat, chmod, > >> chown, etc). I would like to hear some opinions on if and how it would > >> be possible in a more elegant/python way. > > > Are you using a system that supports the creation > > of a hard link? > > > If so, try os.link. > > May be I missed something exposing my q. > I need to process an input file "foo" to produce a different contents > file "bar". "bar" must have the same attributes/permissions of "foo". > I forgot to say that the OS is Linux. Sorry, I did misunderstand your question at first. Well, you do have stat, chown, chmod in Python; but if you're on Linux, you might just want to use the "cp" command with the "-p" switch: import subprocess retcode = subprocess.call([ "/bin/cp", "-p", oldfile, newfile ]) On my system, this preserves the access permissions and ownership. And if you modify the file after copying, you can alter the access and modification times with posix.utime to match that of the original. -- Hope this helps, Steven From paddy3118 at googlemail.com Sat Apr 14 17:00:44 2007 From: paddy3118 at googlemail.com (Paddy) Date: 14 Apr 2007 14:00:44 -0700 Subject: Python Feature Request: Allow changing base of member indices to 1 In-Reply-To: References: <1176546465.632410.52630@w1g2000hsg.googlegroups.com> <1176579205.948684.171640@q75g2000hsh.googlegroups.com> Message-ID: <1176584444.335732.111740@n76g2000hsh.googlegroups.com> On Apr 14, 8:55 pm, Sherm Pendley wrote: > "Paddy" writes: > > Having more than one index start point would be a maintenance > > nightmare best avoided. > > Quite right. > > > (It can be done in Perl). > > When was the last time you used Perl? It was allowed in Perl 4 and earlier, > because many Perl users were moving from Awk, which uses an array base of 1. > Even then, having multiple index start points within a single program wasn't > the idea; the idea was to allow programs originally written in Awk to be > ported to Perl with minimal updating. > > It was deprecated as of 5.0 though - which was released in '94. It still > works, for the sake of backwards compatibility, but its use in new code is > highly discouraged. > > sherm-- > > -- > Web Hosting by West Virginians, for West Virginians:http://wv-www.net > Cocoa programming in Perl:http://camelbones.sourceforge.net I use both Perl and Awk regularly. I did at one stage use the Awk-to- Perl translator as I learned Awk before Perl, but gave it up as the generated Perl was hard to extend, and I learned more Perl. So Perl had it, and now has it deprecated. Python does not have it, but the original poster wants it. I don't think we should add it to Python because it would make porting VB code easier. - Paddy. From psdasilvaX at esotericaX.ptX Tue Apr 3 15:32:41 2007 From: psdasilvaX at esotericaX.ptX (Paulo da Silva) Date: Tue, 03 Apr 2007 20:32:41 +0100 Subject: getattr/setattr q. In-Reply-To: References: <1175573213.682671@jubilee.claranet.pt> Message-ID: <1175628773.321049@iceman.esoterica.pt> > Yes, but you shouldn't unless you really need to. You're better off > rethinking your algorithm. I need it but inside a class. The idea is to pass an instance of a class (think of something like a record but with some methods inside) with "fields", whose names are not known in advance, to another class that must handle those "fields" at the caller request given their names as parameter strings. Another use I am thinking of is in a xml driven program where some parameters "foo=bar", read as strings, must be converted into internal variables xxx_foo=bar. I have written a 1st draft using dicts but this way it is much easier and readable. Regards Paulo From jstroud at mbi.ucla.edu Mon Apr 30 06:06:32 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Mon, 30 Apr 2007 03:06:32 -0700 Subject: How do I parse a string to a tuple?? In-Reply-To: <1177926452.830059.269230@n59g2000hsh.googlegroups.com> References: <1177926452.830059.269230@n59g2000hsh.googlegroups.com> Message-ID: Soren wrote: > Hi! > > I have a string that contains some text and newline characters. I want > to parse the string so that the string just before a newline character > goes in as an element in the tuple. > > ex: > > --> (text1, text2, text3, text4) > > Is there an easy way to do this? > > Thanks!, > Soren > For this particular, very narrow, example, following the example as closely as I possibly can: import re atext = "text1 \n text2 \n text3 \n text4" atup = tuple(re.split(r'\s*\n', atext)) James From jzgoda at o2.usun.pl Sun Apr 29 08:35:46 2007 From: jzgoda at o2.usun.pl (Jarek Zgoda) Date: Sun, 29 Apr 2007 14:35:46 +0200 Subject: While we're talking about annoyances In-Reply-To: <878xcbflcv.fsf@benfinney.id.au> References: <878xcbflcv.fsf@benfinney.id.au> Message-ID: Ben Finney napisa?(a): >> On the other hand, there seem to be some progress that could be made >> to reduce the amount of work in writing documentation. >> Documentation in Esperanto instead of English maybe? > > Lojban is both easier to learn world-wide > than Euro-biased Esperanto, and computer-parseable. Seems a better[0]_ > choice for computer documentation to me. German seems to be less "wordy" than English, despite the fact that most of nouns is much longer. ;) -- Jarek Zgoda http://jpa.berlios.de/ From fuzzyman at gmail.com Thu Apr 26 15:57:29 2007 From: fuzzyman at gmail.com (Fuzzyman) Date: 26 Apr 2007 12:57:29 -0700 Subject: EuroPython vs PyconUK In-Reply-To: <4630D480.7050308@gmail.com> References: <4630D480.7050308@gmail.com> Message-ID: <1177617449.064076.250150@t38g2000prd.googlegroups.com> On Apr 26, 5:34 pm, EuGeNe Van den Bulke wrote: > I do realize that the UK is not really part of Europe (no polemic :P) > but I am nevertheless curious about the logic behind creating another > major Python event in Europe. Wasn't EuroPython enough? > > Like many I am sure, I probably won't be able to attend both (and I > really enjoyed the Geneva experience so definitely want to renew "it"). > How would you go about selecting which conference to attend? > I assume you have the same problem with the Italian one? Seriously though, it is *great* to see the UK Python scene flourishing (and the Italian one). The more events that happen the better, and I don't think they need be in competition with each other... I *hope* the Europython guys don't see it like that. Fuzzyman http://www.voidspace.org.uk/ironpython/index.shtml > They are only 2 months apart, 6 would have been easier for the > attendees! Could the organizers liaise one way or another to make > Pythoneers life as easy and fun as the language and give as much > information out as possible as early as possible (early bird early) for > people to make the best decision? > > I know marketing matters but ... > > EuGeNe --http://www.3kwa.com From http Sat Apr 7 00:40:59 2007 From: http (Paul Rubin) Date: 06 Apr 2007 21:40:59 -0700 Subject: block scope? References: <7xr6qwal50.fsf@ruckus.brouhaha.com> Message-ID: <7xtzvseqzo.fsf@ruckus.brouhaha.com> John Nagle writes: > In a language with few declarations, it's probably best not to > have too many different nested scopes. Python has a reasonable > compromise in this area. Functions and classes have a scope, but > "if" and "for" do not. That works adequately. I think Perl did this pretty good. If you say "my $i" that declares $i to have block scope, and it's considered good practice to do this, but it's not required. You can say "for (my $i=0; $i < 5; $i++) { ... }" and that gives $i the same scope as the for loop. Come to think of it you can do something similar in C++. From hlubenow2 at gmx.net Fri Apr 6 18:55:35 2007 From: hlubenow2 at gmx.net (hlubenow) Date: Sat, 07 Apr 2007 00:55:35 +0200 Subject: Hide the python-script from user References: <8ktie4-0i9.ln1@athlon.my> <1175898877.869321.112310@w1g2000hsg.googlegroups.com> Message-ID: <7ovie4-nfa.ln1@athlon.my> ts-dev wrote: > On Apr 6, 3:19 pm, hlubenow wrote: >> recently there was a thread about hiding the python-script from the user. >> The OP could use > > Interesting - thanks Well, testing it, it doesn't seem to work very well ... It seems, Python-code is rather difficult to obfuscate, probably because of its clear syntax and indentations. Here's yet another approach: http://pythonhacker.is-a-geek.net/my_programs/pyfuscate/pyfuscate-0.1.zip/view H. From S.Mientki-nospam at mailbox.kun.nl Wed Apr 25 16:03:03 2007 From: S.Mientki-nospam at mailbox.kun.nl (Stef Mientki) Date: Wed, 25 Apr 2007 22:03:03 +0200 Subject: conditional print statement ? Message-ID: <2c923$462fb3e0$d443bb3a$18429@news.speedlinq.nl> hello, As part of a procedure I've a number sequences like this: if Print_Info: print Datafile.readline() else: Datafile.readline() Is there a more compressed way to write such a statement, especially I dislike the redundancy "Datafile.readline()". thanks, Stef Mientki From thardy99 at gmail.com Sun Apr 29 21:50:59 2007 From: thardy99 at gmail.com (Teresa Hardy) Date: Sun, 29 Apr 2007 18:50:59 -0700 Subject: Beginner question on threads Message-ID: I have successfully made the threading work on a Window XP machine with quad processors but now I am trying to pass some variables around and am fighting with Lock() I have searched through several different documents and forums, some of which hint at problems with threading on Windows machines so I thought I should ask... Can I get use the .acquire() and .release()? The thread dies unless I comment out these two commands. But I can't thread unless I can control ilock = threading.Lock() ImgGrabber.ilock.aquire() self.i_inthreads = ImgGrabber.i_temp ImgGrabber.i_temp += 1 ImgGrabber.ilock.release() Other details about what I am using Python 2.4 modPython Apache server Hope that's enough info for somebody to give me a recommendation. To the other beginners that are listening, here are the references I am using to get this far... http://heather.cs.ucdavis.edu/~matloff/Python/PyThreads.pdf Python How to Program by Deitel, Deitel, Liperi, and Wiedermann Thanks, Teresa -------------- next part -------------- An HTML attachment was scrubbed... URL: From nomailreplies at nowhere.com Sun Apr 29 20:55:11 2007 From: nomailreplies at nowhere.com (Juan T. Llibre) Date: Sun, 29 Apr 2007 20:55:11 -0400 Subject: SEO - Search Engine Optimization - Seo Consulting References: <1177808356.681710.42980@n76g2000hsh.googlegroups.com> Message-ID: re: !>>>Top posting !>> Did not. I replied to the message at the bottom of the thread. !> Congratulations, you've now made a fool of yourself in public. OK, cut it out. Top or bottom posting is a user choice. No need to flame someone for using either. Juan T. Llibre, asp.net MVP asp.net faq : http://asp.net.do/faq/ foros de asp.net, en espa?ol : http://asp.net.do/foros/ =================================== "Sherm Pendley" wrote in message news:m21wi2lmkg.fsf at local.wv-www.com... > "Alvin Bruney [MVP]" writes: > >>>Top posting >> Did not. I replied to the message at the bottom of the thread. > > Congratulations, you've now made a fool of yourself in public. > > Top posting has nothing to do with where your reply is placed with > respect to other messages. Top posting is when you add your text > above the quoted material in your reply - as you did once again in > what I'm replying to. > > When you open a book, do you start at the bottom of the page and > read up? I didn't think so. > >>>Call yourself an MVP, that's a joke Slick. >> Yup, I do call myself an MVP, it's not a joke either. > > It is when you don't have a clue. > > sherm-- From grante at visi.com Fri Apr 20 15:08:09 2007 From: grante at visi.com (Grant Edwards) Date: Fri, 20 Apr 2007 19:08:09 -0000 Subject: Newbie question regarding string.split() References: <1177095062.826018.63590@n59g2000hsh.googlegroups.com> Message-ID: <132i3spo637vuf4@corp.supernews.com> On 2007-04-20, kevinliu23 wrote: > Hey guys, > > So I have a question regarding the split() function in the string > module. Let's say I have an string... > > input = "2b 3 4bx 5b 2c 4a 5a 6" > projectOptions = (input.replace(" ", "")).split('2') > print projectOptions > > ['', 'b34bx5b', 'c4a5a6'] > > My question is, why is the first element of projectOptions an > empty string? The presense of a delimiter indicates that there is a field both before and after the delimiter. If it didn't work that way, then you'd get the same results for input = "2b 3 4bx 5b 2c 4a 5a 6" as you would for input = "b 3 4bx 5b 2c 4a 5a 6" you would get the same results for input = "2222b22222" as you would for intput = "b" > What can I do so that the first element is not an empty > string? but the 'b34bx5b' string as I expected? projectOptions = (input.replace(" ", "")).split('2') if projectOptions[0] == '': del projectOptions[0] print projectOptions -- Grant Edwards grante Yow! I feel like a wet at parking meter on Darvon! visi.com From gagsl-py2 at yahoo.com.ar Tue Apr 10 07:35:30 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 10 Apr 2007 08:35:30 -0300 Subject: Custom Python Runtime References: <2NudnVn5jsm2QIvbnZ2dnUVZ_vqpnZ2d@comcast.com> Message-ID: En Tue, 10 Apr 2007 00:17:33 -0300, Jack escribi?: > 1. One Windows, it's possible to zip all files in a Python24.zip. I'm not > very clear if it's used in the stardard distribution. What can, > and what can not be put into this file? I suppose zip file will help > reduce the distribution size. (Not just on Windows) pythonXX.zip is always on sys.path, and is searched like any other path (using zipimport). You might in principle put all the standard library there, if you wish. py2exe, by example, searches for all dependent modules and puts then all in a .zip file. But zips can only contain .py/.pyc files, not dynamic libraries like .dll/.so. > 3. Some files go to the Windows\system32 directory, including some > win32all > files. Can they be in the current directory as python.exe? .dll files? Sure. > 4. Are the registry entries necessary? No, but if you have added entries into the PythonPath key, you may need to configure your Python search path (using a PYTHONPATH environment variable or .pth files). -- Gabriel Genellina From franz.steinhaeusler at gmx.at Wed Apr 18 10:25:32 2007 From: franz.steinhaeusler at gmx.at (Franz Steinhaeusler) Date: Wed, 18 Apr 2007 16:25:32 +0200 Subject: Wanted: Email Client with GUI References: <1176905369.228287.224870@l77g2000hsb.googlegroups.com> Message-ID: On 18 Apr 2007 07:09:29 -0700, kyosohma at gmail.com wrote: >On Apr 18, 8:07 am, Franz Steinhaeusler >wrote: >> Hi, although I have googled, I didn't find a Python >> email client program fitting to my needs. >> >> What I want is a program (it doesn't have to be so sophisticated >> as thunderbird) written totally in python and using a gui >> toolkit like pyqt, pygtk, wxpyhton or tkinter. >> >> Who knows such a program? ;) >> >> best regards, > >I'm not finding much either. There is this: http://sourceforge.net/projects/usablemail/ > >This also looked promising: http://wiki.laptop.org/go/Email > >It looks like their might be some kind of tkinter email client in the >Programming Python book by Lutz. ( See >http://proquest.safaribooksonline.com/0596000855/python2-CHP-11-SECT-4 >) > >Hope that helps. > >Mike Thanks, that I also found already. I know XPN, which has also some email functionality. I only wonder, why there doesn't exist a nice one. Oh, I here, why do you not write such a thing yourself? It fails on lack of time. ;) From email at christoph-haas.de Mon Apr 16 10:07:06 2007 From: email at christoph-haas.de (Christoph Haas) Date: Mon, 16 Apr 2007 16:07:06 +0200 Subject: More newbie help required with dictionaries In-Reply-To: <1176731017.008097.21590@o5g2000hsb.googlegroups.com> References: <1176731017.008097.21590@o5g2000hsb.googlegroups.com> Message-ID: <20070416140706.GA19212@torf.workaround.org> On Mon, Apr 16, 2007 at 06:43:37AM -0700, loial wrote: > The following code only returns the last row(222222) added to the > machines dictionary. > presumably I need some additional syntax to add rows to the dictionary > rather than overwrite. > > What do I need to add? > > machinekey = "111111" > > machines = { machinekey:[1,0,0,0,0,0,0,0,0,0,0,0,0] } > > machinekey = "222222" > > machines = { machinekey:[0,1,0,0,0,0,0,0,0,0,0,0,0] } You redefine the "machines" dictionary here. So it just contains one entry. What you mean: machines.update({ machinekey:[0,1,0,0,0,0,0,0,0,0,0,0,0] }) Or: machines[machinekey] = [0,1,0,0,0,0,0,0,0,0,0,0,0] Christoph From lorenzo at diespammerhethurmans.com Sun Apr 8 12:34:22 2007 From: lorenzo at diespammerhethurmans.com (Lorenzo Thurman) Date: Sun, 08 Apr 2007 11:34:22 -0500 Subject: How do I get a slice of a string held in a tuple? Message-ID: <25ine4-rvt.ln1@Hedley.internal.thethurmans.com> I have tuple which hold a string in tup[0]. I want to get a slice of that string. I thought I would do something like: tup[0][start:end] But this fails. How do I go about it? I googled this and found a couple of references, but no solution. TIA From bdeck at user.sourceforge.com Thu Apr 19 12:35:16 2007 From: bdeck at user.sourceforge.com (caddit) Date: Fri, 20 Apr 2007 02:35:16 +1000 Subject: PythonD 2.4.2 for older Windows / DOS / DJGPP Message-ID: <46279af8$0$4610$61c65585@un-2park-reader-01.sydney.pipenetworks.com.au> Hello. There has been some confusion as to the current version of the python programming language available for DOS. This is partially due to incorrect information kept on python.org, that says "python2.2.1 available for DOS". The actual version is currently 2.4.2. I am also happy to announce that a second release of PythonD. Additionally, there are many fine module libraries hat have been made available including Python-opengl and curses. The URL for PythonD has moved. It is now http://www.caddit.net/pythond not that this is NOT the same as http://www.caddit.net/pythond.php, which it was formerly. Please update your bookmarks. It would also be nice if someone else could raise a ticket to have python.org website updated. Regards, Ben Decker director caddit.net From andriu_m at hotmail.com Wed Apr 25 18:30:56 2007 From: andriu_m at hotmail.com (=?iso-8859-1?B?QW5kculzIE0u?=) Date: Wed, 25 Apr 2007 22:30:56 +0000 Subject: getting scancodes In-Reply-To: <1177534979.599075.41980@b40g2000prd.googlegroups.com> Message-ID: >From: faulkner >To: python-list at python.org >Subject: Re: getting scancodes >Date: 25 Apr 2007 14:02:59 -0700 > >On Apr 23, 8:39 pm, andma... at gmail.com wrote: > > Anyone knows if its possible to get scan codes ??? > > I tried with getch () but with no success, just keycodes. > > May be using the something in the sys.stdin module ?? > >is this what you're looking for? >http://cheeseshop.python.org/pypi/sysio/1.0 I downloaded it, but it has no documentation! I dont know how to use it. :S thanks anyway. ;) >and sys.stdin isn't a module. it's a file. thanks for the data. _________________________________________________________________ Consigue aqu? las mejores y mas recientes ofertas de trabajo EE.UU. http://latino.msn.com/empleos From steve at REMOVE.THIS.cybersource.com.au Sat Apr 28 05:46:44 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Sat, 28 Apr 2007 19:46:44 +1000 Subject: My newbie annoyances so far References: <1177688082.758043.133920@r30g2000prh.googlegroups.com> <59f5btF2k70baU2@mid.individual.net> <59gglhF2l1u43U2@mid.individual.net> Message-ID: On Sat, 28 Apr 2007 10:58:25 +0200, Bjoern Schliessmann wrote: > Dennis Lee Bieber wrote: > >> You didn't take account of what b, c, and d were... >> >> RPL: if else end >> Python: if else >> >> (RPL is a somewhat common reference to the stack based language of >> the later calculators -- HP48, for instance) > > I still don't see the "more sense". Python's variant seems logical > to me -- " if else ". > > The HP equivalent will be, if I understand correctly: > > " if [else ]" As I explained in another post, the syntax given is wrong for RPL, but if it were right, then that description would be correct: the if would pop a flag off the stack, in this case , and then branch to either the code after the if or after the else . > I see two problems here: > > - Also from my error in the last posting it's quite clear that the > RPL statement doesn't do what one would suppose. There are bad programmers in every language, but RPL conditional blocks aren't the cause of them. Once you learn how RPL works, if statements work consistently and obviously (although maybe not to programmers who don't get RP notation). > Isn't this what > Python always tries to avoid: Doing something different from what > is "obvious". RP order doesn't fit in Python, IMHO. I agree that blindly trying to copy RP notation into Python wouldn't work. > - What should the expression's value be if the else is omitted? > None? What's it in the original? I can't imagine a use case here > since I always have two alternatives when I use "a if b else c". In RPL, there are no expressions. RPL programs are constructed from data and commands, not expressions. So you shouldn't think of if [else ] as an expression. Think of it as a block, equivalent to the Python: if garbage_can_full: fetch out garbage else: don't except that you can write it as a single line. Newlines in RPL are just another sort of whitespace, with no special significance. If the else clause is missing, then nothing is executed and processing simply continues past the end of the block. I agree with you that in the case of Python _expressions_, it doesn't make sense to have a missing else part. But in the case of RPL, it is perfectly natural for the else block to be missing. -- Steven. From tinaweb at bestemselv.com Sat Apr 14 01:39:10 2007 From: tinaweb at bestemselv.com (Tina I) Date: Sat, 14 Apr 2007 07:39:10 +0200 Subject: Append data to a list within a dict Message-ID: Hello group, Say I have the following dictionary: ListDict = { 'one' : ['oneone' , 'onetwo' , 'onethree'], 'two' : ['twoone' , 'twotwo', 'twothree'], 'three' : ['threeone' , 'threetwo', threethree']} Now I want to append 'twofour' to the list of the 'two' key but I can't figure out how to that? Some pointers would be greatly appreciated. Thanks Tina From aafshar at gmail.com Sat Apr 14 04:46:12 2007 From: aafshar at gmail.com (Ali) Date: 14 Apr 2007 01:46:12 -0700 Subject: Python editor/IDE on Linux? In-Reply-To: <8ZadnS79krqFwL3bnZ2dnUVZ_sWdnZ2d@comcast.com> References: <8ZadnS79krqFwL3bnZ2dnUVZ_sWdnZ2d@comcast.com> Message-ID: <1176540372.025899.27690@o5g2000hsb.googlegroups.com> On 14 Apr, 05:48, "Jack" wrote: > That's a good one. I got to find out what's special with Emacs :) The users. From kyosohma at gmail.com Tue Apr 10 10:00:46 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: 10 Apr 2007 07:00:46 -0700 Subject: Python Speech tools In-Reply-To: References: Message-ID: <1176213646.394072.254480@q75g2000hsh.googlegroups.com> On Apr 10, 2:15 pm, Amit K Saha wrote: > Hi list > I intend to design a Speech Recognition system.Can I have some pointers > to the available Python speech tools? > > Till date I am aware of only Python bindings for a speech tool called > Snack (http://www.speech.kth.se/snack/) > > Any help will be appreciated. > > -- > Amit K Saha > > Send instant messages to your online friendshttp://in.messenger.yahoo.com I've played with the win32 module's text-to-speech abilities a little. You may be able to get ideas from that. Here's a link to more info: http://surguy.net/articles/speechrecognition.xml http://www.cs.unc.edu/~parente/tech/tr02.shtml This isn't pure Python, but it may be helpful as well: http://sourceforge.net/projects/VoiceCode/ Good luck! Mike From nospam at nospam.com Tue Apr 24 18:06:02 2007 From: nospam at nospam.com (Gilles Ganault) Date: Wed, 25 Apr 2007 00:06:02 +0200 Subject: Building browser-like GET request References: <1177192075.699770.304600@d57g2000hsg.googlegroups.com> Message-ID: On Sun, 22 Apr 2007 18:07:57 -0400, Steve Holden wrote: >On a point of information, Wireshark wokrs very effectively under >Windows. The only thing you shouldn't expect to be able to do is tap >into the loopback network, and that's down to the Windows driver structure. Thanks for the tip. Someone mentionned a lighter alternative to display what goes on between browser and web server: PocketSoap's TCPTrace http://www.pocketsoap.com/tcptrace/ From samjnaa at gmail.com Sat Apr 14 10:27:20 2007 From: samjnaa at gmail.com (jamadagni) Date: 14 Apr 2007 07:27:20 -0700 Subject: Option Explicit In-Reply-To: <1176560418.992348.70200@b75g2000hsg.googlegroups.com> References: <1176560418.992348.70200@b75g2000hsg.googlegroups.com> Message-ID: <1176560840.826103.254430@l77g2000hsb.googlegroups.com> On Apr 14, 7:20 pm, "Clement" wrote: > Is there any command like Option Explicit[In visual basic]......... We have been discussing that over the past few hours. Please see the thread: "Python Feature Request: Explicit Variable Declarations". From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Sat Apr 14 17:06:19 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Sat, 14 Apr 2007 23:06:19 +0200 Subject: Python Feature Request: Allow changing base of member indices to 1 References: <1176546465.632410.52630@w1g2000hsg.googlegroups.com> <4620b47b$0$14410$9b622d9e@news.freenet.de> <1176557999.665663.299740@y80g2000hsf.googlegroups.com> <1176559643.450533.296850@n59g2000hsh.googlegroups.com> Message-ID: <58cu2bF2gtuo3U2@mid.individual.net> jamadagni wrote: > OK fine. It is clear that this feature must be implemented if at > all only on a per-module basis. So can we have votes for > per-module implementation of this feature? I don't think it's worth the hassle. BTW, what's, IYHO, the distinct advantage of starting array indices at 1? Regards, Bj?rn -- BOFH excuse #90: Budget cuts From bbxx789_05ss at yahoo.com Fri Apr 13 05:47:04 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: 13 Apr 2007 02:47:04 -0700 Subject: reading from sys.stdin In-Reply-To: <1176457007.589050.285400@d57g2000hsg.googlegroups.com> References: <1176366058.261031.111870@p77g2000hsh.googlegroups.com> <1176387908.406115.270630@w1g2000hsg.googlegroups.com> <1176438754.995753.50190@d57g2000hsg.googlegroups.com> <1176454871.538968.176620@n76g2000hsh.googlegroups.com> <1176457007.589050.285400@d57g2000hsg.googlegroups.com> Message-ID: <1176457624.259636.197030@p77g2000hsh.googlegroups.com> On Apr 13, 3:36 am, "7stud" wrote: > > > It is if the file is smaller than the buffer size. > > How is that relevant? > If I put 100 lines of text in a file with each line having 50 characters, and I run this code: import sys lst = [] for line in open("aaa.txt"): print "an iteration" lst.append(line) break print lst The output is: $ python test1.py an iteration ['helleo haljdfladj ahdflasdjf ds hdljfalsdjfdsljfds \n'] It seems clear to me that the whole file wasn't first read into a buffer before the code started processing the data. From dillonco at comcast.net Thu Apr 19 23:21:19 2007 From: dillonco at comcast.net (DillonCo) Date: Thu, 19 Apr 2007 23:21:19 -0400 Subject: List of Objects In-Reply-To: <1177037915.042476.153190@n76g2000hsh.googlegroups.com> References: <1177037915.042476.153190@n76g2000hsh.googlegroups.com> Message-ID: <200704192321.19115.dillonco@comcast.net> On Thursday 19 April 2007, datamonkey.ryan at gmail.com wrote: > Howdy, a (possibly) quick question for anyone willing to listen. > I have a question regarding lists and Classes; I have a class called > "gazelle" with several attributes (color, position, etc.) and I need > to create a herd of them. I want to simulate motion of individual > gazelles, but I don't want to have to go through and manually update > the position for every gazelle (there could be upwards of 50). I was > planning to create an array of these gazelle classes, and I was going > to iterate through it to adjust the position of each gazelle. That's > how I'd do it in C, anyway. However, Python doesn't support pointers > and I'm not quite sure how to go about this. Any help you can provide > would be greatly appreciated. > Thanks a lot! Actually, Python _only_ supports pointers: they're the names of objects. So for example, if I write x = Gazelle(...), then I create the name "x" that points to an instance of Gazelle. The storage for the instance is managed 'magically' by Python. If I were then to say "y = x", I'd also have a name "y" that points to the same instance. It's also worth noting that everything, including ints, strings and lists are objects as well. Because of this, a pointer to an object is the only storage class in python. Therefore, a name can point to any object of any type. As a result, an "array" in Python, which is commonly a list, is simply a list of pointers. They can point to strings, ints, other lists or anything. And because they store pointers, they can actually include themself! To demonstrate: >>> a=[1,'a',[1,2,3]] >>> for i in a: print i 1 a [1, 2, 3] >>> a.append(a) >>> for i in a: print i 1 a [1, 2, 3] [1, 'a', [1, 2, 3], [...]] Python's clever enough to not print out the circular reference. Finally, it's worth pointing out that in a language like this, where there are no arbitrary pointers (as there are in C), the pointer-to-object is called a reference. I just used "pointer" because you did ;). From i3dmaster at gmail.com Tue Apr 10 13:58:42 2007 From: i3dmaster at gmail.com (i3dmaster) Date: 10 Apr 2007 10:58:42 -0700 Subject: Universal Feed Parser issue Message-ID: <1176227922.910993.36910@y80g2000hsf.googlegroups.com> I have a sample Atom feed like this: http://app.example.com/fjie4id939xdl3io23 foo bar foo at foo.com 2007-04-09T22:14:15.000Z After parsed by feedparser, the timezone element does not get the attribute "America/Mountain". Same thing on status element. This does not sound an expected result. I am wondering if it should be considered a bug... From skip at pobox.com Mon Apr 16 13:18:29 2007 From: skip at pobox.com (skip at pobox.com) Date: Mon, 16 Apr 2007 12:18:29 -0500 Subject: script for seconds in given month? In-Reply-To: <1176742604.907208.310290@l77g2000hsb.googlegroups.com> References: <1176740556.859125.221980@l77g2000hsb.googlegroups.com> <1176742604.907208.310290@l77g2000hsb.googlegroups.com> Message-ID: <17955.45029.946528.711138@montanaro.dyndns.org> Matt> from time import mktime Matt> def secondsInMonth(year, month): Matt> s1 = mktime((year,month,1,0,0,0,0,0,-1)) Matt> s2 = mktime((year,month+1,1,0,0,0,0,0,-1)) Matt> return s2-s1 Probably won't work if month==12. ;-) Skip From vizcaynot at gmail.com Thu Apr 26 20:34:15 2007 From: vizcaynot at gmail.com (asker) Date: 26 Apr 2007 17:34:15 -0700 Subject: Correct behavior? Message-ID: <1177634055.017575.236810@t39g2000prd.googlegroups.com> Hello: I have next Python 2.5.1 instructions: >>> a=12.34 >>> b=11.23 >>> print a+b 23.57 >>> print "%15.2f" % (a+b) 23.57 But: >>> print "%15.2f" % a+b Traceback (most recent call last): File "", line 1, in TypeError: cannot concatenate 'str' and 'float' objects Is this correct for Python to issue this error? Thanks From nmilkovits at gmail.com Wed Apr 18 18:42:03 2007 From: nmilkovits at gmail.com (Nicholas Milkovits) Date: Wed, 18 Apr 2007 18:42:03 -0400 Subject: using the sysloghandler class Message-ID: <71a75690704181542r4e55faf1p6aee93cc1d7f90b3@mail.gmail.com> Hello all, I have a small script which attempts to write to the user.log syslog import logging, logging.handlers logger = logging.getLogger('bender') handler = logging.handlers.SysLogHandler(('localhost', logging.handlers.SYSLOG_UDP_PORT), logging.handlers.SysLogHandler.LOG_USER) formatter = logging.Formatter('%(filename)s: %(levelname)s: %(message)s') handler.setFormatter(formatter) logger.addHandler(handler) logger.error('what') but no log entries show up, however if I use the syslog module as such: >>> import syslog >>> syslog.syslog('testing syslog') everything works fine. I am not sure what I am doing wrong. Any help would be appreciated. Thanks, Nick From google at mrabarnett.plus.com Fri Apr 6 22:24:49 2007 From: google at mrabarnett.plus.com (MRAB) Date: 6 Apr 2007 19:24:49 -0700 Subject: Using os.popen3() to get binary data In-Reply-To: References: <1175857372.585042.239310@y80g2000hsf.googlegroups.com> Message-ID: <1175912689.335794.200350@w1g2000hsg.googlegroups.com> On Apr 6, 6:09 pm, Dennis Lee Bieber wrote: > On 6 Apr 2007 04:02:52 -0700, "Christoph Krammer" > declaimed the following in comp.lang.python: > > > Hello everybody, > > > I need to get the different frames from a GIF image in my python > > script and want to use the giftopnm program from netpbm to get the > > frames and directly convert them to pnm files. I tried to use the > > following code: > > > for image in images: > > if (image[0:3] == 'GIF'): > > What type of data /is/ "image" that the FIRST three characters > identify the type? If it's the name of the file (I don't know what > giftopnm requires for input) I'd have expected the last three to > identify.. > [snip] FYI, the first 3 bytes of a GIF image are the ASCII characters "GIF". From howe.steven at gmail.com Wed Apr 25 12:31:00 2007 From: howe.steven at gmail.com (Steven Howe) Date: Wed, 25 Apr 2007 09:31:00 -0700 Subject: popen2 results In-Reply-To: <000601c7870f$3b0a52e0$b11ef8a0$@rawlins@thinkbluemedia.co.uk> References: <000601c7870f$3b0a52e0$b11ef8a0$@rawlins@thinkbluemedia.co.uk> Message-ID: <462F8244.6020407@gmail.com> Robert Rawlins - Think Blue wrote: > Hello guys, > > > > I've recently ported my application from bash to python, however there are > still a few bash line utilities I -have- to use in the application as there > isn't any alternative available to me. In the old days of bash I would have > grep'd the output from these commands to determine the outcome. > > > > I'm now using popen2 to run the command which works a charm, but I'm > struggling to parse the results of the function, has anyone had any > experience with this? I've found a few suggested solutions dotted around, > such as this one. > > > > import os > > > > def filtered(command, source): > > dest, result = os.popen2(command) > > dest.write(source) > > dest.close() > > try: > > return result.read() > > finally: > > result.close() > > > > But to be honest I'm struggling to get it to do anything as it doesn't > states what the 'source' object is or should be. > > > > Thanks for any help guys, I'm just looking to capture the output from the > command and then I can go about a little REGEX on it. > > > > Thanks, > > > > Rob > > > check out os.popen3 as well. An Example? Let's assume you were doing 'ls -1', which at the console would give you a one column list of files (and yes, I know I can use glob.glob for this; this is an example). from os import popen3 ( sin, sout, serr ) = popen3( 'ls -1 /tmp' ) fList = sout.readlines() for f in fList: print f errors = serr.readlines() for line in errors: print line Now you have 3 file handles. sin: input (which I've never used, as I give popen3 a complete command) sout: the standard output stream serr: the standard error output You can read sout and serr and take action on them. Oh and each line has a '\n' linefeed (probably '\r\n' on Windows). Depending on what your doing with the output, you might want to use string.strip to eliminate the linefeeds. sph -------------- next part -------------- An HTML attachment was scrubbed... URL: From slug57_98 at yahoo.com Thu Apr 19 00:09:29 2007 From: slug57_98 at yahoo.com (Chad) Date: 18 Apr 2007 21:09:29 -0700 Subject: Question about Tkinter MenuOption variable Message-ID: <1176955769.756104.59440@y80g2000hsf.googlegroups.com> Is there anyway to set the individual options in Tkinter to a particular variable. For example, I have a menu option(code is below) which has January, February, March and so on, which I would like to have corresponding values of 01, 02, 03 and so on. Can someone please tell me how to do that within the context of the code I have below - or even totally modify it if you must. Label(self, text = "Month" ).grid(row = 5, column = 1, sticky = W) OPTIONS = [ "Jan", "Feb", "Mar", "Apr", "May", "June", "July", "Aug", "Sep", "Oct", "Nov", "Dec"] default_option = StringVar(self) default_option.set(OPTIONS[0]) self.month_option = OptionMenu(self, default_option, *OPTIONS) self.month_option.grid(row = 5, column = 2, sticky = W) From apardon at forel.vub.ac.be Tue Apr 10 09:21:03 2007 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 10 Apr 2007 13:21:03 GMT Subject: tuples, index method, Python's design References: <1175867771.114540.61810@n76g2000hsh.googlegroups.com> <1175884427.779950.267220@y80g2000hsf.googlegroups.com> <1175953520.316208.241490@o5g2000hsb.googlegroups.com> <7xzm5igbrb.fsf@ruckus.brouhaha.com> Message-ID: On 2007-04-10, Carsten Haese wrote: > On 10 Apr 2007 09:48:41 GMT, Antoon Pardon wrote >> If someone states: "Show me your use case for using tuple.index and I >> will show you how to avoid it." or words to that effect I think there >> is little use trying. > > Or maybe you just can't think of any good use cases, and that's annoying you > because it proves my point. Please, prove me wrong by showing use cases for > tuple.index that can't be rewritten. No you just have proven my point. I predicted that whatever use case would be given, people would stand ready to rewrite is and use those rewritals as argument againt the use case. Here you are ready to do just that. Since you can just write an index function that works with any sequence or you could simply write something like list(tup).index('...'), any code that would use tupple.index can be rewritten to do without. But that is not such a strong argument. Should the case be reversed and tuples have an index method and lists not, you would be able to rewrite any code that would use list.index into code that wouldn't. But if you are so eager to rewrite, how about the following: I am using the struct module to get binary data from a file. Sometimes I want to skip until I find a particular binary number. Somewhat simplified it looks like this: class Itemfile: def __init__(self, fn): self.fl = open(fn) self.ix = 80 def nextitem(self): if self.ix == 80: self.buf = struct.unpack("80i", self.fl.read(320)) self.ix = 0 result = self.buf[self.ix] self.ix += 1 return result def skipuntil(self, val): done = False while not done: try: self.ix = self.buf.index(val, self.ix) done = True except ValueError: self.ix = 0 self.buf = struct.unpack("80i", self.fl.read(320)) Now I'm sure you can rewrite this without the need of tuple.index. It just seems odd that I have to go through extra hoops here to get the effect of tuple.index because struct.unpack returns its result in a tuple and a tuple doesn't provide index. -- Antoon Pardon From tgrav at mac.com Fri Apr 27 12:37:51 2007 From: tgrav at mac.com (Tommy Grav) Date: Fri, 27 Apr 2007 12:37:51 -0400 Subject: editing scripts on a mac In-Reply-To: References: Message-ID: > him> I do not have a text editor, but here are the answers to > him> questions 1-5. > > Now, frankly, I don't think this answer is correct, since I know OS > X is > a UNIX derivative, but I am loathe to involve a programming noob > with vi > or something similar. So I wondered if one of the c.l.py mac users > could > give brief instructions for firing up a visual text editor of some > sort > and saving a file somewhere it can easily be accessed from a terminal > window (which I presume starts up in his home directory). I think emacs is bundled with OS X and can be started in a terminal window with emacs. If you want a non-terminal editor Aquaemacs (http://aquamacs.org/) is available and easily installed on mac. Cheers Tommy From anjeshtuladhar at gmail.com Mon Apr 2 04:38:55 2007 From: anjeshtuladhar at gmail.com (anjesh) Date: 2 Apr 2007 01:38:55 -0700 Subject: Extract information from HTML table In-Reply-To: References: <1175429635.278697.92690@b75g2000hsg.googlegroups.com> <1175431924.800332.325820@n76g2000hsh.googlegroups.com> <1175439364.515873.142340@p15g2000hsd.googlegroups.com> Message-ID: <1175503135.234560.51730@n59g2000hsh.googlegroups.com> On Apr 2, 12:54 am, "Dotan Cohen" wrote: > On 1 Apr 2007 07:56:04 -0700, Ulysse wrote: > > > I have seen the Beautiful Soup online help and tried to apply that to > > my problem. But it seems to be a little bit hard. I will rather try to > > do this with regular expressions... > > If you think that Beautiful Soup is difficult than wait till you try > to do this with regexes. Granted you know the exact format of the HTML > you are scraping will help, if you ever need to parse HTML from an > unknown source than Beautiful Soup is the only way to go. Not all HTML > authors close their td and tr tags, and sometimes there are attributes > to those tags. If you plan on ever reusing the code or the format of > the HTML may change, then you are best off sticking with Beautiful > Soup. > > Dotan Cohen > > http://lyricslist.com/http://what-is-what.com/ Have you tried HTMLParser. It can do the task you want to perform http://docs.python.org/lib/module-HTMLParser.html -anjesh From piyali.de.bis at gmail.com Mon Apr 16 04:39:25 2007 From: piyali.de.bis at gmail.com (piyali biswas) Date: Mon, 16 Apr 2007 14:09:25 +0530 Subject: please sort this out Message-ID: <75c5d9400704160139q145a8b0akd9f3b7337397734f@mail.gmail.com> Hi, I am using networkx and pylab for creating a graph using a python script abc.py. I have saved the networkx folder in "C:/Python24/Lib/site-packages". When I run the script from command prompt, it creates the graph and saves it to the place I want to but when I write a python-cgi script and run it as os.system('python abc.py') it doesn't gives me any result. I have included the path of my system using os.environ['PATH'] = ".........". I also appended the path of networkx directory using sys.path.append('C:/Python24/Lib/site-packages') as it seems to me that it is a path related problem and the cgi result page shows error (1) networkx *undefined* (2)* *drawing undefined (3) nx_pylab *undefined* (4) matplotlib *undefined* *(5) raise RuntimeError("'%s' is not a writable dir; you must set environment variable HOME to be * * a writable dir "%h)* Can you please tell me how to enable cgi to run this program on runtime. I have kept both the cgi script as well as python script in Apache/cgi-bin folder. Thanks, Piyali -------------- next part -------------- An HTML attachment was scrubbed... URL: From paul at boddie.org.uk Mon Apr 16 11:02:19 2007 From: paul at boddie.org.uk (Paul Boddie) Date: 16 Apr 2007 08:02:19 -0700 Subject: OverflowError: mktime argument out of range ??? In-Reply-To: <1176640607.972087.153470@o5g2000hsb.googlegroups.com> References: <11e49df10704150341p1a9056e7hfba36a523517fad3@mail.gmail.com> <1176640607.972087.153470@o5g2000hsb.googlegroups.com> Message-ID: <1176735739.422686.227960@d57g2000hsg.googlegroups.com> John Machin wrote: > > Maybe it does. It sure would be nice to get a definite answer. Pity > nobody documented the time module. "The epoch is the point where the time starts. On January 1st of that year, at 0 hours, the ``time since the epoch'' is zero. For Unix, the epoch is 1970. To find out what the epoch is, look at gmtime(0)." "The functions in this module do not handle dates and times before the epoch or far in the future." http://docs.python.org/lib/module-time.html > > >>> import time > > >>> time.mktime((1928, 12,28, 0, 0, 0, 0, 0, 0)) > > -1294164000.0 I think the consensus is that you're lucky if your system (the C library, more specifically) lets you play with negative time values. Here, the inquirer happens to be playing with negative time values (under the time module's API) and should therefore consider using the datetime module instead. Paul From bj_666 at gmx.net Sat Apr 7 10:26:07 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Sat, 07 Apr 2007 16:26:07 +0200 Subject: subprocess.Popen output to file? References: <1175948939.049050.74630@l77g2000hsb.googlegroups.com> Message-ID: In <1175948939.049050.74630 at l77g2000hsb.googlegroups.com>, John Pye wrote: > I am trying to set up a python script to manage backups of a mysql > database the 'right way' using pipes. I want to send the output of the > 'mysqldump' command to a file. Using a normal shell script this would > be easy using a ">" operator. What is the efficient and best way to do > this using pure python, bearing in mind that it will be too much data > to keep in memory? I presume using the subprocess module, but how to > get the output to a file? It's not really documented, AFAICS. I think it is documented, that's what the `stderr` and `stdout` arguments are used for. Untested: f = open('dump.txt', 'wb') p = Popen(('mysqldump', '--option', '--another-option'), stdout=f) r = p.wait() Ciao, Marc 'BlackJack' Rintsch From ruiligc at NOSPAM.earthlink.net Sat Apr 21 00:41:35 2007 From: ruiligc at NOSPAM.earthlink.net (Ray) Date: Sat, 21 Apr 2007 04:41:35 GMT Subject: TK-grid problem, please help Message-ID: <3CgWh.23821$PL.17381@newsread4.news.pas.earthlink.net> hi, I have a question about how to use .grid_forget (in python/TK) I need to work on grid repeatly. everytime when a button is pressed, the rows of grid is different. such like, first time, it generate 10 rows of data. 2nd time, it maybe only 5 rows. so I need a way to RESET the grid data every time. how can I do it? by grid_forger()?, then would anyone can help on how to use grid_forget() the sample code as following: #####begin of program############### from Tkinter import * def mygrid(text): ######## how to use grid_forget() to clean the grid??########### rows = [] count=int(text) for i in range(count): cols = [] for j in range(4): e = Entry(frame3, relief=RIDGE) e.grid(row=i, column=j, sticky=NSEW) e.insert(END, '%d.%d' % (i, j)) cols.append(e) rows.append(cols) root=Tk() frame1=Frame(root, width=150, height=100) frame1.pack() text=Entry(frame1) text.pack(side=LEFT) button=Button(frame1, text='generate grid', command=(lambda: mygrid(text.get()))) button.pack() frame2=Frame(root, width=150, height=100) frame2.pack() button2=Button(frame2, text='exit', command=root.quit) button2.pack() frame3=Frame(root, width=150, height=300) frame3.pack() root.mainloop() #####end of program############### From gagsl-py2 at yahoo.com.ar Mon Apr 9 15:09:26 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 09 Apr 2007 16:09:26 -0300 Subject: Database Timestamp conversion error References: <1175892527.110813.26570@n76g2000hsh.googlegroups.com> <1175901654.390331.150420@e65g2000hsc.googlegroups.com> <1175915704.435784.213830@b75g2000hsg.googlegroups.com> <1176129753.861995.132950@n59g2000hsh.googlegroups.com> Message-ID: En Mon, 09 Apr 2007 11:42:33 -0300, escribi?: > Here's my results: > > # bad > > > > # good > > datetime.datetime(2007, 4, 9, 0, 0) You can convert a DbiDate object into a datetime object using: dt = datetime.datetime.fromtimestamp(float(dbidate)) Only dates after 1970 are supported. -- Gabriel Genellina From spamspam at spam.eggs Wed Apr 25 17:14:31 2007 From: spamspam at spam.eggs (Ben C) Date: Wed, 25 Apr 2007 16:14:31 -0500 Subject: Controlling gnuplot via subprocess.Popen References: <599hu0F2k8k1qU1@mid.uni-berlin.de> Message-ID: On 2007-04-25, Peter Beattie wrote: > I am trying to plot something in gnuplot 4.2 using co-ordinates a Python > 2.5 program computes. Here's what I'm doing: > > py> from subprocess import * > py> plot = Popen("c:/progs/gp/bin/wgnuplot.exe", stdin=PIPE) > py> plot.stdin.write("plot x*x") > > The first command dutifully opens gnuplot, but the second doesn't do > anything. Could someone favour me with an explanation as to the whyness? I think it may just be that you need a newline after "plot x*x", i.e. plot.stdin.write("plot x*x\n") or print >>plot.stin, "plot x*x" But some interactive programs need to be controlled with expect rather than just writing to their stdin. I'm unclear of the details, perhaps it's just ones that use curses in some form. I usually write the gnuplot commands to a file, and then use os.system("gnuplot plot.gpi") to run gnuplot in batch mode (or gnuplot -persist if you want the window). You can also use Popen instead of os.system. From gagsl-py2 at yahoo.com.ar Wed Apr 11 14:48:44 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 11 Apr 2007 15:48:44 -0300 Subject: text file vs. cPickle vs sqlite a design question References: Message-ID: En Wed, 11 Apr 2007 13:40:02 -0300, Dag escribi?: > I have an application which works with lists of tuples of the form > (id_nr,'text','more text',1 or 0). I'll have maybe 20-50 or so of these > lists containing anywhere from 3 to over 30000 tuples. The actions I > need to do is either append a new tuple to the end of the list, display > all the tuples or display all the tuples where the last element is a 1 > > Basically what I'm wondering is the best way to store these data > stuctures > to disc. As the subject mentioned I've basically got three approaches. > Store each list as a text file, pickle each list to file or shove the > whole thing into a bunch of database tables. I can see pros and cons > with each approach. Does anybody have any advice as to whether any of From your description, none of these three approaches is obviously better. Try to isolate the data from its storage, and use the easiest way now (pickle perhaps?). This way you can change it later easily - maybe to use sqlite if you need more difficult queries. -- Gabriel Genellina From paddy3118 at googlemail.com Wed Apr 11 12:48:17 2007 From: paddy3118 at googlemail.com (Paddy) Date: 11 Apr 2007 09:48:17 -0700 Subject: Shebang or Hashbang for modules or not? In-Reply-To: <1176308951.932721.197630@y80g2000hsf.googlegroups.com> References: <1176308951.932721.197630@y80g2000hsf.googlegroups.com> Message-ID: <1176310097.799841.50080@n59g2000hsh.googlegroups.com> On Apr 11, 5:29 pm, "Chris Lasher" wrote: > Should a Python module not intended to be executed have shebang/ > hashbang (e.g., "#!/usr/bin/env python") or not? I'm used to having a > shebang in every .py file but I recently heard someone argue that > shebangs were only appropriate for Python code intended to be > executable (i.e., run from the command line). If you don't intend the module to be executable then adding a shebang line and/or setting the files execute bit are both contrary to intended use. You should therefore leave out the shebang/not set the execute bit to emphasise your intended use. During development however, intended use may differ from use when deployed. - Paddy. From carsten at uniqsys.com Thu Apr 26 08:54:11 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Thu, 26 Apr 2007 08:54:11 -0400 Subject: Now() In-Reply-To: <033801c787ce$f7a755a0$03000080@hendrik> References: <000301c78728$ba634ce0$2f29e6a0$@rawlins@thinkbluemedia.co.uk> <033801c787ce$f7a755a0$03000080@hendrik> Message-ID: <1177592051.3437.6.camel@dot.uniqsys.com> On Thu, 2007-04-26 at 08:42 +0200, Hendrik van Rooyen wrote: > Robert Rawlins - Think Blue wrote: > >With time depicted to the nearest second, from my background in ColdFusion > development we used to have a >datetimeformat() function that I could use as > > > >DateTimeFormat(now(), yyyy-mm-dd HH:mm:ss) > > > >Which would give the current time a mask. > > Here is a hack that does more or less what you want: > [snip horrible hack...] Please tell me you're not seriously suggesting this hack as a solution. -Carsten From bdesth.quelquechose at free.quelquepart.fr Fri Apr 13 16:50:12 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Fri, 13 Apr 2007 22:50:12 +0200 Subject: vocab question In-Reply-To: References: Message-ID: <461fe3d0$0$11935$426a74cc@news.free.fr> Alan G Isaac a ?crit : > Pardon the vocab question; > I'm not a computer science type. > According to the Reference Manual, > a class defintion has the structure:: > > classdef ::= "class" classname [inheritance] ":" suite > > What is the entire part before the suite called? A statement. In this case, a 'class' statement. HTH From tjbell at gmail.com Wed Apr 25 11:10:26 2007 From: tjbell at gmail.com (tstrokes) Date: 25 Apr 2007 08:10:26 -0700 Subject: Python Screen Scraper In-Reply-To: References: Message-ID: <1177513826.055001.61000@c18g2000prb.googlegroups.com> On Apr 24, 6:17 am, Michael Bentley wrote: > On Apr 24, 2007, at 11:50 AM, James Stroud wrote: > > > > > Hello, > > > Does anyone know of an example, however modest, of a screenscraper > > authored in python? I am using Firefox. > > > Basically, I am answering problems via my browser and being scored for > > each problem. I have a tendency to go past my peak for training > > efficiency, so I would like to scrape the result page for each > > problem I > > answer, compile statistics, and have a program alert me when I should > > stop (based on score and accuracy--assuming training value is > > related to > > changes in these metrics). > > > I have no idea how to go about writing such a beast and I am hoping > > that > > I could get some pointers or an example that could get me going in the > > right direction. > > > Parsing, etc, is not a problem, but I'm not exactly sure how I might > > interface python with Firefox, forwarding scraped pages to my browser > > (or forwarding from the browser to the scraper). > > > Thanks in advance for any help or advice. > > Possibly the easiest thing will be to read from firefox' cache. > Otherwise I think your only real options are to either build a proxy > or sniff the wire... You could try twill http://twill.idyll.org/python-api.html From Martin.Drautzburg at web.de Thu Apr 19 01:51:26 2007 From: Martin.Drautzburg at web.de (Martin Drautzburg) Date: Thu, 19 Apr 2007 07:51:26 +0200 Subject: unicode and __repr__() Message-ID: <3017205.ViBn82uq2M@beaureve.gmx.net> I am using repr() to pass arrays, dicts and combinations therof to javascript as it already returns a valid javascript expression (a string) right away. But for some reason it does not handle Umlaute correctly and those characters finally appear as two strange characters on the browser. I am using UTF-8 and assembling the string expression manually works okay and the umlaute appear correctly in the browser (so I could probably write my own serializer and it would work). The commandline shows a difference too: >>> print "["+"'?'"+"]" ['?'] <-- this is openbracket quote oumlaut quote closebracket >>> print ["?"].__repr__() ['\xf6'] It works okay for all other chars, just the umlaute seem to be a problem. How can I get __repr__() to handle the umlauter correctly, or is there an easy way to postprocess the output ? From steve at holdenweb.com Tue Apr 3 12:11:45 2007 From: steve at holdenweb.com (Steve Holden) Date: Tue, 03 Apr 2007 12:11:45 -0400 Subject: getattr/setattr q. In-Reply-To: <1175614741.823795@jubilee.claranet.pt> References: <1175573213.682671@jubilee.claranet.pt> <1175614741.823795@jubilee.claranet.pt> Message-ID: Paulo da Silva wrote: > Steven Bethard escreveu: >> Paulo da Silva wrote: > ... > >> If you're at the module level, you can do:: >> >> globals()['x'] = 10 >> >> If you're inside a function, you probably want to look for another way >> of doing what you're doing. >> >> What's the actual task you're trying to accomplish here? > > > None. I asked just for curiosity. My problem has to do with the normal > case of a class or class instance. When I saw setattr/getattr as the way > to solve my problem I just felt curiosity on if and how it could be done > outside a class. > > Thank you very much for your response. > Paulo You don't need setattr/getattr if you know in advance the name of the attribute you need to access and you can get a reference to the object whose attribute it is. So: >>> import sys >>> x = "Hello, Paulo" >>> sys.modules['__main__'].x 'Hello, Paulo' >>> globals()['x'] 'Hello, Paulo' >>> 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 Florian.Lindner at xgm.de Wed Apr 4 06:45:50 2007 From: Florian.Lindner at xgm.de (Florian Lindner) Date: Wed, 04 Apr 2007 12:45:50 +0200 Subject: RSS feed parser References: <1175531874.535702.212510@n76g2000hsh.googlegroups.com> <1175543462.493944.51110@b75g2000hsg.googlegroups.com> Message-ID: irstas at gmail.com wrote: > On Apr 2, 10:20 pm, Florian Lindner wrote: >> Some of the question I have but found answered nowhere: >> >> I have a feedparser object that was created from a string. How can I >> trigger a update (from a new string) but the feedparser should treat the >> new string like the same feed (thus setting feed.updated etc.). > > Hmm. Do you mean that the feed object should stay the same? Like the > difference between "a = [1,2,3]; a = [1,2,3]+[4]" and "a = [1,2,3]; > a.append(4)"? I glanced at the parse function in the source code and > it looks like it's not directly possible. You could modify it so that > the "result" dictionary is optionally given as an argument, so when > updating you'd do: feedparser.parse(string, oldFeed). You'd also have > to clear the oldFeed object before update. > > But you might also be able to solve the problem by using an additional > layer of indirection. Instead of passing around the "feed" object, > you'd pass around a proxy object like this: > > class Empty: pass > proxy = Empty() > proxy.feed = feedparser.parse(string) > storeProxyForLaterUse(proxy) > proxy.feed = feedparser.parse(string2) > useStoredProxy() #this would use the updated feed through the proxy > > Then just use proxy.feed.updated everywhere instead of directly > feed.updated. A smarter proxy would automatically translate > proxy.updated into proxy.feed.updated so usage would stay as simple as > without the proxy. Doing this is quite easy in Python (search for > __getattr__ examples). I already use something like that (with __getattr__). The problem is that with this way there is still a new feed object created everytime a new string needs to be passed to. But since I want to use use the updated_parsed etc. function it's not possible that each time the feed is parsed a new object is created (the update times will always be the time of the last parsing). Any idea? Regards, Florian From darklord at timehorse.com Sun Apr 8 12:29:25 2007 From: darklord at timehorse.com (TimeHorse) Date: 8 Apr 2007 09:29:25 -0700 Subject: starship.python.net is down In-Reply-To: <1172522790.976949@sj-nntpcache-2.cisco.com> References: <1171634223.13643@sj-nntpcache-2.cisco.com> <1172072586.601115.304110@s48g2000cws.googlegroups.com> <1172522790.976949@sj-nntpcache-2.cisco.com> Message-ID: <1176049765.862499.232610@q75g2000hsh.googlegroups.com> On Feb 26, 4:46 pm, Tom Bryan wrote: > Yes. Unfortunately, there may be a hardware problem. Stefan, the admin Any word from the ISP what the hardware problem might be, Tom? Jeffrey. From chengzhiannahuang at gmail.com Sun Apr 15 21:05:41 2007 From: chengzhiannahuang at gmail.com (chengzhiannahuang at gmail.com) Date: 15 Apr 2007 18:05:41 -0700 Subject: Getting started with python In-Reply-To: <1176645201.901480.277030@d57g2000hsg.googlegroups.com> References: <1176598011.463543.96990@q75g2000hsh.googlegroups.com> <1176645201.901480.277030@d57g2000hsg.googlegroups.com> Message-ID: <1176685541.604911.57630@d57g2000hsg.googlegroups.com> On Apr 15, 9:53 am, "Eric_Dex... at msn.com" wrote: > On Apr 14, 7:46 pm, "Eric" wrote: > > > Hello, after reading some of the book Programming Python it seems that > > python is something I would like to delve deeper into. The only thing > > is, I have no idea what I should try and write. So I was hoping that > > someone here could help point me to a group/project that would be a > > good starting place for a person with limited python knowledge, but > > that is willing to learn whatever is necessary. I'm hoping that with a > > goal I can start to learn python instead of just playing around with > > it. Thanks. > > I have a little sub-project where I generate random numbers to a music > file (a simpe ascii format that works in a grid)http://www.stormpages.com/edexter/csound.htmlor if you see some other > part of it you would like to work on or expand..https://sourceforge.net/projects/dex-trackerI haven't added the sub- > project yet but I can upload it to some google space if you are > intrested.. (uses wxwindows and python 2.5) I just installed Python 2.5 a few days ago. I like to play with csound. However, I am a window user knowing Java and C#. I do not have any experience with unix system and c. I appreciate if you would send me some instructions and examples to get me started so that In the future, I can use midi input and get ourput from csound with a final objective to generate some music not representable by midi. Chin From bbxx789_05ss at yahoo.com Thu Apr 5 13:04:50 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: 5 Apr 2007 10:04:50 -0700 Subject: shelve error In-Reply-To: References: <1175746456.995618.186190@e65g2000hsc.googlegroups.com> <1175746966.023613.178830@n76g2000hsh.googlegroups.com> <1175756092.643182.142420@n76g2000hsh.googlegroups.com> Message-ID: <1175792690.918231.205480@n76g2000hsh.googlegroups.com> On Apr 5, 5:20 am, Steve Holden wrote: > 7stud wrote: > > On Apr 4, 10:22 pm, mik3l3... at gmail.com wrote: > >> how did you generate aaa.txt? > > > Ok, I got it to work by supplying a filename that didn't previously > > exist. Neither the book I am reading, "Beginning Python: From Novice > > to Professional" nor the book I am using as a reference, "Python in > > Nutshell", happens to mention that important fact. > > It seems to make sense that you have to open a file as writable in order > to be able to change its contents, though, doesn't it? > My text file was writable. From rokkamraja at gmail.com Wed Apr 25 00:51:10 2007 From: rokkamraja at gmail.com (Raja) Date: 24 Apr 2007 21:51:10 -0700 Subject: Override sys.settrace() Message-ID: <1177476670.366725.53310@r30g2000prh.googlegroups.com> Hi, I want to override the sys.settrace() call, create a way to trace the execution of a python program. Keep track of all objects created and destroyed. Keep track of the call pattern throughout the execution of the program and output a simplified "call graph" to standard out. Please help me in this regard. Thank You, From duncan.booth at invalid.invalid Mon Apr 23 08:05:52 2007 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 23 Apr 2007 12:05:52 GMT Subject: Two syntax questions (newbie) References: <1177316126.432039.232300@o5g2000hsb.googlegroups.com> Message-ID: Szabolcs wrote: > In Python this would be something like > result = processData(list(reversed(sorted(data)))) I know that is only intended as an example, but by trying to use Mathematica idioms in Python you are perhaps blinding yourself to using Python's own idioms. A more Pythonic way to write your example in Python would be: result = processData(sorted(data, reverse=True)) sorted already returns a list, and giving it 'reverse=True' is almost always identical to sorting and then reversing (and in the rare cases where it matters the reverse parameter is probably what you want). > The second question: > > Of course Python is not Mathematica and not as friendly with this > style as Mma is. Sometimes it forces me to use some temporary > variables (e.g. because lines get too long and breaking lines with a > backslash is ugly). I like to get rid of these variables as soon as > they aren't needed, e.g.: > > temp = data[:] > temp.sort() > temp.reverse() > result = processData(temp) > del temp > > Is it possible to avoid the explicit del temp? In C/C++ I would simply > enclose the piece of code in curly brackets. Is it possible to somehow > separate a block of code from the rest of the program and make > variables local to it? Move the code using the temporary variable into a function and it will disappear as soon as the function returns. If you find you want to delete the temporary before the function returns then your function is too long. As always there are caveats on this: don't depend on either 'del' or a return from a function actually destroying objects immediately as any surviving references to the value will prolong its life. Also, while the current C-Python implementation deletes values immediately if they have no references other Python implementations do not. In this case the obvious fix is to use a function which copies, sorts and reverses a sequence and then you don't need the temporary. Since that function already exists you don't even need to write it. From apardon at forel.vub.ac.be Tue Apr 10 00:26:51 2007 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 10 Apr 2007 04:26:51 GMT Subject: how can I clear a dictionary in python References: Message-ID: On 2007-04-04, Delaney, Timothy (Tim) wrote: > Antoon Pardon wrote: > >> People are often enough not very exact in their communication and >> that goes double for people who are new in a particular subject. >> So I think it is entirely appropiate to think about the real question >> the person is strugling with that hides between the question >> actually asked. >> >> Yes sometimes those who try to guess the intentions of the OP >> are going totally off in the wrong direction. But I have also >> seen those people providing very helpfull information, while >> those that would stick to the "actual" question didn'y provide >> very usefull information. > > And yet it's giving the *wrong* information if the person was asking > exactly the question they intended to ask. So? You are in a sitituation where it isn't clear what answer will be the most usefull. So you make a judgement call and judgment calls can sometimes be wrong. > If you think there is some ambiguity, you should *clarify* the question > before answering. Answering a different question to the one that is > asked just causes problems, and the kind of thread this has degenerated > into. I disagree. This thread has degenerated, not because some people answered a different question, but because other people didn't like that and reacted. If you think an answer to a particular question needs extra clarification, you can just provide that clarification. Of course some people can always find complains. Even if you point out errors in what other say, you can draw complaints because they think you are bothering with details they think are unimportant which may detract from what they think is the real issue. So my advise is not to bother with telling how questions should be answered but to just provide the information you think is missing. -- Antoon Pardon From gigs at hi.t-com.hr Wed Apr 18 16:43:17 2007 From: gigs at hi.t-com.hr (Gigs_) Date: Wed, 18 Apr 2007 22:43:17 +0200 Subject: tkinter canvas Message-ID: how to write text on canvas. i know that i need to use canvas.create_text, but how to write text than when i create_text? or how to access object ID in canvas and change some options? thanks in advance! From jstroud at mbi.ucla.edu Tue Apr 10 23:29:27 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Tue, 10 Apr 2007 20:29:27 -0700 Subject: Please help!!! In-Reply-To: <1176238783.257926.67310@30g2000cwc.googlegroups.com> References: <1176234239.436463.195870@n33g2000cwc.googlegroups.com> <1176236179.443346.162070@h3g2000cwc.googlegroups.com> <1176238783.257926.67310@30g2000cwc.googlegroups.com> Message-ID: gslm wrote: > On 10 Nisan, 23:16, "Paul McGuire" wrote: > >>On Apr 10, 2:43 pm, "gslm" wrote: >> >> >>In fact ? know this, but I asked some questions like this, but ? haven't get any answer.And I thought that may be it could be better to use a header like this for help.Sorry! >> >> >>>Hi to all! >>>I want to do a calendar with pictures near months. >>>I have designed the form's view.But unfortunately, I am not be able to >>>save this view as an image file.And so I am not be able to print this >>>image file too. >>>Question: >>>How can I determine the coordinates of a button?Namely How can I use >>>the comand ImageGrab for this purpose? >> >>>But only I wan to get the button's ares.Because my applicationis on >>>this. >> >>>Or if it's possible, how can I print the area of this button with the >>>components on it? >> >>>Thanks... >> >>Suggestion 1: "Please help!!!" is just about the worst newsgroup >>subject line there is (other than those related to government >>conspiracies or earthquake prediction). You are unlikely to attract >>the attention of those who really know anything - they are quite busy >>and must husband their time carefully. Instead, you'll get those who >>are idly curious, to see what sort of junk is floating about Usenet. >> >>Suggestion 2: Consider your audience. What the heck are you talking >>about?! Your post goes on about calendars and buttons and views. In >>fact, trying to make sense of your post, it sounds like you've done >>something truly bizarre, like making the whole view one giant button >>with lots of images on it, and you want to print it out when the >>"button" is clicked. Is this even a Python question? Any particular >>GUI package you are using, such as Tk, wxPython, QT, your own homebrew >>invention? ImageGrab? Sounds promising, what do the docs say? >> >>A more thorough discussion of these suggestions:http://www.catb.org/~esr/faqs/smart-questions.html >> >>-- Paul- Al?nt?y? gizle - >> >>- Al?nt?y? g?ster - > > > gslm: Just so you know, you are annoying everyone on this list with your ill formed "questions"--Not just Paul who happened to be nice enough to give you some advice. James From rehceb at no.spam.plz Sat Apr 7 14:12:05 2007 From: rehceb at no.spam.plz (Rehceb Rotkiv) Date: Sat, 07 Apr 2007 13:12:05 -0500 Subject: Checking whether list element exists References: Message-ID: Thanks for your many helpful tips! Rehceb Rotkiv From larry.bates at websafe.com Thu Apr 26 09:06:15 2007 From: larry.bates at websafe.com (Larry Bates) Date: Thu, 26 Apr 2007 08:06:15 -0500 Subject: Store variable name in another variable In-Reply-To: <1177592072.498517.139260@b40g2000prd.googlegroups.com> References: <1177592072.498517.139260@b40g2000prd.googlegroups.com> Message-ID: loial wrote: > I need to store a list of variable names in a dictionary or list. I > then later need to retrieve the names of the variables and get the > values from the named variables. The named variables will already have > been created and given a value. > > I hope thats clear!!! > > How can I do this? > Use a dictionary. Example: var1=10 var2="abc" var2=1.2 vardict['var1']=var1 vardict['var2']=var2 vardict['var3']=var3 print vardict['var1'] print vardict['var2'] print vardict['var3'] -Larry From beliavsky at aol.com Sun Apr 15 17:08:20 2007 From: beliavsky at aol.com (Beliavsky) Date: 15 Apr 2007 14:08:20 -0700 Subject: Python Feature Request: Allow changing base of member indices to 1 In-Reply-To: References: <1176546465.632410.52630@w1g2000hsg.googlegroups.com> <4620b47b$0$14410$9b622d9e@news.freenet.de> <1176557999.665663.299740@y80g2000hsf.googlegroups.com> <1176559643.450533.296850@n59g2000hsh.googlegroups.com> Message-ID: <1176671300.119131.297370@n76g2000hsh.googlegroups.com> On Apr 14, 10:55 am, Dennis Lee Bieber wrote: > The FORTRAN family had started as 1-based (F95, and Ada, now allow > for each array to have its own "base" => x : array (-10..10) of float). Fortran has allowed a user-specified base since at least the 1977 standard -- see for example http://www.umiacs.umd.edu/~jhu/DOCS/SP/docs/essl/essl159.html . From spamtrap at dot-app.org Wed Apr 4 21:13:25 2007 From: spamtrap at dot-app.org (Sherm Pendley) Date: Wed, 04 Apr 2007 21:13:25 -0400 Subject: Why NOT only one class per file? References: <1175721799.714907.52770@o5g2000hsb.googlegroups.com> <46142acc$0$7532$426a34cc@news.free.fr> Message-ID: Bruno Desthuilliers writes: > Chris Lasher a ?crit : > >> so I thought I'd ask here to >> see why the Python idiom is the way it is: why should we NOT be >> placing classes in their own separate files? > > Because it just sucks. ... > Just ask him why Java insists on 'one-(public)-class-per-file', and > why it's considered good form in C++. I mean, the real *technical* > reasons... Yeah, as if "because it just sucks" is a technical reason. :-) It's a stylistic thing, nothing more. There's no technical basis for it, just personal preference. sherm-- -- Web Hosting by West Virginians, for West Virginians: http://wv-www.net Cocoa programming in Perl: http://camelbones.sourceforge.net From martin at v.loewis.de Thu Apr 12 17:16:22 2007 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Thu, 12 Apr 2007 23:16:22 +0200 Subject: Portably generating infinity and NaN In-Reply-To: References: Message-ID: <461ea1a6$0$15266$9b622d9e@news.freenet.de> Michael Hoffman schrieb: > What's the best way to portably generate binary floating point infinity > and NaNs? I only know two solutions: > > 1. Using the fpconst module proposed in IEEE 754, which I believe shifts > bits around. > > 2. Using an extension module (for example, numarray.ieeespecial will do > it). Use the struct module to pack/unpack a double value. On an IEEE 754 system, this should work - on a non-IEEE-754 system, it's not clear that +/-inf and NaN actually exist. Regards, Martin From dadapapa at googlemail.com Tue Apr 3 18:31:38 2007 From: dadapapa at googlemail.com (Harold Fellermann) Date: 3 Apr 2007 15:31:38 -0700 Subject: passing options to __import__ Message-ID: <1175639497.973152.281270@e65g2000hsc.googlegroups.com> Dear list, I looked through the list but could not find any solutions for my current problem. Within my program, I am importing a module via __import__(module_name,globals(),locals()) and I want to pass comand line options to this module. I would prefer not to save them in a config module or a Config class but rather use the globals and locals dictionaries that are given to __import__. Unfortunately, they don't show up in the globals or locals in the module. Even setting them specifically by params = globals() params['module_opts'] = module_opts __import__('my_module',params,locals()) does not work. When I put the debug statement print 'module_opts' in globals() into my_module, it prints 'False'. Unfortunately, the docs for __import__ are a bit vague about the precise role of the globals argument. Is there any way, to acheive what I am trying, or do I need to fall back on a config module/class? Thanks! - harold - From steve at holdenweb.com Fri Apr 20 16:14:24 2007 From: steve at holdenweb.com (Steve Holden) Date: Fri, 20 Apr 2007 16:14:24 -0400 Subject: urlopen.read() In-Reply-To: <1177098732.490602.301530@l77g2000hsb.googlegroups.com> References: <1177098732.490602.301530@l77g2000hsb.googlegroups.com> Message-ID: ken wrote: > Hi, > > When I call urlopen.read() like this: > > data = urlopen("http://localhost").read(). > > Does that mean I will read the whole document to data, regardless how > many data being sent back? > > Thank you. > Yes. However you can read (and presumably process)one line at a time with readline() or by iterating over the object returned by urlopen(). I'd recommend trying something like: u = urlopen("http://localghost/") for line in u: print line # or process it some other way or line = u.readline() while line: # process the line line = u.readline() There is no need to buffer the whole content before you process it unless you choose to do so. 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 jstroud at mbi.ucla.edu Fri Apr 6 15:05:51 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Fri, 06 Apr 2007 19:05:51 GMT Subject: No subject In-Reply-To: References: Message-ID: C.L. wrote: > James Stroud mbi.ucla.edu> writes: >> C.L. wrote: >>> I was looking for a function or method that would return the index to the >>> first matching element in a list. ... >>> ... __please don't be overly defensive__ ... >> The amount of typing wasted to defend design decisions such as this can >> boggle one's mind. Just use lists unless you have on overwhelming reason >> to do otherwise. >> >> James > > > Read the quote. I *am* using a list. > > That doesn't change the fact that this is unfriendly design. It's an ugly > inconsistent chunk of a Python's past in which built-in types didn't behave like > objects. It sticks out like a sore thumb, maybe just not very often. > > Oh, and thanks for the insulting tone of your anticipated response. Have you > anything better to do with your time than wasting bytes writing empty responses > to what you already deem a waste of typing? > > *sighs* just what I expected: another idle troll defending something just for > the sake of defending it. On the other hand, thanks 7stud, for the truly helpful > response. > I think you misinterpreted my post, I agree with you. Please read it again. You have touched on a very old topic. Many people have fought tooth and nail to defend arbitrary design decisions such as a tuple not having an index. It boils down to the fact that tuples are useless as a result unless you know you really need them--and you never really NEED them. James From steve at REMOVE.THIS.cybersource.com.au Sat Apr 14 04:22:01 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Sat, 14 Apr 2007 18:22:01 +1000 Subject: tuples, index method, Python's design References: Message-ID: On Sat, 14 Apr 2007 08:19:36 +0200, Hendrik van Rooyen wrote: > This is the point where the whole thing falls apart in my head and > I get real confused - I can't find a reason why, list or tuple, the first > item can't be something, the second something else, etc... It's not that they _can't_ be, but that the two sequence types were designed for different uses: Here are some tuples of statistics about people: fred = (35, 66, 212) # age, height, weight george = (42, 75, 316) They are tuples because each one is like a Pascal record or a C struct. It isn't likely that you'll be in a position where you know that Fred's age, height or weight is 66, but you don't know which one and so need fred.index() to find out. Hence, tuples weren't designed to have an index method. Here are some lists of statistics about people: ages = [35, 42, 26, 17, 18] heights = [66, 75, 70, 61, 59] weights = [212, 316, 295, 247, 251] # notice that the first column is fred, the second column is george, etc. They are mutable lists rather than immutable tuples because you don't know ahead of time how many data items you need to store. Now, it is likely that you'll want to know which column(s) have an age of 26, so lists were designed to have an index method. Now, that's the sort of things tuples and lists were designed for. If you want to use them for something else, you're free to. -- Steven. From gagsl-py2 at yahoo.com.ar Thu Apr 5 03:14:02 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 05 Apr 2007 04:14:02 -0300 Subject: Why does my callback funtion collapse? References: <461498B6.109@gmail.com> Message-ID: En Thu, 05 Apr 2007 03:35:34 -0300, lialie escribi?: > I try to callback from a thread in C. But it collapsed. I can't figure > it out. - If you are using threads, you must handle the Global Interpreter Lock (GIL), see http://docs.python.org/api/threads.html - You don't handle refcounts well: my_callback = temp; Py_XINCREF(temp); Py_XDECREF(my_callback); The code above does nothing. You must decrement my_callback *before* the assignment (because you are about to lose a reference to the previous value) and increment it after (because you keep a reference to the new value). -- Gabriel Genellina From yozara at terra.es Tue Apr 17 06:59:35 2007 From: yozara at terra.es (Zara) Date: Tue, 17 Apr 2007 12:59:35 +0200 Subject: Python Feature Request: Allow changing base of member indices to 1 References: <1176546465.632410.52630@w1g2000hsg.googlegroups.com> <1176579205.948684.171640@q75g2000hsh.googlegroups.com> <1176668873.556584.237410@p77g2000hsh.googlegroups.com> Message-ID: On Mon, 16 Apr 2007 10:15:19 +0200, "Javier Bezos" wrote: >Paddy, > >>> Dijkstra's argument is obsolete, as it is based on >>> how array length was computed many years ago -- if >>> we have an array a = b..e, then the lenght of a >>> is e-b (half open range). Good at low level >>> programming. >>> >>> But a quarter of a century after we know concepts >>> are much better than low level programming and >>> explicit computations -- if we have an array >>> a = b..e, then the length of a should be a.length() >>> (or a.length(b,e)), and it is independent of > >> Hi Javier, >> You seem to have missed out array *indexing* >> in your argument, or is array indexing obsolete? > >Of course, it isn't, but it has evolved over the >past 25 years. When Djikstra wrote that, many >people (including me) was using a Spectrum--- >Now we have OO programming to deal with concepts >and a more generic programming. So, to me it's >clear his _argument_ is very outdated and cannot >be applied directly and withot reservations to >modern languages like Python. > One language created by and for mathematicians: Haskell. It uses zero based list indexing (the most similar to array indexing they have), so that list!!0 is the first element and list!!3 the fourth element. And they tend to reason in Dijkstra's style. They love natural numbers beginning with zer: zara From bbxx789_05ss at yahoo.com Fri Apr 13 07:16:13 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: 13 Apr 2007 04:16:13 -0700 Subject: wxPython, mac, wx.HSCROLL not working In-Reply-To: <5895rrF2en0c0U1@mid.individual.net> References: <1176364597.741079.25840@n59g2000hsh.googlegroups.com> <586qvsF2fbq3rU1@mid.individual.net> <1176392605.298630.8210@y5g2000hsa.googlegroups.com> <1176404918.079527.148440@d57g2000hsg.googlegroups.com> <587i0iF2fu57fU1@mid.individual.net> <1176417535.246590.158780@y80g2000hsf.googlegroups.com> <5895rrF2en0c0U1@mid.individual.net> Message-ID: <1176462973.509322.145010@q75g2000hsh.googlegroups.com> On Apr 13, 4:54 am, Bjoern Schliessmann wrote: > 7stud wrote: > > Thanks. It looks like someone asked the same question yesterday. > > No -- it looks like I was a bit stressed and the first google hit or > a direct jump to wxpython.org would have provided the solution :) > Huh? Are you saying you found a solution? From braindead at braindead.com Sat Apr 7 19:51:03 2007 From: braindead at braindead.com (enquiring mind) Date: Sat, 07 Apr 2007 23:51:03 GMT Subject: beginner - py unicode Q Message-ID: <46182E68.34A35F01@braindead.com> I read the posting by Rehceb Rotkiv and response but don't know if it relates to my problem in any way. I only want to write German to the screen/console for little German programs/exercises in python. No file w/r will be used. #! /usr/bin/env python # -*- coding: utf-8 -*- # Filename: 7P07png.py # SUSE Linux 10 Python 2.4.1 gedit 2.12.0 print 'Ich z?hle zw?lf wei? H?te.' print 'Wollen Sie' verbs = ( 'k?mmen' , 'essen' , 'trinken' ) print verbs[:3] print ' program ends ' console display is: Ich z?hle zw?lf wei? H?te. Wollen Sie ('k\xc3\xb6mmen', 'essen', 'trinken') program ends The first 2 print statements in German print perfectly to screen/console but not the 3rd. I ran it with these lines below from Rehceb Rotkiv's code but it did not fix problem. import sys import codecs I also tried unicode string u'k?mmen', but it did not fix problem. Any help/direction would be appreciated. Thanks in advance. I found this reference section but I am not sure it applies or how to use it to solve my problem.: This built in setdefaultencoding(name) sets the default codec used to encode and decode Unicode and string objects (normally ascii)and is meant to be called only from sitecustomize.py at program startup; the site module them removes this attribute from sys. You can call reload(sys) to make this attriute available again but this is not a good programming practice. I just thought of this. I suppose because this is py source code, it should not be German but a reference/key to u'strings' to print German text to the screen? The ultimate console output I seek, of course, using a while or for loop and/or random access for second verb, for example: Wollen Sie k?mmen? Wollen Sie essen? Wollen Sie trinken? From aleax at mac.com Thu Apr 19 23:33:58 2007 From: aleax at mac.com (Alex Martelli) Date: Thu, 19 Apr 2007 20:33:58 -0700 Subject: List of Objects References: <1177037915.042476.153190@n76g2000hsh.googlegroups.com> Message-ID: <1hwu3mz.mtc0ed1ogshqlN%aleax@mac.com> wrote: > Howdy, a (possibly) quick question for anyone willing to listen. > I have a question regarding lists and Classes; I have a class called It looks you don't really want what you're saying: you appear to want a list of INSTANCES of one class, *NOT* a list of CLASSES. E.g.: class Gazelle(object): pass class Zip(Gazelle): pass class Zop(Gazelle): pass class Zap(Gazelle): pass thelist = [Zip, Zop, Zap] Now THIS would be a list of classes, but contextual clues in your text appear to suggest that you do NOT want this, and may be deeply mistaken about what "a list of classes" means. I'd rather get confirmation of that point before I address your question; if you use totally, irretrievably wrong terminology, miscommunication's likely:-(. Alex From bthom at cs.hmc.edu Wed Apr 25 17:30:49 2007 From: bthom at cs.hmc.edu (belinda thom) Date: Wed, 25 Apr 2007 14:30:49 -0700 Subject: sorting question Message-ID: Hi, I've had a look at http://wiki.python.org/moin/HowTo/Sorting, but am not sure if I can get the operator.itemgetter to do what I want for my particular need. I'm also not sure why creating my own cmp for pulling tuple parts out and passing it to a list sort doesn't just work. I'm sure this stuff is old hat to many on this list. Suggestions happily accepted. Suppose I've got a list like: l = [(-.3,(4,3)),(.2,(5,1)),(.10,(3,2))] and I want to sort on the 2nd item in the 2nd tuple. I've tried things like: cmp = lambda x,y : x[1][1] > y[1][1] l.sort(cmp=cmp) but l isn't then changed in place. Using sorted(l,operator.itemgetter(1)) behaves as I'd expect, but I really want something like operator.itemgetter(1).itemgetter(1), which (understandably) causes a syntax error. Thx, --b From nogradi at gmail.com Mon Apr 30 05:13:32 2007 From: nogradi at gmail.com (Daniel Nogradi) Date: Mon, 30 Apr 2007 11:13:32 +0200 Subject: I/O Operations ..... In-Reply-To: <1177919063.650070.321560@y80g2000hsf.googlegroups.com> References: <1177919063.650070.321560@y80g2000hsf.googlegroups.com> Message-ID: <5f56302b0704300213q40db8c5am11675cbfbbaa7a0d@mail.gmail.com> > I am parsing an XML file and sending the output to two files.The > code asks the user to enter the input file,something like: > > file_input = raw_input("Enter The ODX File Path:") > input_xml = open(file_input,'r') > > Now suppose the user enters the path as : > C:\Projects\ODX Import\Sample Files\Global _A_UHP_Low_0.7.odx.xml > > I have 2 output files to which i have to redirect the output.The > output file name should be same as input file in the same path ( the > extension has to change to a format "ini" which is basically text file > opened using notepad).Eg.. > output files should be : > C:\Projects\ODX Import\Sample Files\Global _A_UHP_Low_0.7.ini, and, > C:\Projects\ODX Import\Sample Files\Global _A_UHP_Low_0.7.xls If you only would like to know how to write files, this might help: content1 = .............. content2 = ............... f = open( 'file1', 'w' ) f.write( content1 ) f.close( ) f = open( 'file2', 'w' ) f.write( content2 ) f.close( ) HTH, Daniel From ihccab at gmail.com Mon Apr 2 14:07:04 2007 From: ihccab at gmail.com (ihccab) Date: 2 Apr 2007 11:07:04 -0700 Subject: Launch script on Linux using Putty In-Reply-To: <1175536278.510176.183360@l77g2000hsb.googlegroups.com> References: <1175467029.572354.138930@y66g2000hsf.googlegroups.com> <1175536278.510176.183360@l77g2000hsb.googlegroups.com> Message-ID: <1175537224.187987.121810@n76g2000hsh.googlegroups.com> On Apr 2, 1:51 pm, "Ulysse" wrote: > On Apr 2, 12:56 am, Michael Hoffman wrote: > > > > > Ulysse wrote: > > > Hello, > > > > I have a python script which runs all the time (using of library > > > threading). I would like this scipt to run on a remote linux Os using > > > Putty. The problem is, when I close Putty command line window running > > > on my Win PC, the python script stops to run too. > > > > I tried to use cron tables instead. By setting the time and restart > > > cron process, but it's not practical. > > > > Do you know the right way to do this ? > > > There are a few ways to do this, in order of easiest to most involved: > > > 1. The easiest is to run nohup on your script in the background: > > > $ nohup myscript.py > output.txt 2> error.txt & > > > Then you can disconnect but your script will keep running. Try man nohup > > for more information. > > > 2. Use GNU screen on your remote terminal, and detach the screen instead > > of logging off. > > > 3. Set up your script to fork as a daemon. Google for ["python cookbook" > > fork daemon] to find a few recipes for this. > > -- > > Michael Hoffman > > Thanks a lot but in my situation : > > 1. nohup seems not to be installed on my "reduced linux distribution". > It's a OpenWrt tunning on my WRT54GL Broadband router. > > 2. I have looked for the way I can "detach the screen" with Putty but > I've not found (May be you can precise ?) > > 3. The "fork daemon" script found onhttp://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/278731 > seems to be as huge as my own script and little bit hard to undestand. > > So maybe "detach the screen" ? > > Thanks Try running the script with the ampersand (&) at the end. ./myscript.py & that will put it in the background and you can exit the Putty window. You can start the script at boot by adding it to rc.local using the full path to the script. /path/to/myscript.py & From nagle at animats.com Sun Apr 29 19:24:55 2007 From: nagle at animats.com (John Nagle) Date: Sun, 29 Apr 2007 23:24:55 GMT Subject: fastest way to find the intersection of n lists of sets In-Reply-To: References: <1177883328.835058.138990@p77g2000hsh.googlegroups.com> Message-ID: James Stroud wrote: > Prateek wrote: > >> I have 3 variable length lists of sets. I need to find the common >> elements in each list (across sets) really really quickly. >> >> Here is some sample code: >> >> # Doesn't make sense to union the sets - we're going to do >> intersections later anyway >> l1 = reduce(operator.add, list(x) for x in l1) >> l2 = reduce(operator.add, list(x) for x in l2) >> l3 = reduce(operator.add, list(x) for x in l3) >> >> # Should I do this in two steps? Maybe by intersecting the two >> shortest lists first? >> s = frozenset(l1) & frozenset(l2) & frozenset(l3) >> >> I'm assuming frozensets are (somehow) quicker than sets because >> they're immutable. >> >> Any code suggestions? Maybe using something in the new fancy-schmancy >> itertools module? >> >> Thanks, >> Prateek >> > > I don't understand why you cast to list. I would propose: > > lists_of_sets = [l1, l2, l3] > > reduce(set.intersection, (reduce(set.union, x) for x in lists_of_sets)) > > Since this is simplest, I'm guessing it should be fastest because I'm > also guessing that set impelmentation is as optimized as list--I think > this would hold true especially for large sets with sparse overlap > between lists. So it might be reasonable consider the content of your > sets and lists and write your code based on the content or on assuming a > particular composition. Python sets are hashes, like dictionaries, not trees. Intersection is implemented by iterating over the smallest set and trying all its keys on the other set. The Python implementation compares the length of two sets being intersected. This is OK (it's about O(N log N), maybe better). For the above example, it's worth sorting lists_of_sets by the length of the sets, and doing the short ones first. How big are the sets? If they're small, but you have a lot of them, you may be better off with a bit-set representation, then using AND operations for intersection. If they're huge (tens of millions of entries), you might be better off doing sorts and merges on the sets. When you ask questions like this, it's helpful to give some background. We don't know whether this is a homework assignment, or some massive application that's slow and you need to fix it, even if it requires heavy implementation effort. John Nagle From ayaz at dev.slash.null Thu Apr 5 09:21:19 2007 From: ayaz at dev.slash.null (Ayaz Ahmed Khan) Date: Thu, 05 Apr 2007 18:21:19 +0500 Subject: how to remove multiple occurrences of a string within a list? References: <1175624433.206953.214290@n59g2000hsh.googlegroups.com> <1175625098.269660.184790@o5g2000hsb.googlegroups.com> <1175626164.428718.267670@w1g2000hsg.googlegroups.com> <1175626674.836668.293850@b75g2000hsg.googlegroups.com> Message-ID: "Steven Bethard" typed: >> Or, just: >> >> In [1]: l = ["0024","haha","0024"] >> In [2]: filter(lambda x: x != "0024", l) >> Out[2]: ['haha'] > > Only if you want to make your code harder to read and slower:: Slower, I can see. But harder to read? > There really isn't much use for filter() anymore. Even in the one place > I would have expected it to be faster, it's slower:: > > $ python -m timeit -s "L = ['', 'a', '', 'b']" "filter(None, L)" > 1000000 loops, best of 3: 0.789 usec per loop > > $ python -m timeit -s "L = ['', 'a', '', 'b']" "[i for i in L if i]" > 1000000 loops, best of 3: 0.739 usec per loop I am getting varying results on my system on repeated runs. What about itertools.ifilter()? $ python -m timeit -s "L = ['0024', 'haha', '0024']; import itertools" "itertools.ifilter(lambda i: i != '1024', L)" 100000 loops, best of 3: 5.37 usec per loop $ python -m timeit -s "L = ['0024', 'haha', '0024']" "[i for i in L if i != '0024']" 100000 loops, best of 3: 5.41 usec per loop $ python -m timeit -s "L = ['0024', 'haha', '0024']" "[i for i in L if i]" 100000 loops, best of 3: 6.71 usec per loop $ python -m timeit -s "L = ['0024', 'haha', '0024']; import itertools" "itertools.ifilter(None, L)" 100000 loops, best of 3: 4.12 usec per loop -- Ayaz Ahmed Khan Do what comes naturally now. Seethe and fume and throw a tantrum. From irmen.NOSPAM at xs4all.nl Tue Apr 10 20:08:52 2007 From: irmen.NOSPAM at xs4all.nl (Irmen de Jong) Date: Wed, 11 Apr 2007 02:08:52 +0200 Subject: problem with UDP broadcast on Windows XP In-Reply-To: <1176237502.731802.92950@v33g2000cwv.googlegroups.com> References: <461a271c$0$323$e4fe514c@news.xs4all.nl> <461a6523$0$327$e4fe514c@news.xs4all.nl> <012e01c77b3c$09bd3ec0$03000080@hendrik> <461bf42a$0$326$e4fe514c@news.xs4all.nl> <1176237502.731802.92950@v33g2000cwv.googlegroups.com> Message-ID: <461c2755$0$69886$e4fe514c@news.xs4all.nl> Paul McGuire wrote: > I would investigate Windows security settings as a likely culprit. My > guess is that you are running WinXP SP2 with the default security > policies, which are likely to prohibit such promiscuous behavior. > > Here's a URL that may shed some light, it seems surprisingly > instructive for MS support: http://support.microsoft.com/kb/842242 - > Some programs seem to stop working after you install Windows XP > Service Pack 2 Paul, that was terrific. Seems that the windows firewall blocks the broadcast stuff for services. After I disabled the thing, my service works again as intended! Have to add this to the notes of my software ;) Wonderful that my windows specific problem got solved in this Python group. Thanks again for all the ideas everyone for my silly offtopic problem. --Irmen From cam.ac.uk at mh391.invalid Mon Apr 2 14:34:30 2007 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Mon, 02 Apr 2007 19:34:30 +0100 Subject: Launch script on Linux using Putty In-Reply-To: <1175536278.510176.183360@l77g2000hsb.googlegroups.com> References: <1175467029.572354.138930@y66g2000hsf.googlegroups.com> <1175536278.510176.183360@l77g2000hsb.googlegroups.com> Message-ID: [Michael Hoffman] >> 1. The easiest is to run nohup on your script in the background: >> >> $ nohup myscript.py > output.txt 2> error.txt & >> >> Then you can disconnect but your script will keep running. Try man nohup >> for more information. >> >> 2. Use GNU screen on your remote terminal, and detach the screen instead >> of logging off. >> >> 3. Set up your script to fork as a daemon. Google for ["python cookbook" >> fork daemon] to find a few recipes for this. [Ulysse] > 1. nohup seems not to be installed on my "reduced linux distribution". > It's a OpenWrt tunning on my WRT54GL Broadband router. If you are running bash, you can do this: $ myscript.py & [1] 30834 $ disown %1 > 2. I have looked for the way I can "detach the screen" with Putty but > I've not found (May be you can precise ?) Google for GNU screen. But it probably won't be installed either, if nohup isn't. > 3. The "fork daemon" script found on http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/278731 > seems to be as huge as my own script and little bit hard to undestand. OK, another alternative is to simulate nohup yourself, using the signal module. You might want to read the docs and search the cookbook for examples of its use. I think it would be something like: import signal signal.signal(signal.SIGHUP, signal.SIG_IGN) -- Michael Hoffman From apardon at forel.vub.ac.be Tue Apr 24 02:39:38 2007 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 24 Apr 2007 06:39:38 GMT Subject: Tutorial creates confusion about slices References: Message-ID: On 2007-04-23, Michael Bentley wrote: > > On Apr 23, 2007, at 7:38 AM, Antoon Pardon wrote: > >> The following is part of the explanation on slices in the >> tutorial: >> >> The best way to remember how slices work is to think of the indices as >> pointing between characters, with the left edge of the first character >> numbered 0. Then the right edge of the last character of a string of n >> characters has index n, for example: >> >> +---+---+---+---+---+ >> | H | e | l | p | A | >> +---+---+---+---+---+ >> 0 1 2 3 4 5 >> -5 -4 -3 -2 -1 >> >> This is all very well with a simple slice like: >> >> "HelpA"[2:4] => "lp" >> >> >> But it give the wrong idea when using the following extended slice: >> >> "HelpA"[4:2:-1] => "Ap" >> >> So this doesn't result in the reverse of the previous expression while >> the explanation above suggest it does. >> >> >> So I suggest to drop this. > > But 'drop' means to let or make (something) fall vertically... :-) > > At that point in the tutorial, step values had not been discussed. > Just a bit lower down on the page you'll find a link to 'Sequence > Types' where you'll find an explanation of stepping you'll perhaps > find more satisfactory. That is very well posible. The question: Even if we get a good explanation later, do we want an explanation here that can cause confusion. These things are not just read and then discarded. Someone can already have read the whole tutorial and then come back to this place. So at that point he knows about stepping when he is reading this. I suspect that if you give this explanation to someone and explain that there is also a step parameter, chances are he will answer correctly if you ask him, what he thinks the following will result in: "This is an example line"[12:19:2] If you ask him what the following will result in: "This is an example line"[19:12:-1] Chances are he will give the wrong answer. From jeremy+complangpython at jeremysanders.net Mon Apr 9 10:28:55 2007 From: jeremy+complangpython at jeremysanders.net (Jeremy Sanders) Date: Mon, 09 Apr 2007 15:28:55 +0100 Subject: Database in memory References: <1176124752.172926.129850@w1g2000hsg.googlegroups.com> Message-ID: Jim wrote: > I have an application that will maintain an in-memory database in the > form of a list of lists. Does anyone know of a way to search for and > retreive "records" from such a structure? The dictionary is the obvious way to index things: # items consist of name and age data = [ ['fred', 42], ['jim', 16], ... ] name_index = {} for item in data: name_index[item[0]] = item >>> name_index['fred'] ['fred', 42] Dictionaries are one of the most useful things in Python. Make sure you know how to take adavantage of them... Jeremy -- Jeremy Sanders http://www.jeremysanders.net/ From stephen04 at tiscali.co.uk Fri Apr 20 18:28:20 2007 From: stephen04 at tiscali.co.uk (Stephen Lewitowski) Date: Fri, 20 Apr 2007 23:28:20 +0100 Subject: Testing GUI's Message-ID: <46293e84$1_2@mk-nntp-2.news.uk.tiscali.com> Can any of you guy's out there point me to information on automating GUI's that use Tkinter. I would like to find out more and possibly get involved if there are any projects under development. Thanks in advance. Steve From webraviteja at gmail.com Thu Apr 19 08:43:11 2007 From: webraviteja at gmail.com (Ravi Teja) Date: 19 Apr 2007 05:43:11 -0700 Subject: Helpbook and CHM In-Reply-To: <1176982702.528426.326770@b75g2000hsg.googlegroups.com> References: <1176979477.204864.72900@n59g2000hsh.googlegroups.com> <1176980292.290091.10420@y5g2000hsa.googlegroups.com> <1176982417.221318.215750@n59g2000hsh.googlegroups.com> <1176982702.528426.326770@b75g2000hsg.googlegroups.com> Message-ID: <1176986591.583908.288210@l77g2000hsb.googlegroups.com> > > > > Teja wrote: > > > > > how to generate CHM files in Boa(Python)??? > > > > > http://www.rutherfurd.net/software/rst2chm/index.html > > > > > TJG > > > > Can't I do it in Boa constructor ??? I have seen an option in Boa to > > > create a new helpbook and compile it to CHm and help files, But no > > > clue how to do it....... > > > Not that I know of. Which version are you using? Where in the > > application did you find it? Indicate the menu's you navigated to get > > to that option. > > > MS HTML Help Workshop is the standard compiler for CHM files. There > > are some other freeware/shareware. The workshop is simple enough > > though. > > If u have Boa constructor 0.4.4, Go to File--->New--->helpbook > > Save it. After saving, click File menu option and you will find, "make > HTB" and "make CHM" > But I dont know how to add files and generate a complete CHM file. Right-click the file list view and select "Add files". I didn't see this Helpbook feature before. However, I could not get it to compile after that. Unless, Boa Constructor is doing something while building CHMs that integrates with the app development, I recommend that you try a specialized tool for the job instead. Boa was an extremely promising tool when I saw it about 6 yrs ago or so at 0.0.1 (it already had a streamlined WYSIWYG GUI builder with a code aware editor back then, something we still don't have elsewhere for Python). But the development never seemed to gather steam since then. 0.4.4 is not even listed as a release on the home page and it is almost 2 yrs old. From steve at REMOVE.THIS.cybersource.com.au Sat Apr 14 22:54:36 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Sun, 15 Apr 2007 12:54:36 +1000 Subject: optparse -- anyway to find if the user entered an option? References: <1176594561.971801.211710@y80g2000hsf.googlegroups.com> Message-ID: On Sat, 14 Apr 2007 16:49:22 -0700, Karthik Gurusamy wrote: > I'm wondering if there is a cleaner approach -- something like > parser.opt_seen("-i") What do dir(parser) and help(parser) say? -- Steven. From kyosohma at gmail.com Wed Apr 11 09:33:57 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: 11 Apr 2007 06:33:57 -0700 Subject: py script modify it's Modified Time? In-Reply-To: <1176290057.625687.15150@y80g2000hsf.googlegroups.com> References: <1176290057.625687.15150@y80g2000hsf.googlegroups.com> Message-ID: <1176298437.784719.146850@o5g2000hsb.googlegroups.com> On Apr 11, 6:14 am, "est" wrote: > I guess os.stat() could retrieve information about ctime, mtime of a > path, but how can I change them? Is it possible to make it work both > under Win32 and Linux? > > P.S. How to get the current running python? (Like > WScript.ScriptFullName in vbscript) I am not sure if you can change a creation time of a file on NT, but the rest sounds possible; according to this post anyway: http://mail.python.org/pipermail/python-list/2001-August/100214.html It mentions using the win32 modules, which can be found here: http://aspn.activestate.com/ASPN/docs/ActivePython/2.4/pywin32/win32_modules.html As to your last question of finding the current running python, use the sys module's "executable" method, like so: sys.executable Mike From NutJob at gmx.net Wed Apr 11 10:36:50 2007 From: NutJob at gmx.net (antred) Date: 11 Apr 2007 07:36:50 -0700 Subject: passing class by reference does not work?? In-Reply-To: <1176301439.769248.247720@y5g2000hsa.googlegroups.com> References: <1176301439.769248.247720@y5g2000hsa.googlegroups.com> Message-ID: <1176302210.632948.38590@p77g2000hsh.googlegroups.com> > def b(item, a): > a.val = a.val + 1 > return item + a.val This is where the problem lies, specifically the line a.val = a.val + 1 What happens here is that the 1st a.val refers to a member of the class instance a, called val ... which does not yet exist and is therefore created as the result of taking the val member of the class A and adding 1 to it. In other words, a.val is not the same variable as A.val. Are you following? If not, change your b() method to this: def b(item, a): a.val = a.val + 1 assert a.val is A.val return item + a.val and see what happens. From saroj.nayak at wipro.com Tue Apr 10 10:04:30 2007 From: saroj.nayak at wipro.com (saroj.nayak at wipro.com) Date: Tue, 10 Apr 2007 19:34:30 +0530 Subject: multithreading concept Message-ID: The information contained in this electronic message and any attachments to this message are intended for the exclusive use of the addressee(s) and may contain proprietary, confidential or privileged information. If you are not the intended recipient, you should not disseminate, distribute or copy this e-mail. Please notify the sender immediately and destroy all copies of this message and any attachments. WARNING: Computer viruses can be transmitted via email. The recipient should check this email and any attachments for the presence of viruses. The company accepts no liability for any damage caused by any virus transmitted by this email. www.wipro.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From Eric_Dexter at msn.com Sat Apr 14 02:49:05 2007 From: Eric_Dexter at msn.com (Eric_Dexter at msn.com) Date: 13 Apr 2007 23:49:05 -0700 Subject: How to get a forum for your free site? In-Reply-To: <1176518288.373349.237050@w1g2000hsg.googlegroups.com> References: <1176518288.373349.237050@w1g2000hsg.googlegroups.com> Message-ID: <1176533345.247060.206320@b75g2000hsg.googlegroups.com> On Apr 13, 9:38 pm, "Ann" wrote: > If you have something good and want to show or share it with > eachother ,what would you do then? > Send it one by one ?It's so slow and boring that you will be tired and > have no interested to do that again.The buoyant you will be lost,are > you ?http://www.forumgogo.comthis is the place where can provide you all > things and functions what you want. > The forum is free.It's a very good flat roof for you to communicate > with the other one ,upload things. As you like Beauty & Style?football > or Pets?you can create a special topic such as Football Forum . > We can provide you a free?stable?high-speed ?Professional and > technical Forum.So what are you waiting for? Come on ! Normaly I would consider this way way off topic but I did notice that you offer unlimited space so I suppose it could be usefull for those of us that distribute software.. what else do I get some of the add space?? If you are after killer apps you should consider allowing combination of other boards between websites... (I had a provider that went down in the .com bust that did that) From andmarti at gmail.com Mon Apr 9 21:01:50 2007 From: andmarti at gmail.com (andmarti at gmail.com) Date: Mon, 9 Apr 2007 22:01:50 -0300 Subject: Get Shift + TAB in ncurses. Message-ID: <20070410010150.GA9437@lacordilleraandina.com.ar> Anyone can help me getting the shift + tab key combination ? I tried with getch () but with no success. May be using the sys.stdin ?? Please, help would be very appreciated. -- Andr?s M. --------------------------------------------- From soyouthinkimgonnalikethis at hotmail.com Sat Apr 7 12:01:55 2007 From: soyouthinkimgonnalikethis at hotmail.com (Eric Price) Date: Sat, 07 Apr 2007 11:01:55 -0500 Subject: Can't Get Email Interface Working In-Reply-To: Message-ID: Good grief! And they call a 722-line program "simple"?! LOL! I did what I need to do with a __one_line_shell_script__ LOL! Naw, if I have to go through all that, I'll skip on python this time around, thank you very much! Eric >From: hlubenow >To: python-list at python.org >Subject: Re: Can't Get Email Interface Working >Date: Sat, 07 Apr 2007 17:33:38 +0200 > >Eric Price wrote: > > > Hi; > > I'm writing a script that includes an email function. So I went to the > > cookbook and dug up this, and tweaked it just a bit to make it easier to > > get it to work, but it throws an error: > > > >>>>def createMail(sender, recipient, subject, html, text): > > ... import MimeWriter, mimetools, cStringIO > > ... out = cStringIO.StringIO() > > ... # txtin = cStringIO.StringIO(msg) > > ... writer = MimeWriter.MimeWriter(out) > > ... writer.addheader("From", sender) > > ... writer.addheader("To", recipient) > > ... writer.addheader("Subject", subject) > > ... writer.addheader("MIME-Version", "1.0") > > ... writer.startmultipartbody("alternative") > > ... writer.flushheaders() > > ... subpart = writer.nextpart() > > ... subpart.addheader("Content-Transfer-Encoding", >"quoted-printable") > > ... pout = subpart.startbody("text/plain", [("charset", >'us-ascii')]) > > ... mimetools.encode(txtin, pout, 'quoted-printable') > > ... txtin.close() > > ... subpart = writer.nextpart() > > ... subpart.addheader("Content-Transfer-Encoding", >"quoted-printable") > > ... pout = subpart.startbody("text/html", [("charset", 'us-ascii')]) > > ... mimetools.encode(htmlin, pout, 'quoted-printable') > > ... htmlin.close() > > ... writer.lastpart() > > ... msg = "test" > > ... out.close() > > ... return msg > > ... > >>>># --------------------------------------------------------------- > > ... def sendMail(sender, recipient, subject, html, text): > > ... import smtplib > > ... message = createMail(sender, recipient, subject, html, text) > > ... server = smtplib.SMTP("localhost") > > ... server.sendmail(sender, recipient, message) > > ... server.quit() > > ... > >>>>if __name__=="__main__": > > ... sendMail("root at mail.example.com", "joe at yahoo.com", "Web Stie(s) > > Down!!!", "", "text") > > ... > > Traceback (most recent call last): > > File "", line 2, in ? > > File "", line 4, in sendMail > > File "", line 10, in createMail > > File "/usr/local/lib/python2.4/MimeWriter.py", line 153, in > > startmultipartbody > > self._boundary = boundary or mimetools.choose_boundary() > > File "/usr/local/lib/python2.4/mimetools.py", line 130, in > > choose_boundary > > hostid = socket.gethostbyname(socket.gethostname()) > > socket.gaierror: (8, 'hostname nor servname provided, or not known') > >>>> > > > > Now, I can send email from my server no problem. In fact, I have my >script > > working already...but with a shell script instead of this python code. > >:lol: > > > Please advise. > > TIA, > > Eric > >You may want to take a look at simplemail.py: > >http://gelb.bcom.at/trac/simplemail/browser/trunk/simplemail.py > >that does sending mails in Python comfortably. > >HTH > >H. >-- >http://mail.python.org/mailman/listinfo/python-list _________________________________________________________________ Interest Rates Fall Again! $430,000 Mortgage for $1,399/mo - Calculate new payment http://www.lowermybills.com/lre/index.jsp?sourceid=lmb-9632-18679&moid=7581 From eugene.vandenbulke at gmail.com Thu Apr 26 12:34:08 2007 From: eugene.vandenbulke at gmail.com (EuGeNe Van den Bulke) Date: Thu, 26 Apr 2007 18:34:08 +0200 Subject: EuroPython vs PyconUK Message-ID: <4630D480.7050308@gmail.com> I do realize that the UK is not really part of Europe (no polemic :P) but I am nevertheless curious about the logic behind creating another major Python event in Europe. Wasn't EuroPython enough? Like many I am sure, I probably won't be able to attend both (and I really enjoyed the Geneva experience so definitely want to renew "it"). How would you go about selecting which conference to attend? They are only 2 months apart, 6 would have been easier for the attendees! Could the organizers liaise one way or another to make Pythoneers life as easy and fun as the language and give as much information out as possible as early as possible (early bird early) for people to make the best decision? I know marketing matters but ... EuGeNe -- http://www.3kwa.com From rhamph at gmail.com Sun Apr 15 14:35:20 2007 From: rhamph at gmail.com (Rhamphoryncus) Date: 15 Apr 2007 11:35:20 -0700 Subject: tuples, index method, Python's design In-Reply-To: <_2rUh.121507$eJ3.917600@phobos.telenet-ops.be> References: <1176200361.260546.280510@n76g2000hsh.googlegroups.com> <740c3aec0704100824m132c45fbi5c4c3ec0c0fa3a67@mail.gmail.com> <1176489534.568939.249910@q75g2000hsh.googlegroups.com> <7x3b33k0l9.fsf@ruckus.brouhaha.com> <1176572775.382873.282850@q75g2000hsh.googlegroups.com> <7xr6qmrg4x.fsf@ruckus.brouhaha.com> <1176618596.238855.122000@d57g2000hsg.googlegroups.com> <7xvefym5r6.fsf@ruckus.brouhaha.com> <_2rUh.121507$eJ3.917600@phobos.telenet-ops.be> Message-ID: <1176662120.171024.299060@n59g2000hsh.googlegroups.com> On Apr 15, 8:56 am, Roel Schroeven wrote: > Paul Rubin schreef: > > > "Rhamphoryncus" writes: > >> Indexing cost, memory efficiency, and canonical representation: pick > >> two. You can't use a canonical representation (scalar values) without > >> some sort of costly search when indexing (O(log n) probably) or by > >> expanding to the worst-case size (UTF-32). Python has taken the > >> approach of always providing efficient indexing (O(1)), but you can > >> compile it with either UTF-16 (better memory efficiency) or UTF-32 > >> (canonical representation). > > > I still don't get it. UTF-16 is just a data compression scheme, right? > > I mean, s[17] isn't the 17th character of the (unicode) string regardless > > of which memory byte it happens to live at? It could be that that accessing > > it takes more than constant time, but that's hidden by the implementation. > > > So where does the invariant c==s[s.index(c)] fail, assuming s contains c? > > I didn't get it either, but now I understand. Like you, I thought Python > Unicode strings contain a canonical representation (in interface, not > necessarily in implementation) but apparently that is not true; see > Neil's post and the reference manual > (http://docs.python.org/ref/types.html#l2h-22). > > A simple example on my Python installation, apparently compiled to use > UTF-16 (sys.maxunicode == 65535): > > >>> s = u'\u1d400' You're confusing \u, which is followed by 4 digits, and \U, which is followed by eight: >>> list(u'\u1d400') [u'\u1d40', u'0'] >>> list(u'\U0001d400') [u'\U0001d400'] # UTF-32 output, sys.maxunicode == 1114111 [u'\ud835', u'\udc00'] # UTF-16 output, sys.maxunicode == 65535 -- Adam Olsen, aka Rhamphoryncus From mail at microcorp.co.za Tue Apr 17 01:23:35 2007 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Tue, 17 Apr 2007 07:23:35 +0200 Subject: Queue enhancement suggestion References: <7x4pngluel.fsf_-_@ruckus.brouhaha.com> Message-ID: <006301c780b0$8cad1020$03000080@hendrik> "Antoon Pardon" wrote: > The problem is this doesn't work well if you have multiple producers. > One producer can be finished while the other is still putting values > on the queue. > > The solution I have been thinking on is the following. > > Add an open and close operation. Only threads that have the queue > open can access it. The open call should specify whether you > want to read or write to the queue or both. When all writers > have closed the queue and the queue is empty a q.get will > raise an exception. This may be done by putting a sentinel > on the queue when the last writer closed the queue. > This is beginning to look like a named pipe to me. The nice thing about queues is that there is currently so little BS about them - you just import the module, create one by binding a name to it, and you are in business, and anyone can read and/or write to it. If I were faced with the sort of thing addressed by this thread, I would probably use some sort of time out to decide when the end has happened. After all - if the task is long running, it never stops (hopefully), and if its a batch type job, it runs out of input and stops putting stuff on the queue. It means you have to use non blocking gets and try - except, though. But then - to use any of the methods put forward in this thread, you have to use try - except anyway... Why does this remind me of COBOL: read input_file at end go to close_down ? : - ) - Hendrik From aleax at mac.com Mon Apr 2 01:07:52 2007 From: aleax at mac.com (Alex Martelli) Date: Sun, 1 Apr 2007 22:07:52 -0700 Subject: Sorting a multidimensional array by multiple keys References: Message-ID: <1hvww1d.1k8ozo312a7yazN%aleax@mac.com> Thomas Kr?ger wrote: > 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) A MUCH better way to obtain exactly the same semantics would be: def getid(a): return a.id obj_list.sort(key=getid) Alex From ihccab at gmail.com Mon Apr 2 14:12:08 2007 From: ihccab at gmail.com (ihccab) Date: 2 Apr 2007 11:12:08 -0700 Subject: Launch script on Linux using Putty In-Reply-To: <1175537224.187987.121810@n76g2000hsh.googlegroups.com> References: <1175467029.572354.138930@y66g2000hsf.googlegroups.com> <1175536278.510176.183360@l77g2000hsb.googlegroups.com> <1175537224.187987.121810@n76g2000hsh.googlegroups.com> Message-ID: <1175537527.715246.72670@e65g2000hsc.googlegroups.com> On Apr 2, 2:07 pm, "ihccab" wrote: > On Apr 2, 1:51 pm, "Ulysse" wrote: > > > > > On Apr 2, 12:56 am, Michael Hoffman wrote: > > > > Ulysse wrote: > > > > Hello, > > > > > I have a python script which runs all the time (using of library > > > > threading). I would like this scipt to run on a remote linux Os using > > > > Putty. The problem is, when I close Putty command line window running > > > > on my Win PC, the python script stops to run too. > > > > > I tried to use cron tables instead. By setting the time and restart > > > > cron process, but it's not practical. > > > > > Do you know the right way to do this ? > > > > There are a few ways to do this, in order of easiest to most involved: > > > > 1. The easiest is to run nohup on your script in the background: > > > > $ nohup myscript.py > output.txt 2> error.txt & > > > > Then you can disconnect but your script will keep running. Try man nohup > > > for more information. > > > > 2. Use GNU screen on your remote terminal, and detach the screen instead > > > of logging off. > > > > 3. Set up your script to fork as a daemon. Google for ["python cookbook" > > > fork daemon] to find a few recipes for this. > > > -- > > > Michael Hoffman > > > Thanks a lot but in my situation : > > > 1. nohup seems not to be installed on my "reduced linux distribution". > > It's a OpenWrt tunning on my WRT54GL Broadband router. > > > 2. I have looked for the way I can "detach the screen" with Putty but > > I've not found (May be you can precise ?) > > > 3. The "fork daemon" script found onhttp://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/278731 > > seems to be as huge as my own script and little bit hard to undestand. > > > So maybe "detach the screen" ? > > > Thanks > > Try running the script with the ampersand (&) at the end. > > ./myscript.py & > > that will put it in the background and you can exit the Putty window. > > You can start the script at boot by adding it to rc.local using the > full path to the script. > > /path/to/myscript.py & To check that is is running in the background, do: ps -ef | grep myscript.py You will see the process table entry for your script with the PID and other info. From p at ulmcnett.com Sat Apr 14 00:30:30 2007 From: p at ulmcnett.com (Paul McNett) Date: Fri, 13 Apr 2007 21:30:30 -0700 Subject: File DB instead of real database? In-Reply-To: <1176524076.446204.70730@w1g2000hsg.googlegroups.com> References: <1176524076.446204.70730@w1g2000hsg.googlegroups.com> Message-ID: <462058E6.4040405@ulmcnett.com> Jia Lu wrote: > I donot want to use a real DB like MySQL ... But I need something to > save about more than 1000 articles. > Is there any good ways? (in Python 2.5): #-- begin import sqlite3.dbapi2 as sqlite con = sqlite.connect("path/to/new/filename.db") cur = con.cursor() cur.executescript(""" create table articles (id integer primary key autoincrement, name text, content clob); create index articles_name on articles (name); insert into articles (name, clob) values ("My new article", "Article text. blah blah"); """) con.commit() #-- end -- pkm ~ http://paulmcnett.com From bbxx789_05ss at yahoo.com Sat Apr 7 05:13:52 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: 7 Apr 2007 02:13:52 -0700 Subject: os.path.isfile() error In-Reply-To: <1175936167.548551.289600@n76g2000hsh.googlegroups.com> References: <1175936167.548551.289600@n76g2000hsh.googlegroups.com> Message-ID: <1175937232.735538.308530@p77g2000hsh.googlegroups.com> On Apr 7, 2:56 am, "7stud" wrote: > Here's the code: > ------------ > import os, os.path, pprint > > mydir = "/Users/me/2testing" > > files = [file for file in os.listdir(mydir)] > pprint.pprint(files) > > print os.path.join(mydir, "helloWorld.py") > > files = [file > for file in os.listdir(mydir) > if os.path.isfile(os.path.join(dir, file) ) > ] > > pprint.pprint(files) > ----output:---------------- > > ['.DS_Store', 'cpTest', 'dir1', 'testfile1', 'xmlFile.xml'] > /Users/me/2testing/helloWorld.py > Traceback (most recent call last): > File "test1.py", line 16, in ? > files = [file > File "/System/Library/Frameworks/Python.framework/Versions/2.3/lib/ > python2.3/posixpath.py", line 62, in join > elif path == '' or path.endswith('/'): > AttributeError: 'builtin_function_or_method' object has no attribute > 'endswith' I got it: 'mydir' v. 'dir' > mydir = "/Users/me/2testing" > ... > if os.path.isfile(os.path.join(dir, file) ) From mizipzor at gmail.com Sun Apr 22 08:33:53 2007 From: mizipzor at gmail.com (Mizipzor) Date: 22 Apr 2007 05:33:53 -0700 Subject: Vector classes Message-ID: <1177245233.573675.274580@n59g2000hsh.googlegroups.com> During my coding Ive found two vector classes on the internet. Ive modified them both a little but the do both have advantages and disadvantages. vector1: http://rafb.net/p/4FVdh699.html vector2: http://rafb.net/p/0KShGu30.html With 1, I can typ vec.x and vec.y, very nice. With 2, I need to do vec.vals[0] and vec.vals[1], which makes my eyes bleed. But with 2, I can create a vector by supplying a list of numbers as arguments. And I can also do maths with numbers (ints/floats) and not just vectors (something 1 forces me to do). Is there any way to combine the two? The ultimate would be if I somehow could take vector2 and hook the member self.vals[0] to self.x or something. From duncan.booth at invalid.invalid Mon Apr 30 11:35:03 2007 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 30 Apr 2007 15:35:03 GMT Subject: import structures References: <1177945012.753497.117630@o5g2000hsb.googlegroups.com> Message-ID: spohle wrote: > as of now i have a __init__.py file in the directory with: > from pkgutil import extend_path > __path__ = extend_path(__path__, __name__) > > but i still have to import each class by it's own. im really looking > for something like import wx > and then get all my access right away under this new namespace. You just need to make your __init__.py import anything you want to be available directly under the package. So if the folder pkg contains __init__.py, class1.py, class2.py all you have to do is make pkg/__init__.py contain something like: from class1 import Class1 from class2 import Class2 And then when using the package you can do: from pkg import Class1, Class2 or import pkg ... something = pkg.Class1() as you prefer. From bearophileHUGS at lycos.com Sat Apr 7 09:45:20 2007 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 7 Apr 2007 06:45:20 -0700 Subject: tuples, index method, Python's design In-Reply-To: References: <1175867771.114540.61810@n76g2000hsh.googlegroups.com> <1175884427.779950.267220@y80g2000hsf.googlegroups.com> Message-ID: <1175953520.316208.241490@o5g2000hsb.googlegroups.com> Carsten Haese: > The lack of convincing use cases is still a pertinent reason today. Note > that the original poster on this thread did not present a use case for > tuple.index, they were only asking out of curiosity. > If you have a use case for tuple.index, please show it to me, and I'll > show you what you should be using instead of a tuple. Maybe we can add such methods to the PyPy tuples for some time, to experimentally see if they make the language worse :-) (Adding such methods may reduce the amound of information you have to keep in your brain to program with Python. If tuples and lists share more methods then you don't have to remember what methods tuples don't have. This means less complexity.) Bye, bearophile From steve at holdenweb.com Thu Apr 19 18:36:14 2007 From: steve at holdenweb.com (Steve Holden) Date: Thu, 19 Apr 2007 18:36:14 -0400 Subject: Python un-plugging the Interpreter In-Reply-To: References: Message-ID: Jorgen Grahn wrote: > On Thu, 19 Apr 2007 10:56:25 -0600, S.Mohideen wrote: [...] > >> 4) Acheive true parallelism and performance by getting rid of the >> middle-man Interpreter and GIL. > > Is the GIL really an artifact of the interpreter? > In so far as only the CPython interpreter has one, I'd have to say "yes" to this. It's used to make various operations trivially thread-safe, which allows large speed gains in the programming. A long time ago Greg Stein produced a patch that removed the need for the GIL, but nobody seemed to want to pay the penalty it extracted in speed reduction, so it languished unadopted. 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 bj_666 at gmx.net Sat Apr 14 07:07:53 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Sat, 14 Apr 2007 13:07:53 +0200 Subject: reading from sys.stdin References: <1176366058.261031.111870@p77g2000hsh.googlegroups.com> <1176387908.406115.270630@w1g2000hsg.googlegroups.com> <1176438754.995753.50190@d57g2000hsg.googlegroups.com> <1176454871.538968.176620@n76g2000hsh.googlegroups.com> <1176457007.589050.285400@d57g2000hsg.googlegroups.com> <1176538930.891355.230880@n59g2000hsh.googlegroups.com> Message-ID: In <1176538930.891355.230880 at n59g2000hsh.googlegroups.com>, 7stud wrote: > Anyway, it seems everyone is saying that when you iterate over a file, the > whole file is first read into memory. Therefore iterating over sys.stdin > is consistent: you have to type Ctrl+D to signal EOF before the iteration > can start. Is that about right? Not the whole file is read but a block of it. If you type in enough to fill the buffer the iteration can start without an EOF on `sys.stdin`. See the second example in which demonstrates that not the whole file is read at once by the iterator. Ciao, Marc 'BlackJack' Rintsch From mail at timgolden.me.uk Mon Apr 30 06:26:59 2007 From: mail at timgolden.me.uk (Tim Golden) Date: Mon, 30 Apr 2007 11:26:59 +0100 Subject: Dict Copy & Compare In-Reply-To: <000701c78b10$1e8aa9d0$5b9ffd70$@rawlins@thinkbluemedia.co.uk> References: <00da01c78b01$3e80b900$bb822b00$@rawlins@thinkbluemedia.co.uk> <4635AB95.4010309@timgolden.me.uk> <000601c78b06$b9fb0950$2df11bf0$@rawlins@thinkbluemedia.co.uk> <4635B38E.5020606@timgolden.me.uk> <000701c78b10$1e8aa9d0$5b9ffd70$@rawlins@thinkbluemedia.co.uk> Message-ID: <4635C473.4010109@timgolden.me.uk> Robert Rawlins - Think Blue wrote: > Hello Tim, > > Sorry, that 'value' was a slip up on my part, we're just dealing with keys > here. > > I get that a dict stores unique keys only but we're comparing the two dicts, > so when I say 'unique keys in dict 1' I basically mean all those keys that > are in dict one but not in dict 2. So imagine my 2 dicts with the following > keys. > > Dict 1 Dict 2 > ------ ------- > 00:00:00:00 00:00:00:00 > 11:11:11:11 11:11:11:11 > 22:22:22:22 33:33:33:33 > 44:44:44:44 44:44:44:44 > 55:55:55:55 > > Now, 22:22:22:22 and 55:55:55:55 is unique to dict one, and 33:33:33:33 is > unique to dict 2, does that make sense? Sorry for not explaining this stuff > very well, being so new to dicts its easy to get confused with my terms. > > I then want to pass those keys as a string value into my function as an > argument, like. > > thisFunction('22:22:22:22') > thisFunction('55:55:55:55') > > thatFunction('33:33:33:33') > > I'm hoping that your method will work for me, I've just got to spend my time > understanding what each step of it does. Well I feel a bit guilty now I look back at your original post, because I've probably given you a more complex solution than you really need. Your initial approach is probably quite adequate. Python dicts are highly tuned beasts so unless you're doing something really big or bizarre, you can sensibly do: d1 = { "00:00:00:00" : None, "11:11:11:11" : None, "22:22:22:22" : None, "44:44:44:44" : None, "55:55:55:55" : None } d2 = { "00:00:00:00" : None, "11:11:11:11" : None, "33:33:33:33" : None, "44:44:44:44" : None } for k in d1: if d1 not in d2: thisFunction (d1) for k in d2 if d2 not in d1: thatFunction (k) But even if this is adequate for your purposes, it's always good to be aware of what's in your programming toolbox and there's always the danger you'll end up implementing sets in dicts (which is what everyone did before Python 2.3). TJG From aleax at mac.com Thu Apr 19 23:00:32 2007 From: aleax at mac.com (Alex Martelli) Date: Thu, 19 Apr 2007 20:00:32 -0700 Subject: comparison with None References: <3IqdnfRnCNWPC7vbnZ2dnUVZ_jqdnZ2d@rcn.net> <2qzVh.7373$xL6.982@trnddc05> <_JAVh.1700$jR5.897@trnddc08> Message-ID: <1hwu26k.oyynyowsbxvcN%aleax@mac.com> Alan Isaac wrote: > currently documented behavior: > "objects of different types always compare unequal". Where is that documented? URL please? >>> 1.0 == 1 True >>> type(1.0), type(1) (, ) here, just as an example, are two objects of different types that compare equal; therefore that "documented behavior" is flat wrong and needs to be fixed. Alex From bthom at cs.hmc.edu Tue Apr 3 02:05:39 2007 From: bthom at cs.hmc.edu (belinda thom) Date: Mon, 2 Apr 2007 23:05:39 -0700 Subject: exit to interpreter? In-Reply-To: <_P1Nh.15767$tD2.5060@newsread1.news.pas.earthlink.net> References: <_P1Nh.15767$tD2.5060@newsread1.news.pas.earthlink.net> Message-ID: <98338CCD-FBFC-483B-A3B5-40754C651C24@cs.hmc.edu> On Mar 24, 2007, at 4:30 AM, Dennis Lee Bieber wrote: > On Fri, 23 Mar 2007 10:52:09 -0700, belinda thom > declaimed the following in comp.lang.python: > >> 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. >> > To the Python command line? That seems to imply that you started > Python first, then imported the module with the function and > invoked it. Yup > Surely you don't expect this to be the normal operational mode for > the program? Its more for pedagogical purposes. I'm using Python in an undergrad prog class and I'd like students to be able to either enter one of a set of simple menu choices or quit to the interpreter. It should be command-based as opposed to GUI based. Hence the request. > About the only way I know of to short circuit the calling stack > requires using an exception -- and an exception handler at the top- > level > (which, for your stated goal, probably has a "pass" for its body, > so the > top-level will "exit" to the interpreter prompt). This is similar to Mel's advice, which was what I'd expected but wanted to verify. Thanks. For those who've been following this thread, this is the approach I took. --b From mail at timgolden.me.uk Wed Apr 4 06:49:53 2007 From: mail at timgolden.me.uk (Tim Golden) Date: Wed, 04 Apr 2007 11:49:53 +0100 Subject: bool value 'False' no memory address? In-Reply-To: <1175683317.458791.275270@d57g2000hsg.googlegroups.com> References: <1175682972.507206.29000@n76g2000hsh.googlegroups.com> <1175683317.458791.275270@d57g2000hsg.googlegroups.com> Message-ID: <461382D1.7000007@timgolden.me.uk> Jakub Stolarski wrote: > On Apr 4, 12:36 pm, "autin" wrote: >> such as:>>>b = False >>>>> id(b) >> Traceback (most recent call last): >> File "", line 1, in ? >> TypeError: 'bool' object is not callable >> >> --- >> how to desc it? > >>>> b = False >>>> id(b) > 135311308 > > python 2.4, FreeBSD 6.2 > The OP's almost certainly accidentally used "id" as a flag somewhere previously: id = True # # .. do other stuff # b = False id (b) Also, I'm not quite sure what he wants to do with the id, which is only the machine address (if that's what it is) by implementation detail. TJG From attn.steven.kuo at gmail.com Mon Apr 16 23:36:25 2007 From: attn.steven.kuo at gmail.com (attn.steven.kuo at gmail.com) Date: 16 Apr 2007 20:36:25 -0700 Subject: list insertion question In-Reply-To: <1176771916.236282.206500@n59g2000hsh.googlegroups.com> References: <1176771916.236282.206500@n59g2000hsh.googlegroups.com> Message-ID: <1176780985.126327.193790@n59g2000hsh.googlegroups.com> On Apr 16, 6:05 pm, eight02645... at yahoo.com wrote: > hi > i have a list (after reading from a file), say > data = [ 'a','b','c','d','a','b','e','d'] > > I wanted to insert a word after every 'a', and before every 'd'. so i > use enumerate this list: > for num,item in enumerate(data): > if "a" in item: > data.insert(num+1,"aword") > if "d" in item: > data.insert(num-1,"dword") #this fails > but the above only inserts after 'a' but not before 'd'. What am i > doing wrong? is there better way?thanks Traverse the list from highest index to lowest index: data = [ 'a', 'b', 'c', 'd', 'a', 'b', 'e', 'd' ] print data for idx, value in reversed(list(enumerate(data))): if value == 'a': data.insert(idx+1, 'aword') elif value == 'd': data.insert(idx, 'dword') print data # OR last_idx = len(data) - 1 for idx in range(last_idx+1): ridx = last_idx - idx if data[ridx] == 'a': data.insert(ridx+1, 'aword') elif data[ridx] == 'd': data.insert(ridx, 'dword') print data -- Hope this helps, Steven From kyosohma at gmail.com Tue Apr 3 09:31:47 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: 3 Apr 2007 06:31:47 -0700 Subject: Finding and copying files with python. In-Reply-To: <1175606497.896681.119490@l77g2000hsb.googlegroups.com> References: <1175606497.896681.119490@l77g2000hsb.googlegroups.com> Message-ID: <1175607107.690245.145130@l77g2000hsb.googlegroups.com> On Apr 3, 8:21 am, "gtb" wrote: > I wish to copy the highest version number of a file from directory \ > \ > \fileserver\D:\scripts to C:\scripts where the file names are of the > form > > filename_MM.NN.SS.zip, where MM, NN, and SS can be one to three > digits. > > Example directory: > other.zip > dx_ver_1.1.63.zip > dx_ver_1.2.01.zip > dx_ver_1.12.7.zip > temp.txt > > Does python have string matching routines that would find the bottom > listed zip file and/or file copying routines? > > A little pointer or two would be much appreciated. > > Thanks, > > jh You could just use string slicing to cut off the first 7 characters and have the numbers available to compare. There's also the os.stat module to find the last modified date of the file. You might be able to use the glob module to grab a list of the files and then sort the list too. Mike From gagsl-py2 at yahoo.com.ar Sun Apr 15 17:52:25 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sun, 15 Apr 2007 18:52:25 -0300 Subject: Any Pythonistas in Mexico? References: <1176386191.990363.112350@y80g2000hsf.googlegroups.com> Message-ID: En Thu, 12 Apr 2007 10:56:32 -0300, Marcpp escribi?: > On 12 abr, 09:41, Hugo Gonz?lez Monteverde wrote: >> Le? este mail viej?simo en una lista. Yo uso Python y tambi?n quer?a >> saber qui?n pythoneaba en M?xico. Todav?a est?s por ah?? > > Yo vivo en Espa?a. Yo en Argentina. Hay un grupo comp.lang.python.general.castellano y su correspondiente lista, no se si habr? alguien de Mexico ahi. -- Gabriel Genellina From steven.bethard at gmail.com Fri Apr 13 17:41:24 2007 From: steven.bethard at gmail.com (Steven Bethard) Date: Fri, 13 Apr 2007 15:41:24 -0600 Subject: vocab question In-Reply-To: References: Message-ID: James Stroud wrote: > Alan G Isaac wrote: >> According to the Reference Manual, >> a class defintion has the structure:: >> >> classdef ::= "class" classname [inheritance] ":" suite >> >> What is the entire part before the suite called? >> (Just pointing to a reference is fine & helpful, >> as long as its not an entire course on BNF.) > > Signature? That's the best suggestion I've heard so far... STeVe From daniele.varrazzo at gmail.com Tue Apr 3 10:42:49 2007 From: daniele.varrazzo at gmail.com (Daniele Varrazzo) Date: 3 Apr 2007 07:42:49 -0700 Subject: Finding and copying files with python. In-Reply-To: <1175608048.094777.183660@l77g2000hsb.googlegroups.com> References: <1175606497.896681.119490@l77g2000hsb.googlegroups.com> <1175607107.690245.145130@l77g2000hsb.googlegroups.com> <1175608048.094777.183660@l77g2000hsb.googlegroups.com> Message-ID: <1175611369.046859.194730@p77g2000hsh.googlegroups.com> > > > I wish to copy the highest version number of a file from directory \ > > > \ > > > \fileserver\D:\scripts to C:\scripts where the file names are of the > > > form > > > > filename_MM.NN.SS.zip, where MM, NN, and SS can be one to three > > > digits. > > > > Example directory: > > > other.zip > > > dx_ver_1.1.63.zip > > > dx_ver_1.2.01.zip > > > dx_ver_1.12.7.zip > > > temp.txt > > > > Does python have string matching routines that would find the bottom > > > listed zip file and/or file copying routines? > > You could just use string slicing to cut off the first 7 characters > > and have the numbers available to compare. There's also the os.stat > > module to find the last modified date of the file. You might be able > > to use the glob module to grab a list of the files and then sort the > > list too. Comparing the version strings is not enough: you have to convert the parts into integers, because else: >>> "dx_ver_1.12.7.zip" < "dx_ver_1.2.1.zip" True > Thanks for posting folks. I didn't make my question clear. Before I > sort the files I need to ensure that I am only sorting the files that > match the profile of "filename_MM.NN.SS.zip", where MM, NN, and SS can > be one to three > digits. Match the file names against the pattern "dx_ver_(\d+).(\d+).(\d +).zip". You may also use the glob function, but then you will have to parse the version number from the file name anyway: with the regexp you can use match.groups() to get the version number. You can do: import re ver_re = re.compile(r"dx_ver_(\d+).(\d+).(\d+).zip") def getVer(fn): """Return a *comparable* file version, None for bad file names""" m = ver_re.match(fn) return m and map(int, m.groups()) print sorted(os.listdir('/path/to/wherever'), key=getVer)[-1] --Daniele P.S. I guess in Obfuscated Python one would write something like: >>> print sorted((pair for pair in ((re.match(r"dx_ver_(\d+).(\d+).(\d+).zip", fn), fn) for fn in os.listdir('/path/to/wherever')) if pair[0]), key=lambda _: map(int, _[0].groups()))[-1][1] dx_ver_1.12.7.zip From cam.ac.uk at mh391.invalid Fri Apr 13 20:15:50 2007 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Sat, 14 Apr 2007 01:15:50 +0100 Subject: Portably generating infinity and NaN In-Reply-To: References: <462008d1$0$11763$9b622d9e@news.freenet.de> Message-ID: skip at pobox.com wrote: > >> (Note the absence of a demonstration on Windows.) Can't the above be > >> blessed as the One True Way and wormed around in floatmodule.c for > >> those platforms where float'ing "NaN" or "Inf" doesn't currently > >> work? > > Martin> How would you do the worming-around? > > I don't know. On I was just asking. On unixoid systems I sort of assume > you could add tests to the configure script to detect what worked. If > converting the strings works you're done. If not, maybe Robert Kern's numpy > code could be run in the configure script to generate constants for NaN and > Inf that could be used in floatmodule.c. Windows would probably have to be > hard-coded, but except for 32-bit and 64-bit differences it should be the > same all over, yes? If you're going to change CPython to do this, I think adopting PEP 754, and using the fpconst module would be better than changing how float() works when called on string literals. The only thing I don't like about it is the camelcasing of the functions. http://www.python.org/dev/peps/pep-0754/ -- Michael Hoffman From paddy3118 at googlemail.com Mon Apr 16 16:02:03 2007 From: paddy3118 at googlemail.com (Paddy) Date: 16 Apr 2007 13:02:03 -0700 Subject: Compare regular expressions In-Reply-To: References: Message-ID: <1176753723.382697.268430@y80g2000hsf.googlegroups.com> On Apr 16, 10:50 am, Thomas Dybdahl Ahle wrote: > Hi, I'm writing a program with a large data stream to which modules can > connect using regular expressions. > > Now I'd like to not have to test all expressions every time I get a line, > as most of the time, one of them having a match means none of the others > can have so. > > But ofcource there are also cases where a regular expression can > "contain" another expression, like in: > "^strange line (\w+) and (\w+)$" and "^strange line (\w+) (?:.*?)$" in > which case I'd like to first test the seccond and only if it mathces test > the seccond. > > Do anybody know if such a test is possible? > if exp0.contains(exp1): ... you could OR all the individual RE's test them all at once then find out which matched. big_re = "|".join( r"(?P<__match_%i__>%s)" % (i, r) for i,r in enumerate(regexps) ) now if one of the regexps matches then the corresponding named group should have a non-empty string value. - Paddy. From python at hope.cz Thu Apr 26 05:09:43 2007 From: python at hope.cz (Johny) Date: 26 Apr 2007 02:09:43 -0700 Subject: How to find complementary colour for pixel Message-ID: <1177578583.205643.65200@r35g2000prh.googlegroups.com> I use PIL to write some text to a picture.The text must be seen wery clearly. I write the text to different pictures but to the same position. As pictures maybe different, colour, in the position where I write the text, is also different. Is there a way how to set the font colour so that it will be seen very clearly in the picture? For example, if the picture is bright ( for example yellow), the font colour should be dark( e.g. black) and vice versa. Is there a routine in PIL available that calculates complementary colour for RGB pixel format? Can anyone help? Thanks L. From Glich.Glich at googlemail.com Thu Apr 26 11:45:31 2007 From: Glich.Glich at googlemail.com (Glich) Date: 26 Apr 2007 08:45:31 -0700 Subject: SPE Message-ID: <1177602331.523239.54930@b40g2000prd.googlegroups.com> Is SPE open source? I want to try to implement a windows compiler into the GUI using py2exe. thanks! -Glich From rowen at cesmail.net Fri Apr 27 18:26:58 2007 From: rowen at cesmail.net (Russell E. Owen) Date: Fri, 27 Apr 2007 15:26:58 -0700 Subject: Which are your favorite UML tools? References: <463265f0$0$19018$426a34cc@news.free.fr> Message-ID: In article <463265f0$0$19018$426a34cc at news.free.fr>, Bruno Desthuilliers wrote: > Anastasios Hatzis a ??crit : > > Hello, > > > > I'm working on the light-weight MDA tool pyswarm, > > http://pyswarm.sourceforge.net/ (it is about a code-generator for > > Python/PostgreSQL-based software. I plan to add support of UML CASE tools > > other than the one supported currently. > > > > I would like to learn which UML tools you use (if any), > > Any piece of paper and anything that can be used to write on it. > > > preferrably if it > > comes to modeling a Python application. > > I stll wait for UML to be able to describe common hi-level dynamic > languages idioms and patterns without requiring more space and time than > source code. I am inclined to agree, though my experience is limited. I work on a project that is trying to model all its software using Enterprise Architect. EA has some nice features, but overall I find it clumsy and frustrating. Some problems are intrinsic to UML (for instance it has no concept of linking use case information to other elements). And I don't know of any way to model functions (only classes). Others are EA's fault. For instance it is very slow and clumsy to add or edit lists of items (such as class methods or database fields). Also, shared development is a pain because there is no concurrent version control (it uses CVS to keep track of revisions, but not in a concurrent way; checking out a package locks out everybody else). I tried using a competing product but the interporability was terrible. Which brings up another point: it is likely the original poster would need to do a lot of work for each CASE tool supported. -- Russell From antroy at gmail.com Fri Apr 27 04:15:58 2007 From: antroy at gmail.com (Ant) Date: 27 Apr 2007 01:15:58 -0700 Subject: List objects are un-hashable In-Reply-To: <1177660237.470851.170200@s33g2000prh.googlegroups.com> References: <1177660237.470851.170200@s33g2000prh.googlegroups.com> Message-ID: <1177661758.725027.101430@r30g2000prh.googlegroups.com> > for line in inp: > lines +=1 > # a list of words > tempwords = line.split(None) > if keyword.iskeyword(tempwords): > print tempwords You are trying here to ask if a list of words (tempwords) is a keyword. The error is due to the implementation of the iskeyword function which converts the keyword list into a frozenset (in which elements must be hashable) for, I presume, performance reasons: >>> f_set = frozenset((1,2,3,4)) >>> ["test"] in f_set Traceback (most recent call last): File "", line 1, in TypeError: list objects are unhashable What you want is something like: for line in inp: lines +=1 # a list of words tempwords = line.split() for k in tempwords: if keyword.iskeyword(k): print tempwords Which iterates over each word in your tempwords list in turn. Note though the following: >>> if(True):print"Hey!" ... Hey! >>> s = 'if(True):print"Hey!"' >>> s.split() ['if(True):print"Hey!"'] Which may be a problem for you if you are trying to parse badly spaced python source files! From SuperM at ssiveBlackHoleAtTheCenterOfTheMilkyWayGalaxy.org Tue Apr 24 19:51:08 2007 From: SuperM at ssiveBlackHoleAtTheCenterOfTheMilkyWayGalaxy.org (SuperM) Date: Tue, 24 Apr 2007 16:51:08 -0700 Subject: *** Watch BOMBSHELL video of Senator John Kerry admitting 911 was in INSIDE JOB ??? References: <1177387965.127809.175390@l77g2000hsb.googlegroups.com> Message-ID: On 23 Apr 2007 21:12:45 -0700, lemnitzer at india.com Gave us: >Senator John Kerry was questioned You're an idiot, and so is Kerry. From PlankensteinC at stle.sci Wed Apr 4 21:31:19 2007 From: PlankensteinC at stle.sci (Dr. V I Plankenstein) Date: Wed, 4 Apr 2007 20:31:19 -0500 Subject: Over a billion people believe Allah will provide 72 virgins to some Muslims. References: <1175713650.228538.165920@p77g2000hsh.googlegroups.com> Message-ID: <5oWdnfYyjuySzonbnZ2dnUVZ_oSnnZ2d@comcast.com> > I am surprised at the number of un-informed, ill-informed sheeple on > earth as well as politically correct hypocrites. > > Several polls have consistently shown that about 84% of the American > people believe that 911 was an inside job. I dont know where you got that statistic - unless maybe your polling was limited to members of the Aryan Brotherhood, Knights of the KKK or some other loonie outfit. In other words, there are no such polls which indicate that 911 was as you say - an "inside job". The anthrax attack was almost certainly carried out by someone who had access to Gov labs or other secure facilities, but the attack on WTC was an act of Islamic fanaticism, and you're an ass to suggest otherwise without having some very solid proof to back your ridiculous claims - which you lack. From bjourne at gmail.com Sat Apr 14 23:29:01 2007 From: bjourne at gmail.com (=?ISO-8859-1?Q?BJ=F6rn_Lindqvist?=) Date: Sun, 15 Apr 2007 05:29:01 +0200 Subject: function with list argument defaulting to [] - what's going on here??? In-Reply-To: References: <46217e8f$0$19437$4c368faf@roadrunner.com> Message-ID: <740c3aec0704142029q1892b1edl729f86b6c7c3bd2e@mail.gmail.com> > This comes up so often that I wonder whether Python should issue a warning > when it sees [] or {} as a default argument. > > > What do people think? A misuse or good use of warnings? I think Python should reevaluate the default values. -- mvh Bj?rn From irstas at gmail.com Mon Apr 2 10:59:40 2007 From: irstas at gmail.com (irstas at gmail.com) Date: 2 Apr 2007 07:59:40 -0700 Subject: Problem with global variables In-Reply-To: <57ciafF2cf6qdU1@mid.individual.net> References: <1311u48bqkehk24@corp.supernews.com> <57ciafF2cf6qdU1@mid.individual.net> Message-ID: <1175525980.281735.202210@o5g2000hsb.googlegroups.com> On Apr 2, 5:29 pm, Bjoern Schliessmann wrote: > Laurent Pointal wrote: > > And so the solution to add "global foo" before using it. > > Didn't you read his final question? > > | All of a sudden, tiny() can see the global variable "foo". Very > | confusing! Why is it that tiny() sometimes can, and sometimes > | can't, see the global variable "foo"? > > I have no explanation for this, but I'm interested in one, too. > > Regards, > > Bj?rn Laurent Pointal did explain this. "foo" is considered to be a local variable (scope limited to the function) if it's being assigned to in a function and there's no "global foo" statement. So even the "foo" before the actual assignment will refer to the local variable. But the local variable hasn't been assigned yet at that point and an exception is thrown. Yes, one could have a perfectly working function, then add an innocent-looking assignment statement at the very end of the function, and suddenly you'd get an exception thrown at the beginning of the function where that variable is used - Far away from the place where the modification was made. Why does it work like this? Couldn't it be somehow more uniform or less surprising? Well, if one had to define "global foo" even when one were to just read the variable foo, that'd be a pain in the ass. You'd have to use "global math" to use math module in a function and "global anotherFunction" to call anotherFunction, and so on. There's plenty of stuff in the global scope that you don't normally assign to. Another option would be to scrap "global" keyword and let "foo = bar" do an assignment to the global variable if a global variable named "foo" exists, but create (or assign) to a function local variable if it doesn't exist. That'd work but programming would be horrible. Now you'd have to know all the symbols that exist at the global scope, because if you accidentally accessed a global variable instead of local, your function would probably have undesirable side-effects. Now, name clashes could be solved with a naming convention (which could be enforced at the language level). It could be possible that all accesses to global scope would have to be prefixed by some symbol like $. E.g. "$foo = 4; foo = 6" where former assigns to global foo, latter to local foo. That's one option that might work and be somewhat readable.. But not a good tradeoff IMO, considering how rarely global assignment is needed and how often global variables are read. A remaining option is to use different operator for assignment and initialization. So you'd have to do e.g. "a := 4; a = 7". I'm not sure Pythonistas would prefer this either, although many other languages choose this route (through lets or declarations typically). From C.delete_this.Sanders at BoM.GOv.AU Tue Apr 17 02:34:10 2007 From: C.delete_this.Sanders at BoM.GOv.AU (Charles Sanders) Date: Tue, 17 Apr 2007 16:34:10 +1000 Subject: strange behaviour sys.argv In-Reply-To: <1176781699.486440.213770@l77g2000hsb.googlegroups.com> References: <1176772070.349541.80890@y5g2000hsa.googlegroups.com> <46243841$0$75690$c30e37c6@lon-reader.news.telstra.net> <1176781699.486440.213770@l77g2000hsb.googlegroups.com> Message-ID: <46246a63$0$75691$c30e37c6@lon-reader.news.telstra.net> schnupfy wrote: > > ok, thanks for the answers. I try to hand over the 3rd part (the long > trap) as one cmd argument. I will ask in a shell ng. Thanks again. > > Cheers Should be as simple as removing the backslashes /root/mk/services.py $HOST $SEVERITY "$TRAP" should pass TRAP as a single arg Charles From eknowles at gmail.com Fri Apr 6 15:59:59 2007 From: eknowles at gmail.com (eknowles at gmail.com) Date: 6 Apr 2007 12:59:59 -0700 Subject: HTML Parser in python In-Reply-To: <1175882709.295125.289820@y66g2000hsf.googlegroups.com> References: <1175882709.295125.289820@y66g2000hsf.googlegroups.com> Message-ID: <1175889599.501608.194510@l77g2000hsb.googlegroups.com> Beautiful Soup. http://www.crummy.com/software/BeautifulSoup/ Works, well...beautifully. From afaNOSPAM at neuf.fr Sat Apr 14 17:49:39 2007 From: afaNOSPAM at neuf.fr (Amaury Forgeot d'Arc) Date: Sat, 14 Apr 2007 23:49:39 +0200 Subject: wx and SOAPpy interaction In-Reply-To: <7KSdndOfrr1uQYPbnZ2dnUVZ_vmqnZ2d@comcast.com> References: <7KSdndOfrr1uQYPbnZ2dnUVZ_vmqnZ2d@comcast.com> Message-ID: alf a ?crit : > Hi, > > there is problem when I import (python 2.4) wx and SOAPpy at the same > time. I narrowed the problem to following (on Linux): > > >>import wx > >>import pyexpat > > Traceback (most recent call last): > File "", line 1, in ? > ImportError: > /apps/public/python_2.4.4/lib/python2.4/lib-dynload/pyexpat.so: > undefined symbol: XML_StopParser > > > any insight? It seems that the process is trying to load two versions of the "expat" XML library: http://mail.python.org/pipermail/python-list/2006-April/377070.html The problem is that wxWidgets embeds its own copy of expat. You may have to recompile either python or wxWidgets so that they use the same expat version. -- Amaury Forgeot d'Arc From gandalf at designaproduct.biz Wed Apr 4 15:30:51 2007 From: gandalf at designaproduct.biz (Laszlo Nagy) Date: Wed, 04 Apr 2007 21:30:51 +0200 Subject: calling super() In-Reply-To: <1175714555.413502.77390@o5g2000hsb.googlegroups.com> References: <1175714555.413502.77390@o5g2000hsb.googlegroups.com> Message-ID: <4613FCEB.1070709@designaproduct.biz> > And here's the error message I get: > > Traceback (most recent call last): > File "e:/PyEN/inherit.py", line 16, in > N = NewPage(); > File "e:/PyEN/inherit.py", line 12, in __init__ > super(NewPage, self).__init__(); > TypeError: super() argument 1 must be type, not classobj > Super works correctly for new-style classes only. Try to inherit from "object". class HTMLMain(object): Best, Laszlo From grahn+nntp at snipabacken.dyndns.org Fri Apr 13 06:54:18 2007 From: grahn+nntp at snipabacken.dyndns.org (Jorgen Grahn) Date: 13 Apr 2007 10:54:18 GMT Subject: Shebang or Hashbang for modules or not? References: <1176308951.932721.197630@y80g2000hsf.googlegroups.com> <461d56e9$0$27586$426a74cc@news.free.fr> Message-ID: On Thu, 12 Apr 2007 00:24:12 +0200, Bruno Desthuilliers wrote: > Chris Lasher a ?crit : >> Should a Python module not intended to be executed have shebang/ >> hashbang (e.g., "#!/usr/bin/env python") or not? > > The shebang is only useful for files that you want to make directly > executable on a *n*x system. They are useless on Windows, Probably (unless setup.py uses them for something meaningful there, too). But of course often you don't know that the file will always be used only on Windows, or that the Windows user won't prefer Cygwin. > and not > technically required to use the file as a main program -ie: you can > always run it like this: > $ /path/to/python filename.py You can, but sometimes it's not appropriate. If you distribute a Python program to Unix users in that form, they may not want to know or care which language it's written in. Especially if you decide, a few releases later, that you want to switch to Perl or something. I realise that you took a more narrow view than I do above, so please see this as additional notes rather than critisism. It's just that I am struggling with people at work who feel program names should encode whatever language they happen to be written in, and so I am a bit oversensitive ... >> I'm used to having a >> shebang in every .py file > > An encoding declaration might be more useful IMHO !-) They are not mutually exclusive, if that is what you mean. I always use both. /Jorgen -- // Jorgen Grahn R'lyeh wgah'nagl fhtagn! From bbxx789_05ss at yahoo.com Wed Apr 4 13:05:00 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: 4 Apr 2007 10:05:00 -0700 Subject: how to remove multiple occurrences of a string within a list? In-Reply-To: References: <1175624433.206953.214290@n59g2000hsh.googlegroups.com> <1175626905.957243.301870@w1g2000hsg.googlegroups.com> <1175637235.783612.45980@o5g2000hsb.googlegroups.com> <1175673563.212459.322290@y66g2000hsf.googlegroups.com> Message-ID: <1175706300.560513.113150@y80g2000hsf.googlegroups.com> On Apr 4, 3:08 am, Steven D'Aprano wrote: > On Wed, 04 Apr 2007 00:59:23 -0700, 7stud wrote: > > On Apr 3, 3:53 pm, "bahoo" wrote: > >> > target = "0024" > >> > l = ["0024", "haha", "0024"] > > >> > for index, val in enumerate(l): > >> > if val==target: > >> > del l[index] > > >> > print l > > >> This latter suggestion (with the for loop) seems to be buggy: if there > >> are multiple items in the list "l" equal to "target", then only the > >> first one will be removed! > > >> Thanks anyways. > > > Prove it. > > Try replacing l = ["0024", "haha", "0024"] > with > > l = ["0024", "0024", "haha"] > > and re-running the code. > > Actually, the description of the bug isn't quite right. The behaviour of > the for loop isn't defined -- sometimes it will work, sometimes it won't, > depending on how many items there are, and which of them are equal to the > target. > Thank you for the explanation. From iansan at gmail.com Fri Apr 6 19:19:56 2007 From: iansan at gmail.com (IamIan) Date: 6 Apr 2007 16:19:56 -0700 Subject: 08 and 09 in sequence create "invalid token" error?! In-Reply-To: References: <1175900482.804005.256900@l77g2000hsb.googlegroups.com> Message-ID: <1175901596.515469.8990@p77g2000hsh.googlegroups.com> Thank you! Ian From robert.rawlins at thinkbluemedia.co.uk Wed Apr 18 10:31:33 2007 From: robert.rawlins at thinkbluemedia.co.uk (Robert Rawlins - Think Blue) Date: Wed, 18 Apr 2007 15:31:33 +0100 Subject: Signals In-Reply-To: <1176900171.3424.16.camel@dot.uniqsys.com> References: <002001c7818c$af280ab0$0d782010$@rawlins@thinkbluemedia.co.uk> <1176900171.3424.16.camel@dot.uniqsys.com> Message-ID: <004f01c781c6$45e80610$d1b81230$@rawlins@thinkbluemedia.co.uk> Thanks Carsten, Sorry for not mentioning the dbus before, I thought that the signals were a general python thing, I didn?t realize it was a specific dbus thing. I've now modified the code so it looks like this. #!/usr/bin/python import dbus from gobject import MainLoop, idle_add from dbus.mainloop.glib import DBusGMainLoop def main_function(): bus = dbus.SystemBus() manager = dbus.Interface(bus.get_object('org.bluez', '/org/bluez'),'org.bluez.Manager') adapter = dbus.Interface(bus.get_object('org.bluez', manager.DefaultAdapter()),'org.bluez.Adapter') def remote_device_found(addr, class_, rssi): print 'Found:', addr adapter.connect_to_signal('RemoteDeviceFound', remote_device_found) adapter.DiscoverDevices() if __name__ == '__main__': idle_add(main_function) dbus_mainloop_wrapper = DBusGMainLoop(set_as_default=True) mainloop = MainLoop() mainloop.run() Which should implement the main loop and keep the application alive, however when running the program I get the following error thrown at me. File "./scan4.py", line 5, in ? from dbus.mainloop.glib import DBusGMainLoop ImportError: No module named mainloop.glib Any ideas what might be causing this? My guess is that I don?t have one of the dependency installed properly, but I have no idea which ones I need. Thanks for any more help you can offer, its greatly appreciated. Rob -----Original Message----- From: Carsten Haese [mailto:carsten at uniqsys.com] Sent: 18 April 2007 13:43 To: Robert Rawlins - Think Blue Cc: python-list at python.org Subject: Re: Signals On Wed, 2007-04-18 at 08:39 +0100, Robert Rawlins - Think Blue wrote: > Hello Chaps, > > > > I posted about this the other day but I?m still struggling to get any > form of result from it. Basically I have the following piece of code, > and according to its API is produces singals when particular events > occur, but i have no idea how to list for events, I?ve tried all sorts > of combinations using the signal module but haven?t been able to get > it working. > [...] > import dbus, signal > [...] > > Now here is a copy of the API documentation that lists the signals > thrown by the API, this is the one I?m trying to listen for. > > > > void RemoteDeviceFound(string address, uint32 class, int16 > rssi) > > > > This signal will be send every time an inquiry result > > has been found by the service daemon. In general they > > only appear during a device discovery. > > > > Basically I?m just looking to run a function that will print those > details to screen. Can anyone help with working out how to listen for > this signal? The signal module is for handling process signals the operating system sends to your python process. The API you're using (dbus, a crucial detail you neglected to mention before) doesn't send this kind of signal. Googling for 'python dbus documentation' brings up http://dbus.freedesktop.org/doc/dbus-python/api/ , which seems to explain everything you need. You need to get an instance of dbus.Interface, which you seem to have done, and call its connect_to_signal() method, which you don't seem to have done. > I?d also like to know how i can keep the application running until I > decided to stop it manually, as the DiscoverDevices() can take a while > to complete and send out several RemoteDeviceFound() signals in that > period. The very first section of the above mentioned documentation talks about needing a main loop for receiving signals, and it provides example boilerplate code for how to set up a main loop. Hope this helps, Carsten. From sai438 at gmail.com Thu Apr 5 05:19:34 2007 From: sai438 at gmail.com (sairam) Date: 5 Apr 2007 02:19:34 -0700 Subject: Can we make a local variable in a function as global variable??? Message-ID: <1175764774.260576.286420@y66g2000hsf.googlegroups.com> I have some local variables defined in one method and Can I make those variables as global variables? If so , can any one explain me how can I do that Thanks, Sairam From gagsl-py2 at yahoo.com.ar Tue Apr 10 10:35:39 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 10 Apr 2007 11:35:39 -0300 Subject: Breaking up Strings correctly: References: <1176175701.971632.164360@l77g2000hsb.googlegroups.com> <000d01c77b61$2ee32230$0d7d12ac@kearfott.com> Message-ID: En Tue, 10 Apr 2007 08:12:53 -0300, Michael Yanowitz escribi?: > I guess what I was looking for was something simpler than parsing. > I may actually use some of what you posted. But I am hoping that > if given a string such as: > '((($IP = "127.1.2.3") AND ($AX < 15)) OR (($IP = "127.1.2.4") AND ($AY > != > 0)))' > something like split(), where I can pass it something like [' AND ', ' > OR > ', ' XOR '] > will split the string by AND, OR, or XOR. > BUT split it up in such a way to preserve the parentheses order, so > that > it will > split on the outermost parenthesis. > So that the above string becomes: > ['OR', '(($IP = "127.1.2.3") AND ($AX < 15))', '(($IP = "127.1.2.4") AND > ($AY != 0))'] > No need to do this recursively, I can repeat the process, however if I > wish on each > string in the list and get: > ['OR', ['AND', '($IP = "127.1.2.3")', '($AX < 15)'], ['AND', '($IP = > "127.1.2.4")', '($AY != 0)']] > > Can this be done without parsers? This is exactly what parsers do. Sure, it can be done without using a preexistent general parser, but you'll be writing your own specialized one by hand. > Perhaps with some variation of re or > split. Regular expressions cannot represent arbitrary expressions like yours (simply because they're not regular). If you know beforehand that all input has some fixed form, like "condition AND condition OR condition AND condition", or at least a finite set of fixed forms, it could be done with many re's. But I think it's much more work than using PyParsing or similar tools. If you have some bizarre constraints (parserphobia?) or for whatever reason don't want to use such tools, the infix evaluator posted yesterday by Gerard Flanagan could be an alternative (it only uses standard modules). > Has something like this already been written? Yes, hundreds of times since programmable computers exist: they're known as "lexers" and "parsers" :) -- Gabriel Genellina From sam_spam_cat at verizon.net Mon Apr 23 18:13:18 2007 From: sam_spam_cat at verizon.net (Sam the Cat) Date: Mon, 23 Apr 2007 22:13:18 GMT Subject: Python and Javascript equivalence References: Message-ID: <2caXh.1653$1M1.577@trnddc01> >> >> I am writing some COM code in Python to control photoshop. Several >> functions of PS require an "Array" argument. In the examples of VBscript >> or javascript the Array type is used. I have tried what would appear to >> be the equivalent in Python -- Lists and Tuples -- but to no avail. >> Anyone have any insight on what via the COM interface is equivalent to >> an Array in javascript ? >> > > The nest way to approach an answer to your question would be for you to > post a VB snippet from one of the examples together with your attempt to > do the same thing in Python plus the error traceback (or other such > messages as you may see) generated when your attempts fails. > > Otherwise the question is just a bit too broad to give an answer. > > regards > Steve > -- > Here is the Javascript example code ..... selRegion = Array(Array(1,1),Array(1,2),Array(2,2),Array(2,1)) Doc.Selection.Select(selRegion,1,0,0) ..... Here is my interpretation in Python ....... selregion = [(1,1),(1,2),(2,2),(2,1)] print selregion doc.Selection.Select(selregion,1,0,0) ...... Here is the error code generated .......... F:\automation>test2.py [(1, 1), (1, 2), (2, 2), (2, 1)] Traceback (most recent call last): File "F:\automation\test2.py", line 19, in ? doc.Selection.Select(selregion,1,0,0) File ">", line 3, in Select pywintypes.com_error: (-2147352567, 'Exception occurred.', (0, 'Adobe Photoshop', 'Illegal argument - argument 1\n- Only arrays with dimension 1 are supported', None, 0, -2147220262), None) ............ From deets at nospam.web.de Sat Apr 14 13:25:22 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sat, 14 Apr 2007 19:25:22 +0200 Subject: ctypes and pointers Message-ID: <58ch42F2fnojeU1@mid.uni-berlin.de> Hi, I'm working under mac os x with the OpenCV-library that I load via ctypes. From a ObjectiveC-methodcall I get an integer, that "really" is a pointer to an IplImage-structure. I've got a function that takes such a pointer. But I don't find a way to pass it to that very function. These are the relevant parts of my code: cvImage = self._f.cvImage() print "Address of IplImage: %x" % cvImage cvImage = c_void_p(cvImage) print cvImage cvImage2 = macopencv.cvCloneImage(cvImage) The output is 2007-04-14 19:22:53.910 SequenceGrabberTest[5320] Returning IplImage at Address of IplImage: e860c60 e860c60 c_void_p(243666016) 2007-04-14 19:22:53.915 SequenceGrabberTest[5320] Exception raised during posting of notification. Ignored. exception: exceptions.ValueError: depythonifying 'pointer', got 'int' The first line is actually from the ObjectivC-method, a log-statement. As one can see, the pointer is passed back as integer. But then I'm stuck. Any suggestions would be appreciated! diez From utabintarbo at gmail.com Tue Apr 17 14:18:59 2007 From: utabintarbo at gmail.com (utabintarbo) Date: 17 Apr 2007 11:18:59 -0700 Subject: ??? POLICE AND CITY/UNIVERSITY OFFICIALS INCOMPETENCE LEADS TO 33 KILLED BY KOREAN-ALQAEDA TERRORIST ??? In-Reply-To: <1176820374.597357.315110@b75g2000hsg.googlegroups.com> References: <1176818165.135834.214220@y80g2000hsf.googlegroups.com> <1176820374.597357.315110@b75g2000hsg.googlegroups.com> Message-ID: <1176833939.948693.128300@o5g2000hsb.googlegroups.com> On Apr 17, 10:32 am, Muhammad wrote: > On Apr 17, 7:56 am, therm... at india.com wrote: >> - > You mentioned "Korean Al-Qaeda Terrorist" in the title! Honesty > demands that you establish it as a fact that the person was connected > to Al-Qaeda and that he was a terrorist and not some mentally sick > fellow. > Muhammad Just do it in a more appropriate forum, mmmkay? From steve at holdenweb.com Sat Apr 28 14:27:36 2007 From: steve at holdenweb.com (Steve Holden) Date: Sat, 28 Apr 2007 14:27:36 -0400 Subject: Cgi File Upload without Form In-Reply-To: <1177708242.553577.226530@n15g2000prd.googlegroups.com> References: <1177708242.553577.226530@n15g2000prd.googlegroups.com> Message-ID: <46339218.6090108@holdenweb.com> Karsten.G.Weinert at googlemail.com wrote: > Hello, > > what is the simplest way to upload a file (or a long string) to a > server using cgi/python? > > Since I want to upload the data programmatically, a form based > solution is not good. I am not experienced with SOAP/WSDL and I > believe that would be more difficult than necessary. The client > program I have to use does not support FTP. > A "form-based" solution is actually just what you want - you write a Python program that does just what the user's browser would do after they filled in a form. You can do this with urllib fairly easily. If you get stuck then look for a library called mechanise. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden ------------------ Asciimercial --------------------- Get Python in your .sig and on the web. Blog and lens holdenweb.blogspot.com squidoo.com/pythonology tag items: del.icio.us/steve.holden/python All these services currently offer free registration! -------------- Thank You for Reading ---------------- From marco at waven.com Fri Apr 6 00:21:53 2007 From: marco at waven.com (Marco) Date: Fri, 6 Apr 2007 12:21:53 +0800 Subject: communication between two classes which in different threading In-Reply-To: <5c62a320704051905k1f0c514fuf79ff3ebe109ae99@mail.gmail.com> References: <5c62a320704051905k1f0c514fuf79ff3ebe109ae99@mail.gmail.com> Message-ID: <5c62a320704052121p26ece47eo34863cb906a12501@mail.gmail.com> Yes, use signal/slot could reslove this question! On 4/6/07, Marco wrote: > Hello, > > I write two class, which one is Gui(PyQt4) other is socket server. I > wanna: if socket recv() something, Gui will show it in a label. > But it seems that I cannot call the func from other threading. How to > reslove it? > > Thank you! > > > -- > LinuX Power > -- LinuX Power From slm_guzel at hotmail.com Tue Apr 10 16:59:43 2007 From: slm_guzel at hotmail.com (gslm) Date: 10 Apr 2007 13:59:43 -0700 Subject: Please help!!! In-Reply-To: <1176236179.443346.162070@h3g2000cwc.googlegroups.com> References: <1176234239.436463.195870@n33g2000cwc.googlegroups.com> <1176236179.443346.162070@h3g2000cwc.googlegroups.com> Message-ID: <1176238783.257926.67310@30g2000cwc.googlegroups.com> On 10 Nisan, 23:16, "Paul McGuire" wrote: > On Apr 10, 2:43 pm, "gslm" wrote: > > > In fact ? know this, but I asked some questions like this, but ? haven't get any answer.And I thought that may be it could be better to use a header like this for help.Sorry! > > > Hi to all! > > I want to do a calendar with pictures near months. > > I have designed the form's view.But unfortunately, I am not be able to > > save this view as an image file.And so I am not be able to print this > > image file too. > > Question: > > How can I determine the coordinates of a button?Namely How can I use > > the comand ImageGrab for this purpose? > > > But only I wan to get the button's ares.Because my applicationis on > > this. > > > Or if it's possible, how can I print the area of this button with the > > components on it? > > > Thanks... > > Suggestion 1: "Please help!!!" is just about the worst newsgroup > subject line there is (other than those related to government > conspiracies or earthquake prediction). You are unlikely to attract > the attention of those who really know anything - they are quite busy > and must husband their time carefully. Instead, you'll get those who > are idly curious, to see what sort of junk is floating about Usenet. > > Suggestion 2: Consider your audience. What the heck are you talking > about?! Your post goes on about calendars and buttons and views. In > fact, trying to make sense of your post, it sounds like you've done > something truly bizarre, like making the whole view one giant button > with lots of images on it, and you want to print it out when the > "button" is clicked. Is this even a Python question? Any particular > GUI package you are using, such as Tk, wxPython, QT, your own homebrew > invention? ImageGrab? Sounds promising, what do the docs say? > > A more thorough discussion of these suggestions:http://www.catb.org/~esr/faqs/smart-questions.html > > -- Paul- Al?nt?y? gizle - > > - Al?nt?y? g?ster - From rafaelc at dcc.ufmg.br Sat Apr 7 04:22:39 2007 From: rafaelc at dcc.ufmg.br (Rafael Almeida) Date: Sat, 7 Apr 2007 05:22:39 -0300 Subject: Understanding Python's interpreter References: <20070407032024.bb27f5ee.rafaelc@dcc.ufmg.br> Message-ID: <20070407052239.38f9b21e.rafaelc@dcc.ufmg.br> On Sat, 07 Apr 2007 04:35:49 +0200 Gabriel Genellina wrote: > Speed? Eficiency? File size? Ease of use? > A .pyc *could* be written in ASCII, but what do you gain? Replacing a > few trivial functions in the Python core with a printf/scanf equivalent? > At the same time you lose a lot of speed, so I don't see the point. Hm, I didn't realise that it would be that much slower. > Why harder? Once you read the file, they're just numbers. Anyway, being > harder to program the *interpreter* is not a problem, if you gain > something like speed or eficiency for the interpreted language. Well, it's harder to get 4 bytes and create an int out of it in a portable way than just call strtol or scanf, that's what I thought while I was coding my interpreter. It's not the hardest thing to do, of course, but it made me wonder why not just do the simplest thing. Since I've never seen a .pyc bigger than a few kilobytes, I thought an ascii file would take more space, but it wouldn't be anything really prohibitive. I didn't think using strtol would make that much difference in speed. But now you talked about it, and after thinking a little bit more about it, I'm convinced that the speed difference may be relevant. > > And when I tried to code an assembler my problems got greater, as I > > wanted to code it in python (the interpreter was in C++) and I had a > > hard time trying to figure out how I would print something that's not a > > ascii or unicode string. As for the benefits, I couldn't figure out any. > > Sorry, I could not understand what you said here. It's not anything important, I was just saying that I had to write a little more code to make an integer such as 0xff into '\0\0\0\377' than it would need to just print the integer. Well, unless there's already a python function that does just that and I didn't know about. It's was just an example on how writting in ascii is easier. From robert.rawlins at thinkbluemedia.co.uk Wed Apr 25 03:56:28 2007 From: robert.rawlins at thinkbluemedia.co.uk (Robert Rawlins - Think Blue) Date: Wed, 25 Apr 2007 08:56:28 +0100 Subject: popen2 results Message-ID: <000601c7870f$3b0a52e0$b11ef8a0$@rawlins@thinkbluemedia.co.uk> Hello guys, I've recently ported my application from bash to python, however there are still a few bash line utilities I -have- to use in the application as there isn't any alternative available to me. In the old days of bash I would have grep'd the output from these commands to determine the outcome. I'm now using popen2 to run the command which works a charm, but I'm struggling to parse the results of the function, has anyone had any experience with this? I've found a few suggested solutions dotted around, such as this one. import os def filtered(command, source): dest, result = os.popen2(command) dest.write(source) dest.close() try: return result.read() finally: result.close() But to be honest I'm struggling to get it to do anything as it doesn't states what the 'source' object is or should be. Thanks for any help guys, I'm just looking to capture the output from the command and then I can go about a little REGEX on it. Thanks, Rob -------------- next part -------------- An HTML attachment was scrubbed... URL: From yossi.kreinin at gmail.com Sun Apr 1 03:39:49 2007 From: yossi.kreinin at gmail.com (yossi.kreinin at gmail.com) Date: 1 Apr 2007 00:39:49 -0700 Subject: saving Python process state for later debugging In-Reply-To: <1175382476.172386.97370@q75g2000hsh.googlegroups.com> References: <1175352493.387046.32510@q75g2000hsh.googlegroups.com> <1175382476.172386.97370@q75g2000hsh.googlegroups.com> Message-ID: <1175413189.156480.149640@o5g2000hsb.googlegroups.com> On Apr 1, 2:07 am, "aspineux" wrote: > > Pylon has something like that.http://pylonshq.com/docs/0.9.4.1/interactive_debugger.html > > Turbogears has the same with option tg.fancy_exception > I could get it wrong, but these things seem to be about debugging crashed processes "online", not saving snapshots to files for later inspection. Can you e-mail a process snapshot to a different machine with them, for example? I understood that you are supposed to debug the original process, which is kept alive, via the web. I'm talking about a situation where you have a Python program deployed to a user who is not running a web server, and have the user send you a snapshot as a bug report. -- Yossi From andrew.veitch at yahoo.co.uk Fri Apr 20 15:58:02 2007 From: andrew.veitch at yahoo.co.uk (Andrew Veitch) Date: Fri, 20 Apr 2007 20:58:02 +0100 (BST) Subject: Domain Keys in Python In-Reply-To: <979299.95854.qm@web27101.mail.ukl.yahoo.com> Message-ID: <361415.48206.qm@web27114.mail.ukl.yahoo.com> --- Andrew Veitch wrote: > In Perl I would just use Crypt:RSA which has a sign > method with an armour option which generates exactly > what I want but I can't find a way of doing this in > Python. I've worked it out, just for the archives the answer is: import base64 from M2Crypto import RSA key = RSA.load_key('rsa.private') msg='Hello world' print base64.b64encode(key.sign(msg)) I will publish my DomainKey implementation shortly. A From ptmcg at austin.rr.com Tue Apr 10 15:53:05 2007 From: ptmcg at austin.rr.com (Paul McGuire) Date: 10 Apr 2007 12:53:05 -0700 Subject: OT: Question about RGB color method In-Reply-To: <461be63b$0$31839$c3e8da3@news.astraweb.com> References: <461be63b$0$31839$c3e8da3@news.astraweb.com> Message-ID: <1176234785.473773.181840@s48g2000cws.googlegroups.com> On Apr 10, 2:32 pm, John Salerno wrote: > Sorry for this non-Python question, but since it's computer related I > know you guys will have an answer, and I don't really know where else to > ask. Mainly I'm just curious anyway. > > I'm wondering, why do computers use a RGB color scheme instead of the > primary colors? Is there something you can't do with yellow? It seems > weird that RGB can be combined to make all colors, when that's supposed > to be the job of the primary colors. I'm sure there some technical > computer-related reason that it had to be this way. > > Thanks. See this link: http://www.rgbworld.com/color.html The "red-yellow-blue" system we used in elementary school art classes corresponded to the color mixing capabilities available using the Tempra paint technology at hand. At the RGBworld URL, the web page shows how paints and inks follow a "subtractive" color system (called CMY for cyan-magenta-yellow, instead of blue-red-yellow, but close enough), in that paint reflects a given color by subtracting out all frequencies that are not that color. So mixing two subtractive filters follows a subtractive color "algebra". However, computer monitors do not follow a substractive scheme, but rather an additive one, by adding brightness along red-green-and-blue (RGB) dimensions, mixing red and green light to get yellow. This raises an interesting problem when *printing* a color image. You cannot just render the RGB colors from the monitor's additive system into CMY colors on your inkjet printer's subtractive system. Google for "RGB color" and you will be presented with a long list of references for dealing with this issue, including several competing standards on how to handle it. Even the Wikipedia article on RGB colors is largely devoted to this issue (as opposed to your more common question). -- Paul From bearophileHUGS at lycos.com Sun Apr 15 18:44:47 2007 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 15 Apr 2007 15:44:47 -0700 Subject: Making a tree out of a 2 column list In-Reply-To: References: <1176568327.669229.22910@b75g2000hsg.googlegroups.com> Message-ID: <1176677087.151276.223580@b75g2000hsg.googlegroups.com> Sebastian Bassi: > I guess this should make the program enter into a endless loop. But > the data won't have such a redundancy, because it was taken from a > philogenetic tree. But errors and bugs do happen, inside data too; so often it's better to be on safe side if the safe code is fast enough. Bye, bearophile From aisaac at american.edu Mon Apr 30 10:20:55 2007 From: aisaac at american.edu (Alan Isaac) Date: Mon, 30 Apr 2007 14:20:55 GMT Subject: relative import broken? References: <1hxa9x3.c0unyd1jw7vu9N%aleax@mac.com> <1hxcdkq.47p2r6beuctcN%aleax@mac.com> Message-ID: "Alex Martelli" wrote in message news:1hxcdkq.47p2r6beuctcN%aleax at mac.com... > To me, it makes sense: if a module is top-level, and thus not part of a > package (and __main__ in particular is always in that state), then > saying "import from the current package" has no well defined meaning, > because there IS no "current package". Thanks for the explanations. I do not have an opinion because I have not really thought this through. One of the things I was hoping for, however, was for a less hackish way for scripts bundled with a package to access the package modules. That is, suppose I have directory ``mypackage`` with subdirectory ``scripts``. What is the pretty way for the scripts to access ``mypackage`` without assuming ``mypackage`` is in ``sys.path``? Thanks, Alan Isaac From phil at riverbankcomputing.co.uk Fri Apr 6 04:18:12 2007 From: phil at riverbankcomputing.co.uk (Phil Thompson) Date: Fri, 6 Apr 2007 09:18:12 +0100 Subject: Freeze vs cx_Freeze In-Reply-To: <1175846910.468253.271490@q75g2000hsh.googlegroups.com> References: <1175846910.468253.271490@q75g2000hsh.googlegroups.com> Message-ID: <200704060918.12764.phil@riverbankcomputing.co.uk> On Friday 06 April 2007 9:08 am, mathieu wrote: > Hello, > > I am currently investigating how to distribute a python based > application on a targeted linux system (debian) and so far I only > found two options: > - Freeze (shipped with python dist) > - cx_Freeze (*) > > As far as I understand those two options are very close. According to > the cx_Freeze README cx_Freeze is simply easier to use (no dependencie > of gcc, faster to create binaries) and it is cross-platform (no > interest for me in this case). > > Anything else ? http://pyinstaller.python-hosting.com/ Phil From gagsl-py2 at yahoo.com.ar Mon Apr 23 03:08:08 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 23 Apr 2007 04:08:08 -0300 Subject: Support for new items in set type References: <1177211624.069474.3960@y5g2000hsa.googlegroups.com> <1hwxx1e.1un7urc1de872aN%aleax@mac.com> <1177305469.398817.80600@y80g2000hsf.googlegroups.com> Message-ID: En Mon, 23 Apr 2007 02:17:49 -0300, Prateek escribi?: > Oh dear god, I implemented this and it overall killed performance by > about 50% - 100%. The same script (entering 3000 items) takes between > 88 - 109s (it was running in 55s earlier). > > Here is the new Set implementation: > class SeaSet(set): [...] > The surprising thing is that commits *ARE* running about 50% faster > (according to the time column in the hotshot profiler). But, now, the > longest running operations seem to be the I/O operations which are > taking 10 times longer! (even if they're only reading or writing a few > bytes. Could this have something to do with the set implementation > being in Python as opposed to C? Hard to tell - you have posted only your SeaSet implementation, and no I/O is involved in that code. > For instance, this method: > def __readTableHeader(self, f): > hdr = f.read(sz__TABLE_HEADER_FORMAT__) > if len(hdr) < sz__TABLE_HEADER_FORMAT__: > raise EOFError > t = THF_U(hdr) > #t = unpack(__TABLE_HEADER_FORMAT__, hdr) > return t > > is now taking > 13s when it was taking less than 0.8s before! (same > number of calls, nothing changed except the set implementation) I don't see where your SeaSet class is used. -- Gabriel Genellina From king_of_bellmund at bluewin.ch Mon Apr 9 16:20:48 2007 From: king_of_bellmund at bluewin.ch (Marco) Date: Mon, 9 Apr 2007 22:20:48 +0200 Subject: install wxPython Message-ID: Hi, I have a problem to install wxPython on my MacBook (Pythonversion 2.5). If would install the wxPython (python setup.py install), then I got this error: Traceback (most recent call last): File "/Users/marco/Desktop/flexo1/wxpython/wxPython-src-2.8.3.0/ wxPython/setup.py", line 49, in copy_file('config.py', 'wx/build', update=1, verbose=1) File "/Users/marco/python//lib/python2.5/distutils/file_util.py", line 119, in copy_file "can't copy '%s': doesn't exist or not a regular file" % src distutils.errors.DistutilsFileError: can't copy 'config.py': doesn't exist or not a regular file Where is the problem and how could i fix it? Thx for your answers. marco From bbxx789_05ss at yahoo.com Wed Apr 11 15:10:15 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: 11 Apr 2007 12:10:15 -0700 Subject: pop() clarification In-Reply-To: References: Message-ID: <1176318615.056436.47430@y5g2000hsa.googlegroups.com> On Apr 11, 10:44 am, "Scott" wrote: > As said before I'm new to programming, and I need in depth explaination to > understand everything the way I want to know it, call it a personality quirk > ;p. > > With pop() you remove the last element of a list and return its value: > > Now I know list is a bad name, but for the sake of arguement lets assume its > not a built in sequence> > > >>>list = ['this', 'is', 'an', 'example'] > >>>list.pop() > 'example' > >>>list > > ['this', 'is', 'an'] > > I understand all that. What I don't understand is why all the documentation > I see says, "When removing a specific element from a list using pop() it > must be in this format: list.pop([i]). > At first I took that to mean that list.pop(i) would return some type of > error, but it doesn't. It's understandable that the definition of pop() is confusing in that way. It looks like the argument should be a list. As others have said, that is not what the brackets mean when the documents show the formal definition of a function. A clearer example might be a function definition that requires some mandatory arguments and has some optional arguments: dict.get(key[, default]) That shows that the get() function requires one mandatory argument "key" and that you can also send it one optional argument "default". If a function were to require a list as an argument, it's definition would be written something like this: somefunc(aList) -- where 'aList' is a list of integers From martin at v.loewis.de Wed Apr 18 15:30:18 2007 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Wed, 18 Apr 2007 21:30:18 +0200 Subject: unicode data - accessing codepoints > FFFF on narrow python builts In-Reply-To: References: Message-ID: <462671ca$0$22126$9b622d9e@news.freenet.de> > Is it a bug in unicodedata, or is this the expected behaviour on a > narrow build? It's a bug. It should either raise an exception, or return the correct result. If you know feel like submitting a bug report: please try to come up with a patch instead. > Another problem I have is to access the "characters" and their > properties by the respective codepoints: under FFFF it is possible, > to use unichr(), which isn't valid for higher valules on a narrow > build It is possible to derive the codepoint from the surrogate pair, > which would be usable also for wider codepoints. See PEP 261. This is by design. > Currently, I'm using a kind of parallel database for some unicode > ranges above FFFF, but I don't think, this is the most effective way. Just use a wide Unicode build instead. Regards, Martin From jstroud at mbi.ucla.edu Mon Apr 30 23:25:53 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Mon, 30 Apr 2007 20:25:53 -0700 Subject: Master's Thesis Help Needed In-Reply-To: <1177975197.557114.46700@o5g2000hsb.googlegroups.com> References: <1177898031.790447.253360@n76g2000hsh.googlegroups.com> <1hxcqfn.11m7qp91766nc4N%aleax@mac.com> <1177975197.557114.46700@o5g2000hsb.googlegroups.com> Message-ID: RobJ wrote: > On Apr 30, 12:00 am, a... at mac.com (Alex Martelli) wrote: > >>RobJ wrote: >> >>>http://pyschool.robj.webfactional.com/ >> >>Things start on a pretty bad note when I'm asked to select my OS: >>Ubuntu Linux >>Windows XP >> >>I'm running MacOSX. What now? Why is there no choice "none of the >>above"...?! >> >>Alex > > > Alex, > > Sorry about that. I'll add on to the front page what 2 OSs are > available.. During my pre-work for my project I did a survey and > WindowsWP and Ubuntu Linux came up as the top two OSs. > > Rob J > I guess you didn't filter on which ones sucked? From rganesan at myrealbox.com Wed Apr 4 08:14:56 2007 From: rganesan at myrealbox.com (Ganesan Rajagopal) Date: Wed, 04 Apr 2007 17:44:56 +0530 Subject: Pexpect: SSH, Command and Password References: <1175685883.565899.282450@q75g2000hsh.googlegroups.com> Message-ID: >>>>> "Gil" == Gil H writes: > class SSH: > def __init__(self, user, password, host): > self.child = pexpect.spawn("ssh %s@%s"%(user, host)) Try adding the following line here self.child.logfile = sys.stdout That should give you some clue. Ganesan -- Ganesan Rajagopal From bruno.42.desthuilliers at wtf.websiteburo.oops.com Fri Apr 27 06:47:23 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Fri, 27 Apr 2007 12:47:23 +0200 Subject: My python annoyances so far In-Reply-To: References: <1177541453.471959.120830@c18g2000prb.googlegroups.com> <59bf34F2k27v5U1@mid.individual.net> <1177603623.774892.230390@t38g2000prd.googlegroups.com> Message-ID: <4631d499$0$23165$426a74cc@news.free.fr> Marc 'BlackJack' Rintsch a ?crit : > In , Steven Howe > wrote: > >> And before someone get's all technical, I know everything in Python is >> an 'object' even None, which implies class, or is it the other way around? > > Objects don't imply classes. There are object oriented languages without > classes like the Io language. Everything there is an object and the base > object has a `clone()` method to make a copy. So you make copies of > objects and modify them to tweak them into the way you want them. And FWIW, in Python, classes are objects too, and are attributes of their instances. Which makes Python quite close to prototype-based languages like Io, Self or Javascript. From bruno.42.desthuilliers at wtf.websiteburo.oops.com Wed Apr 11 03:05:41 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Wed, 11 Apr 2007 09:05:41 +0200 Subject: Does python have the static function member like C++ In-Reply-To: <1176260903.362329.59370@o5g2000hsb.googlegroups.com> References: <1176260903.362329.59370@o5g2000hsb.googlegroups.com> Message-ID: <461c8869$0$24812$426a74cc@news.free.fr> ??????????????? a ?crit : > I define the class like this: > class AAA: > counter = 0 > def __init__(self): > pass > def counter_increase(): > AAA.counter += 1 > print "couter now :", AAA.counter You probably want something like this: class AAA(object): _counter = 0 @classmethod def increase_counter(cls): cls._counter += 1 print "%s._counter is now %d" % (cls.__name__, cls._counter) > But how could I call the function "counter_incrrease" ? With the above correction, you can call it eiter on the class or on an instance: AAA.increase_counter() aaa = AAA() aaa.increase_counter() HTH From sts at mmk.at Thu Apr 12 11:18:11 2007 From: sts at mmk.at (=?UTF-8?B?U3RlZmFuIFNjaHfDpHJ6bGVy?=) Date: Thu, 12 Apr 2007 17:18:11 +0200 Subject: PyX in Console and Script IDE Message-ID: Hi NG, i'm hanging with following problem in python: i have installed PyX to generate eps in python. in console-mode (call python in shell) there are no problem. calling pyx via python-script i got the following error (in a python ide f.e. wing2.0): ImportError: No module named _pykpathsea Have i forgot a path? From carsten at uniqsys.com Mon Apr 9 09:08:26 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Mon, 09 Apr 2007 09:08:26 -0400 Subject: tuples, index method, Python's design In-Reply-To: References: <1175867771.114540.61810@n76g2000hsh.googlegroups.com> <1175884427.779950.267220@y80g2000hsf.googlegroups.com> <1175953520.316208.241490@o5g2000hsb.googlegroups.com> <7xzm5igbrb.fsf@ruckus.brouhaha.com> <7x8xd2iq53.fsf@ruckus.brouhaha.com> Message-ID: <1176124106.3534.24.camel@dot.uniqsys.com> On Mon, 2007-04-09 at 11:50 +1000, Steven D'Aprano wrote: > On Sun, 08 Apr 2007 20:10:21 -0400, Carsten Haese wrote: > > Will tuples also get a sort method? What about append and extend? pop? > > __iadd__? __delslice__? > > Since tuples are immutable, no. > [...] > > If you see tuples as an immutable list, having an index method is quite > useful. If you see them as structs, an index method is useless. Let's recall what GvR said: """ For tuples, I suspect such a function would rarely be used; I think that is most cases where x.index() would be useful, x is generally a list, whose contents varies in time, rather than a tuple (which cannot change easily). """ In Guido's opinion, it's not the "structness" of tuples that negates the need for tuple.index, it's their inability to be mutated easily. So Guido seems to disagree with your notion that an index method is quite useful for immutable lists. I won't presume to speak for Guido, but if I had to connect the dots between "tuples are immutable" and "tuples will rarely need an index method", I'd do it like this: Consider an object X and a tuple T. Tuples have "X in T" tests, so you can check if there exists some N such that T[N]==X. The lack of the index method means you won't know the value of N, but what would knowing N give you? You can't modify T, so all you can do is read T[N], but you already know that that's going to return X, so you might as well just use X. Any use case for actually having to know N would have to involve an operation where you end up explicitly using an index other than N, such as slicing T from 0 to N-1, or looking at T[2*N] or something like that. Of course such operations might be useful, but algorithms that need an operation like that would self-document their design more clearly by using a list instead of a tuple. I hope this explains at least to some people how this seemingly gratuitous inconsistency can actually be viewed as a justified design decision. -Carsten From bbxx789_05ss at yahoo.com Sun Apr 15 06:50:41 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: 15 Apr 2007 03:50:41 -0700 Subject: Python editor/IDE on Linux? In-Reply-To: <1176626030.729710.321520@d57g2000hsg.googlegroups.com> References: <1176575715.649316.130430@n76g2000hsh.googlegroups.com> <1176626030.729710.321520@d57g2000hsg.googlegroups.com> Message-ID: <1176634241.244351.41990@b75g2000hsg.googlegroups.com> On Apr 15, 2:33 am, "Daniel Gee" wrote: > > anything more than line > numbering, simple syntax highlighting, and auto-indent when you hit > enter just doesn't seem necessary. Vim has b and c, but not a. > a: :set nu :set nonu From kar1107 at gmail.com Mon Apr 16 13:57:00 2007 From: kar1107 at gmail.com (Karthik Gurusamy) Date: 16 Apr 2007 10:57:00 -0700 Subject: Compare regular expressions In-Reply-To: References: Message-ID: <1176746220.503947.167520@b75g2000hsg.googlegroups.com> On Apr 16, 2:50 am, Thomas Dybdahl Ahle wrote: > Hi, I'm writing a program with a large data stream to which modules can > connect using regular expressions. > > Now I'd like to not have to test all expressions every time I get a line, > as most of the time, one of them having a match means none of the others > can have so. > > But ofcource there are also cases where a regular expression can > "contain" another expression, like in: > "^strange line (\w+) and (\w+)$" and "^strange line (\w+) (?:.*?)$" in > which case I'd like to first test the seccond and only if it mathces test > the seccond. > > Do anybody know if such a test is possible? > if exp0.contains(exp1): ... What you want is finding if R2 is a superset of R1 for two given regular languages R1 and R2. I know of some methods for finding intersection of two regular languages; and I think the time/space complexity is big. So the simple answer is it is not feasible to provide such support for two generic r.e.s without a large time/space usage. You may consult any of the math/theory groups for more insights. If you know already R2 >= R1 (that is you precompute and remember), then it's a trivial to skip checking for R1 if R2 turned up negative. You can even arrange all the Rs in a binary tree like fashion and skip checking a whole subtree if the sub-tree's root node gave negative for r.e. match. Karthik From gagsl-py2 at yahoo.com.ar Tue Apr 17 19:27:06 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 17 Apr 2007 20:27:06 -0300 Subject: Screen Control in WinXP and Linux References: <1176847598.832345.220270@b75g2000hsg.googlegroups.com> Message-ID: En Tue, 17 Apr 2007 19:06:38 -0300, peter escribi?: > I've been wrestling on and off with this problem for over a year now, > without success. Basically, I am looking for a simple set of screen > and keyboard manipulation commands that will run identically under > Linux and Windows. Nothing fancy - just clear the screen, print a > string at an arbitrary xy position and detect a keystroke. I've > googled around this newsgroup and elsewhere, and come across various > suggestions (and even posted my own partial solutions), but still > haven't come up with an elegant solution. What about curses (Linux) and Console (XP)? You could wrap just the bits needed for your application in a more-or-less generic way. -- Gabriel Genellina From justin.mailinglists at gmail.com Wed Apr 11 22:51:04 2007 From: justin.mailinglists at gmail.com (Justin Ezequiel) Date: 11 Apr 2007 19:51:04 -0700 Subject: python newbie beautifulSoup question In-Reply-To: References: Message-ID: <1176346264.708905.245820@e65g2000hsc.googlegroups.com> On Apr 12, 4:15 am, Jon Crump wrote: > Is it possible to feed findAll() a list of tags WITH attributes? >>> BeautifulSoup.__version__ '3.0.3' >>> s = '''\nboo\nhello\nboo\nhi\n''' >>> soup = BeautifulSoup.BeautifulSoup(s) >>> def func(tag): ... if tag.name not in ('y', 'z'): return False ... if tag.name=='y': return tag.get('a')=='foo' ... return tag.get('a')=='foo' and tag.get('b')=='bar' ... >>> soup.findAll(func) [hello, hi] >>> def get_func(lst): ... def func(tag): ... for name, attrs in lst: ... if tag.name==name: ... for k, v in attrs.items(): ... if tag.get(k, None)==v: continue ... else: return False ... else: return True ... else: return False ... return func ... >>> func2 = get_func([('y', {'a': 'foo'}), ('z', {'b': 'bar', 'a': 'foo'})]) >>> soup.findAll(func2) [hello, hi] >>> From martin at v.loewis.de Fri Apr 20 20:12:30 2007 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sat, 21 Apr 2007 02:12:30 +0200 Subject: service for file monitoring In-Reply-To: <1177103856.200965.139840@b75g2000hsg.googlegroups.com> References: <1177099611.498274.323180@y5g2000hsa.googlegroups.com> <1177103856.200965.139840@b75g2000hsg.googlegroups.com> Message-ID: <462956EE.9000503@v.loewis.de> > well i tried reading that but that way i'll have to make the program > monitor each and every directory. > when a file is created or deleted or filename modified , a call must > be made to the os kernel . > isn't there any way i can utilize that with any api or package > functions so that i can monitor the whole filesystem but at lesser > expense of cpu n memory On Windows W2k+, you can use the USN journal: http://msdn2.microsoft.com/en-us/library/aa364586.aspx You may have to use ctypes or write an extension module to access that journal. Regards, Martin From wojciech_mula at poczta.null.onet.pl.invalid Fri Apr 6 19:15:01 2007 From: wojciech_mula at poczta.null.onet.pl.invalid (=?ISO-8859-2?Q?Wojciech_Mu=B3a?=) Date: Sat, 07 Apr 2007 01:15:01 +0200 Subject: 08 and 09 in sequence create "invalid token" error?! In-Reply-To: <1175900482.804005.256900@l77g2000hsb.googlegroups.com> References: <1175900482.804005.256900@l77g2000hsb.googlegroups.com> Message-ID: IamIan wrote: > I am confused as to why including 08 or 09 in a sequence (list or > tuple) causes this error. All other numbers with a leading zero work. All literals that start with "0" digit are considered as octal numbers, i.e. only digits "0".."7" are allowed. See octinteger lexical definition: http://docs.python.org/ref/integers.html w. From wswilson at gmail.com Sun Apr 1 21:56:05 2007 From: wswilson at gmail.com (wswilson) Date: 1 Apr 2007 18:56:05 -0700 Subject: can a method access/set another's variables? In-Reply-To: References: <1175477764.549115.159410@n59g2000hsh.googlegroups.com> Message-ID: <1175478965.803665.15040@o5g2000hsb.googlegroups.com> On Apr 1, 9:43 pm, Michael Hoffman wrote: > asdf1234234 wrote: > > -a.py- > > import b > > > class A: > > def __init__(self): > > pass > > def my_method(self): > > var = 1 > > self.var = 2 > > b.set_var(self) > > print var > > print self.var > > > my_a = A() > > my_a.my_method() > > > -b.py- > > def set_var(self): > > var = 2 > > self.var = 2 > > > I want both var and self.var to be 2 at the end. Is there anything I > > can pass to set_var() that will give it access to the variables in > > my_method() like I can use self for the variables in the class A? > > I hope there isn't a way to do this that simply. :) Why do you want to > do this, or is it idle curiosity? There is almost surely a better way to > solve your underlying problem. > > You can *read* your caller's local variables (either pass locals() as an > argument or use inspect to get the frame locals), but writing to this > dictionary has undefined behavior. > -- > Michael Hoffman I am parsing a document which contains some lines with code I want to eval or exec. However, due to the complexity of the parsing, I am splitting it among different methods. So, if I eval something in one method, it won't be there if I try to access its value a few lines later since I happen to be in a different method in the parser. Thanks for the help! From clajo04 at mac.com Thu Apr 5 16:33:37 2007 From: clajo04 at mac.com (John Clark) Date: Thu, 5 Apr 2007 16:33:37 -0400 Subject: grandparent method with super In-Reply-To: <20070405161939.694d51a1@localhost> References: <20070405161939.694d51a1@localhost> Message-ID: <01b701c777c1$b37a2af0$fefea8c0@haengma> Pretty sure you can do this: class A(object): def m(self): class B(A): def m(self): class C(A): def m(self): class D(B,C): def m(self): A.m(self) I don't think you want to try to use super() in this case. -jdc -----Original Message----- From: python-list-bounces+clajo04=mac.com at python.org [mailto:python-list-bounces+clajo04=mac.com at python.org] On Behalf Of Martin Manns Sent: Thursday, April 05, 2007 4:20 PM To: python-list at python.org Subject: grandparent method with super Hi, I have a class structure as follows and I would like to invoke the method A.m() from D.m class A(object): def m(self): class B(A): def m(self): class C(A): def m(self): class D(B,C): def m(self): # Call A.m with super? I have read http://www.python.org/download/releases/2.2/descrintro/ but I am still stuck. Thanks in advance Martin -- http://mail.python.org/mailman/listinfo/python-list From ianare at gmail.com Wed Apr 4 02:27:28 2007 From: ianare at gmail.com (=?iso-8859-1?B?aWFuYXLp?=) Date: 3 Apr 2007 23:27:28 -0700 Subject: only loading a language installed on system Message-ID: <1175668048.344217.185780@n76g2000hsh.googlegroups.com> i'm doing this: mylocale = wx.Locale(wx.LANGUAGE_POLISH, wx.LOCALE_LOAD_DEFAULT) if not wx.Locale.IsOk(mylocale): mylocale = wx.Locale(wx.LANGUAGE_DEFAULT, wx.LOCALE_LOAD_DEFAULT) and getting this: Segmentation fault (core dumped) I'm trying to see if I can properly load a language. If the system will not load it, then use system default. What am I doing wrong? TIA From ptmcg at austin.rr.com Mon Apr 16 13:28:25 2007 From: ptmcg at austin.rr.com (Paul McGuire) Date: 16 Apr 2007 10:28:25 -0700 Subject: script for seconds in given month? In-Reply-To: <1176740556.859125.221980@l77g2000hsb.googlegroups.com> References: <1176740556.859125.221980@l77g2000hsb.googlegroups.com> Message-ID: <1176744505.863580.182390@e65g2000hsc.googlegroups.com> On Apr 16, 11:22 am, "edfialk" wrote: > Hi, does anyone happen to know of a script that would return the > number of seconds in a month if I give it a month and a year? > > My python is a little weak, but if anyone could offer some suggestions > I think I could handle it myself, or if anyone happens to know of a > script already written that performs this I would be extremely > grateful. > > Thanks! > -Ed Do you need to handle leap seconds too? (not a joke) -- Paul From jackson at hotmail.com Thu Apr 26 00:59:32 2007 From: jackson at hotmail.com (Bill Jackson) Date: Wed, 25 Apr 2007 21:59:32 -0700 Subject: Preferred Random Library Message-ID: Is there a preferred random library? scipy.random random Besides scipy's library returning ndarrays, is there any other advantage/disadvantage? From 80xuuxk02 at sneakemail.com Fri Apr 6 06:11:26 2007 From: 80xuuxk02 at sneakemail.com (Lucas Malor) Date: 6 Apr 2007 10:11:26 -0000 Subject: [optparse] Problem with getting an option value Message-ID: <20122-46107@sneakemail.com> Hello all. I'm trying to do a little script. Simply I want to make a list of all options with them default values. If the option is not specified in the command line, the script must try to read it in a config.ini file. If it's not present also there, it must set the default value. The problem is I maked a simple list for this: optname = [ [ "delete", False ], [ "file", "file" ], [ "dir", "" ], But I must check that the option was specified in command line: (options, args) = parser.parse_args() for opt in optname : if not options.opt[0] : # read the options from config.ini The problem is options is an instance, so options."delete", for example, is wrong; I should pass options.delete . How can I do? -------------------------------------- Protect yourself from spam, use http://sneakemail.com From ptmcg at austin.rr.com Thu Apr 26 03:40:21 2007 From: ptmcg at austin.rr.com (Paul McGuire) Date: 26 Apr 2007 00:40:21 -0700 Subject: Python not giving free memory back to the os get's me in real problems ... In-Reply-To: <1177510121.882503.145560@n15g2000prd.googlegroups.com> References: <1177510121.882503.145560@n15g2000prd.googlegroups.com> Message-ID: <1177573221.052806.190470@r35g2000prh.googlegroups.com> You might try looking at references between objects, especially if there are any cyclic refs. For instance, if you have a data structure in which child nodes have back refs to their parents, try changing these to use weakref's. This may help the garbage collector to better reclaim discarded objects, so that not so many will need to be held in memory. -- Paul From lew at nospam.lewscanon.com Wed Apr 4 18:37:24 2007 From: lew at nospam.lewscanon.com (Lew) Date: Wed, 04 Apr 2007 18:37:24 -0400 Subject: Requirements For A Visualization Software System For 2010 In-Reply-To: <1175714617.095757.162510@y80g2000hsf.googlegroups.com> References: <1175628186.459945.290750@d57g2000hsg.googlegroups.com> <1175714617.095757.162510@y80g2000hsf.googlegroups.com> Message-ID: galathaea wrote: > On Apr 3, 12:23 pm, "Xah Lee" wrote: > [top posting for clarity] You mean to reduce clarity. Please do not top-post - instead, trim the post and respond in line. It makes the messages easier for the rest of us. -- Lew From nagle at animats.com Sun Apr 1 14:44:59 2007 From: nagle at animats.com (John Nagle) Date: Sun, 01 Apr 2007 18:44:59 GMT Subject: Character set woes with binary data In-Reply-To: References: <1175415685.21349.79.camel@pepper.trausch.us> Message-ID: Michael B. Trausch wrote: > In short: How do I create a string that contains raw binary content > without Python caring? Is that possible? Given where we're now at with strings in Python, Python should really have a "byte" type and a way to deal with arrays of bytes, independent of the string operators. Efficient handling of lists of bytes would do it. John Nagle From uzi18 at o2.pl Mon Apr 30 17:08:30 2007 From: uzi18 at o2.pl (Bart) Date: Mon, 30 Apr 2007 23:08:30 +0200 Subject: removing module Message-ID: <46365ACE.2070207@o2.pl> I have static linked module in application plugin. Thirst thing how to remove this module from memory after Py_Finalize(); Because there is segfault after - deactivate,activate this plugin. PyImport_AppendInittab("module_name",init_module_name); Py_Initialize(); How to check what provides this module ? import sys print sys.modules (is loaded?) dir(module_name) is it enough? Thanks for Help. Bart. From QncyMI at netscape.net Sat Apr 28 16:50:19 2007 From: QncyMI at netscape.net (Major Quaternion Dirt Quantum) Date: 28 Apr 2007 13:50:19 -0700 Subject: Video: Professor of Physics Phd at Cal Tech says: 911 Inside Job In-Reply-To: <1177792809.503415.182480@o5g2000hsb.googlegroups.com> References: <1177467203.719625.93920@u32g2000prd.googlegroups.com> <1177780530.539758.275660@c35g2000hsg.googlegroups.com> <1177792809.503415.182480@o5g2000hsb.googlegroups.com> Message-ID: <1177793419.474675.156860@y80g2000hsf.googlegroups.com> here's a question that came-up recently, in battling with the controlled-demo advocates at teh Promenade: how is it that the metal was still molten, after weeks? it seems taht an additional hypothesis is required, to explain that. because I doubt that there was sufficient nukular material "left-over" from a hypothetical suitcase-device. there are similar question, from what I recall of Jones' report (I just stopped at the first thing that seemed funny, today .-) publications:http://www.physics.uiowa.edu/~cgrabbe/writing/ research.html > > > demanding of INTELLECTUAL HONESTY. thus: this was basically assuming that floor 50 of a 100-floor building started the collapse?... interesting analysis; I hope to look at it, again, later. have you seen the old analysis by the MIT Head Welder, that I only saw a couple of weeks ago? > At time t=0, the top 50 floors begin to fall, independently of each > other. The first actual impact is when floor 50 hits floor 49. On > impact, those 2 floors fall together with an initial velocity that is > less than that of higher floors due to conservation of momentum. Thus > the next impact will not be floors 50,49 with floor 48 but rather it > will be floor 51 hitting the slower moving 50,49 combo. The 3 floors > 51,50,49 then become a unit. The initial velocity of the new 51,50,49 > combo will be greater than the velocity of the 50-49 combo just before > impact, but still less than that of the floors above (which are still > in free fall). http://www.rwgrayprojects.com/synergetics/plates/figs/plate01.html thus: "Global Warning," an *anonymous* article in an old issue of *National Review*, the so-called conservative mag of the grotesque Establishment creature, William Buckley, was a sort of benignly-spun expose of the Mont Pelerin Society, the vehicle of British imperialist "free trade," free beer & free dumb, whose many "rightwing" affiliate foundations are always in the news. the universally-newspaper-lauded-when- he-died founding president, Mitlon Friedman, used Sir Henry of Kiss.Ass. to conduct their first experiment in Chile, with the help of Augusto Pinochet & Dick Nixon. (the fact that it was an awful failure, with the privatization of Chile's social security, was only recently mention, but only before Uncly Milty died.) I realized, much later, since it was anonymous, that it was probably taken from The Holy Spook Economist, but I haven't checked that hypothesis. yes, "Warning" was meant to evoke "warming," although nowhere mentioned in the article, as I recall; can you say, "emmissions trading schemes," Boys and Girl?... can you say, "hedge funds on out-of-the-way desert islands?..." Just Desserts Island? thus: why do Dick, Borat, Osama, Harry P., Rumsfeld and Tony B. want us to underwrite the 3rd British Invasion of Sudan, so badly? anyway, Bertrand Russel published a jeremyad in the Bulletin of the Atomic Scientists, while the USA was the only thermonukey power, that we should bomb them into the Stone Age; that's your British "pacifist," whether before or after he went nuts because of Godel's proof. thus: if you can't prove that all Fermat numbers are pairwise coprime, again! Darfur 'Mini-Summit' http://www.larouchepub.com/other/1998/rice_2546.html thus: uh yeah; Borat wants you in Sudan, why, Baby?... Harry Potter wants you in Iran -- yeah, Baby; shag'US with a spoon? --DARFURIA CONSISTS OF ARABs & nonARABs; NEWS-ITEM: we are marching to Darfuria, Darfuria, Darfuria! Harry Potter IIX, ?Ordeal @ Oxford//Sudan ^ Aircraft Carrier! http://larouchepub.com/other/2007/3410caymans_hedges.html ALgoreTHEmovieFORpresident.COM: http://larouchepub.com/eirtoc/site_packages/2007/al_gore.html From __peter__ at web.de Mon Apr 23 04:09:46 2007 From: __peter__ at web.de (Peter Otten) Date: Mon, 23 Apr 2007 10:09:46 +0200 Subject: python cgi problem with textarea References: <1177222084.696307.128620@n59g2000hsh.googlegroups.com> Message-ID: Adrian Smith wrote: > ...and I get an internal server error if I have any spaces in the > textarea, which is really going to limit its usefulness to me. Oddly, While debugging you should put > #!/usr/bin/python import cgitb cgitb.enable() > import cgi > print "Content-type: text/html\n" > form = cgi.FieldStorage() > print form["essay"].value at the beginning of your cgi -- just in case the error is in the python script. Peter From ken.carlino at gmail.com Sun Apr 1 17:52:12 2007 From: ken.carlino at gmail.com (ken) Date: 1 Apr 2007 14:52:12 -0700 Subject: Question about using urllib2 to load a url Message-ID: <1175464332.246623.30090@b75g2000hsg.googlegroups.com> Hi, i have the following code to load a url. My question is what if I try to load an invalide url ("http:// www.heise.de/"), will I get an IOException? or it will wait forever? Thanks for any help. opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj)) urllib2.install_opener(opener) txheaders = {'User-agent': 'Mozilla/5.0 (X11; U; Linux i686; en- US; rv:1.8.1.3) Gecko/20070309 Firefox/2.0.0.3'} try: req = Request(url, txdata, txheaders) handle = urlopen(req) except IOError, e: print e print 'Failed to open %s' % url return 0; From gherron at islandtraining.com Fri Apr 6 11:10:49 2007 From: gherron at islandtraining.com (Gary Herron) Date: Fri, 06 Apr 2007 08:10:49 -0700 Subject: How to access multiple group matches? In-Reply-To: <1175869893.960239.194850@p77g2000hsh.googlegroups.com> References: <1175869893.960239.194850@p77g2000hsh.googlegroups.com> Message-ID: <461662F9.9020705@islandtraining.com> Christoph Krammer wrote: > Hello, > > I want to use the re module to split a data stream that consists of > several blocks of data. I use the following code: > > iter = re.finditer('^(HEADER\n.*)+$', data) > > The data variable contains binary data that has the word HEADER in it > in some places and binary data after this word till the next > appearance of header or the end of the file. But if I iterate over > iter, I only get one match and this match only contains one group. How > to access the other matches? Data may contain tens of them. > > Thanks in advance, > Christoph > > Use .*? instead of .* in your regular expression. From the manual page: *|*?|, |+?|, |??|* The "*", "+", and "?" qualifiers are all /greedy/; they match as much text as possible. Sometimes this behaviour isn't desired; if the RE <.*> is matched against |'

title

'|, it will match the entire string, and not just |'

'|. Adding "?" after the qualifier makes it perform the match in /non-greedy/ or /minimal/ fashion; as /few/ characters as possible will be matched. Using .*? in the previous expression will match only |'

'|. Gary Herron From dmbkiwi at gmail.com Sat Apr 7 03:12:11 2007 From: dmbkiwi at gmail.com (dumbkiwi) Date: 7 Apr 2007 00:12:11 -0700 Subject: Convert xml symbol notation In-Reply-To: <1175923387.811717.279580@n76g2000hsh.googlegroups.com> References: <1175899141.354348.207530@q75g2000hsh.googlegroups.com> <1175923387.811717.279580@n76g2000hsh.googlegroups.com> Message-ID: <1175929931.687229.122510@p77g2000hsh.googlegroups.com> On Apr 7, 5:23 pm, "Gabriel Genellina" wrote: > dumbkiwi wrote: > > I'm working on a script to download and parse a web page, and it > > includes xml symbol notation, such as ' for the ' character. Does > > anyone know of a pre-existing python script/lib to convert the xml > > notation back to the actual symbol it represents? > > Try the htmlentitydefs module. Is that a standard module? I can't see it anywhere - googled it. From aahz at pythoncraft.com Sat Apr 7 19:45:41 2007 From: aahz at pythoncraft.com (Aahz) Date: 7 Apr 2007 16:45:41 -0700 Subject: block scope? References: <1hw72cg.115yokgarr9enN%aleax@mac.com> <1hw7kzo.1hepj3c1who5zhN%aleax@mac.com> Message-ID: In article <1hw7kzo.1hepj3c1who5zhN%aleax at mac.com>, Alex Martelli wrote: >Steve Holden wrote: >> >> What do you think the chances are of this being accepted for Python 3.0? >> It is indeed about the most rational approach, though of course it does >> cause problems with dynamic namespaces. > >What problems do you have in mind? The compiler already determines the >set of names that are local variables for a function; all it needs to do >is diagnose an error or warning if the set of names for a nested >function overlaps with that of an outer one. exec? -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Why is this newsgroup different from all other newsgroups? From cam.ac.uk at mh391.invalid Sat Apr 21 09:28:50 2007 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Sat, 21 Apr 2007 14:28:50 +0100 Subject: Suggestion: str.itersplit() In-Reply-To: References: <1177160280.784224.53460@b58g2000hsg.googlegroups.com> Message-ID: Marc 'BlackJack' Rintsch wrote: > In <1177160280.784224.53460 at b58g2000hsg.googlegroups.com>, Dustan wrote: > >> From my searches here, there is no equivalent to java's >> StringTokenizer in python, which seems like a real shame to me. >> >> However, str.split() works just as well, except for the fact that it >> creates it all at one go. I suggest an itersplit be introduced for >> lazy evaluation, if you don't want to take up recourses, and it could >> be used just like java's StringTokenizer. >> >> Comments? > > Does it really make such a difference? It would if you were dealing with enormous blocks of text at once, say from a database. -- Michael Hoffman From basilisk96 at gmail.com Sun Apr 1 00:54:46 2007 From: basilisk96 at gmail.com (Basilisk96) Date: 31 Mar 2007 21:54:46 -0700 Subject: Generic logic/conditional class or library for classification of data Message-ID: <1175403286.809692.100080@n59g2000hsh.googlegroups.com> This topic is difficult to describe in one subject sentence... Has anyone come across the application of the simple statement "if (object1's attributes meet some conditions) then (set object2's attributes to certain outcomes)", where "object1" and "object2" are generic objects, and the "conditions" and "outcomes" are dynamic run- time inputs? Typically, logic code for any application out there is hard-coded. I have been working with Python for a year, and its flexibility is nothing short of amazing. Wouldn't it be possible to have a class or library that can do this sort of dynamic logic? The main application of such code would be for classification algorithms which, based on the attributes of a given object, can classify the object into a scheme. In general, conditions for classification can be complex, sometimes involving a collection of "and", "or", "not" clauses. The simplest outcome would involve simply setting a few attributes of the output object to given values if the input condition is met. So each such "if-then" clause can be viewed as a rule that is custom-defined at runtime. As a very basic example, consider a set of uncategorized objects that have text descriptions associated with them. The objects are some type of tangible product, e.g., books. So the input object has a Description attribute, and the output object (a categorized book) would have some attributes like Discipline, Target audience, etc. Let's say that one such rule is "if ( 'description' contains 'algebra') then ('discipline' = 'math', 'target' = 'student') ". Keep in mind that all these attribute names and their values are not known at design time. Is there one obvious way to do this in Python? Perhaps this is more along the lines of data mining methods? Is there a library with this sort of functionality out there already? Any help will be appreciated. From gabor.urban at siemens.com Mon Apr 2 03:36:49 2007 From: gabor.urban at siemens.com (Urban, Gabor) Date: Mon, 2 Apr 2007 09:36:49 +0200 Subject: IDLE problem Message-ID: <38F58D7B92CB20438DF49D28B572CC6FE3B38A@budgw09a.ww300.siemens.net> Hi, I have a strange problem with the latest 2.4.4 on MS XP. If I rrun a test script in DOS window, it is ok. From the Python shell I got error: Python 2.4.4 (#71, Oct 18 2006, 08:34:43) [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.1.4 >>> ================================ RESTART ================================ >>> ........ ---------------------------------------------------------------------- Ran 8 tests in 0.016s OK Traceback (most recent call last): File "D:\Gabaux\Python\TodoList\datetest.py", line 76, in -toplevel- unittest.main() File "D:\Python24\lib\unittest.py", line 759, in __init__ self.runTests() File "D:\Python24\lib\unittest.py", line 797, in runTests sys.exit(not result.wasSuccessful()) SystemExit: False >>> The script I was executing was a simple unittest.TestCase descendant. Any ideas? Gabor Urban NMC - ART -------------- next part -------------- An HTML attachment was scrubbed... URL: From ptmcg at austin.rr.com Fri Apr 27 11:34:42 2007 From: ptmcg at austin.rr.com (Paul McGuire) Date: 27 Apr 2007 08:34:42 -0700 Subject: My newbie annoyances so far Message-ID: <1177688082.758043.133920@r30g2000prh.googlegroups.com> Python is not VB and Python is not Java and Python is not Ruby and Python is not any other language that is not Python. 1. Functions cannot be called without the parens (like in VB) 2. Python uses some naming conventions as programmer cues, such as leading and trailing double-underscores to indicate some form of specialness (I'm not overfond of relying on naming for this kind of information encoding either, but I got used to it) 3. Python does not use braces to demarcate executable blocks of code, or to define anonymous code blocks (like in Java, Ruby, or Smalltalk) 4. Python does not require every line of code to be enclosed within a class (like in Java or Smalltalk) 5. Python does not do compile-time type checking on function arguments or variable assignments (like in Java or C or C++) (yet... and will it still be Python when it does?) 6. Python does not have interfaces to enforce object type compatibility (like in Java) Just because Python has features that are different from those in your former language X does not mean it is deficient. Python *might* be deficient - ternary expressions are now part of the language after years of refugees from C and C++ asking how to write "a = b ? c : d", and now they'll get to puzzle/gripe over mapping this to "a = c if b else d". But as a newbie, you need to invest a little more time and effort and study and reflection (collectively called "experience") before bandying about lists of personal gripes and reasons why Python is annoying/stupid/sucks. At least in public. Actually, it might be of value to keep your own personal list, and then revisit it a month or a year later and see if the warts are still as offending to your sensibilities as they originally were. Newbies, please try to work with Python as it is for a bit. Ask questions when the documentation is unclear to you or the results of your efforts confound you. But please hold of on the "reasons Python sucks" lists. You might find that these "deficiencies" actually translate into strengths. Despite its warts, Python is being used productively by at least several dozen people around the world, so it must be good for *something*. -- Paul From gregcorradini at gmail.com Fri Apr 6 08:48:32 2007 From: gregcorradini at gmail.com (Greg Corradini) Date: Fri, 6 Apr 2007 05:48:32 -0700 (PDT) Subject: Simple mx.ODBC prob seeks simple answer Message-ID: <9871804.post@talk.nabble.com> Hello all, I'm having trouble inserting an SQL selection into a new MS Access table. I get a parameter error on my insert statement when I try this (see below for code and error msg). I'm not sure if 'insert' or 'update' is the route I should be taking. CODE: #Import Pythond Standard Library Modules import win32com.client, sys, os, string, copy, glob import mx.ODBC.Windows as odbc # Create the Geoprocessor Object gp = win32com.client.Dispatch("esriGeoprocessing.GpDispatch.1") gp.overwriteoutput = 1 # Variables tempspace = "C:\Documents and Settings\corr1gre\Desktop\Workspace\DBFs & Shapefiles\TEST.mdb" workspace = string.replace(tempspace,"\\","/") worksheet1 = "Mower_I" worksheet2 = "Mower_II" #Conection to Access driv = 'DRIVER={Microsoft Access Driver (*.mdb)};DBQ='+workspace conn = odbc.DriverConnect(driv) curse = conn.cursor() #Drop Tables if they already exist try: curse.execute('Drop table Table_I') curse.execute('Drop table Table_II') curse.execute('Drop table Checker') except: pass #Create a New Tables curse.execute('Create table Table_I (TISCODE TEXT(12), EXISTSIN TEXT(4),STATUS TEXT(3),NOTES TEXT(50))') curse.execute('Create table Table_II(TISCODE TEXT(12), EXISTSIN TEXT(4))') curse.execute('Create table Checker (TISCODE TEXT(12), EXISTSIN TEXT(4),STATUS TEXT(3),NOTES TEXT(50))') conn.commit() #Upload DBF 1 as a List of Tuples: Returns tuple as ('1021500000','BMP') sql = 'SELECT TISCODE,EXISTSIN from '+worksheet2 curse.execute(sql) x = curse.fetchall() #Put the fetched Data into Table_II for i in x: curse.execute('Insert into Table_II (TISCODE,EXISTSIN) values (%s,%s)'%(i[0],i[1])) conn.commit() conn.close() TRACEBACK ERROR MSG: Traceback (most recent call last): File "C:/Documents and Settings/corr1gre/Desktop/Workspace/Python/ArcGIS Python/ExistenceChecker and Update/Access Double Checker/Access_SQL.py", line 40, in ? curse.execute('Insert into Table_II (TISCODE,EXISTSIN) values (%s,%s)'%(i[0],i[1])) ProgrammingError: ('07001', -3010, '[Microsoft][ODBC Microsoft Access Driver] Too few parameters. Expected 1.', 4612) -- View this message in context: http://www.nabble.com/Simple-mx.ODBC-prob-seeks-simple-answer-tf3536661.html#a9871804 Sent from the Python - python-list mailing list archive at Nabble.com. From adonis at REMOVETHISearthlink.net Sat Apr 14 16:09:24 2007 From: adonis at REMOVETHISearthlink.net (Adonis Vargas) Date: Sat, 14 Apr 2007 20:09:24 GMT Subject: Minimal Linux system to run Python In-Reply-To: References: Message-ID: Chaz Ginger wrote: > I have a need for the minimal Linux system to run Python. Basically I > want the system to boot up and instead of starting up Init/etc. I would > love it to run python (and a python script I have written). > > Before embarking on doing it myself I was wondering if anyone knew of > just such a system? > > Peace, > Chaz You can also look into Linux From Scratch (LFS) http://www.linuxfromscratch.org/ in which walks you through how to build a Linux OS by picking what you need, as well as it may give you more insight on the inner workings of a Linux system. Hope this helps. Adonis From apardon at forel.vub.ac.be Tue Apr 10 06:39:00 2007 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 10 Apr 2007 10:39:00 GMT Subject: tuples, index method, Python's design References: <1175867771.114540.61810@n76g2000hsh.googlegroups.com> <1175884427.779950.267220@y80g2000hsf.googlegroups.com> <1175953520.316208.241490@o5g2000hsb.googlegroups.com> <7xzm5igbrb.fsf@ruckus.brouhaha.com> <1176200361.260546.280510@n76g2000hsh.googlegroups.com> Message-ID: On 2007-04-10, Paul Boddie wrote: >> Now with implementation and maintaining. If you would start with a class >> of sequence which classes like tuple and list would inherit from, then >> there also would be a single function to be implemented and maintained. >> It would just be usable in more types. > > There isn't a "big win" in this case: the intersection of useful > methods between mutable and immutable sequence types is rather small. > Nevertheless, providing a slightly deeper abstract class hierarchy > might be appropriate, and this is being considered for Python 3000. Well I wasn't trying to show this aspect as a big win. Just illustrating it doesn't have to be a big cost in this case. >> The same happened with the ternary operator. Every use case someone >> could come up with was rejected by rewriting the code without using >> a ternary operator. AFAICS the only reason the ternary operator >> finaly got introduced was because a python developer was bitten by an >> illusive bug, introduced by one of the idioms that was often used as a >> way to simulate a ternary operator. > > The ternary operator, whilst providing new and occasionally useful > functionality, is rather "badly phrased" in my opinion: when used, > it's a bit like reading one natural language and suddenly having the > grammar of another in use for the rest of the sentence. I agree. The structure of the if-expression doesn't resemble the structure of the if-statement. I think it was a bad choice to have the two so dissimilar. -- Antoon Pardon From exarkun at divmod.com Tue Apr 17 11:03:05 2007 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Tue, 17 Apr 2007 11:03:05 -0400 Subject: Queue enhancement suggestion In-Reply-To: Message-ID: <20070417150305.19381.1529761776.divmod.quotient.2453@ohm> On 17 Apr 2007 14:32:01 GMT, Antoon Pardon wrote: >On 2007-04-17, Jean-Paul Calderone wrote: >> On 17 Apr 2007 13:32:52 GMT, Antoon Pardon wrote: >>>On 2007-04-17, Hendrik van Rooyen wrote: >>> [snip] >> >>>> Not sure I understand this - it sounds vaguely incestous to me. >>>> I normally use a GUI with two queues, one for input, one for >>>> output, to two threads that front end two named pipes to >>>> the next process - I try to avoid more than one thing reading or >>>> writing to one end of a queue or a pipe, so the dataflow diagram >>>> for my stuff always looks like a TinkerToy... >>> >>>The problem is that sometimes the gui thread has something to show >>>too. With the added problem that the code wanting to show something >>>doesn't know when it is executing the gui thread or an other. So >>>it is very difficult to avoid the gui thread putting things on the >>>queue. But since the gui thread is the single reader, it will dead >>>lock if the queue happens to be full at the moment the gui thread >>>want to add another item. >>> >> >> This is pretty easily solved: >> >> def sendToGUI(event): >> if isInGUIThread(): >> gui.scheduleCall(event) >> else: >> guiQueue.put(event) > >No that is not a solution for the simple reason that now things >can be shown out of order. Suppose I have a thread that shows >the value of a certain variable. Now I have a button that can >stop this thread and zero the variable. If I go for your >solution a value may still be in the queue and my window >ends up showing this last value instead of zero. > Addressing that is up to the application code. Threading is tough, there are no magic bullets. The above is a very standard tool for addressing the concern raised earlier in this thread. It's only *part* of a solution though, the rest of the application has to play along. Jean-Paul From kyosohma at gmail.com Tue Apr 3 15:45:38 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: 3 Apr 2007 12:45:38 -0700 Subject: way to extract only the message from pop3 In-Reply-To: <1175628970.874615.127020@y80g2000hsf.googlegroups.com> References: <1175628970.874615.127020@y80g2000hsf.googlegroups.com> Message-ID: <1175629538.022033.212460@e65g2000hsc.googlegroups.com> On Apr 3, 2:36 pm, "flit" wrote: > Hello All, > > Using poplib in python I can extract only the headers using the .top, > there is a way to extract only the message text without the headers? > > like remove the fields below: > " > Return-Path: > X-Original-To: > Received: from [ > by (Postfix) with ESMTP id B32382613C > for Tue, 3 Apr 2007 09:54:28 -0300 (BRT) > Date: Tue, 03 Apr 2007 09:52:15 -0300 > From: <@> > To: > Subject: test > Message-Id: > MIME-Version: 1.0 > Content-Type: text/plain; charset="US-ASCII" > Content-Transfer-Encoding: 7bit > X-Mailer: Becky! ver. 2.24.02 [en] > X-UIDL: !Dn!!HKT!!/k > Status: RO > " > and only get this: > > this is a text message.. > .. > > Thanks I found a tutorial on parsing email that should help you: http://www.devshed.com/c/a/Python/Python-Email-Libraries-SMTP-and-Email-Parsing/ Also see the email module: http://www.python.org/doc/2.3.5/lib/module-email.html Mike From bdesth.quelquechose at free.quelquepart.fr Sat Apr 21 15:43:26 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sat, 21 Apr 2007 21:43:26 +0200 Subject: Better dict of dicts In-Reply-To: References: Message-ID: <462a5fec$0$23160$426a74cc@news.free.fr> Bill Jackson a ?crit : > I have a dictionary of dictionaries where the keys are typically very > long tuples and repeated in each inner dictionary. The dictionary > representation is nice because it handles sparseness well...and it is > nice to be able to look up values based on a string rather than a > number. However, since my keys are quite long, I worry that I am > wasting a lot of memory. I'm looking for better data structures. > Is this actually a *real* problem (or do you have evidences - based on both measurements of the behaviour with test data sets and knowledge of the real data sets- that there will be a problem) ? Or this this just "worrying" ? In the second case, I suggest that you bench and profile your code to know for sure... From johan.t.jeuring at gmail.com Thu Apr 26 03:37:06 2007 From: johan.t.jeuring at gmail.com (johan.t.jeuring at gmail.com) Date: 26 Apr 2007 00:37:06 -0700 Subject: ICFP Programming Contest 2007 Message-ID: <1177573026.378682.166860@t38g2000prd.googlegroups.com> Want to show off your programming skills? Your favorite programming language? Your best programming tools? Join the ICFP Programming Contest 2007! The 10th ICFP Programming Contest celebrates a decade of contests. This is one of the world's most advanced and prestiguous programming contest you can enter. For free! Book July 20 - 23, 2007. Check out http://www.icfpcontest.org/. From facundobatista at gmail.com Tue Apr 24 11:14:44 2007 From: facundobatista at gmail.com (Facundo Batista) Date: Tue, 24 Apr 2007 12:14:44 -0300 Subject: [python-advocacy] Would You Write Python Articles or Screencasts for Money? In-Reply-To: <462E0D93.3090705@holdenweb.com> References: <462DCCE6.9060908@taupro.com> <462E0D93.3090705@holdenweb.com> Message-ID: 2007/4/24, Steve Holden : > and I was more looking for a way to reward authors of excellence, as > judged by some subset of the Python community - this might have to be > the PSF membership given the impracticality of running a meaningful poll > with a larger set of voters. Why? Because of spammers and/or false voters? When I first read about this, I thought about a web page where anybody could "propose" articles for voting, and anybody could vote them. Monthly, an award goes for the top 1, and that article goes out from the poll. Why can't that be done? Other point: what happens with all the non-english articles? Other categories? > There are many other possibilities too. What about an award for "most > helpful responses on c.l.py" over some period? I think one of the How do you evaluate such thing? I think this is too complicated... Regards, -- . Facundo Blog: http://www.taniquetil.com.ar/plog/ PyAr: http://www.python.org/ar/ From jstroud at mbi.ucla.edu Sat Apr 14 16:17:24 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Sat, 14 Apr 2007 20:17:24 GMT Subject: That might be the case for more complex objects... In-Reply-To: <7saUh.37$4S1.2@newsfe12.lga> References: <1176546078.934340.253810@y5g2000hsa.googlegroups.com> <1176557734.456820.275780@p77g2000hsh.googlegroups.com> <7saUh.37$4S1.2@newsfe12.lga> Message-ID: Bart Willems wrote: > Dennis Lee Bieber wrote: >> On 14 Apr 2007 06:35:34 -0700, "jamadagni" declaimed >> the following in comp.lang.python: >> In Python, the "variable" NAME does NOT define storage; unlike most >> other classical languages where the "variable name" is a storage >> address, and the value of the RHS is COPIED to that address. Python does >> not do such copying. Names are references to the RHS object itself. >> >> a = 5 >> >> means that somewhere in memory is an integer object with the value "5"; >> the name "a" is now "pasted onto" that integer object. >> >> b = a >> >> finds the object that has the name "a" stuck to it, and sticks a second >> name "b" onto the same object. There is still only one "5" in memory. > > I can try this in interactive mode: > >>> a = 5 > >>> b = a > >>> a += 1 > >>> print b > 5 > > So, if /a/ and /b/ where pointing to the *same* "5" in memory, then I > would expect b to be increased, just as a. But after increasing a, b is > still 5... > > Lists behave as described above, integers and floats don't. > > By the way, a classic language like C has features like this too; > they're called pointers. I think that after a += 1, a memory location with a 6 is created and now a points to that because += has assignment buried in it. From steve at holdenweb.com Sat Apr 14 09:43:25 2007 From: steve at holdenweb.com (Steve Holden) Date: Sat, 14 Apr 2007 09:43:25 -0400 Subject: reading from sys.stdin In-Reply-To: <1176538930.891355.230880@n59g2000hsh.googlegroups.com> References: <1176366058.261031.111870@p77g2000hsh.googlegroups.com> <1176387908.406115.270630@w1g2000hsg.googlegroups.com> <1176438754.995753.50190@d57g2000hsg.googlegroups.com> <1176454871.538968.176620@n76g2000hsh.googlegroups.com> <1176457007.589050.285400@d57g2000hsg.googlegroups.com> <1176538930.891355.230880@n59g2000hsh.googlegroups.com> Message-ID: 7stud wrote: > On Apr 13, 6:20 am, Michael Hoffman wrote: [...] > > But if you hit return on a blank line, there is no error. In other > words, will stop on a blank line and not return EOFError. > > Anyway, it seems everyone is saying that when you iterate over a file, > the whole file is first read into memory. Therefore iterating over > sys.stdin is consistent: you have to type Ctrl+D to signal EOF before > the iteration can start. Is that about right? > No. The file content is usually buffered, but the buffering doesn't necessarily include the whole content of the file. If you are iterating over the file the correct way to access the next line is to call the file's .next() method, as I indicated before. If you are reading lines the appropriate way is to use readline(). And, as you have already seen an error message telling you, mixing the two types is unlikely to give you usable results. 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 cam.ac.uk at mh391.invalid Wed Apr 18 13:29:24 2007 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Wed, 18 Apr 2007 18:29:24 +0100 Subject: X root Operator help In-Reply-To: References: <1176898887.530470.222830@p77g2000hsh.googlegroups.com> Message-ID: [Michael Hoffman] >> For x root use y**(1/x) [Steve Holden] > >>> 3.14159 ** (1/3) > 1.0 > >>> > > So the cube root of pi is 1? I don't think so. > > For generic roots use y ** (1.0 / x) Yes, good point. :) -- Michael Hoffman From stargaming at gmail.com Thu Apr 26 11:45:36 2007 From: stargaming at gmail.com (Stargaming) Date: Thu, 26 Apr 2007 17:45:36 +0200 Subject: Generalized range In-Reply-To: <1177598743.352743.290730@t39g2000prd.googlegroups.com> References: <1177598743.352743.290730@t39g2000prd.googlegroups.com> Message-ID: tkpmep at hotmail.com schrieb: > I need to create ranges that can start and end with real numbers. > Searching this newsgroup brought me to a function that I then modified > as follows: > > def myRange(iMin, iMax=None, iStep=1): Just as a sidenote: it is not common to prefix your names with its type. It could change at any time and min, max, step would be clear, too. IMO. > """Extends range to real numbers. Wherever possible, use Python's > range . > In other cases, make the behavior follow the spirit of Python's > range """ If you want to stick to the "normal" range-implementation, myRange should consider an one-argument-call as transmission of iMax. > epsilon = 1.e-8 I can't really say if your attempt using an epsilon-environment is good. I think just increasing a "counter" from iMin to iMax should be fine, achieving more precision by making computations fuzzy -- i don't know, perhaps it's very good. I wouldn't do it. If you like to care about precision, you should have a look at the `decimal module `_. > > if iMax == None and iStep == 1: > return range(int(iMin)) > > elif type(iMin).__name__.lower() in ('int', 'long') and \ > type(iMax).__name__.lower() in ('int', 'long') and \ > type(iStep).__name__.lower() in ('int', 'long') and iStep != > 0: > return range( iMin, iMax, iStep) Ouchie! *That* is a bad one. Checking for a name of an object is neither safe nor good nor common. A better way would be directly comparing type(yourobject) with int/long/float/anytype. See http://docs.python.org/lib/comparisons.html for details on comparisons. Another way of type-checking in python is doing something like ``if isinstance(iMin, (int, long))``. Would work for subclasses, too. > > elif iMin <= iMax and iStep > 0: > return [ iMin+i*iStep for i in range( int(math.ceil((iMax - > iMin - epsilon)/iStep)) )] > > elif iMin >= iMax and iStep < 0: > return [ iMin+i*iStep for i in range(-int(math.ceil((iMin - > iMax + epsilon)/iStep)) )] > Will eat your memory. See below. > else: > raise ValueError, 'Cannot construct a range with steps of size > ' + str(iStep) + ' between ' + str(iMin) + ' and ' + str(iMax) In Python, it is common to use string interpolation instead. Like:: print 'Hello from %d to %d' % (iMin, iMax) Read `String Formatting Operations `_ in the manual for details. > > > The one part of my implementation that has me a bit queasy (i.e. > works in my current application, but I can see it misbehaving > elsewhere) is the addition/subtraction of a fixed epsilon to ensure > that my rounding goes the right way. A clean implementation would > modify epsilon based on the achievable level of precision given the > particular values of iMax, iMin and iStep. I suspect this requires a > detailed understanding of the implementation of floating point > arithmetic, I think so, too. That's why it is a bad idea, IMO. > and would appreciate hearing any thoughts you might have > on gilding this lily. > > Sincerely > > Thomas Philips > I'd recommend you to have a look into `generators `_, it is what `xrange `_ uses. You don't put all numbers into your memory ("precompute them") but behave a little bit lazy and compute them whenever the user needs the next one. I expect Google to have lots of example implementations of range as a generator in python for you. :-) HTH, Stargaming From mccredie at gmail.com Tue Apr 10 15:47:12 2007 From: mccredie at gmail.com (Matimus) Date: 10 Apr 2007 12:47:12 -0700 Subject: OT: Question about RGB color method In-Reply-To: <461be63b$0$31839$c3e8da3@news.astraweb.com> References: <461be63b$0$31839$c3e8da3@news.astraweb.com> Message-ID: <1176234432.089666.225300@30g2000cwc.googlegroups.com> On Apr 10, 12:32 pm, John Salerno wrote: > Sorry for this non-Python question, but since it's computer related I > know you guys will have an answer, and I don't really know where else to > ask. Mainly I'm just curious anyway. > > I'm wondering, why do computers use a RGB color scheme instead of the > primary colors? Is there something you can't do with yellow? It seems > weird that RGB can be combined to make all colors, when that's supposed > to be the job of the primary colors. I'm sure there some technical > computer-related reason that it had to be this way. > > Thanks. See the Wikipedia article on primary colors: http://en.wikipedia.org/wiki/Primary_colors The quick answer is that RGB is a method of additive color mixing, and RBY is subtractive (and its not really RBY but YCM). Also, the colors emitted by your monitor are Red, Green and Blue. From gregcorradini at gmail.com Thu Apr 12 21:53:46 2007 From: gregcorradini at gmail.com (Greg Corradini) Date: Thu, 12 Apr 2007 18:53:46 -0700 (PDT) Subject: mx.ODBC minor problem Message-ID: <9971678.post@talk.nabble.com> Hello all, In a script i just wrote, my code calls a function createTables(), which checks for an existing table and then creates it, and then immediately calls selectSQL(), which selects from a different table and inserts on the table I just created (see below). However, I continue to get an Interface Error (see below) when i run it. And yet, if I allow the code to call createTables() and then manually call selectSQL() after a couple seconds, the thing works fine. In short, there's no mismatch in the number of parameters. Why would this be? I've never experienced this before. How can i restructure my code to resolve this problem? --- CODE --- def createTables(): # Drop AddScript Table try: curse.execute('Drop table ' +countyname+'ADD_SCRIPT_TABLE') conn.commit except: pass # Create AddScript Table curse.execute('Create table ' +countyname+'ADD_SCRIPT_TABLE'+ ' (TISCODE TEXT(12), STATUS TEXT(4))') conn.commit() def selectSQL(): sql = "Select TISCODE,STATUS from " +countyname+"0"+ " where STATUS = 'AS'" curse.execute(sql) a = curse.fetchall() curse.executemany('Insert into ' +countyname+'ADD_SCRIPT_TABLE'+ ' (TISCODE,STATUS) values (?,?)',x) conn.commit() --- ERROR --- InterfaceError: mismatch in number of parameters; expected 2, found none -- View this message in context: http://www.nabble.com/mx.ODBC-minor-problem-tf3569303.html#a9971678 Sent from the Python - python-list mailing list archive at Nabble.com. From lycka at carmen.se Fri Apr 20 11:02:02 2007 From: lycka at carmen.se (Magnus Lycka) Date: Fri, 20 Apr 2007 17:02:02 +0200 Subject: Fast and capable XML parser? Message-ID: I'm looking for some library to parse XML code much faster than the libs built into Python 2.4 (I'm stuck with 2.4 for quite a while) and I also need XML Schema validation, and would appreciate support for e.g. XPath and XInclude. I also want an API which is more Pythonic than e.g. a thin wrapper over a C or C++ API. It should be available on at least Linux, Solaris and AIX. Some uses involve parsing lots of (often small) XML files at reasonable speed, i.e. several hundred files per second. That means that we can't use anything like an os.system call to xmllint for XML Schema validation--it gets too slow. I also suspect that the standard Python libs (in Python 2.4 at least) are slower than we'd like them to be. (Not that it matters if they don't support XML Schema validation.) Any suggestions? From michael at jedimindworks.com Tue Apr 24 05:31:55 2007 From: michael at jedimindworks.com (Michael Bentley) Date: Tue, 24 Apr 2007 04:31:55 -0500 Subject: Tutorial creates confusion about slices In-Reply-To: References: Message-ID: <04C5F3AA-5CDF-45E5-BF01-86CFCEAA1AD4@jedimindworks.com> On Apr 24, 2007, at 1:39 AM, Antoon Pardon wrote: > On 2007-04-23, Michael Bentley wrote: >> >> On Apr 23, 2007, at 7:38 AM, Antoon Pardon wrote: >> >>> The following is part of the explanation on slices in the >>> tutorial: >>> >>> The best way to remember how slices work is to think of the >>> indices as >>> pointing between characters, with the left edge of the first >>> character >>> numbered 0. Then the right edge of the last character of a string >>> of n >>> characters has index n, for example: >>> >>> +---+---+---+---+---+ >>> | H | e | l | p | A | >>> +---+---+---+---+---+ >>> 0 1 2 3 4 5 >>> -5 -4 -3 -2 -1 >>> >>> This is all very well with a simple slice like: >>> >>> "HelpA"[2:4] => "lp" >>> >>> >>> But it give the wrong idea when using the following extended slice: >>> >>> "HelpA"[4:2:-1] => "Ap" >>> >>> So this doesn't result in the reverse of the previous expression >>> while >>> the explanation above suggest it does. >>> >>> >>> So I suggest to drop this. >> >> But 'drop' means to let or make (something) fall vertically... :-) >> >> At that point in the tutorial, step values had not been discussed. >> Just a bit lower down on the page you'll find a link to 'Sequence >> Types' where you'll find an explanation of stepping you'll perhaps >> find more satisfactory. > > That is very well posible. The question: Even if we get a good > explanation later, do we want an explanation here that can cause > confusion. These things are not just read and then discarded. > Someone can already have read the whole tutorial and then come > back to this place. So at that point he knows about stepping > when he is reading this. > > > I suspect that if you give this explanation to someone and explain > that there is also a step parameter, chances are he will answer > correctly if you ask him, what he thinks the following will result > in: > > > "This is an example line"[12:19:2] > > > > If you ask him what the following will result in: > > "This is an example line"[19:12:-1] > > Chances are he will give the wrong answer. To be honest, bro -- I'd expect him to have enough intelligence to experiment for a second and figure it out. This isn't rocket science -- you can plainly see what's happening -- so learn it and move on. Or better yet, quietly submit a patch... From rganesan at myrealbox.com Fri Apr 27 04:27:45 2007 From: rganesan at myrealbox.com (Ganesan Rajagopal) Date: Fri, 27 Apr 2007 13:57:45 +0530 Subject: List objects are un-hashable References: <1177660237.470851.170200@s33g2000prh.googlegroups.com> Message-ID: >>>>> "Andy" == Andy writes: > if keyword.iskeyword(tempwords): > print tempwords for word in tempwords: if keyword.iskeyword(word): print word Ganesan -- Ganesan Rajagopal From bbxx789_05ss at yahoo.com Wed Apr 18 19:34:56 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: 18 Apr 2007 16:34:56 -0700 Subject: Newbie: import In-Reply-To: <1176937784.549769.306250@b75g2000hsg.googlegroups.com> References: <1176914096.493758.77120@o5g2000hsb.googlegroups.com> <1176937784.549769.306250@b75g2000hsg.googlegroups.com> Message-ID: <1176939296.377362.115580@n76g2000hsh.googlegroups.com> Here's an example where you are trying to import a function in one of your .py files--when that .py file is not in the current directory: import sys sys.path.append("/Users/me/2testing/dir1/") #directory that contains the file import test1 #name of file without .py extension test1.greet() From sjmachin at lexicon.net Sun Apr 1 22:37:06 2007 From: sjmachin at lexicon.net (John Machin) Date: 1 Apr 2007 19:37:06 -0700 Subject: reverse engineering Excel spreadsheet In-Reply-To: <460fd6d0.0@entanet> References: <460fd6d0.0@entanet> Message-ID: <1175481426.182703.250400@q75g2000hsh.googlegroups.com> On Apr 2, 1:59 am, Duncan Smith wrote: > Hello, > I am currently implementing (mainly in Python) 'models' that come > to me as Excel spreadsheets, with little additional information. I am > expected to use these models in a web application. Some contain many > worksheets and various macros. > > What I'd like to do is extract the data and business logic so that I can > figure out exactly what these models actually do and code it up. An > obvious (I think) idea is to generate an acyclic graph of the cell > dependencies so that I can identify which cells contain only data (no > parents) and those that depend on other cells. If I could also extract > the relationships (functions), then I could feasibly produce something > in pure Python that would mirror the functionality of the original > spreadsheet (using e.g. Matplotlib for plots and more reliable RNGs / > statistical functions). There are two things you have to consider that can create those dependencies (1) formulas (2) macros. If it were only formulas, you wouldn't need to generate an acyclic graph. A no-parents cell will be defined by a type-specific record (e.g. NUMBER). Dependent cells are defined by a FORMULA etc record. Similar story with the XML format in Office 2007. I'm not aware of any way to use Python to access the content of macros. It may be possible using COM ... I'm a bit puzzled by your notion of creating a dependency graph *without* first extracting the "relationships (functions)" [which you could do only by parsing the formulas and macros]. "pure Python that would mirror the functionality of the original spreadsheet": mammoth job; speed? Before you do that, have a look at (1) xlrd docs (2) xlrd source (3) Openoffice.org docs of XLS format (4) MS docs (now an ECMA standard) of Office 2007 XML-based files. > > The final application will be running on a Linux server, but I can use a > Windows box (i.e. win32all) for processing the spreadsheets (hopefully > not manually). Any advice on the feasibility of this, and how I might > achieve it would be appreciated. > > I assume there are plenty of people who have a better knowledge of e.g. > COM than I do. I suppose an alternative would be to convert to Open > Office and use PyUNO, but I have no experience with PyUNO and am not > sure how much more reliable the statistical functions of Open Office > are. At the end of the day, the business logic will not generally be > complex, it's extracting it from the spreadsheet that's awkward. Any > advice appreciated. TIA. Cheers. > > Duncan PyUNO: Google around a bit. My experience was: tried it, got lost in the jungle of its documentation. HTH, John From ptmcg at austin.rr.com Thu Apr 12 20:38:13 2007 From: ptmcg at austin.rr.com (Paul McGuire) Date: 12 Apr 2007 17:38:13 -0700 Subject: Emergence of Grok Message-ID: <1176424693.546746.238660@d57g2000hsg.googlegroups.com> I just stumbled upon a great-looking project, to make Zope3 more approachable to mere mortals such as myself. Echoing the ROR mantra of "convention over configuration", the Grok project (http:// grok.zope.org/) aims to stand on the shoulders of Zope3, while providing the ease of development of ROR (for instance, no more ZCML). Philipp von Weitershausen has a set of slides at http://philikon.de/files/grok-bbq-sprint.pdf, and the Grok project page links to a number of tutorials. Am I the last person to hear about this? -- Paul From carsten at uniqsys.com Mon Apr 23 16:39:11 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Mon, 23 Apr 2007 16:39:11 -0400 Subject: script for seconds in given month? In-Reply-To: <1177360091.516469.77830@l77g2000hsb.googlegroups.com> References: <1176740556.859125.221980@l77g2000hsb.googlegroups.com> <1hwokmz.1ropcwj17pg55dN%aleax@mac.com> <1176796031.889407.323950@b75g2000hsg.googlegroups.com> <1177360091.516469.77830@l77g2000hsb.googlegroups.com> Message-ID: <1177360751.3442.26.camel@dot.uniqsys.com> On Mon, 2007-04-23 at 13:28 -0700, edfialk wrote: > Alex, very nice. That should be good enough for me. > The rest of you as well, thanks for all the help. > > I, unfortunately, failed to realize the actual platform the script is > for is IronPython. When trying to import calendar in IronPython, I > get: > > SyntaxError: future feature is not defined: with_statement (c: > \Python25\Lib\calendar.py, line 8) > > so, incompatible. I have moved my question over to the IronPython > group, but if anyone is familiar with IronPython and knows how to > perform the same function, that's what I'm looking for now. :) Try this on for size: def seconds_in_month(mo,yr): import datetime start_date = datetime.date(yr,mo,1) mo += 1 if mo==13: mo=1; yr += 1 end_date = datetime.date(yr,mo,1) delta = end_date - start_date return 24*60*60*delta.days -Carsten From apardon at forel.vub.ac.be Tue Apr 10 09:25:21 2007 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 10 Apr 2007 13:25:21 GMT Subject: tuples, index method, Python's design References: <1175867771.114540.61810@n76g2000hsh.googlegroups.com> <1175884427.779950.267220@y80g2000hsf.googlegroups.com> <1175953520.316208.241490@o5g2000hsb.googlegroups.com> <7xzm5igbrb.fsf@ruckus.brouhaha.com> Message-ID: On 2007-04-10, Duncan Booth wrote: > Antoon Pardon wrote: > >> On 2007-04-10, Duncan Booth wrote: >>> There is a cost to every new language feature: it has to be >>> implemented, documented, maintained, and above all learned by the >>> users. Good design involves, in part, not adding to these burdens >>> except where there is a benefit at least equal to the cost. >> >> So what is the easiest to learn: "All sequences have an index method" >> or "Such and so sequences have an index method and others don't" >> >> Which of the above is the easiest to document? > > The second would be if it were true. However it would mean you would have > to add an index method to *all* sequences. > > FWIW, The current documentation says that 's.index' is a method defined on > all *mutable* sequence types: almost as simple as your second wording but > unfortunately misleading since strings also have index. Which illustrate that the mutable unmutable distinction is not very usefull to decide whether a sequence could use "index" or not. >> If someone states: "Show me your use case for using tuple.index and I >> will show you how to avoid it." or words to that effect I think there >> is little use trying. > > I genuinely cannot think of a use case. I didn't ask you to suggest one so > I could show you how to avoid it, I asked you to suggest one so that we > could take the discussion from the purely hypothetical to a more concrete > discussion of whether it would be a worthwhile enhancement. I have given a use case in an other article in this thread. Feel free to comment. -- Antoon Pardon From bj_666 at gmx.net Thu Apr 12 07:43:49 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Thu, 12 Apr 2007 13:43:49 +0200 Subject: sqlite3 question References: Message-ID: In , Jorgen Bodde wrote: >>>> r = c.execute('select * from song where id = 1') >>>> for s in r: > ... print s > ... > (1, u'Spikedrivers Blues', u'Mississippi John Hurt') > > That works. But when I can't restore the row by e.g. an ID that does > not exist, I cannot see any method in 'r' (which is a SQLite.Cursor) > that can tell me if I have rows. As explained in the help, r.rowcount > does not give a valid result because it can't determine how many rows > are restored in advance. This should not work because `r` should not be a `Cursor` object. The `execute()`-Method returns an integer with the number of "affected rows". Ciao, Marc 'BlackJack' Rintsch From steve at REMOVE.THIS.cybersource.com.au Sat Apr 14 22:58:53 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Sun, 15 Apr 2007 12:58:53 +1000 Subject: function with list argument defaulting to [] - what's going on here??? References: <46217e8f$0$19437$4c368faf@roadrunner.com> Message-ID: On Sat, 14 Apr 2007 17:33:11 -0800, Troy Melhase wrote: > On 4/14/07, Mike wrote: >> While trying to write a recursive function involving lists, I came >> across some (to me) odd behavior which I don't quite understand. Here's >> a trivial function showing the problem. > > from http://docs.python.org/ref/function.html : > > Default parameter values are evaluated when the function definition is > executed. This means that the expression is evaluated once, when the > function is defined, and that that same ``pre-computed'' value is used > for each call. This is especially important to understand when a > default parameter is a mutable object, such as a list or a dictionary: > if the function modifies the object (e.g. by appending an item to a > list), the default value is in effect modified. This comes up so often that I wonder whether Python should issue a warning when it sees [] or {} as a default argument. What do people think? A misuse or good use of warnings? -- Steven. From soren.skou.nielsen at gmail.com Sat Apr 28 10:03:27 2007 From: soren.skou.nielsen at gmail.com (Soren) Date: 28 Apr 2007 07:03:27 -0700 Subject: Multiple select in wx.GenericDirCrtl In-Reply-To: <1177679613.209726.90510@s33g2000prh.googlegroups.com> References: <1177677090.037403.209940@n15g2000prd.googlegroups.com> <1177679613.209726.90510@s33g2000prh.googlegroups.com> Message-ID: <1177769007.369586.244180@y80g2000hsf.googlegroups.com> On Apr 27, 3:13 pm, kyoso... at gmail.com wrote: > On Apr 27, 7:31 am, Soren wrote: > > > Hi! > > > Is it possible to do multiple file selections in a wx.GenericDirCtrl?? > > > Thanks, > > Soren > > I'm not finding anything. I do know you can select multiple files > using the FileDialog. You should email the wxPython users group > though. They may have a custom control or they will likely be able to > point you in the right direction. > > http://www.wxpython.org/maillist.php > > Mike I'll try that, thanks Mike! Soren From steven.bethard at gmail.com Tue Apr 24 23:17:53 2007 From: steven.bethard at gmail.com (Steven Bethard) Date: Tue, 24 Apr 2007 21:17:53 -0600 Subject: Where's the source code for __builtin__? In-Reply-To: <87lkghgp72.fsf@benfinney.id.au> References: <1177457545.075398.204990@r3g2000prh.googlegroups.com> <462EA63C.6080805@lexicon.net> <87lkghgp72.fsf@benfinney.id.au> Message-ID: <-NadnSatQtP9VbPbnZ2dnUVZ_rTinZ2d@comcast.com> Ben Finney wrote: > John Machin writes: >> On 25/04/2007 9:32 AM, Dustan wrote: >>> I've been paging through the source code for various C modules in >>> python, and wanted to find the source of some of the builtin >>> functions. >> What's the 2nd file (in alphabetical order) in the Python folder? > > What is "the Python folder"? > > Assuming you mean "the folder for the Python standard library > modules": Actually, he meant the folder named 'Python' in the checkout from the repository: C:\...\python\2.X>dir Python Directory of C:\...\python\2.X\Python 03/21/2007 12:13 PM . 03/21/2007 12:13 PM .. 02/17/2007 03:11 PM 697 asdl.c 03/19/2007 04:31 PM 103,444 ast.c 02/17/2007 03:11 PM 865 atof.c 03/19/2007 04:31 PM 66,286 bltinmodule.c Probably 'bltinmodule.c' is a good place to start. STeVe From fsckedagain at gmail.com Tue Apr 3 11:39:16 2007 From: fsckedagain at gmail.com (fscked) Date: 3 Apr 2007 08:39:16 -0700 Subject: XML/encoding/prolog/python hell... In-Reply-To: <1175179882.563945.199760@n59g2000hsh.googlegroups.com> References: <1175103659.463125.39370@y66g2000hsf.googlegroups.com> <570b3oF2b2uk9U1@mid.uni-berlin.de> <1175179882.563945.199760@n59g2000hsh.googlegroups.com> Message-ID: <1175614756.396037.58490@w1g2000hsg.googlegroups.com> Any ideas? From dwmaillist at gmail.com Tue Apr 17 14:11:56 2007 From: dwmaillist at gmail.com (Daniel Watrous) Date: Tue, 17 Apr 2007 12:11:56 -0600 Subject: python - dll access (ctypes or swig) Message-ID: <883e18590704171111q67f57aefp66f4b1215e25dfe7@mail.gmail.com> Hello, I am interested in using python to script access to some hardware for which there are existing drivers in the form of DLLs. The DLLs each have four exported functions and a host of COM Properties and COM Methods. The four exported functions are as follows: DllCanUnloadNow DllGetClassObject DllRegisterServer DllUnregisterServer The COM methods and properties all begin with I, followed by a unique name. I am able to load the DLL using ctypes and it can access the exported functions, but I'm not sure how to access the COM methods and properties. I have read that ctypes once had support for COM but that it has since been separated into its own project. I couldn't find any information about how these work together. All help is appreciated. THANKS in advance... Daniel From cam.ac.uk at mh391.invalid Thu Apr 26 15:55:43 2007 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Thu, 26 Apr 2007 20:55:43 +0100 Subject: Generalized range In-Reply-To: References: <1177598743.352743.290730@t39g2000prd.googlegroups.com> <1177616211.476888.38360@r30g2000prh.googlegroups.com> Message-ID: Michael Hoffman wrote: > How about something like this: > > index = 0 > while res < maximum: > yield minimum + (step * index) > index += 1 Well it really would have to be something LIKE that since I never defined res. Let's try that again: index = 0 res = minimum while res < maximum: yield res res = minimum + (step * index) index += 1 -- Michael Hoffman From saif.shakeel at gmail.com Mon Apr 30 05:19:44 2007 From: saif.shakeel at gmail.com (saif.shakeel at gmail.com) Date: 30 Apr 2007 02:19:44 -0700 Subject: I/O Operations ..... In-Reply-To: References: <1177919063.650070.321560@y80g2000hsf.googlegroups.com> Message-ID: <1177924784.122690.233540@p77g2000hsh.googlegroups.com> On Apr 30, 2:13 pm, "Daniel Nogradi" wrote: > > I am parsing an XML file and sending the output to two files.The > > code asks the user to enter the input file,something like: > > > file_input = raw_input("Enter The ODX File Path:") > > input_xml = open(file_input,'r') > > > Now suppose the user enters the path as : > > C:\Projects\ODX Import\Sample Files\Global _A_UHP_Low_0.7.odx.xml > > > I have 2 output files to which i have to redirect the output.The > > output file name should be same as input file in the same path ( the > > extension has to change to a format "ini" which is basically text file > > opened using notepad).Eg.. > > output files should be : > > C:\Projects\ODX Import\Sample Files\Global _A_UHP_Low_0.7.ini, and, > > C:\Projects\ODX Import\Sample Files\Global _A_UHP_Low_0.7.xls > > If you only would like to know how to write files, this might help: > > content1 = .............. > content2 = ............... > > f = open( 'file1', 'w' ) > f.write( content1 ) > f.close( ) > > f = open( 'file2', 'w' ) > f.write( content2 ) > f.close( ) > > HTH, > Daniel- Hide quoted text - > > - Show quoted text - Hi, File writing can be done in that way,but my query is something different.I have to rename the output file by default with input file name(only changing the extension. Thanks From gagsl-py2 at yahoo.com.ar Sat Apr 28 01:59:46 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sat, 28 Apr 2007 02:59:46 -0300 Subject: Cgi File Upload without Form References: <1177708242.553577.226530@n15g2000prd.googlegroups.com> Message-ID: En Fri, 27 Apr 2007 18:10:42 -0300, escribi?: > what is the simplest way to upload a file (or a long string) to a > server using cgi/python? > > Since I want to upload the data programmatically, a form based > solution is not good. I am not experienced with SOAP/WSDL and I > believe that would be more difficult than necessary. The client > program I have to use does not support FTP. I don't understand your question. Do you control the server, the client, or both? Which one is in Python? -- Gabriel Genellina From see_signature at nospam.nowire.org Mon Apr 23 10:03:05 2007 From: see_signature at nospam.nowire.org (=?ISO-8859-1?Q?Thomas_Kr=FCger?=) Date: Mon, 23 Apr 2007 16:03:05 +0200 Subject: [SQLite] Recommended wrapper? In-Reply-To: References: Message-ID: It's all there: http://docs.python.org/lib/module-sqlite3.html Thomas -- sinature: http://nospam.nowire.org/signature_usenet.png From admin at loial.co.uk Mon Apr 16 10:18:49 2007 From: admin at loial.co.uk (loial) Date: 16 Apr 2007 07:18:49 -0700 Subject: More newbie help required with dictionaries In-Reply-To: References: <1176731017.008097.21590@o5g2000hsb.googlegroups.com> Message-ID: <1176733129.094616.13890@e65g2000hsc.googlegroups.com> machines[machinekey] = [0,1,0,0,0,0,0,0,0,0,0,0,0] is what I needed...thanks On 16 Apr, 15:07, Christoph Haas wrote: > On Mon, Apr 16, 2007 at 06:43:37AM -0700, loial wrote: > > The following code only returns the last row(222222) added to the > > machines dictionary. > > presumably I need some additional syntax to add rows to the dictionary > > rather than overwrite. > > > What do I need to add? > > > machinekey = "111111" > > > machines = { machinekey:[1,0,0,0,0,0,0,0,0,0,0,0,0] } > > > machinekey = "222222" > > > machines = { machinekey:[0,1,0,0,0,0,0,0,0,0,0,0,0] } > > You redefine the "machines" dictionary here. So it just contains one > entry. What you mean: > > machines.update({ machinekey:[0,1,0,0,0,0,0,0,0,0,0,0,0] }) > > Or: > > machines[machinekey] = [0,1,0,0,0,0,0,0,0,0,0,0,0] > > Christoph From enleverlesX.XmcX at XmclaveauX.com Sun Apr 1 07:01:13 2007 From: enleverlesX.XmcX at XmclaveauX.com (Méta-MCI) Date: Sun, 1 Apr 2007 13:01:13 +0200 Subject: Opening Photoshop EPS with PIL? References: <1175350344.418087.288320@q75g2000hsh.googlegroups.com> Message-ID: <460fd449$0$27399$ba4acef3@news.orange.fr> .eps ==> vector ; not bitmap From slm_guzel at hotmail.com Wed Apr 4 17:47:43 2007 From: slm_guzel at hotmail.com (gslm) Date: 4 Apr 2007 14:47:43 -0700 Subject: ImageGrab Message-ID: <1175723262.109991.253500@n59g2000hsh.googlegroups.com> Hi, My application's base is a button, namely all of frames, labels on a button.And I want to print this view when click the button. For this I want to use ImageGrabe.grab(bbox) function.But unfortunately, I can't use this for taking buttons area as bbox. How can i do these? From martin at v.loewis.de Sun Apr 29 05:40:38 2007 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sun, 29 Apr 2007 11:40:38 +0200 Subject: Tracebacks for `exec`ed code? In-Reply-To: <1177823329.567989.281420@c35g2000hsg.googlegroups.com> References: <1177823329.567989.281420@c35g2000hsg.googlegroups.com> Message-ID: <46346816.3040201@v.loewis.de> Adam Atlas schrieb: > Is it possible to make more traceback information available for > exceptions code dynamically run via `exec`? Normally it just says > things like "File '', line 3, in ?", which is not very > helpful. I'm looking for a way for it to show the line of source code > below it, like it would for an exception in a physical file. Is this > possible? Yes. You will need to print the traceback yourself; see traceback.print_tb for an example. Regards Martin From steve at holdenweb.com Thu Apr 26 12:58:03 2007 From: steve at holdenweb.com (Steve Holden) Date: Thu, 26 Apr 2007 12:58:03 -0400 Subject: EuroPython vs PyconUK In-Reply-To: <4630D480.7050308@gmail.com> References: <4630D480.7050308@gmail.com> Message-ID: EuGeNe Van den Bulke wrote: > I do realize that the UK is not really part of Europe (no polemic :P) > but I am nevertheless curious about the logic behind creating another > major Python event in Europe. Wasn't EuroPython enough? > > Like many I am sure, I probably won't be able to attend both (and I > really enjoyed the Geneva experience so definitely want to renew "it"). > How would you go about selecting which conference to attend? > > They are only 2 months apart, 6 would have been easier for the > attendees! Could the organizers liaise one way or another to make > Pythoneers life as easy and fun as the language and give as much > information out as possible as early as possible (early bird early) for > people to make the best decision? > > I know marketing matters but ... > > EuGeNe -- http://www.3kwa.com So by this reasoning there should have been no "Python UK" conference for the last four years (in case you didn't know it ran as a track of the C/C++ conference, but ths track has now broadened to include all scripting languages). And what about the people who can't get the time and/or money to attend EuroPython? Diversity is good, so it isn't one vs. the other. And the UK really *is* part of Europe (no matter how its politicians behave) :P regards Steve -- Steve Holden +1 571 484 6266 +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 mikeminer53 at hotmail.com Fri Apr 6 19:25:42 2007 From: mikeminer53 at hotmail.com (mkPyVS) Date: 6 Apr 2007 16:25:42 -0700 Subject: Indentifying the LAST occurrence of an item in a list In-Reply-To: <1175819867.740913.96430@y80g2000hsf.googlegroups.com> References: <1175702329.330032.250750@w1g2000hsg.googlegroups.com> <1175723121.298681.56600@n76g2000hsh.googlegroups.com> <1175799330.683339.93400@e65g2000hsc.googlegroups.com> <1175819867.740913.96430@y80g2000hsf.googlegroups.com> Message-ID: <1175901942.342121.304730@l77g2000hsb.googlegroups.com> On Apr 5, 6:37 pm, "John Machin" wrote: >>> help(list.index) > Help on method_descriptor: > > index(...) > L.index(value, [start, [stop]]) -> integer -- return first index > of value > > I look forward to your next version. Great point! I was assuming the temp variable space was static but the pointer to the start of the list was moving-> shame on me (what language is this now ;)! Couldn't resist the temptation to just collect all of the locations as I traversed m = [2,9,1,5,6,3,1,1,9,2] f = 1 #What we're looking for location = 0 #Start at beginning of list fIndexs = [] while 1: try: location = m.index(f,location) + 1 fIndexs.append(location-1) except ValueError: break print("Last location = %d" % fIndexs[-1]) print("All Items = %s" % fIndexs) From mmanns at gmx.de Thu Apr 5 17:13:06 2007 From: mmanns at gmx.de (Martin Manns) Date: Thu, 5 Apr 2007 17:13:06 -0400 Subject: grandparent method with super References: <20070405161939.694d51a1@localhost> <20070405163845.2ffa8d32@localhost> Message-ID: <20070405171306.0264fb70@localhost> On Thu, 5 Apr 2007 16:55:38 -0400 "John Clark" wrote: > >That works, but when I replace A with something else, I do not get > >the > grandparent anymore > >without changing all the method calls. Basically, I would like to > >call the > method m in the first > >grandparent of D. > > > >Martin > > I think the problem you may run into is with the term "first > grandparent" - when you look at the method resolution order of the > class D, you will find that the MRO goes "D, C, B, A"... I think it's > going to be difficult to figure out where the "first grandparent" is > in the MRO. > > For example: > > class A(object): > def m(self): > pass > class B(A): > def m(self): > pass > class C(B): > def m(self): > pass > class D(A): > def m(self): > pass > class E(C,D): > def m(self): > firstgrandparent(E,self).m() #Should call B.m > class F(D,C): > def m(self): > firstgrandparent(F,self).m() # Should call F.m > > > The mro for class E is going to be "E,C,B,D,A" where as the mro for > class F is going to be "F,D,C,B,A". However, the first grandparent > for E should be B, where as the first grandparent for F should be A. > > Because the MRO isn't just a depth first traversal, the term "first > grandparent" gets tricky to define... Not really. The first grandparent would be the first occurrence in the list from left to right, which satisfies the requirement that its shortest path to the current class is 2. The only problem: How do I get it? Martin From zawrotny at sb.fsu.edu Wed Apr 11 16:21:49 2007 From: zawrotny at sb.fsu.edu (Michael Zawrotny) Date: 11 Apr 2007 20:21:49 GMT Subject: tuples, index method, Python's design References: <1176210960.3430.20.camel@dot.uniqsys.com> <740c3aec0704100810g5f962e8eu614fbaedecf3608e@mail.gmail.com> <1176219856.3430.76.camel@dot.uniqsys.com> <740c3aec0704101021i1fd79ef2l99eac4ced1e252d9@mail.gmail.com> <1176226682.3430.86.camel@dot.uniqsys.com> <4866bea60704101104r4600d281h135286b66378f4d4@mail.gmail.com> <740c3aec0704101534y3c65f5a7je382f97e1f6301b7@mail.gmail.com> <1176305859.581010.199600@n76g2000hsh.googlegroups.com> Message-ID: On Wed, 11 Apr 2007 10:57:19 -0500, Chris Mellon wrote: > > The primary use case for index on tuple is because people use them as > immutable lists. That's fine as far as it goes, but I want to know > what the justification is for using an immutable list, and if you have > one why you need to use index() on it. There's only 2 use cases I've > heard so far for that: certain types of binary parsing, which I don't > think is common enough to justify modification to the language core, > and third party libs returning silly things, which I *certainly* don't > think justifies changes to the language core. In regard to unpacking binary data and similar uses, those are often perfomance sensitive, here is some benchmark data from timeit.Timer on looking for an item in a list/tuple via list.index() or list(tuple).index(). The best case scenario (short list) takes about a 20% performance hit. run time (sec) size runs list tuple ratio (t/l) 1000000 100 1.997614 5.526909 2.766755 100000 1000 2.049710 5.291704 2.581684 10000 10000 1.970400 2.714083 1.377428 1000 100000 2.325089 3.013624 1.296133 100 1000000 6.213748 7.661165 1.232938 10 10000000 44.970536 53.685698 1.193797 For whatever it's worth, I'm mildly in favor of index() and count() being added to tuples. Mike -- Michael Zawrotny Institute of Molecular Biophysics Florida State University | email: zawrotny at sb.fsu.edu Tallahassee, FL 32306-4380 | phone: (850) 644-0069 From g.brandl at gmx.net Wed Apr 18 07:25:45 2007 From: g.brandl at gmx.net (Georg Brandl) Date: Wed, 18 Apr 2007 13:25:45 +0200 Subject: What makes an iterator an iterator? In-Reply-To: <4625CCED.5090106@strank.info> References: <4625CCED.5090106@strank.info> Message-ID: Stefan Rank schrieb: > on 18.04.2007 07:39 Steven D'Aprano said the following: >> I thought that an iterator was any object that follows the iterator > > replace object with "instance of a class", i.e. the relevant methods are > looked up in the __class__ not in the instance (I think). > I had the same troubles trying to dynamically reassign a __call__ method... This is correct. It's not properly documented though, and not applied consistently, e.g. __enter__ and __exit__ are looked up in the instance itself. Georg From cfriedl at bigpond.net.au Fri Apr 27 06:18:50 2007 From: cfriedl at bigpond.net.au (Chris) Date: Fri, 27 Apr 2007 10:18:50 GMT Subject: what python technology for my app? Message-ID: I have an database containing lots of numerical data. I want to write a browser based interface that will allow selection of various key parameters and yield tables, plots and/or printouts of the data according to the selections. Ultimately I want this to run on an intranet so that others can get access via their browsers. The application is for in-house use only and not likely to have more than a few users at any one time. I've managed to hack out enough understanding of sql and sqlAlchemy over the last couple of days to create and access an sqlite3 based database for my data. This seems to suit my purposes for now. Now for a front end and some simple distribution over a network. I have written some small Wxpython & matplotlib apps for data analysis and display but I'm not sure how these would work in a browser based world, or even if they are appropriate. Any advice on what technologies I should be looking at for this? Python based naturally, and hopefully simple and lightweight. I'm not a programmer by trade and that's not what I really get paid for but I've learned to love python and its myriad of modules for all the data analysis work I need to do. If I can throw something moderately functional together in a week or two (along with all the learning that entails) I'll be happy. btw - Platform needs to be windows because that's what on my desk. thanks. From kay.schluehr at gmx.net Sun Apr 1 15:25:29 2007 From: kay.schluehr at gmx.net (Kay Schluehr) Date: 1 Apr 2007 12:25:29 -0700 Subject: Shed Skin Python-to-C++ Compiler 0.0.21, Help needed In-Reply-To: References: <576vhbF2ca1guU1@mid.individual.net> <1175376373.241744.6220@y80g2000hsf.googlegroups.com> <1175413310.295953.230840@e65g2000hsc.googlegroups.com> Message-ID: <1175455529.936887.249170@e65g2000hsc.googlegroups.com> On Apr 1, 6:07 pm, John Nagle wrote: > Kay Schluehr wrote: > > Indeed. The only serious problem from an acceptance point of view is > > that Mark tried to solve the more difficult problem first and hung on > > it. Instead of integrating a translator/compiler early with CPython, > > doing some factorization of Python module code into compilable and > > interpretable functions ( which can be quite rudimentary at first ) > > together with some automatically generated glue code and *always have > > a running system* with monotone benefit for all Python code he seemed > > to stem an impossible task, namely translating the whole Python to C++ > > and created therefore a "lesser Python". > > Trying to incrementally convert an old interpreter into a compiler > is probably not going to work. I'm talking about something that is not very different from what Psyco does but Psyco works at runtime and makes continous measurements for deciding whether it can compile some bytecodes just-in-time or let the interpreter perform their execution. You can also try a different approach and decide statically whether you can compile some function or interpret it. Then you factorize each module m into m = m_native * m_interp. This factorization shall depend only on the capabilities of the translator / native compiler and the metadata available for your functions. Since you care for the correct interfaces and glue code early and maintain it continually you never run into severe integration problems. ---------------------------------------------------------- A factorization always follows a certain pattern that preserves the general form and creates a specialization: def func(x,y): # algorithm ====> from native import func_int_int def func(x,y): if isinstance(x, int) and isinstance(y, int): return func_int_int(x,y) # wrapper of natively compiled specialized function else: # perform original unmodified algorithm on bytecode interpreter Or in decorator notation: from native import func_int_int @apply_special( ((int, int), func_int_int) ) def func(x,y): # algorithm where apply_special transforms the first version of func into the second version. Now we have the correct form and the real and hard work can begin i.e. the part Mark was interested and engaged in. > > > Otherwise it > > wouldn't be a big deal to do what is necessary here and even extend > > the system with perspective on Py3K annotations or other means to ship > > typed Python code into the compiler. > > Shed Skin may be demonstrating that "annotations" are unnecessary > cruft and need not be added to Python. Automatic type inference > may be sufficient to get good performance. You still dream of this, isn't it? Type inference in dynamic languages doesn't scale. It didn't scale in twenty years of research on SmallTalk and it doesn't in Python. However there is no no-go theorem that prevents ambitious newbies to type theory wasting their time and efforts. > The Py3K annotation model is to some extent a repeat of the old > Visual Basic model. Visual Basic started as an interpreter with one > default type, which is now called Variant, and later added the usual types, > Integer, String, Boolean, etc., which were then manually declared. > That's where Py3K is going. Read the related PEP, John. You will see that Guidos genius is that of a good project manager in that case who knows that the community works for him. The trade is that he supplies the syntax/interface and the hackers around him fantasize about semantics and start implementations. Not only annotations are optional but also their meaning. This has nothing to do with VB and it has not even much to do with what existed before in language design. Giving an example of annotation semantics: def func(x:int, y:int): # algorithm can be translated according to the same pattern as above. The meaning of the annotation according to the envisioned annotation handler is as follows: try to specialize func on the types of the arguments and perform local type inference. When successfull, compile func with these arguments and map the apply_special decorator. When translation is unfeasible, send a warning. If type violation is detected under this specialization send a warning or an exception in strict-checking- mode. I fail to see how this violates duck-typing and brings VisualBasic to the Python community. But maybe I just underrate VB :) Kay From martin at v.loewis.de Sat Apr 7 04:47:50 2007 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sat, 07 Apr 2007 10:47:50 +0200 Subject: Convert xml symbol notation In-Reply-To: <1175923387.811717.279580@n76g2000hsh.googlegroups.com> References: <1175899141.354348.207530@q75g2000hsh.googlegroups.com> <1175923387.811717.279580@n76g2000hsh.googlegroups.com> Message-ID: <46175AB6.8070602@v.loewis.de> >> I'm working on a script to download and parse a web page, and it >> includes xml symbol notation, such as ' for the ' character. Does >> anyone know of a pre-existing python script/lib to convert the xml >> notation back to the actual symbol it represents? > > Try the htmlentitydefs module. That won't help: this is a character reference, not an entity reference. htmlentitydefs only contains the definitions of entities. Regards, Martin From Leisure.207 at gmail.com Sun Apr 29 13:06:44 2007 From: Leisure.207 at gmail.com (Leisure.207 at gmail.com) Date: 29 Apr 2007 10:06:44 -0700 Subject: Free Windows Vista Download Message-ID: <1177866404.344342.175400@h2g2000hsg.googlegroups.com> http://freewindowsvista.blogspot.com/ - Get Windows Vista for Free From Szkandera.Karel at seznam.cz Mon Apr 16 12:36:43 2007 From: Szkandera.Karel at seznam.cz (=?us-ascii?Q?Szkandera=2EKarel?=) Date: Mon, 16 Apr 2007 18:36:43 +0200 (CEST) Subject: =?us-ascii?Q?Python=20=2B=20ogr=20module=3F?= Message-ID: <2183.3375-6916-181585672-1176741403@seznam.cz> Hi, I need to do web service, which will be convert vector formats, like shapefile, dgn, mapinfo..(and other formats, which are supported in gdal - ogr2ogr). I want to do it with using ogr2ogr in the ogr python module, but i am newbie in python, so here is my questions. Is here anybody, who wrote any similar scripts and can give it me? If not, can at least anyone point me to few examples of using ogr2ogr in the ogr python module? Thank you for every answer, K.Szkandera From surekap at gmail.com Sun Apr 29 18:20:27 2007 From: surekap at gmail.com (Prateek) Date: 29 Apr 2007 15:20:27 -0700 Subject: help in debugging file.seek, file.read In-Reply-To: <1177884066.570052.186820@y5g2000hsa.googlegroups.com> References: <1177884066.570052.186820@y5g2000hsa.googlegroups.com> Message-ID: <1177885227.832869.35580@u30g2000hsc.googlegroups.com> Sorry, I forgot to mention - the RTH line only prints when the time taken is > 0.1 second (so that I don't pollute the output with other calls that complete normally) From bdesth.quelquechose at free.quelquepart.fr Fri Apr 13 16:46:03 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Fri, 13 Apr 2007 22:46:03 +0200 Subject: Shebang or Hashbang for modules or not? In-Reply-To: References: <1176308951.932721.197630@y80g2000hsf.googlegroups.com> <461d56e9$0$27586$426a74cc@news.free.fr> Message-ID: <461fe2d8$0$11935$426a74cc@news.free.fr> Jorgen Grahn a ?crit : > On Thu, 12 Apr 2007 00:24:12 +0200, Bruno Desthuilliers wrote: > >>Chris Lasher a ?crit : >> >>>Should a Python module not intended to be executed have shebang/ >>>hashbang (e.g., "#!/usr/bin/env python") or not? >> >>The shebang is only useful for files that you want to make directly >>executable on a *n*x system. They are useless on Windows, > > > Probably (unless setup.py uses them for something meaningful there, > too). But of course often you don't know that the file will always be > used only on Windows, or that the Windows user won't prefer Cygwin. From a practical POV, I consider cygwin as a *n*x system. And FWIW, I mentionned this platform specificness because it might not be clear to anyone reading the OP. > >>and not >>technically required to use the file as a main program -ie: you can >>always run it like this: >>$ /path/to/python filename.py > > > You can, but sometimes it's not appropriate. That's another question. What I meant here is that you don't technically need the shebang and x bit to allow execution of a Python file. IOW, the shebang is only meaningfull for python files intented to be effectivly used as a program. > If you distribute a > Python program to Unix users in that form, they may not want to know > or care which language it's written in. Especially if you decide, a > few releases later, that you want to switch to Perl or something. No one in it's own mind would decide to switch from Python to Perl !-) More seriously, and as far as I'm concerned, when I want to make a python script (by opposition to a python 'module') available as a unix command, I either use a symlink or a shell script calling the python script. > I realise that you took a more narrow view than I do above, I mostly tried to answer the OP question. > so > please see this as additional notes rather than critisism. It's just > that I am struggling with people at work who feel program names > should encode whatever language they happen to be written in, OMG. > and so > I am a bit oversensitive ... I can understand this... > >>>I'm used to having a >>>shebang in every .py file >> >>An encoding declaration might be more useful IMHO !-) > > > They are not mutually exclusive, if that is what you mean. Of course not. But one is always usefull (and will become more or less mandatory in a near future IIRC), while the other is either totally useless (module files) or only partially useful (script files). > I always use both. Even in modules ????? From kw at codebykevin.com Sat Apr 21 11:27:20 2007 From: kw at codebykevin.com (Kevin Walzer) Date: Sat, 21 Apr 2007 11:27:20 -0400 Subject: Do other Python GUI toolkits require this? In-Reply-To: References: Message-ID: <2163b$462a2d59$4275d90a$19243@FUSE.NET> Kevin Walzer wrote: > From the introduction to PyObjC, the Python-Objective-C bridge on Mac > OS X: > > "As described in Objective-C for PyObjC users the creation of > Objective-C objects is a two-stage process. To initialize objects, first > call a class method to allocate the memory (typically alloc), and then > call an initializer (typically starts with init). Some classes have > class methods which perform this behind the scenes, especially classes > that create cached, immutable, or singleton instances." > > An example: > > myObject = NSObject.alloc().init() > > I know Tkinter doesn't require any manual memory allocation of this > sort. Does wxPython, PyQt, PyGtk require anything like this when > creating objects? > Thanks to all for an illuminating thread on the mathematical implications of "learning curve" and other aspects. This thread has wandered pretty far from my original question (above) but I got at least one useful answer, so I am grateful. -- Kevin Walzer Code by Kevin http://www.codebykevin.com From bj_666 at gmx.net Sat Apr 28 07:58:06 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Sat, 28 Apr 2007 13:58:06 +0200 Subject: Beginner Ping program References: <1177739647.737759.32610@u30g2000hsc.googlegroups.com> <1177755579.454423.35590@n59g2000hsh.googlegroups.com> Message-ID: In <1177755579.454423.35590 at n59g2000hsh.googlegroups.com>, Linus Cohen wrote: > Actually the class ping bit is a placeholder. I'm actually developing > a module with python implementations of most standard network/internet > tools such as telnet, tracert, whois etc. It will be called inettools, > and the ping function is what I'm working on first. Still doesn't explain why it is a class. Ciao, Marc 'BlackJack' Rintsch From nate.finch at gmail.com Thu Apr 5 09:04:36 2007 From: nate.finch at gmail.com (Nate Finch) Date: 5 Apr 2007 06:04:36 -0700 Subject: Why NOT only one class per file? In-Reply-To: References: <1175721799.714907.52770@o5g2000hsb.googlegroups.com> <46142acc$0$7532$426a34cc@news.free.fr> <4614b40e$0$26843$426a74cc@news.free.fr> Message-ID: <1175778276.603838.86500@l77g2000hsb.googlegroups.com> So, here's a view from a guy who's not a python nut and has a long history of professional programming in other languages (C++, C, C#, Java) I think you're all going about this the wrong way. There's no reason to *always* have one class per file. However, there's also no reason to have 1600 lines of code and 50 classes in one file either. You talk about the "changing file dance", but what about the "scroll for 30 seconds" dance? What about the "six different conflicts in source control because everything's in one file" dance? I think it doesn't matter how many classes and/or functions you have in one file as long as you keep files to a reasonable size. If you've ever worked on a medium to large-scale project using multiple developers and tens or hundreds of thousands of lines of code, then you know that keeping code separate in source control is highly important. If I'm working on extending one class and someone else is working on another class... it's much less of a headache if they're in separate files in source control. Then you don't have to worry about conflicts and merging. I think that's the number one benefit for short files (not necessarily just one class per file). My cutoff is around 500 lines per file. If a file goes much over that, it's really time to start looking for a way to break it up. Sure, if all your classes are 4 lines long, then by all means, stick them all in one file. But I don't think that's really any kind of valid stance to argue from. Sure, if you don't need organization, it doesn't matter what organization technique you use. But if you do need organization, it does matter. And I think one class per file is an acceptable way to go about it, especially when your classes tend to be over a couple hundred lines long. -Nate From rafaelc at dcc.ufmg.br Sat Apr 7 02:20:24 2007 From: rafaelc at dcc.ufmg.br (Rafael Almeida) Date: Sat, 7 Apr 2007 03:20:24 -0300 Subject: Understanding Python's interpreter Message-ID: <20070407032024.bb27f5ee.rafaelc@dcc.ufmg.br> Hello, I'm studying compilers now on my university and I can't quite understand one thing about the python interpreter. Why is its input a binary file (pyc)? The LOAD_CONST opcode is 100 (dec) and STORE_FAST's is 125 (dec). The translation of the following code: foo.py: x = 10 Could be this: foo.pyc: 100 10 125 0 That way you wouldn't need code such as static void w_long(long x, WFILE *p) { w_byte((char)( x & 0xff), p); w_byte((char)((x>> 8) & 0xff), p); w_byte((char)((x>>16) & 0xff), p); w_byte((char)((x>>24) & 0xff), p); } since you could read it with strtol and write back using a simple printf. So you wouldn't need a buch of casts by simple using ascii input and output. What's the reason for having it in a binary form instead of writting it in ascii? (yeah, I know ascii would be binary also, but I think you get my point.) So I was writting this interpreter for some assembly language defined in class and I did something like python does, so I had a binary file to interpret. After a while I thought it was far harder to program. And when I tried to code an assembler my problems got greater, as I wanted to code it in python (the interpreter was in C++) and I had a hard time trying to figure out how I would print something that's not a ascii or unicode string. As for the benefits, I couldn't figure out any. I hope I'm not too offtopic here, but I thought this was probably the best news to ask this. If someone thinks there's another news that's more appropriate, please tell me. []'s Rafael From pecora at anvil.nrl.navy.mil Wed Apr 4 13:06:59 2007 From: pecora at anvil.nrl.navy.mil (Lou Pecora) Date: Wed, 04 Apr 2007 13:06:59 -0400 Subject: An error of matrix inversion using NumPy References: <1175692530.364381.77110@n59g2000hsh.googlegroups.com> <1175698343.919351.9710@o5g2000hsb.googlegroups.com> Message-ID: In article <1175698343.919351.9710 at o5g2000hsb.googlegroups.com>, "lancered" wrote: > Here is the eigenvalues of KK I obtained: > > >>> linalg.eigvals(KK) > array([ 1.11748411e+05, 3.67154458e+04, 3.41580846e+04, > 2.75272440e+04, 2.09790868e+04, 1.86242332e+04, > 8.68628325e+03, 6.66127732e+03, 6.15547187e+03, > 4.68626197e+03, 3.17838339e+03, 2.84888045e+03, > 1.88279736e+03, 1.32427574e+03, 1.04946287e+03, > 5.79303171e+02, 3.83111876e+02, 4.93826556e-12, > 1.50263232e-12]) > > You are right. The ratio of max/min eigenvalues is 7.4368432669e+016 > Maybe this exceed the of precision of my machine? > > Is there any tricks for me to be able to deal with this matrix > correctly with > NumPy? That sounds large to me, too. Close to the floating point accuracy. The problem is not with NumPy,but with double precision numbers. No routine can save you if the condition number is large. However, several people here have noted that you might be able to solve your problem by avoiding inverting the matrix in the first place. In other words, depending on your particular problem, there may be other ways to solve it beside brute force inversion. Can you Use a QR or SVD approach? -- Lou Pecora (my views are my own) REMOVE THIS to email me. From bbxx789_05ss at yahoo.com Mon Apr 9 02:17:07 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: 8 Apr 2007 23:17:07 -0700 Subject: Exec Statement Question In-Reply-To: References: Message-ID: <1176099427.158621.45580@o5g2000hsb.googlegroups.com> On Apr 8, 11:31 pm, "Gregory Pi?ero" wrote: > I'm curious why this code isn't working how I expect it to: > > import sys > d=3 > > def func1(a,b,c): > print a,b,c,d > print sys.path > > exec "func1(1,2,3)" in {'func1':func1} > > ---- > returns: > 1 2 3 3 > [ sys.path stuff ....] > > Since I'm telling exec to operate only within the context of the > dictionary I give it, why does it still see sys.path and d? I figured > it would throw a NameError. > > Is there a way to call exec such that it won't have access to any more > objects than I explicitly give it? > > Thanks, > > Greg I think the way it works is that when the def is parsed, a function object is created and assigned to the name func1. When the function object is created, d is "bound" to the global value 3, while a,b,c lie in wait for arguments to land in their gullets like venus fly traps. Your dictionary has a key whose value is a reference to the function object, which already has the value 3 bound to d. From __peter__ at web.de Sun Apr 15 01:13:26 2007 From: __peter__ at web.de (Peter Otten) Date: Sun, 15 Apr 2007 07:13:26 +0200 Subject: Making a tree out of a 2 column list References: <1176568327.669229.22910@b75g2000hsg.googlegroups.com> Message-ID: Sebastian Bassi wrote: > On 14 Apr 2007 09:32:07 -0700, mensanator at aol.com wrote: > > > def tree_path(key,tree,indent): > >?????print?'\t'*indent,key > >?????if?tree.has_key(key): > >?????????for?m?in?tree[key]: > >?????????????tree_path(m,tree,indent+1) > >?????return > > Thank you. It worked!. > I changed it a bit to return a list with the results: > > def tree_path(key,tree,hijos): > ????????hijos.append(key) > ????????if tree.has_key(key): > ????????????????for m in tree[key]: > ????????????????????????tree_path(m,tree,hijos) > ????????return hijos > > Then I call it like this: > > MyList=tree_path(9608,tree,[]) Depending on your input data you may need to add some cycle detection. For example, try it with tree_path(1, {1:[2], 2:[1]}, []) Peter From steve at REMOVE.THIS.cybersource.com.au Sun Apr 22 02:21:55 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Sun, 22 Apr 2007 16:21:55 +1000 Subject: Handy short cut for formatting elapsed time in floating point seconds References: <1177204141.785661.203320@n59g2000hsh.googlegroups.com> Message-ID: On Sat, 21 Apr 2007 18:09:01 -0700, Paul McGuire wrote: > I am doing some simple timing of some elements of Python scripts, and > the simplest is to just call time.time() before and after key elements > of the script: > > t1 = time.time() > > # do lengthy operation > > t2 = time.time() > print "That took %f seconds" % (t2-t1) I dispute that this is easiest. I think the timeit module is easier, and more reliable. You probably should be putting the lengthy operation in a function (you're going to run the test more than once, right?), so you can do this: import timeit timeit.Timer("function()", "from __main__ import function").repeat() or even: s = """ # insert your code # for the length operation # here """ timeit.Timer(s, "").repeat() Call help(timeit) for more details. -- Steven. From oscartheduck at gmail.com Sat Apr 28 20:07:18 2007 From: oscartheduck at gmail.com (James) Date: Sat, 28 Apr 2007 18:07:18 -0600 Subject: strip newline from string Message-ID: I have a program that reads as follows: #!/usr/bin/env python import string import os def ssher(): #ssher takes a port input (if none entered, it defaults to 2024) and def connector(): #connector checks to see if the autoconfigure file exists. If so, it uses that #for information for where the public ssh machine exists, if not then it tries #something sensible. global ipAddress, username if os.path.isfile("autoconf.txt"): autoconfigurer = open ( 'autoconf.txt' ) ipAddress = autoconfigurer.readline() username = autoconfigurer.readline() autoconfigurer.close() string.strip(ipAddress) string.strip(username) print "IPAddress is %s and username is %s" % (ipAddress, username) print "using if" else: from getpass import getuser ipAddress = raw_input("We're 'pitching' this connection to another machine. What's its IP address? Remember, this is probably a public address.") username = getuser() string.strip(username) print "username is %s" % username print "Attempting to set up the tunnel from %s as %s" % (ipAddress, username) cmd2 = 'ssh -nNT -R 2024:localhost:2024 %s@%s' % (username, ipAddress) os.system(cmd2) connector() The autoconf.txt contains two lines, which first has an ip address and second a username. The problem I'm having is that the string.strip() doesn't appear to be stripping the newline off the username. Any ideas? If you need more information, just ask! James -------------- next part -------------- An HTML attachment was scrubbed... URL: From spradml at gmail.com Sat Apr 14 06:38:31 2007 From: spradml at gmail.com (Pradnyesh Sawant) Date: Sat, 14 Apr 2007 16:08:31 +0530 Subject: problem with qthread and signal/slot In-Reply-To: <80628d680704132144w65418cf1sd5406b709c9eb16c@mail.gmail.com> References: <80628d680704132144w65418cf1sd5406b709c9eb16c@mail.gmail.com> Message-ID: <80628d680704140338w3c931491r6de147a2fe308fef@mail.gmail.com> Hello, i've written a small pyqt code which increments a counter in the backend, and prints it on the frontend. However, i'm passing a dummy string var along with it in the signal/slot mechanism. The problem is that from the 2nd call onwards, the string gets printed, but NOT in the 1st call. (eg, in the foll code i get:- 1, (2, 'a'), (3, 'a'), ...) The code is:- ************************************************** import time import sys from PyQt4 import QtGui, QtCore class Counter(QtCore.QThread): def __init__(self): QtCore.QThread.__init__(self) self.cntr = 0 def run(self): while True: self.cntr += 1 self.emit(QtCore.SIGNAL("showCntr"), (self.cntr, "a")) time.sleep(1) if self.cntr == 10: break class Gui(QtGui.QDialog): def __init__(self, parent = None): QtGui.QDialog.__init__(self, parent) frameStyle = QtGui.QFrame.Sunken | QtGui.QFrame.Panel self.lCntr = QtGui.QLabel() self.lCntr.setFrameStyle(frameStyle) loGrd = QtGui.QGridLayout() loGrd.addWidget(self.lCntr, 0, 0) self.setLayout(loGrd) self.setWindowTitle(self.tr("Counter")) def showCntr(self, val): print val self.lCntr.setText(str(val)) if __name__ == "__main__": app = QtGui.QApplication(sys.argv) dialog = Gui() cntr = Counter() cntr.start() QtCore.QObject.connect(cntr, QtCore.SIGNAL("showCntr"), dialog.showCntr, QtCore.Qt.QueuedConnection) sys.exit(dialog.exec_()) ************************************************** Also, this is my 1st ever prog with signals/slots across threads; and am a newbie to python and pyqt. So please be considerate and kind enough to point out mistakes/better approaches with the above code. Thanks a lot! -- warm regards, Pradnyesh Sawant -- Be yourself, everyone else is taken. --Anon From gagsl-py2 at yahoo.com.ar Thu Apr 12 19:32:43 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 12 Apr 2007 20:32:43 -0300 Subject: Binary To File References: <695408014765593209@unknownmsgid> <5f56302b0704121616n1d3e05dfv2e5fbb4fe4d3fc6e@mail.gmail.com> Message-ID: En Thu, 12 Apr 2007 20:16:28 -0300, Daniel Nogradi escribi?: >> Is there an easy way to take binary data and build it into a file? > > myblob = ......... # let's say you got it from your database somehow > myjpeg = open( 'image.jpg', 'w' ) > myjpeg.write( myblob ) > myjpeg.close( ) For some platforms using open(..., "wb") is important, and won't hurt on the others, so it's the preferred way. -- Gabriel Genellina From stephen04 at tiscali.co.uk Wed Apr 18 20:54:53 2007 From: stephen04 at tiscali.co.uk (Stevie) Date: Thu, 19 Apr 2007 01:54:53 +0100 Subject: Using the Python interpreter References: <1176942756.283173.234750@n76g2000hsh.googlegroups.com> Message-ID: <0001HW.C24C7C6D00157A3CB019F94F@news.tiscali.co.uk> On Thu, 19 Apr 2007 01:32:36 +0100, tkpmep at hotmail.com wrote (in article <1176942756.283173.234750 at n76g2000hsh.googlegroups.com>): > Instead of starting IDLE as I normally do, I started the Python > interpreter and tried to run a program. I got a Python prompt (>>>), > and then tried unsuccessfully to run a Python script named Script1.py > that runs perfectly well in IDLE. Here's what I did: > >>>> Script1.py > Traceback (most recent call last): > File "", line 1, in ? > NameError: name Script1 is not defined > >>>> python Script1.py > File "", line 1 > python Script1.py > SyntaxError: invalid syntax > > I can load it (and have it execute) by typing > >>>> import Script1 > 0 > 1 > 2 > 3 > 4 > > and if I edit it, I can then execute it by reloading it > >>>> import Script1 > 0 > 1 > 2 > 3 > 4 > > > But this seems contrived - is there no way to repeatedly run Script1 > from the interpreter without reloading it? > > Thomas Philips > Why dont you wrap the code into a procedure (a def statement) in your script1 file import it using the from xxx import yyy statement. Then you can use it over and over. By the sounds of it your script is full of inline code that is executed when its imported and therefore only runs once. To get it to re-run you have to repeatedly import it. Your really should only need to do this under very specific circumstances. Steve From spamtrap at dot-app.org Sun Apr 29 20:42:39 2007 From: spamtrap at dot-app.org (Sherm Pendley) Date: Sun, 29 Apr 2007 20:42:39 -0400 Subject: SEO - Search Engine Optimization - Seo Consulting References: <1177808356.681710.42980@n76g2000hsh.googlegroups.com> Message-ID: "Alvin Bruney [MVP]" writes: >>Top posting > Did not. I replied to the message at the bottom of the thread. Congratulations, you've now made a fool of yourself in public. Top posting has nothing to do with where your reply is placed with respect to other messages. Top posting is when you add your text above the quoted material in your reply - as you did once again in what I'm replying to. When you open a book, do you start at the bottom of the page and read up? I didn't think so. >>Call yourself an MVP, that's a joke Slick. > Yup, I do call myself an MVP, it's not a joke either. It is when you don't have a clue. sherm-- -- Web Hosting by West Virginians, for West Virginians: http://wv-www.net Cocoa programming in Perl: http://camelbones.sourceforge.net From dbenson at eecs.wsu.edu Sun Apr 15 19:00:11 2007 From: dbenson at eecs.wsu.edu (dbenson at eecs.wsu.edu) Date: 15 Apr 2007 16:00:11 -0700 Subject: is laziness a programer's virtue? In-Reply-To: <1176654319.273907.167280@q75g2000hsh.googlegroups.com> References: <1176654319.273907.167280@q75g2000hsh.googlegroups.com> Message-ID: <1176678011.470381.261290@b75g2000hsg.googlegroups.com> Of course, for functional languages, 'lazy' means something rather different... From steve at holdenweb.com Thu Apr 5 09:14:25 2007 From: steve at holdenweb.com (Steve Holden) Date: Thu, 05 Apr 2007 09:14:25 -0400 Subject: operator overloading In-Reply-To: <1175726966.127531.273500@b75g2000hsg.googlegroups.com> References: <1175679412.741899.45990@l77g2000hsb.googlegroups.com> <1175711246.488717.262560@e65g2000hsc.googlegroups.com> <1175726966.127531.273500@b75g2000hsg.googlegroups.com> Message-ID: <4614F631.7060302@holdenweb.com> sjdevnull at yahoo.com wrote: > On Apr 4, 4:55 pm, "Terry Reedy" wrote: >> "Ziga Seilnacht" wrote in message >> >> news:1175711246.488717.262560 at e65g2000hsc.googlegroups.com... >> | This looks like a bug in Python. It works for all the other >> | operators: > [SNIP] >> | >>> i ** 3 >> | 74088 >> | >> | You should submit a bug report to the bug tracker: >> | >> |http://sourceforge.net/bugs/?group_id=5470 >> >> Nice test. I thought maybe __pow__ might be different in not having a >> reverse form, but indeed, int has an __rpow__ method. >> >> Before submitting, make sure that this does not work in 2.5, and then say >> so in the bug report. In fact, copy the version/system info that the >> interactive interpreter puts up when it starts. > > FWIW: > Python 2.5 (r25:51908, Jan 21 2007, 03:10:25) > [GCC 3.4.6 20060404 (Red Hat 3.4.6-3)] on HOSTNAME_REDACTED > Type "help", "copyright", "credits" or "license" for more information. >>>> class MyInt(int): > ... __pow__ = int.__add__ > ... >>>> i=MyInt(42) >>>> i**3 > 74088 > Interestingly, Jython doesn't suffer from this drawback, which I suspect is due to special-casing of the __pow__ operator that was discussed quite recently on python-dev without anybody noticing this aspect of things. C:\jython2.2b1>jython [...] >>> class S(int): ... pass ... >>> S.__pow__ = S.__add__ >>> s = S(12) >>> s ** 2 14 >>> Note that it still doesn't work to override the *instance's* method. 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 howe.steven at gmail.com Thu Apr 5 03:55:50 2007 From: howe.steven at gmail.com (Steven Howe) Date: Thu, 05 Apr 2007 00:55:50 -0700 Subject: Why NOT only one class per file? In-Reply-To: References: <1175721799.714907.52770@o5g2000hsb.googlegroups.com> Message-ID: <4614AB86.50103@gmail.com> Dennis Lee Bieber wrote: > On 4 Apr 2007 14:23:19 -0700, "Chris Lasher" > declaimed the following in comp.lang.python: > > >> A friend of mine with a programming background in Java and Perl places >> each class in its own separate file in . I informed him that keeping >> all related classes together in a single file is more in the Python >> idiom than one file per class. He asked why, and frankly, his valid >> question has me flummoxed. >> >> > As I recall, Java essentially doesn't offer a CHOICE... So I'd > consider any argument that "one per file" is best to be flawed if based > upon Java practice. After all, if one can not even experiment with other > ways, how can one really evaluate the options? {and I consign Perl to > realms described by Dante} > On class per file was easier to do when Java was developed (remember it was develop to control vending machines; scary. Reminds me of the movie 'Tron'). The desktop computer for Sun was an IPC workstation. Nice but no balls and no good editors that could have 24+ tabs open or a way to 'close' sections of coherent text (which are common in my preferred editor, Komodo). So your friend is arguing the past. Ask him if he's a Republican too or needs a serious reboot. I have a good pair of boot to give him a kick in the ass (Democrats would need a kick in the head to reset; we all know what organ Republican think with). sph From gigs at hi.t-com.hr Wed Apr 25 18:40:37 2007 From: gigs at hi.t-com.hr (Gigs_) Date: Thu, 26 Apr 2007 00:40:37 +0200 Subject: tkinter listbox In-Reply-To: References: Message-ID: Gigs_ wrote: > I have two listbox on frame, and at same time i need to use one option > from both listbox. But when I click on first than on second listbox > first get deselected. > > How to make this? Is it possiblE? i found, just need to use exportselection=0 From aleax at mac.com Sat Apr 14 21:29:35 2007 From: aleax at mac.com (Alex Martelli) Date: Sat, 14 Apr 2007 18:29:35 -0700 Subject: Python Feature Request: Allow changing base of member indices to 1 References: <1176546465.632410.52630@w1g2000hsg.googlegroups.com> <1176577744.688946.317740@y5g2000hsa.googlegroups.com> Message-ID: <1hwko6m.8kp2vn1vil22iN%aleax@mac.com> faulkner wrote: ... > __future__ is used to access upcoming features, and changing the base > offset is not [and never will be] slated for future development. zero > has been used as the base offset in all real languages since the dawn > of time, and isn't something that can be changed without seriously > breaking heads. While I agree that base-1 indexing in Python would be crazy, I resent the implication that Fortran isn't "a real language" -- it WAS the first high level language of any real worth, it survived over 50 years so far, and its chief developer John Backus, alas recently departed, vastly deserved his 1977 Turing Award (and not just for his later contributions in syntax notation [the BNF] and functional programming). "The dawn of time" for high-level languages was exactly the '50s, when Fortran was born -- with 1-based array indexing, arguably a minor technical error (as definitely was the case for the fact that DO-loops always executed 1+ times, never 0 times), but definitely not enough to disqualify it as "a real language". Alex From development-2006-8ecbb5cc8aREMOVETHIS at ANDTHATm-e-leypold.de Tue Apr 17 09:25:22 2007 From: development-2006-8ecbb5cc8aREMOVETHIS at ANDTHATm-e-leypold.de (Markus E Leypold) Date: Tue, 17 Apr 2007 15:25:22 +0200 Subject: is laziness a programer's virtue? References: <1176757271.282365.319740@n76g2000hsh.googlegroups.com> <1176797558.403629.53140@b75g2000hsg.googlegroups.com> Message-ID: <5pwt0bnnel.fsf@hod.lan.m-e-leypold.de> Mirco Wahab writes: > Markus E Leypold wrote: >> Trying to correct Xah's behaviour is probably impossible. People who >> publish pictures of themselves as he does on the WWW probably don't >> have any sense of embarrasment left ... > > you think of stuff like this > www DOT m-e-leypold DOT de SLASH leypold-small.jpg > ;-) ;-) No. This actually is a picture of myself I like (very much indeed), even if the long hair has gone now (I have to update the site some time within the next weeks, but the original site generator has died and the new site ain't ready yet). No, what I mean, is what one poster already posted to c.l.f, what you'll find looking for Xah Lee with Google image search and I won't link here. My warning: You probably don't want to see a picture of Xah's penis in full readiness. That is, what I consider embarrasing. > The reason why I answered your posting at all (besides > seeing your x-post going into 5 ng's) is your mentioning Your's too (you only changed the f'up) , and now I've done the ultimate sin and reset the F'up for this answer (if you post URLs to pictures of me, I reserve the right to say that I LIKE this picture :-) But that's the last x-post in this thread, I promise. Regards -- Markus From reder at ieee.org Sat Apr 14 21:19:56 2007 From: reder at ieee.org (Leonard J. Reder) Date: Sun, 15 Apr 2007 01:19:56 GMT Subject: Python and XML? In-Reply-To: <46209A55.9070102@web.de> References: <46209A55.9070102@web.de> Message-ID: <46217DAE.7040501@ieee.org> Thanks for the response. This package does look interesting. What I as really after though was other possible solutions like JAX in the Java world or Gnosis in the Python world. Something that can take a Relax NG Schema and compile it into a bunch of parser/generator objects for handling an XML format. Guess I am going to just have try out Gnosis since it seems like the only game in town. Len Stefan Behnel wrote: > Leonard J. Reder wrote: >> What is the best way to process a Relax NG Schema and auto generate XML >> Python parser/generator code? >> Any suggestions? > > Not sure what you mean with "XML Python parser/generator code", but regarding > RNG, you should definitely give lxml a try. It may already be what you were > looking for anyway. > > http://codespeak.net/lxml > > Have fun, > Stefan -- =================================== Leonard J. Reder Home office email : reder at ieee.org Lab email : reder at jpl.nasa.gov Lab web page : http://reder.jpl.nasa.gov =================================== From arnodel at googlemail.com Wed Apr 18 14:54:35 2007 From: arnodel at googlemail.com (Arnaud Delobelle) Date: 18 Apr 2007 11:54:35 -0700 Subject: Iterate through a dictionary of lists one "line" at a time In-Reply-To: <1176921542.567121.248820@b58g2000hsg.googlegroups.com> References: <1176921542.567121.248820@b58g2000hsg.googlegroups.com> Message-ID: <1176922475.420167.57490@p77g2000hsh.googlegroups.com> On Apr 18, 7:39 pm, wswilson wrote: > Here is my code: > > listing = {'id': ['a', 'b', 'c'], 'name': ['Joe', 'Jane', 'Bob']} > > I need to output: > > id name > a Joe > b Jane > c Bob > > I could do: > > print 'id', 'name' > for id, name in zip(listing['id'], listing['name']): print id, name > > but that only works if there are two entries in the dictionary, id and > name, and I know what they are. My problem is I don't know how many of > these entries there will be. Thanks for any help you can give! You can use zip(*sequence_of_sequences) eg zip(*[[1,2,3],[4,5,6]) returns [[1,4], [2,5], [3,6]] (You can think of it as a transposition function) For example: keys, item_lists = zip(*listing.iteritems()) print " ".join(keys) for items in zip(*item_lists): print " ".join(items) would work. HTH -- Arnaud From jeremy+complangpython at jeremysanders.net Thu Apr 19 04:27:23 2007 From: jeremy+complangpython at jeremysanders.net (Jeremy Sanders) Date: Thu, 19 Apr 2007 09:27:23 +0100 Subject: Beginner: Formatting text output (PyQt4) References: Message-ID: Glen wrote: > What seems to be happening is that the font that pyqt is using is not > fixed width, so I did this: > qTxtFormat = QTextCharFormat() > qTxtFormat.setFontFixedPitch(True) > ui.textEdit.setCurrentCharFormat(qTxtFormat) Does something like ui.textEdit.setCurrentFont(QFont('fixed')) work? It seems to work for me if you use plain text. Tabs or html/rich text formatting should be a better way to get the layout (or just use a table). Jeremy -- Jeremy Sanders http://www.jeremysanders.net/ From carsten at uniqsys.com Thu Apr 12 10:37:55 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Thu, 12 Apr 2007 10:37:55 -0400 Subject: tuples, index method, Python's design In-Reply-To: References: <1175953520.316208.241490@o5g2000hsb.googlegroups.com> <7xzm5igbrb.fsf@ruckus.brouhaha.com> <1176200361.260546.280510@n76g2000hsh.googlegroups.com> <740c3aec0704100824m132c45fbi5c4c3ec0c0fa3a67@mail.gmail.com> Message-ID: <1176388675.4220.46.camel@dot.uniqsys.com> On Thu, 2007-04-12 at 14:10 +0000, Antoon Pardon wrote: > People are always defending duck-typing in this news group and now python > has chosen to choose the option that makes duck-typing more difficult. Au contraire! The "inconsistent" behavior of "in" is precisely what duck-typing is all about: Making the operator behave in a way that makes sense in its context. Nobody seems to be complaining about "+" behaving "inconsistently" depending on whether you're adding numbers or sequences. -Carsten From danb_83 at yahoo.com Sat Apr 14 23:34:46 2007 From: danb_83 at yahoo.com (Dan Bishop) Date: 14 Apr 2007 20:34:46 -0700 Subject: Python Feature Request: Allow changing base of member indices to 1 In-Reply-To: References: <1176546465.632410.52630@w1g2000hsg.googlegroups.com> <4620b47b$0$14410$9b622d9e@news.freenet.de> <1176557999.665663.299740@y80g2000hsf.googlegroups.com> <1176559643.450533.296850@n59g2000hsh.googlegroups.com> Message-ID: <1176608086.323323.154260@d57g2000hsg.googlegroups.com> On Apr 14, 10:55 am, Dennis Lee Bieber wrote: > The FORTRAN family had started as 1-based (F95, and Ada, now allow > for each array to have its own "base" => x : array (-10..10) of float). > Pascal, I forget... Pascal allows arbitrary array bases. It's where Ada got the idea. From exarkun at divmod.com Sun Apr 22 15:37:55 2007 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Sun, 22 Apr 2007 15:37:55 -0400 Subject: Select weirdness In-Reply-To: Message-ID: <20070422193755.19381.1909688744.divmod.quotient.4117@ohm> On Sun, 22 Apr 2007 11:42:10 -0700, Ron Garret wrote: >I think I've figured out what's going on. > > [snip] > >As you can see, the select call shows input available for a while (five >lines) and then shows no input available despite the fact that there is >manifestly still input available. > >The answer is obvious: select is looking only at the underlying socket, >and not at the rfile buffers. > >So... is this a bug in select? Or a bug in my code? In your code, unfortunately. select() is for file descriptors, not arbitrary buffering Python file objects. You shouldn't use readline if you want select to work right, and vice versa. Use read() and do your own line buffering (it's trivial) or don't use select (which I believe has been suggested, and I can't tell from your code why you want to use select in the first place). Or avoid the low-level networking entirely and use a high-level HTTP library that takes care of these details for you. Jean-Paul From bdesth.quelquechose at free.quelquepart.fr Tue Apr 3 17:53:27 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Tue, 03 Apr 2007 23:53:27 +0200 Subject: Need help on reading line from file into list In-Reply-To: <1175633434.823351.69800@q75g2000hsh.googlegroups.com> References: <1175630106.220186.107900@y66g2000hsf.googlegroups.com> <4612b8f2$0$28546$426a74cc@news.free.fr> <1175633434.823351.69800@q75g2000hsh.googlegroups.com> Message-ID: <4612c400$0$26325$426a74cc@news.free.fr> bahoo a ?crit : > On Apr 3, 5:06 pm, Bruno Desthuilliers > wrote: > (snip) >> >>> open('source.txt').readlines() >>['0024\n'] >> >>> map(str.strip, open('source.txt').readlines()) >>['0024'] >> >>> open('source.txt').read() >>'0024\n' >> >>> list(open('source.txt').read().strip()) >>['0', '0', '2', '4'] >> >>> > > > Thanks, this helped a lot. > I am now using the suggested > map(str.strip, open('source.txt').readlines()) Note that for production code, you should do it the long way (ie: explicitely opening and handling exceptions to make sure you're closing it). > However, I am a C programmer, Welcome onboard then. > and I have a bit difficulty > understanding the syntax. > > I don't see where the "str" came from, It's the builtin string type. strip() is a method of string objects, and in Python, instance.method() is equivalent to Class.method(instance). > so perhaps the output of > "open('source.txt').readlines()" is defaulted to "str? Nope. The result of file.readlines() is a list of strings. The builtin function map(callable, sequence) return the result of applying function 'callable' to each element of the sequence - the imperative equivalent would be: f = open('source.txt') result = [] for line in f.readlines(): # line is a str instance, so we call strip() directly on it result.append(line.strip()) f.close() There's also the 'list comprehension' syntax, which you'll see quite frequently: result = [line.strip() for line in f.readlines()] HTH From scanepa at gmail.com Sun Apr 29 09:52:49 2007 From: scanepa at gmail.com (Stefano Canepa) Date: 29 Apr 2007 06:52:49 -0700 Subject: Asynchronous XML-RPC client library? In-Reply-To: References: Message-ID: <1177854769.627406.214270@n59g2000hsh.googlegroups.com> On 29 Apr, 07:11, Jarek Zgoda wrote: > Is there anything like that? Googling yields many articles on async > servers, but virtually nothing on clients. I have to talk to remote in > an environment that does not allow threads... > > -- > Jarek Zgodahttp://jpa.berlios.de/ Why don't you try twisted (http://www.twistedmatrix.com) Bye Stefano From nitte.sudhir at gmail.com Wed Apr 4 03:49:44 2007 From: nitte.sudhir at gmail.com (kath) Date: 4 Apr 2007 00:49:44 -0700 Subject: how to build a forum in Python? Message-ID: <1175672984.836097.21610@n76g2000hsh.googlegroups.com> Hi everybody, I am planning to build a web portal, which is mainly a discussion forum for our corporate environment. I want to implement it with Python. Because this project is very new to me and I have no idea about how to go about this. I searched in google for getting some tuts/ guidelines about this but ended up in getting tuts for building website in PHP. I would like to know some useful links to learn or some usefull guidelines to build my fourm in Python. Also is any forums which are built using Python? I would appreciate your help, Thanks in advance, kath. From sbassi at clubdelarazon.org Sun Apr 15 19:08:19 2007 From: sbassi at clubdelarazon.org (Sebastian Bassi) Date: Sun, 15 Apr 2007 20:08:19 -0300 Subject: Making a tree out of a 2 column list In-Reply-To: <1176677087.151276.223580@b75g2000hsg.googlegroups.com> References: <1176568327.669229.22910@b75g2000hsg.googlegroups.com> <1176677087.151276.223580@b75g2000hsg.googlegroups.com> Message-ID: <9e2f512b0704151608q685190fet96f5ac7f33d00e4d@mail.gmail.com> On 15 Apr 2007 15:44:47 -0700, bearophileHUGS at lycos.com wrote: > But errors and bugs do happen, inside data too; so often it's better > to be on safe side if the safe code is fast enough. Yes, I agree since I've seen lot of errors in data. But this data comes from a taxonomy tree made by the NCBI, that is why I assume the data is right. From steven.bethard at gmail.com Wed Apr 4 11:41:38 2007 From: steven.bethard at gmail.com (Steven Bethard) Date: Wed, 04 Apr 2007 09:41:38 -0600 Subject: optparse option prefix In-Reply-To: References: Message-ID: <4613C732.1030307@gmail.com> Mathias Waack wrote: > We've integrated python into a legacy application. Everything works fine (of > course because its python;). There's only one small problem: the > application reads the commandline and consumes all arguments prefixed with > a '-' sign. Thus its not possible to call a python module from the > commandline with a parameter list containing options prefixed by '-' > or '--' signs. Thats not a major problem, but it prevents us from using th > optparse module. Is there a way to change to prefix, so one could use a '+' > (for instance) to mark command line options for optparse? If your arguments come in a particular order, you could use argparse (http://argparse.python-hosting.com/) to parse them as positional arguments:: >>> parser = argparse.ArgumentParser() >>> parser.add_argument('foo') >>> parser.add_argument('bar', nargs='+') >>> parser.add_argument('baz') >>> parser.parse_args('FOO BAR1 BAR2 BAR3 BAZ'.split()) Namespace(bar=['BAR1', 'BAR2', 'BAR3'], baz='BAZ', foo='FOO') I've also filed a feature request for you asking for options with '+' as a prefix: http://argparse.python-hosting.com/ticket/30 I'll see if I can make some time to implement it, but if you'd like to take a look yourself, I can see '-' being hard-coded in at least: add_argument() _get_optional_kwargs() consume_optional() within _parse_args() _parse_optional() _get_option_prefix_tuples() I guess there ought to be an easy way to customize the prefix characters... Maybe something like:: parser = argparse.ArgumentParser(prefix_chars='+') STeVe From samjnaa at gmail.com Sat Apr 14 10:24:32 2007 From: samjnaa at gmail.com (jamadagni) Date: 14 Apr 2007 07:24:32 -0700 Subject: Python Feature Request: Add the "using" keyword which works like "with" in Visual Basic In-Reply-To: References: <1176547372.584539.89170@q75g2000hsh.googlegroups.com> Message-ID: <1176560672.108264.44890@p77g2000hsh.googlegroups.com> > You already can emulate the using statement like this: You can emulate only assignments like this. How would you emulate function calls, like the ones in my example? From hq4ever at gmail.com Sat Apr 14 07:02:05 2007 From: hq4ever at gmail.com (Maxim Veksler) Date: Sat, 14 Apr 2007 14:02:05 +0300 Subject: ulimit on open sockets ? In-Reply-To: <82069913-B174-4701-8E81-7A82FAB7D040@mac.com> References: <1hwbp5h.1fnai9snzd1vpN%aleax@mac.com> <82069913-B174-4701-8E81-7A82FAB7D040@mac.com> Message-ID: On 4/13/07, Alex Martelli wrote: > > On Apr 12, 2007, at 1:17 PM, Maxim Veksler wrote: > ... > > Now, someone I work with suggested a simple work around "Pass the list > > objects in groups of 1024 each time to the select.select structure". I > > think it's acceptable and good advice, the thing is I don't know how > > to implement this "the python way" (that is - with out it being ugly). > > I don't understand how you're going to make it work (I see no select > calls in your code and I don't understand how you'd get one in there > by polling), but I'm going to just explain how to get slices of 1024 > items at a time from a long list. > Thank you. I'm attaching the full code so far for reference, sadly it still doesn't work. It seems that select.select gets it's count of fd's not from the amount passed to it by the sub_list but from the kernel (or whatever) count for the process; The main issue here is that it seems I won't be able to use select for the simple non-blocking process and am forced to check poll to see if that helps. The error I'm getting is still the same: # ulimit -n 500000 # python listener_sockets_range.py Traceback (most recent call last): File "listener_sockets_range.py", line 22, in ? ready_to_read, ready_to_write, in_error = select.select(select_cap_sockets, [], [], 0) ValueError: filedescriptor out of range in select() """ #!/usr/bin/env python import socket, select def get_non_blocking_socket(port_number): print port_number s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.setblocking(0) s.bind(('0.0.0.0', port_number)) s.listen(1) return s def slice_by_fd_limit(longlist, N=1024): for i in xrange(0, len(longlist), N): yield longlist[i:i+N] all_sockets = map(get_non_blocking_socket, xrange(10000, 20000)) while 1: for select_cap_sockets in slice_by_fd_limit(all_sockets): ready_to_read, ready_to_write, in_error = select.select(select_cap_sockets, [], [], 0) for nb_active_socket in all_sockets: if nb_active_socket in ready_to_read: conn, addr = nb_active_socket.accept() while 1: data = conn.recv(1024) if not data: break conn.send(data) conn.close() """ -- Cheers, Maxim Veksler "Free as in Freedom" - Do u GNU ? From surekap at gmail.com Sun Apr 29 19:41:42 2007 From: surekap at gmail.com (Prateek) Date: 29 Apr 2007 16:41:42 -0700 Subject: fastest way to find the intersection of n lists of sets In-Reply-To: References: <1177883328.835058.138990@p77g2000hsh.googlegroups.com> Message-ID: <1177890102.708578.70460@y5g2000hsa.googlegroups.com> On Apr 30, 3:48 am, James Stroud wrote: > Prateek wrote: > > I have 3 variable length lists of sets. I need to find the common > > elements in each list (across sets) really really quickly. > > > Here is some sample code: > > > # Doesn't make sense to union the sets - we're going to do > > intersections later anyway > > l1 = reduce(operator.add, list(x) for x in l1) > > l2 = reduce(operator.add, list(x) for x in l2) > > l3 = reduce(operator.add, list(x) for x in l3) > > > # Should I do this in two steps? Maybe by intersecting the two > > shortest lists first? > > s = frozenset(l1) & frozenset(l2) & frozenset(l3) > > > I'm assuming frozensets are (somehow) quicker than sets because > > they're immutable. > > > Any code suggestions? Maybe using something in the new fancy-schmancy > > itertools module? > > > Thanks, > > Prateek > > I don't understand why you cast to list. I would propose: > The reason why I'm casting to a list first is because I found that creating a long list which I convert to a set in a single operation is faster (although probably less memory efficient - which I can deal with) than doing all the unions. Prateek From alainpoint at yahoo.fr Wed Apr 4 07:34:11 2007 From: alainpoint at yahoo.fr (alain) Date: 4 Apr 2007 04:34:11 -0700 Subject: SNMP agent In-Reply-To: References: <1175680387.575097.4590@e65g2000hsc.googlegroups.com> Message-ID: <1175686451.614022.171650@b75g2000hsg.googlegroups.com> On Apr 4, 1:30 pm, alf wrote: > twistedmatrix.org? I already took a look at it but the agent functionality is somewhat primitive. I need something production-ready. Alain From jzgoda at o2.usun.pl Fri Apr 13 03:43:07 2007 From: jzgoda at o2.usun.pl (Jarek Zgoda) Date: Fri, 13 Apr 2007 09:43:07 +0200 Subject: Python and JMS? In-Reply-To: References: Message-ID: Leonard J. Reder napisa?(a): > I would like to write some Python to monitor a JMS middleware software bus. > JMS being Java Messaging Service. Can anyone recommend a Python > wrapper to JMS for this? My goal is to listen for XML being transfered > over > a JMS implementation. All the applications so far are in Java. Quick googling for "python jms" yields http://hjb.python-hosting.com/ as 1st result and for a long time this seems the only solution that works. Unfortuantely, it's functionality is severely limited. If you happen to use ActiveMQ, you can try to use stomp protocol, but this isn't a standard (I don't know any other implementation of queuing software that uses this). -- Jarek Zgoda "We read Knuth so you don't have to." From siona at chiark.greenend.org.uk Mon Apr 30 09:03:40 2007 From: siona at chiark.greenend.org.uk (Sion Arrowsmith) Date: 30 Apr 2007 14:03:40 +0100 (BST) Subject: My python annoyances so far References: <1177541453.471959.120830@c18g2000prb.googlegroups.com> <1177599046.406827.5210@t38g2000prd.googlegroups.com> Message-ID: 7stud wrote: >I know what you mean. I always write: > >someStringVar.len > >and then I backspace and retype: > >len(someString). > >But then again, I can never remember whether length is a member or a >method in other languages. ... or whether it's called length, size, count or len. Or even whether the language is consistent from one container class to the next. -- \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" -- Arthur C. Clarke her nu become? se bera eadward ofdun hl?ddre heafdes b?ce bump bump bump From marcpp at gmail.com Thu Apr 12 06:51:44 2007 From: marcpp at gmail.com (Marcpp) Date: 12 Apr 2007 03:51:44 -0700 Subject: Pyqt programming question In-Reply-To: References: <1176369822.364743.243700@n76g2000hsh.googlegroups.com> <1176372437.336751.75840@d57g2000hsg.googlegroups.com> Message-ID: <1176375104.478693.108480@q75g2000hsh.googlegroups.com> On 12 abr, 12:34, Phil Thompson wrote: > On Thursday 12 April 2007 11:07 am, Marcpp wrote: > > > On 12 abr, 11:48, Phil Thompson wrote: > > > On Thursday 12 April 2007 10:23 am, Marcpp wrote: > > > > I have a program (python + pyqt), with a button I'll would to open a > > > > new dialog window to input text, when press save or ok, this text is > > > > returned to the principal program. > > > > I've seek in internet but i don't find anything. > > > > Use QInputDialog.getText() > > > > Phil > > > I can't do it, have you any example? > > Look at the standarddialogs.py example that it included with PyQt. > > Phil I've need a personal dialog, not a standard. Thank you. From hg at nospam.org Fri Apr 20 10:26:57 2007 From: hg at nospam.org (hg) Date: Fri, 20 Apr 2007 16:26:57 +0200 Subject: Do other Python GUI toolkits require this? (OT) References: <462697A6.6010007@codebykevin.com> <465B30B4-5BA0-459A-BE6F-1038874FA74B@jedimindworks.com> Message-ID: Roel Schroeven wrote: > Hendrik van Rooyen schreef: >> "Steve Holden" wrote: >> >> >>> Perhaps in Belgium they prefer climbing mountains over walking up and >>> down gentle hills? >> >> Mountains ? Hills ? In Belgium ?? >> >> Its not called the battlefield of Europe for nothing... > > I'm not sure if this adds anything of interest (well actually I'm pretty > sure it doesn't), but our king Albert I was a fanatic mountain climber, > until he died from a fall in 1934. > > -- > If I have been able to see further, it was only because I stood > on the shoulders of giants. -- Isaac Newton > > Roel Schroeven You never know ... was it a 'steep curve' ? hg From timr at probo.com Sat Apr 28 01:46:04 2007 From: timr at probo.com (Tim Roberts) Date: Sat, 28 Apr 2007 05:46:04 GMT Subject: Dedicated CPU core for Python? References: <1177607759.916727.180950@t39g2000prd.googlegroups.com> <4630e90c$0$16272$88260bb3@free.teranews.com> <1177636213.350003.164430@c18g2000prb.googlegroups.com> Message-ID: Louise Hoffman wrote: > >Have I understood CPU affinity correct, that it is similar to SMP/ >NUMA, only that I can force a process/thread to a cpu core? > >In regards to forcing the Python virtual machine (thanks Michael for >the explanation=) ), is the problem that the "OS core" and the "VM >core" would need to copy each others cache/exchange data too often? You do not understand what you are asking. The only possible effect of your suggestion would be to REDUCE overall system throughput. Your operating system's scheduler has been carefully tuned to make sure that all of your CPU cores are kept busy, and are shared evenly amongst all of the tasks that are ready to run. By artificially limiting the options as you suggest, you tie the hands of the scheduler so that it can't make the most effective use of the resources. Except for specific needs in some drivers, the use of CPU and thread affinity is virtually never a good idea. -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From theller at ctypes.org Wed Apr 18 11:36:48 2007 From: theller at ctypes.org (Thomas Heller) Date: Wed, 18 Apr 2007 17:36:48 +0200 Subject: python - dll access (ctypes or swig) In-Reply-To: <1hwr93q.ym0vh4baceh6N%aleax@mac.com> References: <1hwq9na.98800513op6liN%aleax@mac.com> <1hwr93q.ym0vh4baceh6N%aleax@mac.com> Message-ID: Alex Martelli schrieb: > Larry Bates wrote: > ... >> I guess I was the only one it wasn't "obvious" to . I've always >> written my COM servers as .EXE files even though they cannot be run >> independently. What I find is "odd" is that I can create a .DLL or an >> .EXE of my COM server and after I register it, my application doesn't >> appear to know the difference. The difference seems to be hidden from >> the actual application and doesn't affect it (at least that I can >> determine). > > Yes, except for performance (a DLL affords within-process communication > without the overhead of IPC, so it can be much faster when appropriate) > and some technical issues such as threading (if COM client and server > are in separate processes, their threading models are independent from > each other; if they are in the same process, they'd better have > compatible threading approaches -- a thread-unsafe DLL server can make a > single-threaded client happy but would cause problems and crashes if a > freely-threaded client tried using it). I think that the latter problem (incompatible threading models in the same process) are solved by COM apartments - aren't they? Thomas From jan.m.danielsson at gmail.com Tue Apr 3 23:52:42 2007 From: jan.m.danielsson at gmail.com (Jan Danielsson) Date: Wed, 04 Apr 2007 05:52:42 +0200 Subject: SimpleXMLRPCServer - revisited Message-ID: <4613210a$1@griseus.its.uu.se> Hello all, I want to be able to determine the IP address of the client making an XMPRPC call. I got the tip to use this: ------------------------------- class RPCServer(SimpleXMLRPCServer): def _dispatch(self, method, params): """Extend dispatch, adding client info to some parameters.""" if method in ({my list of methods I needed client address}): return SimpleXMLRPCServer._dispatch(self, method, params+(self.client_address,)) return SimpleXMLRPCServer._dispatch(self, method, params); ------------------------------- But it complains that it can not find 'client_address'. It may be relevant to point out that I am using this: ------------------------------- class AsyncXMLRPCServer(SocketServer.ThreadingMixIn,SimpleXMLRPCServer): pass ------------------------------- If anyone has any hints or tips.. Please share them. -- Kind regards, Jan Danielsson From matt.rasmus at gmail.com Thu Apr 5 14:12:02 2007 From: matt.rasmus at gmail.com (matt.rasmus at gmail.com) Date: 5 Apr 2007 11:12:02 -0700 Subject: SUMMON - Rapid prototyping of 2D visualizations Message-ID: <1175796722.021072.142110@b75g2000hsg.googlegroups.com> I have been using python for the last two years to create various visualizations for my research in computational biology. Over the years, I found that I often needed the same kinds of features for many of my visualizations (OpenGL graphics with basic scrolling and zooming). I have implemented these features in an extension module for python called SUMMON which I have made freely available on my website for anyone who is interested . Although, there are many visualization frameworks, I believe SUMMON provides a fairly unique combination. - First, SUMMON is designed to be fast and able to visualize extremely large datasets. In the examples included, there is a visualization of a binary tree with roughly 40,000 leaves (a hierarchical clustering of all protein sequences from the human and dog genomes). Specifying how to draw the tree is done once in using python functions provided by SUMMON (relatively slowly in about 10secs), however once constructed, it uses natively compiled C++ to handle interaction. Callbacks such as mouse movements, clicks, and key strokes can all be bound to python functions to customize interaction. - SUMMON is designed for prototyping visualizations. Often times in science, one wants to visualize something in order to understand whether it has any interesting patterns. If the answer is "no", you have to be able to throw away the visualization and move on to another approach. However, if there is a large amount of overhead in creating a visualization (designing dialog boxes, toolbars, laying out check boxes), it can become difficult to give up a visualization with that much investment so easily. The philosophy with SUMMON is to rely on the python shell for handling basic interaction (reading in data, specifying options, interacting with visualization) in order to avoid GUI design. Once, you realize a visualization is worth while for your research, you can then reimplement it in your favorite full featured GUI-toolkit. - It provides basic scrolling and zooming for an arbitrarily large coordinate space. As a user you simply draw out your visualization with lines, polygons, and text in the coordinate system you wish, completely ignoring how many pixels anything may take. SUMMON will handle the display, including smart display of text (automatic clipping, sizing, and justification of text). - Its cross-platform: It only relies on python2.4, OpenGL, GLUT, and SDL. So if this sounds like something you may need for your work, please check it out and let me know what you think. Matt From exarkun at divmod.com Mon Apr 23 07:22:12 2007 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Mon, 23 Apr 2007 07:22:12 -0400 Subject: Select weirdness In-Reply-To: Message-ID: <20070423112212.19381.1885775150.divmod.quotient.4275@ohm> On Mon, 23 Apr 2007 00:33:22 -0700, Ron Garret wrote: >In article <462c54cb$0$336$e4fe514c at news.xs4all.nl>, > Irmen de Jong wrote: > >> Ron Garret wrote: >> > I don't understand why socketserver calling select should matter. (And >> > BTW, there are no calls to select in SocketServer.py. I'm using >> > Python2.5.) >> >> You don't *need* a select at all. > >Yes I do, because what I'm really writing is a dispatching proxy that >has to serve many simultaneous connections. Calling select() in a while loop doesn't give you this. > [snip] > >I have not been able to find a proxy server that can proxy to unix >sockets, so I need to write my own. Conceptually its a very simple >thing: read the first line of an HTTP request, parse it with a regexp to >extract the sandbox name, connect to the appropriate unix server socket, >and then bidirectionally pipe bytes back and forth. But it has to do >this for multiple connections simultaneously, which is why I need select. Twisted does this out of the box, for what it's worth. Jean-Paul From 12cc104 at gmail.com Sun Apr 22 18:47:07 2007 From: 12cc104 at gmail.com (proctor) Date: 22 Apr 2007 15:47:07 -0700 Subject: recursion depth problem In-Reply-To: References: <1177267774.416169.276780@e65g2000hsc.googlegroups.com> <1177275314.846022.249000@e65g2000hsc.googlegroups.com> <1177276111.720137.315710@b75g2000hsg.googlegroups.com> Message-ID: <1177282027.798037.48210@o5g2000hsb.googlegroups.com> On Apr 22, 4:37 pm, Michael Bentley wrote: > On Apr 22, 2007, at 4:08 PM, proctor wrote: > > > > > On Apr 22, 2:55 pm, half.ital... at gmail.com wrote: > >> On Apr 22, 11:49 am, proctor <12cc... at gmail.com> wrote: > > >>> hello, > > >>> i have a small function which mimics binary counting. it runs > >>> fine as > >>> long as the input is not too long, but if i give it input longer > >>> than > >>> 8 characters it gives > > >>> RuntimeError: maximum recursion depth exceeded in cmp > > >>> i'm not too sure what i am doing improperly. is there really a > >>> lot of > >>> recursion in this code? > > >>> ================== > > >>> import sys > > >>> def ch4(item, n=0): > >>> if n < len(item): > >>> if item[n] == '0': > >>> item[n] = '1' > >>> print ''.join(item) > >>> ch4(item) > >>> elif item[n] == '1': > >>> item[n] = '0' > >>> ch4(item, n+1) > > >>> ch4(list(sys.argv[1])) > > >>> ================== > > >>> this function expects input in the form of a string of zeros, like > >>> this: > > >>> python test-bin.py 00000000 > > >>> and is expected to output a list of permutations like this: > > >>> $ python test-bin.py 0000 > >>> 1000 > >>> 0100 > >>> 1100 > >>> 0010 > >>> 1010 > >>> 0110 > >>> 1110 > >>> 0001 > >>> 1001 > >>> 0101 > >>> 1101 > >>> 0011 > >>> 1011 > >>> 0111 > >>> 1111 > > >>> thanks for all help! > > >>> sincerely, > >>> proctor > > >> If you just want to make it work as is....check > > >> sys.setrecursionlimit() > > >> ~Sean > > > very nice. thanks sean. so is the structure of my original code > > unrescuable? i cannot rearrange it to bypass the recursion? > > Anything that can be done with recursion can be done without > recursion. If you really wanted to mimic a binary counter, why not > write a function that converts a number to binary? > > Then you could just count up from 0, printing the return from your > binary conversion function... > > And the binary converter would be pretty easy too: just think of it > as making change -- for a given number you just divide the number by > each of [2 ** x for x in range(len(sys.argv[1]), 0, -1)] and append > the string representations of the answers to a list and if the answer > is 1, subtract that much from the number... cool... i'm going to have to think about this one... :-) proctor From fatuheeva at yahoo.com Tue Apr 3 18:52:43 2007 From: fatuheeva at yahoo.com (Michael Castleton) Date: Tue, 3 Apr 2007 15:52:43 -0700 (PDT) Subject: File Object behavior In-Reply-To: <4612bf27$0$29887$426a74cc@news.free.fr> References: <9821538.post@talk.nabble.com> <4612bf27$0$29887$426a74cc@news.free.fr> Message-ID: <9827881.post@talk.nabble.com> Bruno Desthuilliers wrote: > > Michael Castleton a ?crit : >> When I open a csv or txt file with: >> >> infile = open(sys.argv[1],'rb').readlines() >> or >> infile = open(sys.argv[1],'rb').read() >> >> and then look at the first few lines of the file there is a carriage >> return >> + >> line feed at the end of each line - \r\n > > Is there any reason you open your text files in binary mode ? > > Unless you're using the csv module (which requires such a mode - but > then you don't care since you're not working with the raw data > yourself), you should consider opening your files in text mode. This > should solve your problem (if not, then you have a problem with > universal newlines support in your Python install). > > HTH > -- > http://mail.python.org/mailman/listinfo/python-list > > Bruno, No particular reason in this case. It was probably as a holdover from using the csv module in the past. I'm wondering though if using binary on very large files (>100Mb) would save any processing time - no conversion to system newline? What do you think? Thanks. -- View this message in context: http://www.nabble.com/File-Object-behavior-tf3520070.html#a9827881 Sent from the Python - python-list mailing list archive at Nabble.com. From hg at nospam.org Sun Apr 22 09:39:31 2007 From: hg at nospam.org (hg) Date: Sun, 22 Apr 2007 15:39:31 +0200 Subject: pickled object, read and write.. References: <1177267228.603237.113070@n59g2000hsh.googlegroups.com> Message-ID: <1JPWh.102090$s8.43708@newsfe21.lga> israphelr at googlemail.com wrote: > Hi all. > > I have to put together some code that reads high scores from a saved > file, then gives the user the opportunity to add their name and score > to the high scores list, which is then saved. > > Trouble is, I can't tell the program to read a file that doesn't > exist, that generates an error. > > So I must have a file created, problem HERE is everytime the program > is run, it will overwrite the current list of saved high scores. > > Advice would be much appreciated. You can run this small script a few times to see that the file does not get deleted hg import shelve class Grades: def __init__(self): self.GRADES = 'GRADES' self.m_gdb = shelve.open('MYGRADES.dat') try: self.m_grades = self.m_gdb[self.GRADES] except: self.m_grades = [] self.m_gdb[self.GRADES] = self.m_grades self.m_gdb.close() def Add(self, p_grade): self.m_gdb = shelve.open('MYGRADES.dat') self.m_grades.append(p_grade) self.m_gdb[self.GRADES] = self.m_grades self.m_gdb.close() def Grades(self): return self.m_grades l_o = Grades() print l_o.Grades() l_o.Add(10) print l_o.Grades() From aljosa.mohorovic at gmail.com Wed Apr 18 11:29:27 2007 From: aljosa.mohorovic at gmail.com (Aljosa Mohorovic) Date: 18 Apr 2007 08:29:27 -0700 Subject: looking for library to read ppt files In-Reply-To: References: <1176747406.722209.126900@w1g2000hsg.googlegroups.com> <1176756401.108945.230880@y5g2000hsa.googlegroups.com> <1176903051.777820.216750@n59g2000hsh.googlegroups.com> Message-ID: <1176910167.061320.145050@l77g2000hsb.googlegroups.com> On Apr 18, 4:02 pm, Carsten Haese wrote: > How about running a headless OpenOffice instance and remote-controlling > it with pyuno: > > http://udk.openoffice.org/python/python-bridge.html > > -Carsten i'll try oo, thanks for link. From openopt at ukr.net Sun Apr 29 15:07:36 2007 From: openopt at ukr.net (dmitrey) Date: 29 Apr 2007 12:07:36 -0700 Subject: howto check is object a func, lambda-func or something else? In-Reply-To: <73086$4634db6f$547078de$28786@news.chello.at> References: <1177867182.115406.4640@h2g2000hsg.googlegroups.com> <73086$4634db6f$547078de$28786@news.chello.at> Message-ID: <1177873656.103714.250050@l77g2000hsb.googlegroups.com> Thank you, I have fixed the bug From steve at REMOVE.THIS.cybersource.com.au Sat Apr 14 22:51:22 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Sun, 15 Apr 2007 12:51:22 +1000 Subject: Useful decorator References: <7xtzvik417.fsf@ruckus.brouhaha.com> Message-ID: On Sat, 14 Apr 2007 15:03:00 -0700, Paul Rubin wrote: > Then to chop bazillion_items to 20 items, I just write: > > @truncate(20) > def generate_bazillion_items(): > for line in bazillion_line_file: > yield itemify(line) > > When I want to run the whole file, I comment out the @truncate line, > and if I want to debug again, I just uncomment it. By All-Father Wodan's one good eye! Why not do something like this? if __debug__: generate_bazillion_items = truncate(20)(generate_bazillion_items) Now you don't have to comment/uncomment dozens of lines all over your application, but only set a single global. -- Steven. From vigacmoe at gmail.com Mon Apr 9 09:27:26 2007 From: vigacmoe at gmail.com (vigacmoe at gmail.com) Date: 9 Apr 2007 06:27:26 -0700 Subject: focus trap in tkinter Message-ID: <1176125246.044107.4240@p77g2000hsh.googlegroups.com> Hi all, I'm trying to write a simple tkinter program, then this problem popped up. The followin code will describe the problem. ------------------------------------------ import Tkinter class countdown(Tkinter.Frame): def __init__(self, master = None): Tkinter.Frame.__init__(self, master) self.ticker = Tkinter.Label(self) self.pack() self.ticker.pack() self.ticker["text"] = "foo" self.master.bind("", self.__focus_in) self.master.bind("", self.__focus_out) self.master.wm_attributes("-topmost", 1) def __focus_in(self, detail): self.master.wm_attributes("-alpha", 1) def __focus_out(self, detail): self.master.wm_attributes("-alpha", 0.8) if ("__main__" == __name__): root = Tkinter.Tk() app = countdown(master = root) app.mainloop() ------------------------------------------ My aim is to set the alpha property of the toplevel window to 0.8 when it lose focus, and set it back to 1 when it regain focus, pretty simple. But the problem is, whenever wm_attributes() is called, a new focus event is generated, and then wm_attributes() will be called again, then the program runs into endless loop of receiving focus events. Simply run above code will see what's going on. I tried to disable FocusIn event in the event handlers, by calling self.master.unbind(), but it doesn't work. I also tried to bind FocusIn and FocusOut event to the frame, the label widgets, instead of the toplevel window, but both frame and label widgets doesn't receive focus event, even after I set their takefocus properties to 1. There should be a way to make it work, just I didn't find it. Any input? Best regards! From irstas at gmail.com Tue Apr 3 12:15:04 2007 From: irstas at gmail.com (irstas at gmail.com) Date: 3 Apr 2007 09:15:04 -0700 Subject: How to have a list of lists (or array of lists) In-Reply-To: <1175616750.744309.156580@n76g2000hsh.googlegroups.com> References: <1175616750.744309.156580@n76g2000hsh.googlegroups.com> Message-ID: <1175616903.932924.171360@b75g2000hsg.googlegroups.com> On Apr 3, 7:12 pm, "bahoo" wrote: > Hi, > > I want to have many lists, such as list0, list1, list2, ..., each one > holding different number of items. > Is there something like > list[0] > list[1] > list[2] > > so that I can iterate through this list of lists? > > Thanks! > bahoo listOfLists = [[1,2], [5,7,9], [4,2,1,4,6,6]] No problem there. The lists can contain any objects, including lists. for x in listOfLists: print 'list:', for y in x: print y, print From jcarlson at uci.edu Fri Apr 6 03:38:36 2007 From: jcarlson at uci.edu (Josiah Carlson) Date: Fri, 06 Apr 2007 00:38:36 -0700 Subject: ANN: PyPE 2.8.5 Message-ID: <20070406003450.6254.JCARLSON@uci.edu> === What is PyPE? === PyPE (Python Programmers' Editor) was written in order to offer a lightweight but powerful editor for those who think emacs is too much and idle is too little. Syntax highlighting is included out of the box, as is multiple open documents via tabs. Beyond the basic functionality, PyPE offers an expandable source tree, filesystem browser, draggable document list, todo list, filterable function list, find and replace bars (no dialog to find or replace simple strings), recordable and programmable macros, spell checker, reconfigurable menu hotkeys, triggers, find in files, external process shells, and much more. === More Information === If you would like more information about PyPE, including screenshots, where to download the source or windows binaries, bug tracker, contact information, or a somewhat complete listing of PyPE's features, visit PyPE's home on the web: http://pype.sf.net/index.shtml If you have any questions about PyPE, please contact me, Josiah Carlson, aka the author of PyPE, at jcarlson at uci.edu (remember to include "PyPE" in the subject). PyPE 2.8.5 includes the following changes and bugfixes since release 2.8: (fixed) issue where double-clicking on a result while search was still going wouldn't actually go to the line of the result. (fixed) macros that use the line-based abstraction will now cause the parse timers to restart (just like hitting a keyboard key). (added) 'GotoLineS' utility method on stc instances for easy navigation to and selection of an entire line. (added) and disabled tagging tool. (fixed) commented/uncommented line discovery for latex documents. (fixed) vim option discovery when opening up latex documents. (added) the ability to disable individual tools if desired (disabling a tool prevents it from being updated, and may reduce tool refresh times). (fixed) calltips. (fixed) removed debug printouts for autocomplete. (fixed) View -> Go To Line Number, now goes to the proper line (not the one after), and now will always show the content of the line. (changed) stopped using combined file/text drop targets, drags could cause extra copies of text to be pasted at the end of the document. (added) ability to have a read-only view of a document in the wide or tall tools. See View -> Split Wide and Split Tall. Note that you can have two different documents displayed in either split. See View -> Unsplit for hiding removing the view to the documents (the split views persist even if you close the open documents, but will not update if you close and re-open the closed document). (changed) moved search code (for the Search tab) use a separate thread in order to increase interactivity, and to prevent lockups due to bad regular expressions. (fixed) checkbox updating for showing or hiding wide or tall tools when using the keyboard to toggle them on some platforms. (known issue) sometimes when attempting to use keyboard shortcuts, PyPE will not recognize the keyboard shortcuts. Click on an open document to allow the keyboard shortcuts to work again. (fixed) the 'Ignore .subdirs' option in the 'Search' tab; if you add a path of foo/, and there was a foo/bar/.subdir, PyPE will now ignore foo/bar/.subdir . PyPE mistakenly only previously ignored foo/.subdir . (fixed) Option Document -> Save Position will now properly go to the right position when there are document folds present. (changed) the way tree controls update their content during refresh. Should prevent unnecessary horizontal scrolling as was the case in PyPE 2.8, and be noticably faster. (fixed) classes or functions with the same names will no longer all be expanded in the browsable source trees when one is expanded. (fixed) icon update issues in the browsable source trees when classes, functions, or methods lose child nodes. (fixed) filter tool to not list #-- stuff -- style labels as having negative lengths, instead will have lengths of zero, and won't affect line counts otherwise. (changed) the included stc-styles.rc.cfg to make // comments the standard font size. (changed) adjusted the layout of the Find/Replace bar to use less horizontal space (really only noticable in the Replace bar). (fixed) pasting in a shell when non-editable data is selected will no longer change the non-editable data or result in an error dialog. From ramalho at gmail.com Fri Apr 6 14:45:26 2007 From: ramalho at gmail.com (Luciano Ramalho) Date: 6 Apr 2007 11:45:26 -0700 Subject: zip files as nested modules? In-Reply-To: References: Message-ID: <1175885126.952514.174480@o5g2000hsb.googlegroups.com> Importing modules from zip files was proposed in PEP-273 [1] Here is how the spec of PEP-273 begins: ''' Currently, sys.path is a list of directory names as strings. If this PEP is implemented, an item of sys.path can be a string naming a zip file archive. ''' My interpretation of the above is that, to be importable, a zip file must be explicitly named in sys.path. So the mere fact that a zip file lies somewhere in a directory which is part of the sys.path does not make it importable. Cheers, Luciano [1] http://www.python.org/dev/peps/pep-0273/ From nospam at invalid.com Fri Apr 6 19:52:16 2007 From: nospam at invalid.com (Jack) Date: Fri, 6 Apr 2007 16:52:16 -0700 Subject: Custom Python Runtime Message-ID: <2NudnVn5jsm2QIvbnZ2dnUVZ_vqpnZ2d@comcast.com> Since the full installation of Python (from either the standard installer or ActiveState installer) is too big for my intended use, I'd like to build a custom distribution of Python for Windows platform, omitting some lib files, such as audio, tk, printing, testing units, etc. Is there a way to customize the Windows build? In my case, there is no need to build an installer. The best way is to have everything in a directory, as long as I know where to find Python and Python knows where to find the necessary libs. Any online docs describing this? Thanks! From tjreedy at udel.edu Sun Apr 1 14:36:45 2007 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 1 Apr 2007 14:36:45 -0400 Subject: Character set woes with binary data References: <1175415685.21349.79.camel@pepper.trausch.us> Message-ID: "Michael B. Trausch" wrote in message news:1175415685.21349.79.camel at pepper.trausch.us... | The protocol calls for binary data to be transmitted, and I cannot seem | to be able to do it, because I get this error: | UnicodeDecodeError: 'ascii' codec can't decode byte 0xff in position 0: | ordinal not in range(128) | When putting the MIME segments (listed line-by-line in a Python list) | together to transmit them. Python byte strings currently serve double duty: text and binary blobs. Best not to mix the two uses. Since most string usage is for text, most string methods are text methods and are not appropriate for binary data. As you discovered. In the present case, do you really need to join the mix of text and binary data *before* sending it? Just send the pre-text, the binary data, and then the post-text and they will be joined in the transmission stream. The receiving site should not know the difference. | It seems that Python thinks it knows better than I do, though. Python is doing what you told it to do. See below. | I want to send this binary data straightaway to the server. :-) Then do just that, as I suggested above. You are *not* sending it 'straightaway'. It you did, you would have no problem.. Instead, you are doing a preliminary mixing, which I suspect is not needed. | Is there any way to tell Python to ignore the situation and treat the | entire thing as simply a stream of bytes? Don't tell Python to treat the byte streams as interpreted text by using a text method. If you really must join before sending, write your own binary join function using either '+' or a slices into a preallocated array (from the array module). Terry Jan Reedy From 12cc104 at gmail.com Mon Apr 23 00:02:45 2007 From: 12cc104 at gmail.com (proctor) Date: 22 Apr 2007 21:02:45 -0700 Subject: recursion depth problem In-Reply-To: References: <1177267774.416169.276780@e65g2000hsc.googlegroups.com> <1177275314.846022.249000@e65g2000hsc.googlegroups.com> <1177276111.720137.315710@b75g2000hsg.googlegroups.com> <1177286778.918119.7490@e65g2000hsc.googlegroups.com> <1177294411.144709.24650@l77g2000hsb.googlegroups.com> Message-ID: <1177300965.951396.245240@l77g2000hsb.googlegroups.com> On Apr 22, 9:28 pm, Dennis Lee Bieber wrote: > On 22 Apr 2007 19:13:31 -0700, proctor <12cc... at gmail.com> declaimed the > following in comp.lang.python: > > > > > :-) > > > this is good stuff. for learning especially! thank you again! > > Took me some time to find... My 30year old BugBooks* are in storage, > along with all the other raw comp-sci texts. > > What you see above is a Python implementation of a 2 1-bit input, > 1-bit sum and 1-bit carry output, full-adder from basic AND/OR/XOR gates > -- you can build the hardware equivalent (except for the variable > length) using old-fashioned 74xx chips (are 74xx TTL chips still made, > or will one need to use the 74Cxx CMOS variants ) [heck; is the > multi-function ALU chip still made?] > > * The Virginia Tech shootings were just a blip on my radar until I > read that this was Blacksburg -- as I once had most of the Blacksburg > BugBooks > -- > 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/ well i'm going to make it a project to understand properly this program. proctor. From aleax at mac.com Fri Apr 27 09:53:48 2007 From: aleax at mac.com (Alex Martelli) Date: Fri, 27 Apr 2007 06:53:48 -0700 Subject: Generalized range References: <1177598743.352743.290730@t39g2000prd.googlegroups.com> <1177616211.476888.38360@r30g2000prh.googlegroups.com> <1hx77al.50av4312e1ysaN%aleax@mac.com> <1177677596.616769.246070@r35g2000prh.googlegroups.com> Message-ID: <1hx7uzz.v0j823u50zsrN%aleax@mac.com> Beliavsky wrote: ... > > I've taught "numerical computing" in university, and I would have had to > > fail anybody who'd misunderstood floating-point computations badly > > enough to try that "+=step" idea (including, sigh, the coders of several > > Fortran compilers who were popular at that time). > > You may be referring to the Fortran DO loop with a REAL loop variable, > for example > > do x=1.5,3.5,0.5 > print*,x > end do > > This was part of standard Fortran 77, so one should blame the > standards committee, not the compiler writers. Very few features of I was thinking of "Fortran IV" aka Fortran '66, where as I recall per the standard you were _supposed_ to only use integers in a DO, but several compilers supplied real loop variables as an extension, and got its implementation wrong. Alex From surekap at gmail.com Sun Apr 29 20:48:36 2007 From: surekap at gmail.com (Prateek) Date: 29 Apr 2007 17:48:36 -0700 Subject: fastest way to find the intersection of n lists of sets In-Reply-To: References: <1177883328.835058.138990@p77g2000hsh.googlegroups.com> <1177889667.450984.88970@p77g2000hsh.googlegroups.com> Message-ID: <1177894116.018987.250930@c35g2000hsg.googlegroups.com> On Apr 30, 5:08 am, John Nagle wrote: > Prateek wrote: > >> For the above example, it's worth sorting lists_of_sets by the > >>length of the sets, and doing the short ones first. > > > Thanks. I thought so - I'm doing just that using a simple Decorate- > > Sort-Undecorate idiom. > > >> How big are the sets? If they're small, but you have a lot of > >>them, you may be better off with a bit-set representation, then > >>using AND operations for intersection. If they're huge (tens of millions > >>of entries), you might be better off doing sorts and merges on the > >>sets. > > > I have either 2 or 3 sets (never more) which can be arbitrarily large. > > Most of them are small (between 0 and few elements - say less that 5). > > A few will be megamonstrous ( > 100,000 items) > > >> When you ask questions like this, it's helpful to give some > >>background. We don't know whether this is a homework assignment, or > >>some massive application that's slow and you need to fix it, even > >>if it requires heavy implementation effort. > > > Its definitely not a homework assignment - its part of a commercial > > database query engine. Heavy implementation effort is no problem. > > > Prateek > > If you're intersecting a set of 5 vs a set of 100,000, the > intersection time won't be the problem. That's just five lookups. > It's building a set of 100,000 items that may be time consuming. > > Does the big set stay around for a while, or do you have to pay > that cost on each query? > > Those really aren't big data sets on modern machines. > > John Nagle 100,000 is an arbitrary number - that is potentially equivalent to the number of unique cells in all tables of a typical database (thats the best analogy I can come up with since this isn't a typical RDBMS). The big set does stay around for a while - I've implemented an LRU based caching algorithm on the code that does the I/O. Since the db is transactioned, I keep one copy in the current transaction cache (which is a simple dictionary) and one in the main read cache (LRU based) (which obviously survives across transactions). Since the largest sets also tend to be the most frequently used, this basically solves my I/O caching issue. My problem is that I had ugly code doing a lot of unnecessary list <-> set casting. Here is what I've got now: from itertools import chain ids1 = [...], ids2 = [...], ids3 = [...] _efs = frozenset() # dbx.get calls return sets l1 = frozenset(chain(*[db1.get(x, _efs) for x in ids1]) l2 = frozenset(chain(*[db2.get(x, _efs) for x in ids2]) l3 = frozenset(chain(*[db3.get(x, _efs) for x in ids3]) decorated = [(len(x), x) for x in [l1, l2, l3]] decorated.sort() result = reduce(set.intersection, [x[1] for x in decorated]) What do you think? Prateek From gagsl-py2 at yahoo.com.ar Mon Apr 9 15:18:46 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 09 Apr 2007 16:18:46 -0300 Subject: Breaking up Strings correctly: References: <1176133184.373854.110520@d57g2000hsg.googlegroups.com> Message-ID: En Mon, 09 Apr 2007 12:39:44 -0300, Paul McGuire escribi?: > On Apr 9, 7:19 am, "Michael Yanowitz" wrote: >> >> Suppose I have a string of expressions such as: >> "((($IP = "127.1.2.3") AND ($AX < 15)) OR (($IP = "127.1.2.4") AND ($AY >> != >> 0))) >> I would like to split up into something like: >> >> [ "OR", >> ["AND", "($IP = "127.1.2.3")", "($AX < 15)"], >> ["AND", "(($IP = "127.1.2.4")", ($AY != 0))"] ] >> > > This problem is right down the pyparsing fairway! Pyparsing is a > module for defining recursive-descent parsers, and it has some built- > in help just for applications such as this. Sometimes I've seen you proposing the usage of PyParsing on problems that, in my opinion, were better solved using some other standard tools, but this time you're absolutely right: this is perfectly suited for PyParsing! :) -- Gabriel Genellina From xah at xahlee.org Sun Apr 15 15:58:11 2007 From: xah at xahlee.org (Xah Lee) Date: 15 Apr 2007 12:58:11 -0700 Subject: is laziness a programer's virtue? In-Reply-To: References: <1176654319.273907.167280@q75g2000hsh.googlegroups.com> Message-ID: <1176667091.415819.152890@n76g2000hsh.googlegroups.com> Dear Ken, I want to thank you for your spirit in supporting and leading the lisp community, in spreading lisp the language both in what you have done technically as well as evangelization, as well as the love and knowledge attitude towards newsgroup communities in general, in part thru your numerous replies to my posts in the past years. (as opposed to, the motherfucking pack of driveling and fuckface ignoramuses that are predominate personalities in newsgroups, including some of the fucking asshole intolerant bigwigs in the lisp newsgroup who think themselves as the holder of justice and goodness (which has contributed significantly to the stagnation of lisp).) Thank you. For those reading this, i also want to mention, that although i think Perl is a motherfucking language on earth, and its leader and ?inventor? Larry Wall has done massive damage to the computing world, but Perl the community is in fact very tolerant in general (which is to Larry's credit), when compared to the motherfucking Pythoners (who knew SHIT) as well as many of the self-appointed lisp bigwig characters. [disclaimer: my statement about Larry Wall is opinion only.] With Knowledge, and, Love. Xah xah at xahlee.org ? http://xahlee.org/ On Apr 15, 10:36?am, Ken Tilton wrote: > XahLeewrote: > > Laziness, Perl, and Larry Wall > > >XahLee, 20021124 > > > In the unix community there's quite a large confusion and wishful > > thinking about the word laziness. In this post, i'd like to make some > > clarifications. > > > American Heritage Dictionary third edition defines laziness as: > > ?Resistant to work or exertion; disposed to idleness.? > > > When the sorcerer Larry Wall said ?The three chief virtues of a > > programmer are: Laziness, Impatience and Hubris?, he used the word > > ?laziness? to loosely imply ?natural disposition that results in being > > economic?. As you can see now, ?Resistant to work or exertion? is > > clearly not positive and not a virtue, but ?natural disposition that > > results in economy? is a good thing if true. > > > When Larry Wall said one of programer's virtue is laziness, he wants > > the unix morons to conjure up in their brains the following > > proposition as true: ?Resistant to work or exertion is a natural human > > disposition and such disposition actually results behaviors being > > economic?. This statement may be true, which means that human laziness > > may be intuitively understood from evolution. However, this statement > > is a proposition on all human beings, and is not some ?virtue? that > > can be applied to a group of people such as programers. > > Xah, you are losing your sense of humor. Wall listed the usually > pejorative "lazy" as a virtue simply to grab the reader, make them > think, and simply to entertain better. Surely The GreatXahunderstands > the virtue of flamboyant writing and does not want every word yanked > from context and slid under the microscope for dissection. > > kzo From sjmachin at lexicon.net Wed Apr 11 08:55:22 2007 From: sjmachin at lexicon.net (John Machin) Date: 11 Apr 2007 05:55:22 -0700 Subject: __file__ In-Reply-To: <1176285795.667520.120230@l77g2000hsb.googlegroups.com> References: <1176250851.946892.273550@l77g2000hsb.googlegroups.com> <1176285795.667520.120230@l77g2000hsb.googlegroups.com> Message-ID: <1176296122.789218.258830@y80g2000hsf.googlegroups.com> On Apr 11, 8:03 pm, "7stud" wrote: > Hi, > > Thanks for the response. > > On Apr 11, 12:49 am, "Gabriel Genellina" > wrote: > > > > > __file__ corresponds to the filename used to locate and load the module, > > whatever it is. When the module is found on the current directory > > (corresponding to '' in sys.path), you get just the filename; if sys.path > > contains a relative path, that's what you get; the same for any absolute > > path. > > Whatever path worked to find and load the module, that's stored as > > __file__. > > > If you plan to use it, it's a good idea to make it early into an absolute > > path (using os.path.abspath(__file__)) just in case the current directory > > changes. > > That last part doesn't seem to fit with your description above. What > does the current working directory have to do with the path that was > used to load a module? I would think the path that was used to load a > module is constant. You are correct, but that is not what GG was talking about. Here is an example of what he meant: While your cwd is /bar, you load module foo from a *relative*( path, e.g. ./foo.py. If you do the os.path.abspath("./foo.py") immediately as recommended, you get the correct answer: /bar/foo.py. However if you change your cwd to /zot, then do the os.path.abspath("./foo.py"), you get /zot/foo.py which is a nonsense. HTH, John From claird at lairds.us Sun Apr 22 11:08:39 2007 From: claird at lairds.us (Cameron Laird) Date: Sun, 22 Apr 2007 15:08:39 +0000 Subject: No speedup on multi-processor machine? References: <1177189332.916296.205280@d57g2000hsg.googlegroups.com> <1177197885.077863.314470@n59g2000hsh.googlegroups.com> Message-ID: In article , John Nagle wrote: >Caleb Hattingh wrote: >> On Apr 21, 11:02 pm, danfan1... at yahoo.com wrote: >> >>>Hi, >>>I am using Python Thread library for my parallel processing course >>>project. I am doing matrix convolution on a multi-processor machine >>>running Solaris. I just found out that no speed-up is obtained with >>>threading. It is probably because of something called GIL in Python. >>>How can I get around >>>that GIL and get speed-up? >>>Thanks in advance. >>>Daniel > > If you're actually doing the convolution in Python, you need >optimization before you need more CPUs. There's a numerics library >for Python called NumPy, but it doesn't have a convolution function, >although it has an FFT, which may be useful. > > But this is just homework. Do something reasonable and turn it >in. A high performance solution to this problem is probably more >work than it's worth. > > John Nagle Along with the excellent advice given by Dennis, John, and the rest, please be aware that *process*-level parallelization of a problem sometimes is a benefit. As already recommended, touches on most of the pertinent concepts. From rganesan at myrealbox.com Sun Apr 15 00:57:50 2007 From: rganesan at myrealbox.com (Ganesan Rajagopal) Date: Sun, 15 Apr 2007 10:27:50 +0530 Subject: Python Feature Request: Explicit variable declarations References: <1176546078.934340.253810@y5g2000hsa.googlegroups.com> <4620b369$0$6937$9b622d9e@news.freenet.de> Message-ID: >>>>> "Martin" == Martin v L?wis writes: > samjnaa at gmail.com schrieb: >> Hello. Please tell me whether this feature request is sane (and not >> done before) for python so it can be posted to the python-dev mailing >> list. I should say first that I am not a professional programmer with >> too much technical knowledge. > I believe it has been requested before, but I'm too lazy now to search > for prior discussion. I remember the benevolent dictator's blogs on this. Googling for "optional static typing" brought up these references: http://www.artima.com/weblogs/viewpost.jsp?thread=85551 http://www.artima.com/weblogs/viewpost.jsp?thread=87182 and an older one: http://www.python.org/~guido/static-typing/ > The request is sane, but is also incomplete: there > is no syntax suggested for the actual declarations of local variables, > and no discussion whether this is meant to apply to local variables > only, or also to global variables and object attributes. None of the above links talk about variable declarations but object attributes are considered. Ganesan -- Ganesan Rajagopal From bdesth.quelquechose at free.quelquepart.fr Sat Apr 21 15:30:10 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sat, 21 Apr 2007 21:30:10 +0200 Subject: Newbie question regarding string.split() In-Reply-To: <1177095062.826018.63590@n59g2000hsh.googlegroups.com> References: <1177095062.826018.63590@n59g2000hsh.googlegroups.com> Message-ID: <462a5cd0$0$4231$426a74cc@news.free.fr> kevinliu23 a ?crit : > Hey guys, > > So I have a question regarding the split() function in the string > module. Let's say I have an string... > > input = "2b 3 4bx 5b 2c 4a 5a 6" > projectOptions = (input.replace(" ", "")).split('2') The parens around the call to input.replace are useless: projectOptions = input.replace(" ", "").split('2') > print projectOptions > > ['', 'b34bx5b', 'c4a5a6'] (snip) > What can I do so that the first element is not an empty > string? but the 'b34bx5b' string as I expected? projectOptions = filter(None, input.replace(" ", "").split('2')) From bytecolor at yahoo.com Tue Apr 3 00:00:41 2007 From: bytecolor at yahoo.com (bytecolor) Date: 2 Apr 2007 21:00:41 -0700 Subject: Tkinter <> and bindtags ordering Message-ID: <1175572841.269301.275100@q75g2000hsh.googlegroups.com> I'm trying to extract the text of the current line on the <> event. It doesnt work if I delete a character. If I type 'abc' I get 'abc' in text_changed(). If I hit backspace I still get 'abc'. Backspace once more, I get 'ab'. So the callback is called before the text is changed. But only on a delete. Someone told me it has to do with bindtags ordering. I've read what docs I can find on the subject, but I cant figure out why it's not working. Maybe I should learn a bit of Tcl, eh? import Tkinter as tk def text_changed(evt): global changing if changing: return changing = True line, col = t.index('insert').split('.') txt = t.get('%s.0' % line, '%s.end' % line) print '|%s|' % txt t.tk.call(t._w, 'edit', 'modified', 0) changing = False changing = False root = tk.Tk() t = tk.Text(master=root) t.pack() t.focus_set() t.tk.call(t._w, 'edit', 'modified', 0) t.bind('<>', text_changed) root.mainloop() -- bytecolor From arkanes at gmail.com Mon Apr 9 13:41:32 2007 From: arkanes at gmail.com (Chris Mellon) Date: Mon, 9 Apr 2007 12:41:32 -0500 Subject: Memory allocation problem with python 2.4.3 In-Reply-To: References: <1176117179.200754.234610@o5g2000hsb.googlegroups.com> Message-ID: <4866bea60704091041v1989a94ehd8a25dc0f64bef93@mail.gmail.com> On 4/9/07, Dennis Lee Bieber wrote: > On 9 Apr 2007 04:12:59 -0700, "Brice-Olivier Demory" > declaimed the following in comp.lang.python: > > > > Nothing indicates a lack of memory. > > No? I'd consider a machine with only 23MB free rather heavily used > (especially when it starts with over 700MB). > > OTOH, I have no idea what this C-library function seeks to perform, > so my comment could just be a wild-goose... > That's physical ram, note that there's lots of swap space left. What seems more likely is that the virtual memory space of the process is being exhausted. From michael at jedimindworks.com Mon Apr 23 06:30:26 2007 From: michael at jedimindworks.com (Michael Bentley) Date: Mon, 23 Apr 2007 05:30:26 -0500 Subject: recursion depth problem In-Reply-To: <1177311447.366904.248130@l77g2000hsb.googlegroups.com> References: <1177267774.416169.276780@e65g2000hsc.googlegroups.com> <1177275314.846022.249000@e65g2000hsc.googlegroups.com> <1177276111.720137.315710@b75g2000hsg.googlegroups.com> <1177282027.798037.48210@o5g2000hsb.googlegroups.com> <90679236-0D2C-42EF-B93F-06A1DD561944@jedimindworks.com> <1177311447.366904.248130@l77g2000hsb.googlegroups.com> Message-ID: <36D156C8-F088-44DB-A97F-B6AF78F4AD6A@jedimindworks.com> On Apr 23, 2007, at 1:57 AM, proctor wrote: > On Apr 22, 5:51 pm, Michael Bentley wrote: >> Oops! Note to self: *ALWAYS* try code before posting to a public >> forum :-( >> >> def binary(val, width): >> print '%10s = the sum of' % val >> for i in [2 ** x for x in range(width - 1, -1, -1)]: >> a = val / i >> print ' ' * 13 + '%s * (2 ** %s)' % (a, width) >> val -= i * a >> width -= 1 >> >> binary(233, 8) > > hi michael, > > just a quick clarification... > > it seems to me that the self-documenting part of the code should be > more like this: > > print ' ' * 13 + '%s * (2 ** %s)' % (a, width-1) > > instead of > > print ' ' * 13 + '%s * (2 ** %s)' % (a, width) > > is this correct, or am i mixed? > No, you're right -- actually I ended up decrementing width after the print instead of before it -- but didn't feel like posting yet another correction. Your correction works though! From marcpp at gmail.com Mon Apr 16 04:04:04 2007 From: marcpp at gmail.com (Marcpp) Date: 16 Apr 2007 01:04:04 -0700 Subject: Qt4 in ubuntu In-Reply-To: <58fhooF2finkjU1@mid.uni-berlin.de> References: <1176668662.770066.208350@n76g2000hsh.googlegroups.com> <58fhooF2finkjU1@mid.uni-berlin.de> Message-ID: <1176710644.702886.314410@y5g2000hsa.googlegroups.com> On 15 abr, 22:54, "Diez B. Roggisch" wrote: > Marcpp schrieb: > > > Is possible install Qt4 pyqt4 under kubuntu? > > Few times ago i tried to run pyqt in ubuntu (gnome) but i can't > > do it. > > It's certainly possible. On ubuntu as well as on kubuntu. You can > install all KDE and Qt stuff on ubuntu as well. > > But unless you are more specific what your actual problems were, you > can't better help. > > Diez Hi Diez, finally I can install a Qt4 on Kubuntu, but now I have problems to install a Qt4Designer. I'm introducing to Qt with python, why tutorial you recommend to me? Thank you. From flyzone at technologist.com Tue Apr 24 11:23:38 2007 From: flyzone at technologist.com (Flyzone) Date: 24 Apr 2007 08:23:38 -0700 Subject: freeze and problem with static libraries Message-ID: <1177428217.892613.125750@u32g2000prd.googlegroups.com> Hi, i need to "compile" a python source (2.3.6) to make it standalone on Solaris 9. I get this warning on freezing my source: "Warning: unknown modules remain: _locale _random _socket array binascii cStringIO datetime fcntl math pwd select strop termios time" in the source i have: "import os, stat, re, datetime, time, glob" and running the frozen application I get: "ImportError: No module named datetime" like i have read in the old post in this newgroup i tried to recompile python to avoid shared libraries (i used ./configure --disable- shared), and to reinstall python of course (recompiling my source) but the same problem occour. In Modules/Setup i don't have shared libraries and the line "*shared*" is commented. I have tried also other freeze application (Gordon MacMillan, cx_freeze), but i get a fatal error importing zlib also if i have installed right. Someone have some tips? Thanks in advance From __peter__ at web.de Wed Apr 4 04:42:34 2007 From: __peter__ at web.de (Peter Otten) Date: Wed, 04 Apr 2007 10:42:34 +0200 Subject: zip list with different length References: <1175673207.231212.28310@n76g2000hsh.googlegroups.com> Message-ID: s99999999s2003 at yahoo.com wrote: > suppose i have 2 lists, a, b then have different number of elements, > say len(a) = 5, len(b) = 3 >>>> a = range(5) >>>> b = range(3) >>>> zip(b,a) > [(0, 0), (1, 1), (2, 2)] >>>> zip(a,b) > [(0, 0), (1, 1), (2, 2)] > > I want the results to be > [(0, 0), (1, 1), (2, 2) , (3) , (4) ] > can it be done? > thanks from itertools import izip, chain, repeat, takewhile, starmap def zip_longest(*seqs): padded = [chain(izip(s), repeat(())) for s in seqs] return takewhile(bool, starmap(sum, izip(izip(*padded), repeat(())))) Just to bring itertools to your attention :-) Peter From jjl at pobox.com Wed Apr 11 16:20:54 2007 From: jjl at pobox.com (John J. Lee) Date: Wed, 11 Apr 2007 20:20:54 GMT Subject: shelve error References: <1175746456.995618.186190@e65g2000hsc.googlegroups.com> <1175746966.023613.178830@n76g2000hsh.googlegroups.com> <1175756092.643182.142420@n76g2000hsh.googlegroups.com> <1hw9lxy.ldrc541w507xyN%aleax@mac.com> <1176095310.492686.78880@p77g2000hsh.googlegroups.com> Message-ID: <87odlu7jdg.fsf@pobox.com> "7stud" writes: [...] > Also, the book is brand new, yet the cover has completely separated > from the spine of the book, and now the cover is only attached to the > first and last pages with a bit of glue. I think they used to advertise that as a feature -- "stay-flat binding" or something... John From aisaac at american.edu Thu Apr 12 14:22:31 2007 From: aisaac at american.edu (Alan Isaac) Date: Thu, 12 Apr 2007 18:22:31 GMT Subject: tuples, index method, Python's design References: Message-ID: I am still puzzled by this discussion. As I said: I doubt that *anyone* who programs in Python has not encountered the situation where they change a tuple to a list *solely* for the purpose of getting access to the index method. This suggests a missing method, does it not? Who has not done this? Name yourself! There is simply no conflict between the index method and immutability, but at the moment one is forced to choose. Why? Nobody has offered a real explanation of this. I offered a simple use case. Consider a game, where the *fixed* set p of players have a *fixed* order. A tuple is natural. Now for a player you want to construct the opponents. If I had the index i it wd be p[:i]+p[i+1:], but how to get the index? Other use cases have also been offered on this thread. What is the basic response? "Do not worry about the loss of immutability, just use a list." What kind of a response is that?? This sounds to me like "I do not really see the point of immutability", which is no response at all. Cheers, Alan Isaac From steve at holdenweb.com Thu Apr 26 07:51:19 2007 From: steve at holdenweb.com (Steve Holden) Date: Thu, 26 Apr 2007 07:51:19 -0400 Subject: If Dict Contains a particular key In-Reply-To: References: <000001c78695$ed321540$c7963fc0$@rawlins@thinkbluemedia.co.uk> <1177436682.3441.15.camel@dot.uniqsys.com> <1177565430.992904.149450@n35g2000prd.googlegroups.com> Message-ID: Gabriel Genellina wrote: > En Thu, 26 Apr 2007 03:56:17 -0300, John Nagle > escribi?: > >>>>>> On Tue, 2007-04-24 at 18:28 +0100, Robert Rawlins - Think Blue wrote: >>>>>>> I'm Looking to build a quick if/else statement that checks a >>>>>>> dictionary for a key like follows. >> It would be useful if there was some direct way to get the value >> associated with a key, and None if there's not one. > > Such wonderful method exists since immemorial ages -at least since Python > 1.5- and its magic name is "get": > > py> d = {'a': 1, 'b': 2} > py> print d.get("a") > 1 > py> print d.get("z") > None > Or, if you are using 2.5, look at collections.defaultdict: http://docs.python.org/lib/defaultdict-objects.html#l2h-735 regards Steve -- Steve Holden +1 571 484 6266 +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 kbk at shore.net Mon Apr 9 01:38:59 2007 From: kbk at shore.net (Kurt B. Kaiser) Date: Mon, 9 Apr 2007 01:38:59 -0400 (EDT) Subject: Weekly Python Patch/Bug Summary Message-ID: <200704090538.l395cxKe013626@bayview.thirdcreek.com> Patch / Bug Summary ___________________ Patches : 349 open ( +7) / 3737 closed (+25) / 4086 total (+32) Bugs : 939 open (-12) / 6648 closed (+60) / 7587 total (+48) RFE : 249 open ( -8) / 278 closed (+12) / 527 total ( +4) New / Reopened Patches ______________________ Python 2.5 "What's New" document contains socket errors (2007-03-17) CLOSED http://python.org/sf/1682878 opened by Jp Calderone ConfigParser support for alt delimiters (2007-03-18) http://python.org/sf/1682942 opened by Stephen Hansen Demo/parser/unparse.py fixes and cleanups (2007-03-19) CLOSED http://python.org/sf/1683328 opened by Piet Delport Refactor test_minidom.py to use unittest. (2007-03-18) CLOSED http://python.org/sf/1683397 opened by Jerry Seutter PEP 361 Warnings (2007-03-19) http://python.org/sf/1683908 opened by Adam Olsen add os.chflags() and os.lchflags() where available (2006-05-17) http://python.org/sf/1490190 reopened by nnorwitz Documentation for C-API string functions (2007-03-21) CLOSED http://python.org/sf/1684834 opened by Bj?rn Lindqvist cgi.py invalid REQUEST_METHOD set (2005-03-08) CLOSED http://python.org/sf/1159139 reopened by joesalmeri new function: os.path.relpath (2005-10-27) CLOSED http://python.org/sf/1339796 reopened by loewis MSVCCompiler creates redundant and long PATH strings (2007-03-21) CLOSED http://python.org/sf/1685563 opened by Scott Dial Add IllegalStateError (2007-03-22) http://python.org/sf/1685642 opened by Bj?rn Lindqvist Method cache (2007-03-22) http://python.org/sf/1685986 opened by Armin Rigo More PEP 3116 classes (2007-03-22) CLOSED http://python.org/sf/1686273 opened by Mark Russell int to Py_ssize_t changes (2007-03-22) CLOSED http://python.org/sf/1686451 opened by Alexander Belopolsky Allow any mapping after ** in calls (2007-03-22) http://python.org/sf/1686487 opened by Alexander Belopolsky extending os.walk to support following symlinks (2005-08-26) CLOSED http://python.org/sf/1273829 reopened by loewis Replace time_t by Py_time_t (2007-03-27) http://python.org/sf/1689402 opened by Christian Heimes Refactor test_sax.py to use unittest. (2007-03-28) CLOSED http://python.org/sf/1690164 opened by Jerry Seutter Refactor test_pyexpat.py to use unittest. (2007-03-28) CLOSED http://python.org/sf/1690169 opened by Jerry Seutter Added support for custom readline functions (2007-03-28) http://python.org/sf/1690201 opened by Ben Timby Don't block on Queue get/put when time is moved back (2007-03-29) http://python.org/sf/1690578 opened by xiaowen Migrate test_minidom.py to unittest (2007-03-30) http://python.org/sf/1691032 opened by Jason Orendorff Fix for bug #1283289 (2007-03-30) http://python.org/sf/1691070 opened by Roger Upole Move initial args assignment to BaseException.__new__ (2007-04-01) http://python.org/sf/1692335 opened by ?iga Seilnacht warnings.py gets filename wrong for eval/exec (2007-04-01) http://python.org/sf/1692664 opened by Adam Olsen trace.py --ignore-module should accept module name list. (2007-04-02) http://python.org/sf/1693149 opened by Raghuram Devarakonda Fix for duplicate "preferences" menu-OS X (2007-04-02) http://python.org/sf/1693258 opened by Kevin Walzer tarfile bug when opening a file directly (2007-04-05) http://python.org/sf/1695229 opened by Arve Knudsen Fix test_urllib on Windows buildbots (2007-04-07) http://python.org/sf/1695862 opened by Ziga Seilnacht Remove redundant code in ntpath.walk() (2007-04-08) http://python.org/sf/1696393 opened by Michael Haggerty Adding an index method to tuples (2007-04-08) http://python.org/sf/1696444 opened by Paul Boddie Patches Closed ______________ TypeError swallowing in UNPACK_SEQUENCE opcode (2007-03-16) http://python.org/sf/1682205 closed by gbrandl Make PyComplex_AsCComplex use __complex__ (2007-03-07) http://python.org/sf/1675423 closed by gbrandl remove sys.exitfunc, rewrite atexit in C (2007-03-14) http://python.org/sf/1680961 closed by collinwinter telnetlib option subnegotiation fix (2003-01-07) http://python.org/sf/664020 closed by gbrandl telnetlib.py change to ease option handling. (2006-07-10) http://python.org/sf/1520081 closed by gbrandl Python 2.5 "What's New" document contains socket errors (2007-03-17) http://python.org/sf/1682878 closed by gbrandl PEP 3115 patch (2007-03-14) http://python.org/sf/1681101 closed by gvanrossum Adding a testcase for the bug in find_longest_match (2007-03-11) http://python.org/sf/1678339 closed by gbrandl Patch to add tempfile.SpooledTemporaryFile (for #415692) (2007-01-07) http://python.org/sf/1630118 closed by collinwinter Demo/parser/unparse.py fixes and cleanups (2007-03-19) http://python.org/sf/1683328 closed by gbrandl Refactor test_minidom.py to use unittest. (2007-03-19) http://python.org/sf/1683397 closed by collinwinter fix Makefile.pre to use config env (2002-12-29) http://python.org/sf/659809 closed by bcannon Documentation for C-API string functions (2007-03-21) http://python.org/sf/1684834 closed by gbrandl cgi.py invalid REQUEST_METHOD set (2005-03-08) http://python.org/sf/1159139 closed by sf-robot Replacing and deleting files in a zipfile archive. (2003-03-10) http://python.org/sf/700858 closed by sf-robot desktop module (providing startfile as open, all platforms) (2005-09-23) http://python.org/sf/1301512 closed by pboddie new function: os.path.relpath (2005-10-27) http://python.org/sf/1339796 closed by collinwinter Adding timeout to socket.py and httplib.py (2007-03-08) http://python.org/sf/1676823 closed by facundobatista New block cipher API (2003-01-27) http://python.org/sf/675698 closed by collinwinter Updates to syntax rules in reference manual (2006-05-16) http://python.org/sf/1489771 closed by zseil MSVCCompiler creates redundant and long PATH strings (2007-03-21) http://python.org/sf/1685563 closed by nnorwitz More PEP 3116 classes (2007-03-22) http://python.org/sf/1686273 closed by gvanrossum int to Py_ssize_t changes (2007-03-23) http://python.org/sf/1686451 closed by loewis extending os.walk to support following symlinks (2005-08-26) http://python.org/sf/1273829 closed by zseil Support CREATE_SUSPENDED flag in subprocess.py for Win32 (2007-03-09) http://python.org/sf/1677688 closed by sf-robot Refactor test_sax.py to use unittest. (2007-03-28) http://python.org/sf/1690164 closed by collinwinter Refactor test_pyexpat.py to use unittest. (2007-03-28) http://python.org/sf/1690169 closed by collinwinter test_timeout updates (2003-04-28) http://python.org/sf/728815 closed by collinwinter ability to pass a timeout to underlying socket (2003-04-17) http://python.org/sf/723312 closed by facundobatista Cygwin case-sensitive import patch (2005-05-07) http://python.org/sf/1197318 closed by zseil Improvements to ceval.c (2006-05-22) http://python.org/sf/1492828 closed by rhettinger httplib : SSL fake sockets to close correctly (2005-10-01) http://python.org/sf/1310381 closed by loewis New / Reopened Bugs ___________________ Documentation error (section 3.4.1) (2007-03-17) CLOSED http://python.org/sf/1682729 opened by emlyn next method assignment is ignored in new-style classes (2007-03-17) http://python.org/sf/1682749 reopened by albert2611 next method assignment is ignored in new-style classes (2007-03-17) http://python.org/sf/1682749 opened by Albert Weichselbraun os.walk should traverse outward symlinks (2007-03-18) CLOSED http://python.org/sf/1682940 opened by Tasci Synx xreload.py won't update class docstrings (2007-03-18) http://python.org/sf/1683288 opened by Jim Jewett select.select() injecting spurious text in stdout (2007-03-19) CLOSED http://python.org/sf/1683316 opened by Peter Williams object.__init__ shouldn't allow args/kwds (2007-03-18) http://python.org/sf/1683368 opened by Blake Ross module-ctypes should show platform availability (2007-03-19) CLOSED http://python.org/sf/1683872 opened by Noah Spurrier regression in webbrowser command line parsing (2007-03-20) CLOSED http://python.org/sf/1684254 opened by Lukas Lalinsky modindex.html builds incorrectly in Python 3 (2007-03-20) CLOSED http://python.org/sf/1684811 opened by Collin Winter Keyword arguments to __init__() of a subclass of set (2007-03-21) CLOSED http://python.org/sf/1684943 opened by J?rgen Fr?jk Kj?rsgaard Explain __method__ lookup semantics for new-style classes (2007-03-21) http://python.org/sf/1684991 opened by Georg Brandl DoS asyncore vulnerability (2007-03-21) http://python.org/sf/1685000 opened by billiejoex email package should work better with unicode (2007-03-21) http://python.org/sf/1685453 opened by Barry A. Warsaw Command line interface to timeit.py (2007-03-21) CLOSED http://python.org/sf/1685704 opened by Tim Heaney tarfile file names under win32 (2007-03-22) CLOSED http://python.org/sf/1685773 opened by ralf msvccompiler.py doesn't recongnize VS2005 (2007-03-22) CLOSED http://python.org/sf/1685775 opened by Minmin Gong socket.getaddrinfo() should take an address tuple. (2007-03-22) http://python.org/sf/1685962 opened by Alan Kennedy logging package failure for NTEventLogHandler (2007-03-22) CLOSED http://python.org/sf/1686200 opened by j vickroy Python SEGFAULT on invalid superclass access (2007-03-22) http://python.org/sf/1686386 opened by toxik os.stat() WindowsError 13 when file in use (2007-03-22) CLOSED http://python.org/sf/1686475 opened by d roberts descrintro: error describing __new__ behavior (2007-03-23) http://python.org/sf/1686597 opened by Gabriel Genellina cannot catch KeyboardInterrupt when using curses getkey() (2007-03-23) http://python.org/sf/1687125 opened by al65536 Inconsistent Exceptions for Readonly Attributes (2007-03-23) CLOSED http://python.org/sf/1687163 opened by Raymond Hettinger Round funcion (2007-03-24) CLOSED http://python.org/sf/1687314 opened by Gust1 Python/C PyClass_* are not documented (2007-03-26) CLOSED http://python.org/sf/1688274 opened by Tommi Vainikainen sock.recvfrom(-24) crashes (2007-03-27) CLOSED http://python.org/sf/1688393 opened by Andrew Bennetts os.path.join.__doc__ should mention absolute paths (2007-03-26) http://python.org/sf/1688564 opened by Eugene Kramer pdb unable to jump to first statement (2007-03-27) http://python.org/sf/1689458 opened by gotgenes strptime(): can't switch locales more than once (2005-09-13) CLOSED http://python.org/sf/1290505 reopened by bcannon Intel icc build fails with optimizations -O2 (2007-03-28) http://python.org/sf/1689617 opened by Michael Forbes trace module borks __file__ (2007-03-28) http://python.org/sf/1690103 opened by Skip Montanaro Typographical Error (2007-03-29) CLOSED http://python.org/sf/1690324 opened by Mervyn Yeo email.utils.formataddr() should be rfc2047 aware (2007-03-29) http://python.org/sf/1690608 opened by Barry A. Warsaw xmlrpclib methods submit call on __str__, __repr__ (2007-03-29) http://python.org/sf/1690840 opened by Greg Hazel struct.pack of floats in non-native endian order (2003-03-18) http://python.org/sf/705836 reopened by collinwinter struct.pack raises TypeError where it used to convert (2006-07-28) http://python.org/sf/1530559 reopened by collinwinter Duplicate "preferences" menu item/Tk Aqua 8.4.14 (2007-03-30) http://python.org/sf/1691411 opened by Kevin Walzer lambda function segfault (2007-04-01) CLOSED http://python.org/sf/1692280 opened by Dasn webbrowser module cannot open the right URL (2007-04-02) CLOSED http://python.org/sf/1692695 opened by Pan Yongzhi \w not helpful for non-Roman scripts (2007-04-02) http://python.org/sf/1693050 opened by nlmiles Can't save empty array in shelve (2007-04-02) CLOSED http://python.org/sf/1693079 opened by IWL email.Message set_param rfc2231 encoding incorrect (2007-04-03) http://python.org/sf/1693546 opened by Anders Hammarquist Portability issie: os.rename behaves differently on win32 (2007-04-03) http://python.org/sf/1693753 opened by cs_ Puzzled over list append bvehavior (2007-04-03) CLOSED http://python.org/sf/1693941 opened by elgordo Python 2.5 installer ended prematurely (2007-04-04) http://python.org/sf/1694155 opened by Miclav Failure to build on AIX 5.3 (2007-04-04) http://python.org/sf/1694442 opened by Jaman Swearingen Overloading int.__pow__ does not work (2007-04-04) http://python.org/sf/1694663 opened by Terry J. Reedy Bad documentation for existing imp methods (2007-04-05) http://python.org/sf/1694833 opened by Christoph Zwerschke Bad documentation of SMTPException (2007-04-05) http://python.org/sf/1694950 opened by Christoph Zwerschke Failure to build on AIX 5.3 (2007-04-05) CLOSED http://python.org/sf/1695179 opened by Jaman Swearingen generator expression produces incomplete list (2007-04-05) CLOSED http://python.org/sf/1695272 opened by wplapper Unexpected feature vs. integer and True values (2007-04-06) CLOSED http://python.org/sf/1695688 opened by dev at bacademy PEP 302 broken (2007-04-06) CLOSED http://python.org/sf/1695718 opened by phil logging.handlers.SocketHandler.makeSocket() blocks app (2007-04-07) http://python.org/sf/1695948 opened by jtdeng codecs.EncodedFile() - the same data and file encodings (2007-04-07) CLOSED http://python.org/sf/1696025 opened by Alexandr V. Demeshko Add collections.counts() (2007-04-07) http://python.org/sf/1696199 opened by Steven Bethard Strange performance with unicode and lists (2007-04-08) CLOSED http://python.org/sf/1696390 opened by Vsevolod Bugs Closed ___________ Python and Indeterminate Forms (Math) (2007-03-15) http://python.org/sf/1681671 closed by tjreedy Documentation error (section 3.4.1) (2007-03-17) http://python.org/sf/1682729 closed by zseil next method assignment is ignored in new-style classes (2007-03-17) http://python.org/sf/1682749 closed by gbrandl os.walk should traverse outward symlinks (2007-03-18) http://python.org/sf/1682940 closed by gbrandl Lib/io.py open uses unset "bs" (2007-03-12) http://python.org/sf/1679498 closed by gvanrossum clarify 80-char limit (2007-01-05) http://python.org/sf/1628906 closed by gvanrossum PyFloat_FromString deprecated form (2007-02-02) http://python.org/sf/1650903 closed by gbrandl Incorrect file path reported by inspect.getabsfile() (2007-02-23) http://python.org/sf/1666807 closed by zseil select.select() injecting spurious text in stdout (2007-03-18) http://python.org/sf/1683316 closed by sf-robot Import value 1e400 from pyc fails (2005-12-11) http://python.org/sf/1378305 closed by gbrandl Python2.5 can't read a (complex) pickle build by python2.4 (2007-03-07) http://python.org/sf/1675967 closed by zseil date-datetime comparison doesn't work (2007-03-04) http://python.org/sf/1673403 closed by collinwinter module-ctypes should show platform availability (2007-03-19) http://python.org/sf/1683872 closed by gbrandl too long string causes segmentation fault (2007-03-15) http://python.org/sf/1681762 closed by gbrandl regression in webbrowser command line parsing (2007-03-20) http://python.org/sf/1684254 closed by gbrandl __cdecl / __stdcall unspecified in *.h (2001-10-15) http://python.org/sf/471432 closed by bcannon modindex.html builds incorrectly in Python 3 (2007-03-20) http://python.org/sf/1684811 closed by collinwinter Explain how to subclass Exception (2002-07-06) http://python.org/sf/578180 closed by bcannon extend namespace docs to cover LOAD_NAME (2002-04-19) http://python.org/sf/546196 closed by bcannon -S hides standard dynamic modules (2002-07-25) http://python.org/sf/586680 closed by bcannon IBCarbon module (2002-07-26) http://python.org/sf/587011 closed by bcannon Using .next() on file open in write mode writes junk to file (2006-10-01) http://python.org/sf/1569057 closed by bcannon Keyword arguments to __init__() of a subclass of set (2007-03-20) http://python.org/sf/1684943 closed by nnorwitz python always searches python23.zip (2003-02-25) http://python.org/sf/692884 closed by collinwinter Move modules out of Carbon (2003-03-02) http://python.org/sf/696206 closed by bcannon socket's makefile file object doesn't work with timeouts. (2004-01-22) http://python.org/sf/882297 closed by facundobatista Command line interface to timeit.py (2007-03-22) http://python.org/sf/1685704 closed by gbrandl tarfile file names under win32 (2007-03-22) http://python.org/sf/1685773 closed by indi4source msvccompiler.py doesn't recongnize VS2005 (2007-03-22) http://python.org/sf/1685775 closed by loewis logging package failure for NTEventLogHandler (2007-03-22) http://python.org/sf/1686200 closed by vsajip os.stat() WindowsError 13 when file in use (2007-03-23) http://python.org/sf/1686475 closed by loewis Inconsistent Exceptions for Readonly Attributes (2007-03-23) http://python.org/sf/1687163 closed by collinwinter Round funcion (2007-03-24) http://python.org/sf/1687314 closed by gbrandl format error in 2.5 ref.pdf in section 5.3.4 Calls (2006-12-20) http://python.org/sf/1619641 closed by zseil texinfo library documentation fails to build (2006-11-12) http://python.org/sf/1595164 closed by loewis broken info files generation (2006-09-30) http://python.org/sf/1568429 closed by zseil Python/C PyClass_* are not documented (2007-03-26) http://python.org/sf/1688274 closed by collinwinter sock.recvfrom(-24) crashes (2007-03-26) http://python.org/sf/1688393 closed by nnorwitz [2.5 regression?] failure to import the ORBit extension (2007-02-17) http://python.org/sf/1662529 closed by nnorwitz strptime(): can't switch locales more than once (2005-09-13) http://python.org/sf/1290505 closed by bcannon .eml attachments in email (2006-10-06) http://python.org/sf/1572084 closed by sf-robot Typographical Error (2007-03-29) http://python.org/sf/1690324 closed by quiver language reference index links are broken (2006-12-27) http://python.org/sf/1622664 closed by gbrandl preferred diff format should be mentioned as "unified". (2006-12-27) http://python.org/sf/1623153 closed by rhettinger thirdparty extensions, --enable-shared, static linking (2007-02-08) http://python.org/sf/1655392 closed by gbrandl lambda function segfault (2007-04-01) http://python.org/sf/1692280 closed by gbrandl webbrowser module cannot open the right URL (2007-04-02) http://python.org/sf/1692695 closed by gbrandl Can't save empty array in shelve (2007-04-02) http://python.org/sf/1693079 closed by rhettinger slice obj with no start index is 0 instead of None sometimes (2007-02-28) http://python.org/sf/1671137 closed by jyzude SystemError with re.match(array) (2007-01-29) http://python.org/sf/1647541 closed by rhettinger Incorrect docs for bisect_left (2006-11-24) http://python.org/sf/1602378 closed by rhettinger Tutorial section 9.5.1 ignores MRO for new-style classes (2005-12-16) http://python.org/sf/1382213 closed by rhettinger incorrect traceback filename from pyc (2004-10-21) http://python.org/sf/1051638 closed by zseil 'Ok' key in options dialog does nothing (2007-02-11) http://python.org/sf/1657034 closed by torhu Puzzled over list append bvehavior (2007-04-03) http://python.org/sf/1693941 closed by rhettinger struct.unpack doens't support buffer protocol objects (2006-09-22) http://python.org/sf/1563759 closed by rhettinger clearing up dictionary keys/set member docs (2005-11-28) http://python.org/sf/1368768 closed by rhettinger zlib.crc32() not cross-platform (2007-03-10) http://python.org/sf/1678102 closed by tjreedy Failure to build on AIX 5.3 (2007-04-05) http://python.org/sf/1695179 deleted by tiriss generator expression produces incomplete list (2007-04-05) http://python.org/sf/1695272 closed by gbrandl Unexpected feature vs. integer and True values (2007-04-06) http://python.org/sf/1695688 closed by gbrandl PEP 302 broken (2007-04-06) http://python.org/sf/1695718 closed by gbrandl codecs.EncodedFile() - the same data and file encodings (2007-04-07) http://python.org/sf/1696025 closed by doerwalter Strange performance with unicode and lists (2007-04-08) http://python.org/sf/1696390 closed by gbrandl New / Reopened RFE __________________ Add tail recursion (2007-03-20) CLOSED http://python.org/sf/1684603 opened by Tommy Nordgren csv sniff example (2007-03-22) http://python.org/sf/1686390 opened by Thomas Guettler Add "methodcaller" to the operator module (2006-06-14) CLOSED http://python.org/sf/1506171 reopened by rhettinger Call sys.except_hook if exception occurs in __del__ (2007-03-30) http://python.org/sf/1691387 opened by John Ehresman Stripping debugging symbols from compiled C extensions (2007-04-02) http://python.org/sf/1692592 opened by Viktor Ferenczi RFE Closed __________ optparse should support arbitrary number of arguments (2006-07-24) http://python.org/sf/1527705 closed by gbrandl smarter temporary file object (2001-04-12) http://python.org/sf/415692 closed by collinwinter Add tail recursion (2007-03-20) http://python.org/sf/1684603 closed by rhettinger dict(key,values) initializer (2007-02-09) http://python.org/sf/1656538 closed by rhettinger Allowing the definition of constants (2006-04-05) http://python.org/sf/1465406 closed by collinwinter itemgetter built-in? (2005-10-10) http://python.org/sf/1322308 closed by collinwinter Add os.path.relpath (2005-09-30) http://python.org/sf/1309676 closed by collinwinter Add a settimeout to ftplib.FTP object (2005-04-06) http://python.org/sf/1177998 closed by facundobatista 'attrmap' function, attrmap(x)['attname'] == x.attname (2005-01-26) http://python.org/sf/1110010 closed by collinwinter Add "methodcaller" to the operator module (2006-06-14) http://python.org/sf/1506171 closed by collinwinter Py_DEBUG (2006-12-09) http://python.org/sf/1612190 closed by collinwinter bug with ill-formed rfc822 attachments (2003-09-30) http://python.org/sf/815563 closed by collinwinter Need Windows os.link() support (2001-11-05) http://python.org/sf/478407 closed by collinwinter From hq4ever at gmail.com Sun Apr 29 16:27:59 2007 From: hq4ever at gmail.com (Maxim Veksler) Date: Sun, 29 Apr 2007 23:27:59 +0300 Subject: I can't inherit from "compiled" classes ? In-Reply-To: References: Message-ID: On 4/29/07, Marc 'BlackJack' Rintsch wrote: > In , Maxim Veksler > wrote: > > > Hello list, > > > > I'm trying to subclass socket and select, for both I get: > > """ TypeError: Error when calling the metaclass bases > > module.__init__() takes at most 2 arguments (3 given) """, I don't > > understand this error. Why would python try to pass 3 arguments (what > > are they) ? > > > > Googling for this error gave random results talking about try to > > inherit a "Package" but socket is definitely a class, > > (/usr/lib/python2.4/socket.py). Not sure about select thought. > > > > I've did the following to receive the error: > > """ > > In [1]: import socket > > > > In [2]: class PollingSocket(socket): > > ...: pass > > ...: > > --------------------------------------------------------------------------- > > exceptions.TypeError Traceback (most > > recent call last) > > > > /home/hq4ever/ > > > > TypeError: Error when calling the metaclass bases > > module.__init__() takes at most 2 arguments (3 given) > > """ > > > > > > What am I breaking wrong? > > You are trying to subclass a module here, just like the error message > says. The module contains a `socket` type: > > In [3]: import socket > > In [4]: type(socket) > Out[4]: > > In [5]: type(socket.socket) > Out[5]: > Great, """ from socket import socket import select class PollingSocket(socket): pass """ > `select.select()` is a function: > > In [6]: import select > > In [7]: type(select.select) > Out[7]: > I understand what you are saying, and at the same time don't understand why it doesn't work. Isn't "everything an object" in python? And if something is an object does it not implies it's an instance of some class? Does this mean I can't somehow make this work: """class PollingSocket(socket.socket, select):""" ? Thanks for the help, > Ciao, > Marc 'BlackJack' Rintsch Maxim. -- Cheers, Maxim Veksler "Free as in Freedom" - Do u GNU ? From http Sat Apr 7 00:00:59 2007 From: http (Paul Rubin) Date: 06 Apr 2007 21:00:59 -0700 Subject: block scope? References: Message-ID: <7xr6qwal50.fsf@ruckus.brouhaha.com> James Stroud writes: > Probably, with good code, block scope would be overkill, except that I > would welcome list comprehensions to have a new scope: Block scope is a win because it gets rid of the uncertainty of whether the variable is used outside the block or not. The "good code" theory (just manually don't use the variable elsewhere) doesn't always hold up under release deadline pressure and so on and doesn't make sense anyway. What's the point of NOT having block scope if you don't want to allow for creating variables in inner blocks and using them in other blocks? I think it's best to require creating the variable in a mutually enclosing scope if you want to use it that way. From attn.steven.kuo at gmail.com Thu Apr 19 15:16:51 2007 From: attn.steven.kuo at gmail.com (attn.steven.kuo at gmail.com) Date: 19 Apr 2007 12:16:51 -0700 Subject: multirember&co In-Reply-To: References: <1176768854.720234.23320@w1g2000hsg.googlegroups.com> <1176790588.024371.119360@n76g2000hsh.googlegroups.com> <1176850352.999231.79260@n59g2000hsh.googlegroups.com> <1176921030.330467.76860@o5g2000hsb.googlegroups.com> <1176925857.535835.130010@b58g2000hsg.googlegroups.com> Message-ID: <1177010211.252779.83620@y5g2000hsa.googlegroups.com> On Apr 19, 9:13 am, Anton Vredegoor wrote: (snipped) > > > How about this one? > > No that can result in an infinite loop after yet another > > print it1.next() > > This one however ... > > from collections import deque > > class sentinel(object): > pass > > class myiter(object): > > def __init__(self,seq): > self.seq = seq > self.index = -1 > > def __iter__(self): > return self > > def next(self): > self.index +=1 > if self.index < len(self.seq): > return self.seq[self.index] > else: > return sentinel > > def xsplitter(seq, pred): > Q = deque(),deque() > it = myiter(seq) > def gen(p): > for x in it: > while Q[p]: yield Q[p].popleft() > if x is sentinel: break > if pred(x) == p: yield x > else: > Q[~p].append(x) > for x in gen(p): yield x > return gen(1),gen(0) > > def test(): > L = 'a', 1, 2, 'a' > it1, it2 = xsplitter(L, lambda x: x == 'a') > print it1.next() > print it2.next() > print it1.next() > print it2.next() > > if __name__=='__main__': > test() > > A. Um, no. That one stops prematurely if your input sequence is: L = 1, 2, 3, 'a', 'a' You get points for persistence, however. :) -- Regards, Steven From steve at REMOVEME.cybersource.com.au Mon Apr 30 23:14:18 2007 From: steve at REMOVEME.cybersource.com.au (Steven D'Aprano) Date: Tue, 01 May 2007 13:14:18 +1000 Subject: Dict Copy & Compare References: Message-ID: On Mon, 30 Apr 2007 12:50:58 -0500, Hamilton, William wrote: >> On quick question, how can I order a dict by the 'values' (not keys) >> before >> looping? Is that possible? >> > > The easiest way I can think of is to create a new dict that's reversed. > > reverseDict = {} > for key in dict1: > if dict1[key] not in reverseDict: > reverseDict[dict1[key]]=[key] > else: > reverseDict[dict1[key]].append(key) > > This gives you a dictionary that has the old dict's values as keys, and > the old dict's keys as lists of values. You can then sort the keys of > this dict and do what you want with it. Of course, the values in dict1 > have to be valid dictionary keys for this to work. If they aren't, you > may be able to get away with converting them to strings. Oh man, maybe you need to re-think what you consider "easier". for value in dict1.itervalues() do_something_with(value) If you need the keys as well: for key, value in dict1.iteritems() do_something_with(key, value) If you need to process the values (say, sort them) first: pairs = list(dict1.iteritems()) # or dict1.items() pairs.sort() for key, value in pairs: do_something_with(key, value) I'll leave sorting by value instead of key as an exercise. -- Steven D'Aprano From hlubenow2 at gmx.net Tue Apr 24 18:15:49 2007 From: hlubenow2 at gmx.net (hlubenow) Date: Wed, 25 Apr 2007 00:15:49 +0200 Subject: Generate report containing pdf or ps figures? References: <132pnp6r4qg0lc2@corp.supernews.com> <1177350202.388337.131110@d57g2000hsg.googlegroups.com> <132q0cpkpgt0ud1@corp.supernews.com> Message-ID: Grant Edwards wrote: > On 2007-04-23, Kjell Magne Fauske wrote: > >>> Is there a PDF generation library that can place EPS or PDF >>> figures on a page? What about http://pybrary.net/pyPdf/ It does some very interesting things. But I'm not really sure, if it does what you're after. At least it can merge one page onto another. H. From aleax at mac.com Sun Apr 15 02:07:05 2007 From: aleax at mac.com (Alex Martelli) Date: Sat, 14 Apr 2007 23:07:05 -0700 Subject: Append data to a list within a dict References: <7xejmnbj0x.fsf@ruckus.brouhaha.com> Message-ID: <1hwl1cg.ioy0ak5hp10zN%aleax@mac.com> Tina I wrote: ... > He he... at the age of 40 I'm well beyond school work ;) Why would that be? My wife's over 40, yet she's a student (currently at Stanford -- they were overjoyed to admit her, with lot of life experience as well as previous studies, apparently). She's not taking elementary courses on Python (having co-written a book on Python, tech-reviewed a few, and having been the first woman coopted as a member of the PSF:-), but she _has_ been taken equivalent ones on Java and C++ (languages she didn't previously know), as well as calculus, neurophysiology, and other strange things that are part of the "Symbolic Systems" studies. Down with ageism!-) Alex From stefan.behnel-n05pAM at web.de Thu Apr 19 08:39:54 2007 From: stefan.behnel-n05pAM at web.de (Stefan Behnel) Date: Thu, 19 Apr 2007 14:39:54 +0200 Subject: Python and XML? In-Reply-To: References: <46209A55.9070102@web.de> <46217DAE.7040501@ieee.org> <4621F54A.3010008@web.de> Message-ID: <4627631A.6030606@web.de> Hi, Leonard J. Reder wrote: > Stefan Behnel wrote: >> http://codespeak.net/lxml/objectify.html > > Looks like this stuff might do what I want. Need to work through the > example. > > Are you the author? Yup! :) > Why is this better then using gnossis? lxml is faster and supports more XML standards. It's also more flexible in that it allows you to replace element classes at basically any granularity and thus add things to the Element API or even replace it as you see fit, without loosing the standard XML features. You can even do that at the C-level, in case you really need high-performance. See the "extending lxml" section in the side menu at http://codespeak.net/lxml/dev/ especially: http://codespeak.net/lxml/dev/element_classes.html Stefan From bj_666 at gmx.net Tue Apr 17 11:30:38 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Tue, 17 Apr 2007 17:30:38 +0200 Subject: Syntax error References: <9w5Vh.8580$OT4.3503@newsfe19.lga> Message-ID: In <9w5Vh.8580$OT4.3503 at newsfe19.lga>, hg wrote: > I had the customer comment out the first two lines of the file: > > """ > #!/bin/env python > # -*- coding: iso-8859-15 -*- > """ > > ... and the problem disappeared. > > I am at a loss. > > Any clue ? There was once a bug in Python that lead to such "errors" if an encoding comment was used. So your costumer might check his Python version and maybe he should update. Ciao, Marc 'BlackJack' Rintsch From mail at timgolden.me.uk Fri Apr 27 11:29:50 2007 From: mail at timgolden.me.uk (Tim Golden) Date: Fri, 27 Apr 2007 16:29:50 +0100 Subject: Accessing SQL View with Python In-Reply-To: <1177687490.404875.170650@s33g2000prh.googlegroups.com> References: <1177687490.404875.170650@s33g2000prh.googlegroups.com> Message-ID: <463216EE.3020400@timgolden.me.uk> kyosohma at gmail.com wrote: > Hi All, > > I need to access a Microsoft SQL database View. Is there a way to do > this with Python? I have done a fair share of "googling" and found > nothing on accessing Views, just executing SQL, which I already know > how to do. > > I am running Windows XP, Python 2.4. Absolutely loads of ways. But (unless I'm missing something here) they all involve executing SQL which accesses a View (such as: SELECT * FROM v_info). Have I missed the point of your question? TJG From apardon at forel.vub.ac.be Mon Apr 16 05:20:24 2007 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 16 Apr 2007 09:20:24 GMT Subject: Queue enhancement suggestion References: <7x4pngluel.fsf_-_@ruckus.brouhaha.com> Message-ID: On 2007-04-16, Paul Rubin wrote: > I'd like to suggest adding a new operation > > Queue.finish() > > This puts a special sentinel object on the queue. The sentinel > travels through the queue like any other object, however, when > q.get() encounters the sentinel, it raises StopIteration instead > of returning the sentinel. It does not remove the sentinel from > the queue, so further calls to q.get also raise StopIteration. > That permits writing the typical "worker thread" as > > for item in iter(q.get): ... > The problem is this doesn't work well if you have multiple producers. One producer can be finished while the other is still putting values on the queue. The solution I have been thinking on is the following. Add an open and close operation. Only threads that have the queue open can access it. The open call should specify whether you want to read or write to the queue or both. When all writers have closed the queue and the queue is empty a q.get will raise an exception. This may be done by putting a sentinel on the queue when the last writer closed the queue. -- Antoon Pardon From kadeko at gmail.com Wed Apr 4 05:36:52 2007 From: kadeko at gmail.com (looping) Date: 4 Apr 2007 02:36:52 -0700 Subject: operator overloading Message-ID: <1175679412.741899.45990@l77g2000hsb.googlegroups.com> Hi, for the fun I try operator overloading experiences and I didn't exactly understand how it works. Here is my try: >>> class myint(int): def __pow__(self, value): return self.__add__(value) >>> a = myint(3) >>> a ** 3 6 OK, it works. Now I try different way to achieve the same result but without much luck: >>> class myint(int): pass >>> myint.__pow__ = myint.__add__ or: >>> class myint(int): __pow__ = int.__add__ or: >>> class myint(int): pass >>> a.__pow__ = a.__add__ but for every try the result was the same: >>> a = myint(3) >>> a ** 3 27 Why it doesn't works ? From deepns7 at gmail.com Sat Apr 21 07:13:10 2007 From: deepns7 at gmail.com (pradeep nair) Date: 21 Apr 2007 04:13:10 -0700 Subject: how to find the OS name..?? Message-ID: <1177153990.286509.274350@y80g2000hsf.googlegroups.com> How do i determine the type of OS i'm working on using python??(i.e whether CentOS,Fedora,SLES,.......along with the version) From khemkaamit at gmail.com Mon Apr 2 05:38:36 2007 From: khemkaamit at gmail.com (Amit Khemka) Date: Mon, 2 Apr 2007 15:08:36 +0530 Subject: Question about text in Python In-Reply-To: <4610c366$0$15022$5a62ac22@per-qv1-newsreader-01.iinet.net.au> References: <4610c366$0$15022$5a62ac22@per-qv1-newsreader-01.iinet.net.au> Message-ID: <1360b7230704020238q532f3c06vf8bb4bf7ef6c0ce8@mail.gmail.com> On 4/2/07, Steve wrote: > Hi, > > I've created a Python program that a user enteres one line of text which > will then create an acronym from that text. > > What I want to add to the program is the abilty to rerun this process (where > the user enteres another line of text) until the user has had enough and > enters a blank line which would then end the program. > > Can anyone help with this? > > thanks > > -- > http://mail.python.org/mailman/listinfo/python-list > Untested: if __name__ == "__main__": userinp=raw_input("Query>") while userinp: callmyabbrvfunction(userinp) userinp=raw_input("Another Query>") print "Exit: You have entered empty string !" 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 Michael.J.Fromberger at Clothing.Dartmouth.EDU Wed Apr 4 19:33:35 2007 From: Michael.J.Fromberger at Clothing.Dartmouth.EDU (Michael J. Fromberger) Date: Wed, 04 Apr 2007 19:33:35 -0400 Subject: how to remove multiple occurrences of a string within a list? References: <1175624433.206953.214290@n59g2000hsh.googlegroups.com> Message-ID: In article <1175624433.206953.214290 at n59g2000hsh.googlegroups.com>, "bahoo" wrote: > Hi, > > I have a list like ['0024', 'haha', '0024'] > and as output I want ['haha'] > > If I > myList.remove('0024') > > then only the first instance of '0024' is removed. > > It seems like regular expressions is the rescue, but I couldn't find > the right tool. If you know in advance which items are duplicated, then there have been several simple solutions already proposed. Here's another way to tackle the problem of removing ANY duplicated item from the list (i.e., any string that appears > 1 time). def killdups(lst): """Filter duplicated elements from the input list, and return the remaining (unique) items in their original order. """ count = {} for elt in lst: count[elt] = count.get(elt, 0) + 1 return [elt for elt in lst if count[elt] == 1] This solution is not particularly tricky, but it has the nice properties that: 1. It works on lists of any hashable type, not just strings, 2. It preserves the order of the unfiltered items, 3. It makes only two passes over the input list. Cheers, -M -- Michael J. Fromberger | Lecturer, Dept. of Computer Science http://www.dartmouth.edu/~sting/ | Dartmouth College, Hanover, NH, USA From hg at nospam.org Wed Apr 25 15:25:49 2007 From: hg at nospam.org (hg) Date: Wed, 25 Apr 2007 21:25:49 +0200 Subject: Where did my post go? References: <1177550534.197992.263190@u32g2000prd.googlegroups.com> Message-ID: flifus at gmail.com wrote: > > I posted to this newsgroup earlier about my annoyances with python and > now I can't find the post. What did you do with it? they found it annoying and removed it. hg From olegalexander at gmail.com Thu Apr 12 12:57:42 2007 From: olegalexander at gmail.com (Oleg Alexander) Date: 12 Apr 2007 09:57:42 -0700 Subject: NLTK, Random Sentence Generators? In-Reply-To: <87k5wh25b3.fsf@localhost.localdomain> References: <87slb8d3uj.fsf@localhost.localdomain> <3CJSh.7608$u03.3757@newssvr21.news.prodigy.net> <87k5wkcuv6.fsf@localhost.localdomain> <87k5wh25b3.fsf@localhost.localdomain> Message-ID: <1176397062.542797.273800@o5g2000hsb.googlegroups.com> On Apr 12, 4:36 am, Passer By wrote: > James Stroud writes: > > Passer By wrote: > > > James Stroud writes: > > > >>Passer By wrote: > > > >>>Has any created or not of examples of random sentence generators > > >>>using n-gram models (or other models might be interesting). I > > >>>know of one example from a course at MIT, but besides that > > >>>nothing. Any help would be great. > > > >>Best is to just cull text from your spam folder as these are often > > >>generated by similar means--but somehow I think you knew that. > > > > Emotive on Usenet? Thats original. > > > Anonimity on usenet? That's suspiscious. > > Paranoid Plunk?- Hide quoted text - > > - Show quoted text - Another way to generate random text is by using context free grammars and recursive substitution. Here are some examples of programs which use this technique: http://nonsense.sourceforge.net/ http://www.elsewhere.org/pomo The programs generate from a user-defined "grammar" file, which looks something like this: ROOT $sentence SENTENCE I $feelabout my $animal! FEELABOUT love hate ANIMAL dog cat The above grammar will generate the following possible sentences: I love my cat! I hate my cat! I love my dog! I hate my dog! Unlike a Markov generator, the output of these programs is grammatically correct. From sjmachin at lexicon.net Sat Apr 21 21:36:39 2007 From: sjmachin at lexicon.net (John Machin) Date: 21 Apr 2007 18:36:39 -0700 Subject: Handy short cut for formatting elapsed time in floating point seconds In-Reply-To: <1177204141.785661.203320@n59g2000hsh.googlegroups.com> References: <1177204141.785661.203320@n59g2000hsh.googlegroups.com> Message-ID: <1177205799.887173.265670@n59g2000hsh.googlegroups.com> On Apr 22, 11:09 am, Paul McGuire wrote: > I am doing some simple timing of some elements of Python scripts, and > the simplest is to just call time.time() before and after key elements > of the script: > > t1 = time.time() > > # do lengthy operation > > t2 = time.time() > print "That took %f seconds" % (t2-t1) Why would you do %f and not %.3f ? > > Unfortunately, this gives very ugly timing output, as just a floating > point number of seconds. After several iterations of writing a > formatter (strftime is not straightforward to use - it omits > milliseconds for one thing), I came up with this: > > def secondsToStr(t): > rediv = lambda ll,b : list(divmod(ll[0],b)) + ll[1:] > return "%d:%02d:%02d.%03d" % tuple(reduce(rediv,[[t*1000,], > 1000,60,60])) > > Now I can write: > > print "That took", secondsToStr(t2-t1),"seconds" > > and get nicely-formatted 0:00:12.345 style output. and it it runs for (say) 83+ seconds you will get "That took 0:01:23.456 seconds" which is ludicrous. And if you want to calculate a percentage speed-up later you will have to convert back to seconds. > > (I also posted this to the Python Cookbook.) > > -- Paul IMHO if your job is short, print "That took %.3f seconds" % (t2 - t1) is adequate, and your leading 0:00: is useless. If it runs for minutes or hours, then minutes or hours to (say) 4 significant digits is more than adequate, and printing milliseconds is useless. From nagle at animats.com Sat Apr 28 14:08:08 2007 From: nagle at animats.com (John Nagle) Date: Sat, 28 Apr 2007 18:08:08 GMT Subject: More urllib timeout issues. In-Reply-To: References: Message-ID: Steve Holden wrote: > John Nagle wrote: >> Then we'd have a reasonable network timeout system. >> We have about half of the above now, but it's not consistent. >> >> Comments? >> > The only comments I'll make for now are > > 1) There is work afoot to build timeout arguments into network libraries > for 2.6, and I know Facundo Batista has been involved, you might want to > Google or email Facundo about that. > 2) The main reason why socket.setdefaulttimeout is unsuitable for many > purposes is its thread-unsafe property, so all threads must use the same > default timeout or have it randomly change according to the whim of hte > last thread to alter it. It has other problems. If you set that value, it affects socket blocking/non blocking modes. It can mess up M2Crypto, causing it to report "Peer did not return certificate". > 3) This is important and sensible work and if properly followed through > will likely lead to serious quality improvements in the network libraries. Agreed. > regards > Steve I took a look at Facundo Batista's work in the tracker, and he currently seems to be trying to work out a good way to test the existing SSL module. It has to connect to something to be tested, of course. Testing network functionality is tough; to do it right, you need a little test network to talk to, one that forces some of the error cases. And network testing doesn't have the repeatability upon which the Python test system/buildbot depends. It's really tough to test this stuff properly. The best I've been able to do so far is to run the 11,000 site list from the Webspam Challenge through our web spider. Here's a list of URLs from our error log which have given us connection trouble of one kind or another. Most of these open an HTTP transaction, but for some reason, don't carry it through to completion properly, resulting in a long stall in urllib. blaby.gov.uk boys-brigade.org.uk cam.ac.uk essex.ac.uk gla.ac.uk open.ac.uk soton.ac.uk uea.ac.uk ulster.ac.uk So that's a short, but useful, set of timeout test cases. Those are the ones that timed out after, not during, TCP connection opening. It's interesting that this problem appears for the root domains of many English universities. They must all run the same server software. Some of these fail because "robotparser", which uses "urllib", hangs for minutes trying to read the "robots.txt" file associated with the domain. This isn't something that requires a major redesign. These are bugs. John Nagle From renfr1dl at cmich.edu Thu Apr 26 10:03:19 2007 From: renfr1dl at cmich.edu (Dave L. Renfro) Date: 26 Apr 2007 07:03:19 -0700 Subject: Video: Professor of Physics Phd at Cal Tech says: 911 Inside Job In-Reply-To: References: <1177467203.719625.93920@u32g2000prd.googlegroups.com> Message-ID: <1177596199.604969.43420@r3g2000prh.googlegroups.com> stj... at rock.com wrote: >> Cal Tech is the ELITE of ELITE in physics. >> >> If Feynman were alive, he would point his finger straight at >> the 911 criminal operators, the yank bastards themselves ....... >> >> http://www.911blogger.com/node/8101 >> >> No self-respecting scientist should keep his mouth shut. >> Its a fundamental challenge to the method of science, >> a detective work most demanding of INTELLECTUAL HONESTY. Gib Bogle wrote: > When did the University of Iowa (Iowhere?) become CalTech. http://www.physics.uiowa.edu/~cgrabbe/ Yikes! This is less than 2 miles from where I live. Plus, there's Alexander Abian who, before he died, was down the road a bit at Iowa State University. And then there were the physics department shootings here a few years ago (5 killed, 3 of whom were professors in the physics department). Maybe I shouldn't be drinking the water. Dave L. Renfro From bobjohnson11 at gmail.com Mon Apr 30 19:19:57 2007 From: bobjohnson11 at gmail.com (RobJ) Date: 30 Apr 2007 16:19:57 -0700 Subject: Master's Thesis Help Needed In-Reply-To: <1hxcqfn.11m7qp91766nc4N%aleax@mac.com> References: <1177898031.790447.253360@n76g2000hsh.googlegroups.com> <1hxcqfn.11m7qp91766nc4N%aleax@mac.com> Message-ID: <1177975197.557114.46700@o5g2000hsb.googlegroups.com> On Apr 30, 12:00 am, a... at mac.com (Alex Martelli) wrote: > RobJ wrote: > >http://pyschool.robj.webfactional.com/ > > Things start on a pretty bad note when I'm asked to select my OS: > Ubuntu Linux > Windows XP > > I'm running MacOSX. What now? Why is there no choice "none of the > above"...?! > > Alex Alex, Sorry about that. I'll add on to the front page what 2 OSs are available.. During my pre-work for my project I did a survey and WindowsWP and Ubuntu Linux came up as the top two OSs. Rob J From aleax at mac.com Sun Apr 22 01:14:43 2007 From: aleax at mac.com (Alex Martelli) Date: Sat, 21 Apr 2007 22:14:43 -0700 Subject: Support for new items in set type References: <1177211624.069474.3960@y5g2000hsa.googlegroups.com> Message-ID: <1hwxx1e.1un7urc1de872aN%aleax@mac.com> Prateek wrote: > I have a bit of a specialized request. > > I'm reading a table of strings (specifically fixed length 36 char > uuids generated via uuid.uuid4() in the standard library) from a file > and creating a set out of it. > Then my program is free to make whatever modifications to this set. > > When I go back to save this set, I'd like to be able to only save the > new items. Currently I am creating a copy of the set as soon as I load > it and then when I go back to save it, i'm calculating the difference > and saving just the difference. > > There are many problems with this approach so far: > 1) Calculating the difference via the standard set implementation is > not very scalable -> O(n) I presume Yep, you do have to look at every item, so O(N) is an obvious lower bound. > 2) Maintaining a copy wastes memory > 3) I don't have a good solution if I delete items from the set > (calculating the difference will return an empty set but I need to > actually delete stuff). (3) is easy -- the difference originalset-finalset is the set of things you have to delete. > Does anyone have any ideas? Your problem is really a thinly disguised version of one of the most ancient and venerable ones in data processing -- the "master file / transaction file" problem. With sets (which are built as hash tables) you have very powerful weapons for this fray (it used to be, many years ago, that sorting and "in-step processing of sorted files" was the only feasible approach to such problems), but you still have to wield them properly. In your shoes, I would write a class whose instances hold three sets: -- the "master set" is what you originally read from the file -- the "added set" is the set of things you've added since then -- the "deleted set" is the set of things you've deleted since them You can implement a set-like interface; for example, your .add method will need to remove the item from the deleted set (if it was there), then add it to the added set (if it wasn't already in the master set); and so on, for each and every method you actually desire (including no doubt __contains__ for membership testing). E.g., with suitably obvious names for the three sets, we could have...: class cleverset(object): ... def __contains__(self, item): if item in self.deleted: return False elif item in self.added: return True else: return item in self.master When the time comes to save back to disk, you'll perform deletions and additions based on self.deleted and self.added, of course. I'm not addressing the issue of how to best represent such sets on disk because it's not obvious to me what operations you need to perform on the on-disk representation -- for example, deletions can be very costly unless you can afford to simply set a "logically deleted" flag on deleted items; but, depending on how often you delete stuff, that will eventually degrade performance due to fragmentation, and maintaining the indexing (if you need one) can be a bear. Normally, I would use a good relational database (which has no doubt already solved on my behalf all of these issues) for purpose of persistent storage of such data -- usually sqlite for reasonably small amounts of data, PostgreSQL if I need enormous scalability and other "enterprise" features, but I hear other people are happy with many other engines for relational DBs, such as Oracle (used to be superb if you could afford full-time specialized db admins), IBM's DB2, SAP's database (now opensourced), Firebird, even MySQL (I've never, but NEVER, had any good experience with the latter, but I guess maybe it's only me, as otherwise it could hardly be so popular). The main point here is that a relational DB's tables _should_ be already very well optimized for storing "sets", since those table ARE exactly nothing but sets of tuples (and a 1-item tuple is a tuple for all that:-). Alex From maxerickson at gmail.com Wed Apr 11 20:31:07 2007 From: maxerickson at gmail.com (Max Erickson) Date: Thu, 12 Apr 2007 00:31:07 +0000 (UTC) Subject: Python Web Servers and Page Retrievers References: <4c0048df0704081442w7a25ee2bqe2b13229dc37769e@mail.gmail.com> <4c0048df0704111508u1fbccadbwa164b6c598f89659@mail.gmail.com> Message-ID: "Collin Stocks" wrote: > ------=_Part_19087_21002019.1176329323968 > I tried it, and when checking it using a proxy, saw that it > didn't really work, at least in the version that I have (urllib > v1.17 and urllib2 v2.5). It just added that header onto the end, > therefore making there two User-Agent headers, each with > different values. I might add that my script IS able to retrieve > search pages from Google, whereas both urllibs are FORBIDDEN with > the headers that they use. > I don't know enough about either library to argue about it, but here is what I get following the Dive Into Python example(but hitting google for a search): >>> import urllib2 >>> opener=urllib2.build_opener() >>> request=urllib2.Request('http://www.google.com/search? q=tesla+battery') >>> request.add_header('User-Agent','OpenAnything/1.0 +http://diveintopython.org/') >>> data=opener.open(request).read() >>> data 'tesla battery - Google Search< [snip rest of results page] This is with python 2.5 on windows. max From steven.bethard at gmail.com Sun Apr 22 21:34:04 2007 From: steven.bethard at gmail.com (Steven Bethard) Date: Sun, 22 Apr 2007 19:34:04 -0600 Subject: recursion depth problem In-Reply-To: <1177278499.378120.246560@o5g2000hsb.googlegroups.com> References: <1177267774.416169.276780@e65g2000hsc.googlegroups.com> <1177271382.859369.104790@q75g2000hsh.googlegroups.com> <1177278499.378120.246560@o5g2000hsb.googlegroups.com> Message-ID: proctor wrote: > On Apr 22, 2:06 pm, Steven Bethard wrote: >> proctor wrote: >>> On Apr 22, 1:24 pm, Michael Bentley wrote: >>>> On Apr 22, 2007, at 1:49 PM, proctor wrote: >>>>> i have a small function which mimics binary counting. it runs fine as >>>>> long as the input is not too long, but if i give it input longer than >>>>> 8 characters it gives >>>>> RuntimeError: maximum recursion depth exceeded in cmp >>>>> i'm not too sure what i am doing improperly. is there really a lot of >>>>> recursion in this code? >>>>> ================== >>>>> import sys >>>>> def ch4(item, n=0): >>>>> if n < len(item): >>>>> if item[n] == '0': >>>>> item[n] = '1' >>>>> print ''.join(item) >>>>> ch4(item) >>>>> elif item[n] == '1': >>>>> item[n] = '0' >>>>> ch4(item, n+1) >>>>> ch4(list(sys.argv[1])) >>>>> ================== >>>> Yes. There really is *that* much recursion in that code. 502 levels >>>> with input length of 8 characters, 1013 with 9 characters, 2035 with >>>> 10 characters... There's a pattern there ;-) >>> ok, thanks michael! >>> is there a way to avoid it here? how could i write this better, (if >>> at all)? >> Google for permutation-like recipies: >> >> http://www.google.com/search?q=Python+permutations >> >> Use the code from the first hit:: >> >> >>> for x in xselections('01', 8): >> ... print ''.join(x) >> ... >> 00000000 >> 00000001 >> 00000010 >> ... >> 11111101 >> 11111110 >> 11111111 >> >> Explaining to your teacher why your code uses generators when you >> haven't been taught them yet is left as an exercise to the reader. ;-) >> >> STeVe > > this is really nice, thanks steve. much slicker than my code. > > for interest sake: is my method unredeemable? Let's just say that I don't currently see an obvious way of redeeming it. ;-) STeVe From Marko.Cain.23 at gmail.com Thu Apr 19 15:00:26 2007 From: Marko.Cain.23 at gmail.com (Marko.Cain.23 at gmail.com) Date: 19 Apr 2007 12:00:26 -0700 Subject: HTTP getreply() never returns Message-ID: <1177009226.847229.34210@n76g2000hsh.googlegroups.com> Hi, I have the following code which send/receive HTTP request/response: # where sampleUrl is '127.0.0.1' and # url is 'www.cnn.com' h = httplib.HTTP(self.sampleUrl, 8080) h.putrequest('GET', '/sample?url=' + self.url) h.endheaders() errcode, errmsg, headers = h.getreply() But it never returns from h.getreply(). I am using python 2.3.4. Can you please tell me what am I missing? I am sure the url is correctly. I try putting this 'http:// 127.0.0.1:8080/sample?url=www.cnn.com' and it works. Thank you for any help. From gagsl-py2 at yahoo.com.ar Wed Apr 4 23:26:10 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 05 Apr 2007 00:26:10 -0300 Subject: Where to find pywin32/win32all for Python 1.5.2? References: <1175656089.023440.286290@q75g2000hsh.googlegroups.com> Message-ID: En Wed, 04 Apr 2007 01:39:32 -0300, Jack escribi?: > Thanks Jay. When I searched the net, I also found mentioning of > win32all-125.exe > but I couldn't find a download link. Does anyone still have it in the HD? Earliest I have is release 147 for Python 2.1, if you want. -- Gabriel Genellina From attn.steven.kuo at gmail.com Sat Apr 21 17:54:08 2007 From: attn.steven.kuo at gmail.com (attn.steven.kuo at gmail.com) Date: 21 Apr 2007 14:54:08 -0700 Subject: Suggestion: str.itersplit() In-Reply-To: <1177160280.784224.53460@b58g2000hsg.googlegroups.com> References: <1177160280.784224.53460@b58g2000hsg.googlegroups.com> Message-ID: <1177192448.271776.154840@n76g2000hsh.googlegroups.com> On Apr 21, 5:58 am, Dustan wrote: > >From my searches here, there is no equivalent to java's > > StringTokenizer in python, which seems like a real shame to me. > > However, str.split() works just as well, except for the fact that it > creates it all at one go. I suggest an itersplit be introduced for > lazy evaluation, if you don't want to take up recourses, and it could > be used just like java's StringTokenizer. > > Comments? If your delimiter is a non-empty string, you can use an iterator like: def it(S, sub): start = 0 sublen = len(sub) while True: idx = S.find(sub,start) if idx == -1: yield S[start:] raise StopIteration else: yield S[start:idx] start = idx + sublen target_string = 'abcabcabc' for subs in it(target_string,'b'): print subs For something more complex, you may be able to use re.finditer. -- Hope this helps, Steven From tjreedy at udel.edu Sun Apr 1 14:43:15 2007 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 1 Apr 2007 14:43:15 -0400 Subject: ISO programming projects References: Message-ID: "kj" wrote in message news:euojdp$mmt$1 at reader2.panix.com... | | | | I'm looking for a collection of useful programming projects, at | the "hobbyist" level. | | My online search did turn up a few collections (isolated projects | are less useful to me at the moment), but these projects are either | more difficult than what I'm looking for (e.g. code a C compiler) | or not terribly useful to the average person (e.g. a function that | efficiently computes the n-th Fibonacci number). | | Any pointers would be much appreciated. There have been similar questions (with responses) on this newsgroup. Have you searched those? From nagle at animats.com Wed Apr 4 14:08:27 2007 From: nagle at animats.com (John Nagle) Date: Wed, 04 Apr 2007 18:08:27 GMT Subject: BeautifulSoup vs. real-world HTML comments Message-ID: The syntax that browsers understand as HTML comments is much less restrictive than what BeautifulSoup understands. I keep running into sites with formally incorrect HTML comments which are parsed happily by browsers. Here's yet another example, this one from "http://www.webdirectory.com". The page starts like this: Environment Web Directory Those are, of course, invalid HTML comments. But Firefox, IE, etc. handle them without problems. BeautifulSoup can't parse this page usefully at all. It treats the entire page as a text chunk. It's actually HTMLParser that parses comments, so this is really an HTMLParser level problem. John Nagle From sjmachin at lexicon.net Mon Apr 30 14:36:08 2007 From: sjmachin at lexicon.net (John Machin) Date: 30 Apr 2007 11:36:08 -0700 Subject: How to convert float to sortable integer in Python In-Reply-To: <4tednQylRK5BcKjbnZ2dnUVZ_qiqnZ2d@comcast.com> References: <4tednQylRK5BcKjbnZ2dnUVZ_qiqnZ2d@comcast.com> Message-ID: <1177958168.211759.308100@c35g2000hsg.googlegroups.com> On Apr 30, 11:23 pm, Larry Bates wrote: > ire... at javeriana.edu.co wrote: > > DEAR SIR, > > I SAW YOUR INTERNET QUESTION AND I HAVE THE SAME TROUBLE. > > CUOLD YOU HELP ME TO MAKE A FLOAT TO INTEGER CONVERTION? > > DO YOU HAVE ANY EXEL FILE THAT CAN DO THAT? > > REGARDS AND THANKS A LOT > > > IVAN REYES > > > ___________________________________ > > > AVISO LEGAL: El presente correo electronico no representa la opinion o el consentimiento oficial de la PONTIFICIA UNIVERSIDAD JAVERIANA. Este mensaje es confidencial y puede contener informacion privilegiada la cual no puede ser usada ni divulgada a personas distintas de su destinatario. Esta prohibida la retencion, grabacion, utilizacion, aprovechamiento o divulgacion con cualquier proposito. Si por error recibe este mensaje, por favor destruya su contenido y avise a su remitente. > > En este aviso legal se omiten intencionalmente las tildes. > > > Este mensaje ha sido revisado por un sistema antivirus, por lo que su contenido esta libre de virus. > > This e-mail has been scanned by an antivirus system, so its contents is free of viruses. > > You have given us an ill defined problem. > > 1) If you want to convert float to int just use int() function. > s=int(f) > > 2) If you want to keep some fractional part of the float multiply > it by 10, 100, 1000, 10000, ... depending on how many digits of > precision you wish to retain and then take int(). > > s=int(f*10000) > > would retain 4 digits of precision and throw away the remainder. > > 3) You can sort on float just fine, so why do you need int()? > and: (4) Who is the "dear sir" and what was his problem? (5) How do you imagine that an Excel file could assist? (6) Please consider giving your CapsLock key a squirt of WD-40 :-) From tim at tdw.net Wed Apr 4 13:55:20 2007 From: tim at tdw.net (Tim Williams) Date: Wed, 4 Apr 2007 18:55:20 +0100 Subject: Indentifying the LAST occurrence of an item in a list In-Reply-To: References: Message-ID: <9afea2ac0704041055i6032e1cel22d88fe26284be9e@mail.gmail.com> On 4 Apr 2007 08:58:49 -0700, tkpmep at hotmail.com wrote: > For any list x, x.index(item) returns the index of the FIRST > occurrence of the item in x. Is there a simple way to identify the > LAST occurrence of an item in a list? My solution feels complex - > reverse the list, look for the first occurence of the item in the > reversed list, and then subtract its index from the length of the list > - 1, i.e. > > LastOcc = len(x) - 1 - x[::-1].index(item) > > Is there a simpler solution? Simpler ? That's subjective. :) You definitely need to search/iterate a reversed list, or start from the far end of a non-reversed list. For fun only. >>> t = [0,1,2,3,0] >>> def place(t,i): ... for x,y in zip(t,range(len(t)))[::-1]: ... if x == i: ... return y ... >>> place(t,3) 3 >>> place(t,0) 4 From nagle at animats.com Mon Apr 30 23:46:42 2007 From: nagle at animats.com (John Nagle) Date: Mon, 30 Apr 2007 20:46:42 -0700 Subject: re-importing modules In-Reply-To: References: <8%pZh.18192$Kd3.76@newssvr27.news.prodigy.net> <1177962288.575008.48490@q75g2000hsh.googlegroups.com> <1177967919.968338.3300@l77g2000hsb.googlegroups.com> Message-ID: Gabriel Genellina wrote: > En Mon, 30 Apr 2007 21:32:20 -0300, John Nagle > escribi?: > >> kyosohma at gmail.com wrote: >> >>>> In addition to the warning that reload() does not recursively reload >>>> modules that the reloaded module depends on, be warned that reloading a >>>> module does not magically affect any functions or objects from the old >>>> version that you may be holding on to. >> >> >> Maybe reloading modules should be deprecated. The semantics >> are awful, and it interferes with higher-performance implementations. > > > Maybe all the drawbacks should be clearly stated instead, telling that > it's not a magic wand as someone could think. It's one of those things which is more of an artifact of the CPython implementation than a designed-in feature. A more compile-oriented implementation like ShedSkin has to go to considerable effort to support a feature like this, and it's not all that useful anyway. There's a discussion of this, as it affects Jython and PyPy, here: http://mail.python.org/pipermail/edu-sig/2007-March/007815.html Some of the enthusiasm for reloading comes from attempts to emulate the older LISP environments, where the development environment lived in the same namespaces as the execution environment. That really wasn't that great an idea even in the LISP era. The Symbolics LISP machines were the greatest expression of that idea, and turned out to be a dead end. John Nagle From kensmith at rahul.net Wed Apr 25 22:41:15 2007 From: kensmith at rahul.net (MooseFET) Date: 25 Apr 2007 19:41:15 -0700 Subject: *** Watch BOMBSHELL video of Senator John Kerry admitting 911 was in INSIDE JOB ??? In-Reply-To: References: <1177387965.127809.175390@l77g2000hsb.googlegroups.com> Message-ID: <1177555274.912718.38320@c18g2000prb.googlegroups.com> On Apr 24, 2:19 pm, "Jon Slaughter" wrote: > wrote in message > > news:1177387965.127809.175390 at l77g2000hsb.googlegroups.com... > > > > >http://www.911blogger.com/node/8053 > > > Senator John Kerry was questioned concerning 9/11 during an appearance > > at Book People in Austin, Texas. Members of Austin 9/11 Truth Now > > asked Kerry about the officially unexplained collapse of WTC Building > > 7." > > > Kerry responded: > > > "I do know that that wall, I remember, was in danger and I think > > they made the decision based on the danger that it had in destroying > > other things-- that they did it in a controlled fashion." > > >http://www.jonesreport.com/articles/220407_kerry_wtc7.html > > > Thanks to the dozen or so people who submitted this as a blog entry :) > > > "Mr. Kerry?!?" > > > "Just a follow-up or two... > > > WHAT THE HELL|?| Are you saying that building was wired that day? Or > > well in advance? 'Splain, please. > > > Does your fellow Bonesman George Walker Bush appreciate you letting > > the cat out of the bag on this? Is that your cell phone I hear > > ringing? > > > Why is your wife squirming like that? Stop it, Theresa! Stop it!" > > So what your saying is that the democrates are behind 9/11? So they tried > to frame Bush? Whats new? Doesn't this then mean that the democrates and > alqaeda are working together? I always that pelosie looked like she had a > little arabic in her(probably in more ways than one). No, it was all staged by Giuliani in preparation for his run for the presidency. Much earlier he was seen on a grassy knoll. :) BTW: Seriously, if you ask a fireman what to "pull" means you get a very different meaning than the one being suggested by the OP. There is also a lot of images from places like the BBC of people green screened onto older pictures of New York etc. From jaford at watford53.freeserve.co.uk Sun Apr 15 16:17:15 2007 From: jaford at watford53.freeserve.co.uk (Jim Ford) Date: Sun, 15 Apr 2007 20:17:15 GMT Subject: is laziness a programer's virtue? In-Reply-To: <1176654319.273907.167280@q75g2000hsh.googlegroups.com> References: <1176654319.273907.167280@q75g2000hsh.googlegroups.com> Message-ID: Xah Lee wrote: > Laziness, Perl, and Larry Wall > > Xah Lee, 20021124 > > In the unix community there's quite a large confusion and wishful > thinking about the word laziness. In this post, i'd like to make some > clarifications. Years ago I used to work with someone who used to say 'I'm a lazy person - I like to do things the easy way!'. I guess this is what Larry Wall means. Jim Ford From fuzzyman at gmail.com Fri Apr 20 18:18:09 2007 From: fuzzyman at gmail.com (Fuzzyman) Date: 20 Apr 2007 15:18:09 -0700 Subject: When are immutable tuples *essential*? Why can't you just use lists *everywhere* instead? In-Reply-To: <58sacjF2i0sviU1@mid.individual.net> References: <1177088796.622928.224890@d57g2000hsg.googlegroups.com> <58sacjF2i0sviU1@mid.individual.net> Message-ID: <1177107489.809244.124400@n76g2000hsh.googlegroups.com> On Apr 20, 6:09 pm, Bjoern Schliessmann wrote: > seber... at spawar.navy.mil wrote: > > Please help me think of an example where immutable tuples are > > essential. > > When used as dictionary keys (also everywhere else where they must > be in a constant order). > > Yes, this *is* used in practice. > Yup - using tuples as dictionary keys is very common. Fuzzyman http://www.voidspace.org.uk/python/index.shtml > Regards, > > Bj?rn > > -- > BOFH excuse #14: > > sounds like a Windows problem, try calling Microsoft support From a.schmolck at gmail.com Wed Apr 11 11:39:11 2007 From: a.schmolck at gmail.com (Alexander Schmolck) Date: 11 Apr 2007 16:39:11 +0100 Subject: [ANN] mlabwrap-1.0final Message-ID: I'm pleased to finally announce mlabwrap-1.0: Project website --------------- Description ----------- Mlabwrap-1.0 is a high-level python to matlab(tm) bridge that makes calling matlab functions from python almost as convenient as using a normal python library. It is available under a very liberal license (BSD/MIT) and should work on all major platforms and (non-ancient) python and matlab versions and either numpy or Numeric (Numeric support will be dropped in the future). Examples -------- Creating a simple line plot: >>> from mlabwrap import mlab; mlab.plot([1,2,3],'-o') Creating a surface plot: >>> from mlabwrap import mlab; from numpy import * >>> xx = arange(-2*pi, 2*pi, 0.2) >>> mlab.surf(subtract.outer(sin(xx),cos(xx))) Creating a neural network and training it on the xor problem (requires netlab) >>> net = mlab.mlp(2,3,1,'logistic') >>> net = mlab.mlptrain(net, [[1,1], [0,0], [1,0], [0,1]], [0,0,1,1], 1000) What the future holds --------------------- Please note that mlabwrap-1.0 will be the last non-bugfix release with Numeric support. Future versions of mlabwrap will require numpy be a part of scipy's scikits infrastructure (so the package name will be ``scikits.mlabwrap``) and use setuptools rather than distutils so that it should be possible to automatically download and install via EasyInstall. The next major version of mlabwrap should also bring more powerful proxying and marshalling facilities, but the default conversion behavior might be changed to reflect the fact that matlab is becoming increasingly less ``double`` (-matrix) centric; although wrappers for old-style behavior will be provided if backwards-incompatible interface changes are introduced, for upwards compatibility it is recommended to explicitly pass in float64 arrays rather than e.g. lists of ints if the desired input type that matlab should see is a double array (i.e. use ``mlab.sin(array([1., 2., 3.])`` rather than ``mlab.sin([1,2,3])`` for production code in order to be on the safe side)). Please have a look at if you're interested in the ongoing development of mlabwrap and planned features. Feedback and support -------------------- The preferred formum for users to request help and offer feedback and keep informed about new releases is mlabwrap-user: the list is low-volume and subscription is recommended. Discussion of mlabwrap development takes place on the scipy-dev (please mention mlabwrap in the subject line): cheers, Alexander Schmolck, mlabwrap author and maintainer From carl at personnelware.com Sun Apr 29 15:22:16 2007 From: carl at personnelware.com (Carl K) Date: Sun, 29 Apr 2007 14:22:16 -0500 Subject: mysql "rows affected" In-Reply-To: References: <1bCdnU80YoYXpazbnZ2dnUVZ_gKdnZ2d@comcast.com> Message-ID: <0OKdnd3B2JL4banbnZ2dnUVZ_ubinZ2d@comcast.com> Dennis Lee Bieber wrote: > On Thu, 26 Apr 2007 18:18:57 -0700, John Nagle > declaimed the following in comp.lang.python: > >> Carl K wrote: >>> using MySQLdb, I do cursor.execute("update...") >>> >>> How can I tell how many rows were affected ? >>> >>> Carl K >> cursor = db.cursor() # get cursor >> cursor.execute(sqlstatement, argtuple) # do command > > According to the documentation, it may be possible to get the result > with > > rws = cursor.execute(...) > > > -=-=-=-=-=-=- >>>> help(cr.execute) > Help on method execute in module MySQLdb.cursors: > > execute(self, query, args=None) method of MySQLdb.cursors.Cursor > instance > Execute a query. > > query -- string, query to execute on server > args -- optional sequence or mapping, parameters to use with query. > > Note: If args is a sequence, then %s must be used as the > parameter placeholder in the query. If a mapping is used, > %(key)s must be used as the placeholder. > > Returns long integer rows affected, if any > > -=-=-=-=-=-=- hey look at that. Thanks. Carl K From robert.kern at gmail.com Tue Apr 3 13:22:50 2007 From: robert.kern at gmail.com (Robert Kern) Date: Tue, 03 Apr 2007 12:22:50 -0500 Subject: Numeric compiling problem under QNX 4.25 In-Reply-To: <1175578324.426293.21970@y80g2000hsf.googlegroups.com> References: <1175578324.426293.21970@y80g2000hsf.googlegroups.com> Message-ID: ZMY wrote: > Dear all, > > I am a real newbie for both python and QNX, but I am still trying to > compile Numeric-24.2 under QNX4.25 with python 2.2. I got following > error message: > > > $ sudo python setup.py install > Password: > running install > ... > building '_numpy' extension > skipping Src/_numpymodule.c (build/temp.qnx-O-PCI-2.2/_numpymodule.o > up-to-date) > skipping Src/arrayobject.c (build/temp.qnx-O-PCI-2.2/arrayobject.o up- > to-date) > skipping Src/ufuncobject.c (build/temp.qnx-O-PCI-2.2/ufuncobject.o up- > to-date) > ld build/temp.qnx-O-PCI-2.2/_numpymodule.o build/temp.qnx-O-PCI-2.2/ > arrayobject.o build/temp.qnx-O-PCI-2.2/ufuncobject.o -o build/lib.qnx- > O-PCI-2.2/_numpy.so > unable to execute ld: No such file or directory > error: command 'ld' failed with exit status 1 It looks like it can't find the command ld. Can you compile any other extension modules? -- 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 dotancohen at gmail.com Sat Apr 14 15:04:18 2007 From: dotancohen at gmail.com (Dotan Cohen) Date: Sat, 14 Apr 2007 22:04:18 +0300 Subject: Python editor/IDE on Linux? In-Reply-To: <1176575715.649316.130430@n76g2000hsh.googlegroups.com> References: <1176575715.649316.130430@n76g2000hsh.googlegroups.com> Message-ID: <880dece00704141204v36fabf5i995049f6555e8911@mail.gmail.com> On 14 Apr 2007 11:35:15 -0700, mystilleef wrote: > On Apr 13, 6:20 pm, "Jack" wrote: > > I wonder what everybody uses for Python editor/IDE on Linux? > > I use PyScripter on Windows, which is very good. Not sure if > > there's something handy like that on Linux. I need to do some > > development work on Linux and the distro I am using is Xubuntu. > > Try Scribes: > > Flash Demo: http://scribes.sf.net/demo.htm > > It's writing in Python and can extended with Python plugins. > Has anyone any experience with Python in Kate or Kdevelop? I program PHP and HTML in Kate and C in Kdevelop. Dotan Cohen http://what-is-what.com/what_is/website.html http://dotancohen.com/photoalbum/images/index.htm From samfeltus at gmail.com Tue Apr 3 22:54:12 2007 From: samfeltus at gmail.com (SamFeltus) Date: 3 Apr 2007 19:54:12 -0700 Subject: Requirements For A Visualization Software System For 2010 In-Reply-To: <1175628186.459945.290750@d57g2000hsg.googlegroups.com> References: <1175628186.459945.290750@d57g2000hsg.googlegroups.com> Message-ID: <1175655252.747590.179020@y80g2000hsf.googlegroups.com> It would be interesting to see a computer language include such functionality from the ground up. If these were core features of a language, you'd have something wicked cool, and not just a new language retreading the same features and functionality. From pavlovevidence at gmail.com Wed Apr 4 14:28:42 2007 From: pavlovevidence at gmail.com (Carl Banks) Date: 4 Apr 2007 11:28:42 -0700 Subject: BeautifulSoup vs. real-world HTML comments In-Reply-To: References: Message-ID: <1175711322.448629.20300@y80g2000hsf.googlegroups.com> On Apr 4, 2:08 pm, John Nagle wrote: > The syntax that browsers understand as HTML comments is much less > restrictive than what BeautifulSoup understands. I keep running into > sites with formally incorrect HTML comments which are parsed happily > by browsers. Here's yet another example, this one from > "http://www.webdirectory.com". The page starts like this: > > > > > > > Environment Web Directory > > Those are, of course, invalid HTML comments. But Firefox, IE, etc. handle them > without problems. > > BeautifulSoup can't parse this page usefully at all. > It treats the entire page as a text chunk. It's actually > HTMLParser that parses comments, so this is really an HTMLParser > level problem. Google for a program called "tidy". Install it, and run it as a filter on any HTML you download. "tidy" has invested in it quite a bit of work understanding common bad HTML and how browsers deal with it. It would be pointless to duplicate that work in the Python standard library; let HTMLParser be small and tight, and outsource the handling of floozy input to a dedicated program. Carl Banks From b83503104 at yahoo.com Tue Apr 3 14:20:33 2007 From: b83503104 at yahoo.com (bahoo) Date: 3 Apr 2007 11:20:33 -0700 Subject: how to remove multiple occurrences of a string within a list? Message-ID: <1175624433.206953.214290@n59g2000hsh.googlegroups.com> Hi, I have a list like ['0024', 'haha', '0024'] and as output I want ['haha'] If I myList.remove('0024') then only the first instance of '0024' is removed. It seems like regular expressions is the rescue, but I couldn't find the right tool. Thanks! bahoo From henriklied at gmail.com Thu Apr 5 18:25:35 2007 From: henriklied at gmail.com (Henrik Lied) Date: 5 Apr 2007 15:25:35 -0700 Subject: Problems with os.spawnv In-Reply-To: References: <1175807996.524018.146070@n76g2000hsh.googlegroups.com> <1175809984.762401.11020@n59g2000hsh.googlegroups.com> Message-ID: <1175811935.298942.150620@d57g2000hsg.googlegroups.com> On Apr 6, 12:09 am, "Gabriel Genellina" wrote: > En Thu, 05 Apr 2007 18:53:04 -0300, Henrik Lied > escribi?: > > > On Apr 5, 11:39 pm, "Gabriel Genellina" > > wrote: > >> v = os.spawnl(os.P_NOWAIT, "mencoder", "mencoder", > >> "/Users/henriklied/test.mov", "-ofps", "25", "-o", "...") > > > Thanks for your reply - but I'm afraid to tell you that spawnl didn't > > do the trick either. > > Here's the full command I used:http://dpaste.com/hold/7982/ > > What means "didnt do the trick"? Do you get an exception? what's the > returned value? > Does the command work OK from the console? > Try from the python interpreter, using P_WAIT, and inspect the returned > value. That's what I've done. P_WAIT returned a the PID 127 - but there's still no sign of the FLV-file, I'm afraid. > > > I'd still love to get a working example of my problem using the > > Subprocess module. :-) > > The same thing: > p = subprocess.Popen(["mencoder", "/users/...", "-ofps", ...]) > That example looked great at first, but on a closer look it didn't quite end up to be what I wanted. In a real environment the user still had to wait for the command to finish. > -- > Gabriel Genellina I'm not sure what to do. I'm thinking of simply creating a crontab which checks the database every five minutes or so, and converts the videos that aren't converted. But if anyone has a good and easy solution in Python, I'd rather have that. I dare to think that people here will understand that. From goodTweetieBird at hotmail.com Tue Apr 3 10:55:31 2007 From: goodTweetieBird at hotmail.com (gtb) Date: 3 Apr 2007 07:55:31 -0700 Subject: Finding and copying files with python. In-Reply-To: <1175611369.046859.194730@p77g2000hsh.googlegroups.com> References: <1175606497.896681.119490@l77g2000hsb.googlegroups.com> <1175607107.690245.145130@l77g2000hsb.googlegroups.com> <1175608048.094777.183660@l77g2000hsb.googlegroups.com> <1175611369.046859.194730@p77g2000hsh.googlegroups.com> Message-ID: <1175612131.540414.88550@e65g2000hsc.googlegroups.com> On Apr 3, 9:42 am, "Daniele Varrazzo" wrote: > > > > I wish to copy the highest version number of a file from directory \ > > > > \ > > > > \fileserver\D:\scripts to C:\scripts where the file names are of the > > > > form > > > > > filename_MM.NN.SS.zip, where MM, NN, and SS can be one to three > > > > digits. > > > > > Example directory: > > > > other.zip > > > > dx_ver_1.1.63.zip > > > > dx_ver_1.2.01.zip > > > > dx_ver_1.12.7.zip > > > > temp.txt > > > > > Does python have string matching routines that would find the bottom > > > > listed zip file and/or file copying routines? > > > You could just use string slicing to cut off the first 7 characters > > > and have the numbers available to compare. There's also the os.stat > > > module to find the last modified date of the file. You might be able > > > to use the glob module to grab a list of the files and then sort the > > > list too. > > Comparing the version strings is not enough: you have to convert the > parts into integers, because else: > > >>> "dx_ver_1.12.7.zip" < "dx_ver_1.2.1.zip" > > True > > > Thanks for posting folks. I didn't make my question clear. Before I > > sort the files I need to ensure that I am only sorting the files that > > match the profile of "filename_MM.NN.SS.zip", where MM, NN, and SS can > > be one to three > > digits. > > Match the file names against the pattern "dx_ver_(\d+).(\d+).(\d > +).zip". You may also use the glob function, but then you will have to > parse the version number from the file name anyway: with the regexp > you can use match.groups() to get the version number. > > You can do: > > import re > ver_re = re.compile(r"dx_ver_(\d+).(\d+).(\d+).zip") > > def getVer(fn): > """Return a *comparable* file version, None for bad file names""" > m = ver_re.match(fn) > return m and map(int, m.groups()) > > print sorted(os.listdir('/path/to/wherever'), key=getVer)[-1] > > --Daniele > > P.S. I guess in Obfuscated Python one would write something like: > > >>> print sorted((pair for pair in ((re.match(r"dx_ver_(\d+).(\d+).(\d+).zip", fn), fn) for fn in os.listdir('/path/to/wherever')) if pair[0]), key=lambda _: map(int, _[0].groups()))[-1][1] > > dx_ver_1.12.7.zip Thanks all. Much to learn, but you have certainly helped me get started. jh From andy.rockford at gmail.com Fri Apr 27 04:23:37 2007 From: andy.rockford at gmail.com (Andy) Date: 27 Apr 2007 01:23:37 -0700 Subject: List objects are un-hashable In-Reply-To: <1177661758.725027.101430@r30g2000prh.googlegroups.com> References: <1177660237.470851.170200@s33g2000prh.googlegroups.com> <1177661758.725027.101430@r30g2000prh.googlegroups.com> Message-ID: <1177662217.626642.60610@r3g2000prh.googlegroups.com> > What you want is something like: > > for line in inp: > lines +=1 > # a list of words > tempwords = line.split() > for k in tempwords: > if keyword.iskeyword(k): > print tempwords I think it should be: if keyword.iskeyword(k): print k From tinaweb at bestemselv.com Sun Apr 15 02:56:53 2007 From: tinaweb at bestemselv.com (Tina I) Date: Sun, 15 Apr 2007 08:56:53 +0200 Subject: Append data to a list within a dict In-Reply-To: <1hwl1cg.ioy0ak5hp10zN%aleax@mac.com> References: <7xejmnbj0x.fsf@ruckus.brouhaha.com> <1hwl1cg.ioy0ak5hp10zN%aleax@mac.com> Message-ID: Alex Martelli wrote: > Tina I wrote: > ... >> He he... at the age of 40 I'm well beyond school work ;) > > Why would that be? My wife's over 40, yet she's a student (currently at > Stanford -- they were overjoyed to admit her, with lot of life > experience as well as previous studies, apparently). She's not taking > elementary courses on Python (having co-written a book on Python, > tech-reviewed a few, and having been the first woman coopted as a member > of the PSF:-), but she _has_ been taken equivalent ones on Java and C++ > (languages she didn't previously know), as well as calculus, > neurophysiology, and other strange things that are part of the "Symbolic > Systems" studies. > > Down with ageism!-) > > > Alex > It's not really ageism, just how I feel *my self* about going back to school. I'm not done learning though, it's just that I can give my self the luxury of learning whatever I want, just what I want at the pace that I want. And since I happen to like computers that's mostly what I concentrate about. Right now I'm hooked on Python, but also messing about with PHP and Javascript. Tried some Java but didn't like it... Threw out Windows a couple of years ago and have spent quite some time learning the ins and outs of Linux. So even if I probably will never go back to school I'm looking forward to many many years learning new and exciting things :) Tina (Sorry for the way OT post. I just couldn't stop my own ramble ;) From skip at pobox.com Sat Apr 14 14:18:21 2007 From: skip at pobox.com (skip at pobox.com) Date: Sat, 14 Apr 2007 13:18:21 -0500 Subject: Portably generating infinity and NaN In-Reply-To: References: <462008d1$0$11763$9b622d9e@news.freenet.de> Message-ID: <17953.6893.141873.987654@montanaro.dyndns.org> Michael> If you're going to change CPython to do this, I think adopting Michael> PEP 754, and using the fpconst module would be better than Michael> changing how float() works when called on string literals. But PEP 754 will only work for architectures supporting IEEE 754. I realize that's the vast majority of systems, but aren't there still a few Crays and VMS machines out there? (Do those architectures support NaN and Inf?) Skip From bbxx789_05ss at yahoo.com Thu Apr 12 01:08:14 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: 11 Apr 2007 22:08:14 -0700 Subject: python regular expression help In-Reply-To: References: <138221.90891.qm@web58906.mail.re1.yahoo.com> Message-ID: <1176354494.297420.278050@b75g2000hsg.googlegroups.com> On Apr 11, 10:50 pm, "Gabriel Genellina" wrote: > En Wed, 11 Apr 2007 23:14:01 -0300, Qilong Ren > escribi?: > > > Thanks for reply. That actually is not what I want. Strings I am dealing > > with may look like this: > > s = 'a = 4.5 b = 'h' 'd' c = 4.5 3.5' > > What I want is > > a = 4.5 > > b = 'h' 'd' > > c = 4.5 3.5 I suppose next you'll post your strings can also look like this: "#!@#$!@%WESDFGASDF at W#%$@%====12341234qeerasdfdae" and you want "A = 3" From jstroud at mbi.ucla.edu Fri Apr 6 23:48:00 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Fri, 06 Apr 2007 20:48:00 -0700 Subject: block scope? In-Reply-To: References: Message-ID: Neal Becker wrote: > One thing I sometimes miss, which is common in some other languages (c++), > is idea of block scope. It would be useful to have variables that did not > outlive their block, primarily to avoid name clashes. This also leads to > more readable code. I wonder if this has been discussed? > Probably, with good code, block scope would be overkill, except that I would welcome list comprehensions to have a new scope: py> i ------------------------------------------------------------ Traceback (most recent call last): File "", line 1, in : name 'i' is not defined py> [i for i in xrange(4)] [0, 1, 2, 3] py> i # hoping for NameError 3 From gagsl-py2 at yahoo.com.ar Tue Apr 10 21:45:13 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 10 Apr 2007 22:45:13 -0300 Subject: Universal Feed Parser issue References: <1176227922.910993.36910@y80g2000hsf.googlegroups.com> Message-ID: En Tue, 10 Apr 2007 14:58:42 -0300, i3dmaster escribi?: > I have a sample Atom feed like this: > > > ... > > > > > After parsed by feedparser, the timezone element does not get the > attribute "America/Mountain". Same thing on status element. This does > not sound an expected result. I am wondering if it should be > considered a bug... Usually it's a good idea to read the documentation... http://www.feedparser.org/docs/namespace-handling.html -- Gabriel Genellina From adamgarstang at googlemail.com Sat Apr 7 16:57:53 2007 From: adamgarstang at googlemail.com (Adam) Date: 7 Apr 2007 13:57:53 -0700 Subject: How to tell when a file is opened In-Reply-To: <1175972570.023449.129080@q75g2000hsh.googlegroups.com> References: <1175960486.759715.317140@y80g2000hsf.googlegroups.com> <1175970161.126550.257090@n59g2000hsh.googlegroups.com> <1175972570.023449.129080@q75g2000hsh.googlegroups.com> Message-ID: <1175979472.961925.132250@q75g2000hsh.googlegroups.com> On Apr 7, 8:02 pm, "Gabriel Genellina" wrote: > Adam wrote: > > On Apr 7, 5:09 pm, Tim Golden wrote: > > > Adam wrote: > > > > I want to know if it possible to tell when a file is opened. However I > > > > don't want it to be the last access time. I want to know how many > > > > times a file opened so I can generate statistics of file usage. > > You may look into some tools like FileMon and Process Monitor fromwww.sysinternals.com;I think that doing the processing in Python > would slow down your system a lot (or not, just try!) > > -- > Gabriel Genellina You see I was mainly hoping that python would not be doing the processing per se. More that, as Tim put it, it would hook itself into whatever monitors the shares to see when files are open and dump that info somewhere (like a database or xml) then at a set time (at night for example) Python would take that information collect it into historical logs and update a web page with recent stats. Obviously I have to check that the most vital part is even possible or at least within my limit programming knowledge (which is why I ask here.) Adam From gagsl-py2 at yahoo.com.ar Sat Apr 7 15:02:50 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: 7 Apr 2007 12:02:50 -0700 Subject: How to tell when a file is opened In-Reply-To: <1175970161.126550.257090@n59g2000hsh.googlegroups.com> References: <1175960486.759715.317140@y80g2000hsf.googlegroups.com> <1175970161.126550.257090@n59g2000hsh.googlegroups.com> Message-ID: <1175972570.023449.129080@q75g2000hsh.googlegroups.com> Adam wrote: > On Apr 7, 5:09 pm, Tim Golden wrote: > > Adam wrote: > > > I want to know if it possible to tell when a file is opened. However I > > > don't want it to be the last access time. I want to know how many > > > times a file opened so I can generate statistics of file usage. You may look into some tools like FileMon and Process Monitor from www.sysinternals.com; I think that doing the processing in Python would slow down your system a lot (or not, just try!) -- Gabriel Genellina From ptmcg at austin.rr.com Wed Apr 18 16:41:33 2007 From: ptmcg at austin.rr.com (Paul McGuire) Date: 18 Apr 2007 13:41:33 -0700 Subject: Martel Package from Biopython In-Reply-To: <1176917299.700081.138420@n76g2000hsh.googlegroups.com> References: <1176917299.700081.138420@n76g2000hsh.googlegroups.com> Message-ID: <1176928893.349982.261610@b58g2000hsg.googlegroups.com> On Apr 18, 12:28 pm, elventear wrote: > Hello, > > I know this is not the best place to ask this but I haven't had luck > in the Biopython forums with my questions, so I'll just try here. > > I want to use the Martel package to do some parsing. I've found it to > be very powerful and convenient. Yet the documentation avaialble is > less than complete. I have a few questions on how to use it, if you > know the answers to my questions: > > - How does Bio.Std.record affect the parsing of a Martel expression. > - How does Bio.RecordReader work? How does it interact with > Martel.HeaderFooter? > - Many of the matching objects (ie. Martel.Digits) have an attrs > argument. How does it work? > > Thanks! Andrew Dalke says in his blog that he finds pyparsing to be similar in concept to Martel. I looked over the Martel presentations at his web site, and I can see some similarities, but pyparsing has some of its own peculiarities, too. So if Martel remains a mystery, you could give pyparsing a shot. Pyparsing tries to make parser-writing a less painful process, so it incorporates some conventions - most notably, pyparsing assumes that whitespace is significant for the purposes of word boundaries and such, but you grammar does not need to explicitly spell out where whitespace would go. Or try one of these other parsing packages on Ned Batchelder's web page: http://nedbatchelder.com/text/python-parsers.html. -- Paul From cam.ac.uk at mh391.invalid Fri Apr 20 11:22:56 2007 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Fri, 20 Apr 2007 16:22:56 +0100 Subject: setDaemon problem. In-Reply-To: References: <1177057029.688992.160020@o5g2000hsb.googlegroups.com> <58rk68F2hof6mU1@mid.uni-berlin.de> <1177076608.110673.305970@d57g2000hsg.googlegroups.com> Message-ID: Richard Brodie wrote: > "Michael Hoffman" wrote in message > news:f0aij2$j59$1 at gemini.csx.cam.ac.uk... > >>> Neither is particularly intuitive; it just depends whether you are more >>> familiar with the Posix terminology or the Java one. I personally prefer >>> detached but there is little chance of a name change now. >> Why not? That's what Python 3.0 is for. > > I think you need a better reason than: "it's mildly confusing to people, if > they don't read the manual" for an API change; but that's just my opinion. One of the goals of Python 3.0 is to clean up previous warts in the language, and there will be a number of API changes. And one of the good things about Python in general is that things frequently can be understood without reading a manual. I think anything to aid this should be encouraged. -- Michael Hoffman From S.Mientki-nospam at mailbox.kun.nl Sat Apr 14 05:26:07 2007 From: S.Mientki-nospam at mailbox.kun.nl (Stef Mientki) Date: Sat, 14 Apr 2007 11:26:07 +0200 Subject: Double backslash in filepaths ? Message-ID: <700ec$46209de2$d443bb3a$21603@news.speedlinq.nl> It looks like sometimes a single backslash is replaced by a double backslash, but sometimes it's not ??? See the error message below, the first backslash is somewhere (not explicitly in my code) replaced, but the second is not ??? Is it in general better to use double backslash in filepaths ? thanks, Stef Mientki >>> Write_Signal_File_Ext (IOO, fSamp, 'D:\data_to_test\test_global.pd') Traceback (most recent call last): File "", line 21, in ? File "D:\data_to_test\Signal_WorkBench.py", line 118, in Write_Signal_File_Ext DataFile.Write_Data (Data) File "D:\data_to_test\Signal_WorkBench.py", line 95, in Write_Data self.Write_Header(Nchan) File "D:\data_to_test\Signal_WorkBench.py", line 83, in Write_Header self.datafile = open(self.filename,'wb') IOError: [Errno 2] No such file or directory: 'D:\\data_to_test\test_global.pd' From bbxx789_05ss at yahoo.com Sun Apr 22 10:02:00 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: 22 Apr 2007 07:02:00 -0700 Subject: serializable object references In-Reply-To: <1242622.P0zHLAfcMH@beaureve.gmx.net> References: <1242622.P0zHLAfcMH@beaureve.gmx.net> Message-ID: <1177250520.161254.308340@e65g2000hsc.googlegroups.com> On Apr 22, 5:07 am, Martin Drautzburg wrote: > > <__main__.Foo instance at 0xb7cfb6ac> > > But how can I look up the real object, > when I only have this string? > You can't because that identifies the instance with an address, and pointers are not part of the python language. From Stephane.Muller at uhp-nancy.fr Tue Apr 3 11:07:05 2007 From: Stephane.Muller at uhp-nancy.fr (=?ISO-8859-1?Q?St=E9phane_Muller?=) Date: Tue, 03 Apr 2007 17:07:05 +0200 Subject: XML DTD analysis, diffing ... In-Reply-To: <1175603926.371027.69390@e65g2000hsc.googlegroups.com> References: <1175603926.371027.69390@e65g2000hsc.googlegroups.com> Message-ID: olive a ?crit : > Hi, > > I have a bunch of similar DTDs written by different coders. > > I would like to normalize, sort elements and attributes by name and > compare those files. > > Do you know any XML DTD parser/normalizer written in Python ? Yes, you can try http://c.python.free.fr/dtdnormalize.zip Parse a sample XML file with the document type declaration. There are XHTML, SVG and MML samples in the zip file. The DTDParser is based on the standard xml.parsers.expat module. Stephane. From martinskou at gmail.com Mon Apr 9 06:05:41 2007 From: martinskou at gmail.com (martinskou at gmail.com) Date: 9 Apr 2007 03:05:41 -0700 Subject: Is there a simple function to generate a list like ['a', 'b', 'c', ... 'z']? In-Reply-To: <1176107364.000517.68580@q75g2000hsh.googlegroups.com> References: <1176107364.000517.68580@q75g2000hsh.googlegroups.com> Message-ID: <1176113141.061350.20230@d57g2000hsg.googlegroups.com> map(chr,range(65,91)) /Martin From gagsl-py2 at yahoo.com.ar Thu Apr 5 17:39:28 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 05 Apr 2007 18:39:28 -0300 Subject: Problems with os.spawnv References: <1175807996.524018.146070@n76g2000hsh.googlegroups.com> Message-ID: En Thu, 05 Apr 2007 18:19:56 -0300, Henrik Lied escribi?: > So, I thought to myself that spawnv would be a good fit for this. The > problem is that it doesn't fire of the command. > > Here's my test script: http://dpaste.com/hold/7981/ > > Why won't this work? The while-loop is printed, but the os command > isn't executed. I've also tried to specify the whole path to mencoder > (/opt/local/bin/mencoder), but to no use. > You are using: v = os.spawnv(os.P_NOWAIT, "mencoder", "/Users/henriklied/test.mov -ofps 25 -o test.flv ...") Read the docs about the spawnv function: http://docs.python.org/lib/os-process.html#l2h-2749 In particular "...The "v" variants are good when the number of parameters is variable, with the arguments being passed in a list or tuple as the args parameter. In either case, the arguments to the child process must start with the name of the command being run." So, for spawnv, you should build a list with each argument as an item, being "mencoder" the first item. But in your case it's a lot easier to use spawnl: v = os.spawnl(os.P_NOWAIT, "mencoder", "mencoder", "/Users/henriklied/test.mov", "-ofps", "25", "-o", "...") -- Gabriel Genellina From irstas at gmail.com Mon Apr 2 15:52:31 2007 From: irstas at gmail.com (irstas at gmail.com) Date: 2 Apr 2007 12:52:31 -0700 Subject: How do you escape % when formatting a string? In-Reply-To: <1175543459.131630.96650@y80g2000hsf.googlegroups.com> References: <1175543459.131630.96650@y80g2000hsf.googlegroups.com> Message-ID: <1175543551.433867.223590@p15g2000hsd.googlegroups.com> On Apr 2, 10:50 pm, "erikcw" wrote: > Hi, > > I'm trying to format a string like so: > > string = "You have a 75% chance of success with %s, don't use %s" %(a, > b) > > This gives me: > TypeError: not enough arguments for format string > > I've tried 75\%, but that doesn't seem to help. What am I missing? > > Thanks! > Erik Use %%. >>> "%d%%" % 75 "75" From __peter__ at web.de Thu Apr 5 02:29:46 2007 From: __peter__ at web.de (Peter Otten) Date: Thu, 05 Apr 2007 08:29:46 +0200 Subject: Newbie Question about sequence multiplication References: <6cOdnVFCLMXxuYnbnZ2dnUVZ_rCsnZ2d@comcast.com> Message-ID: Scott wrote: > sentence = raw_input('Sentence: ') > > screen_width = 80 > text_width = len(sentence) > box_width = text_width + 6 > left_margin = (screen_width - box_width) // 2 > > print > print ' ' * left_margin + '+'???+?'-'?*?(box_width-2)??+??'+' > print ' ' * left_margin + '|??'?+?'?'?*?text_width?????+?'?|' > print ' ' * left_margin + '|??'?+?'?'???sentence???????+?'?|' > print ' ' * left_margin + '|??'?+?'?'?*?text_width?????+?'?|' > print ' ' * left_margin + '+'???+?'-'?*?(box_width-2)??+?'?|' > print > Now that, even though copied straight from "Beginning Python: From Novice > to Professional", returns : > There's an error in your program: invalid syntax The source code available at http://hetland.org/writing/beginning-python/ does work. Peter From veblen.lee at gmail.com Tue Apr 10 02:57:54 2007 From: veblen.lee at gmail.com (veblen.lee at gmail.com) Date: 9 Apr 2007 23:57:54 -0700 Subject: how to get char ASCII value. Message-ID: <1176188274.244322.250780@e65g2000hsc.googlegroups.com> for an example: 'a' value 0x61 '1' value 0x31. From robert.kern at gmail.com Sat Apr 28 00:40:45 2007 From: robert.kern at gmail.com (Robert Kern) Date: Fri, 27 Apr 2007 23:40:45 -0500 Subject: Numeric + wxPython, can't understand a bug... In-Reply-To: <1177721777.885907.18780@n59g2000hsh.googlegroups.com> References: <1177721777.885907.18780@n59g2000hsh.googlegroups.com> Message-ID: John Ladasky wrote: > Hi, folks, > > This probably has to do with Numeric and not with wxPython, but I > mention both for completeness. > > My OS: Win2000 > Python: 2.3.4 > wx: 2.6.1.0, Unicode version > Numeric: 23.8 > > > Here's the minimal code: > ================================================ > > height = 50 > width = 60 > L = [] > for y in range(height): > for x in range(width): > L.append(wx.Point(3+(2*x+y%2)*4, 3+7*y)) > print width, height, len(L) > pos = reshape(array(L), (height, width)) > > > > And here's the output: > ================================================ > > 60 50 3000 > > pos = reshape(array(L), (height, width)) > ValueError: total size of new array must be unchanged > > > > I've used exactly this approach to create 2D arrays from lists of > numbers, with no problems. Why does this fail with wx.Point objects? > Why is it telling me that I'm changing the array size, when the > dimensions indicate that I am NOT? Typecasting the array as > containing PyObject items does not change the error message... wx.Point objects are being recognized as sequences by array(). Consequently, reshape() thinks you are trying to reshape a (height*width, 2) array into a (height, width) array. You might want to create an empty (height, width) PyObject array first, and simply assign wx.Point values into it. That bypasses array()'s attempt at intuiting the structure of the list. -- 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 steve at REMOVEME.cybersource.com.au Mon Apr 2 04:59:18 2007 From: steve at REMOVEME.cybersource.com.au (Steven D'Aprano) Date: Mon, 02 Apr 2007 18:59:18 +1000 Subject: How can i compare a string which is non null and empty References: <1175469766.979636.65020@e65g2000hsc.googlegroups.com> Message-ID: On Mon, 02 Apr 2007 01:35:17 +0200, Georg Brandl wrote: > Plissken.s at gmail.com schrieb: >> Hi, >> >> how can i compare a string which is non null and empty? >> >> >> i look thru the string methods here, but cant find one which does it? >> >> http://docs.python.org/lib/string-methods.html#string-methods >> >> In java,I do this: >> if (str != null) && (!str.equals("")) .... >> >> how can i do that in python? > > Strings cannot be "null" in Python. > > If you want to check if a string is not empty, use "if str". I tried that, and I get something unexpected. >>> if str: ... print "What's going on here?" ... else: ... print "An empty string." ... What's going on here? > This also includes the case that "str" may not only be an empty > string, but also None. What about the case where str hasn't been shadowed and is a built-in type? >>> str -- Steven D'Aprano From bj_666 at gmx.net Sat Apr 14 09:48:06 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Sat, 14 Apr 2007 15:48:06 +0200 Subject: Python Feature Request: Allow changing base of member indices to 1 References: <1176546465.632410.52630@w1g2000hsg.googlegroups.com> <4620b47b$0$14410$9b622d9e@news.freenet.de> <1176557999.665663.299740@y80g2000hsf.googlegroups.com> Message-ID: In <1176557999.665663.299740 at y80g2000hsf.googlegroups.com>, jamadagni wrote: > On Apr 14, 4:01 pm, "Martin v. L?wis" wrote: > >> This one is not sane. It's not possible to change the indexing of >> objects on a per-module basis, as objects may cross module boundaries. > > I do not request for this to be changed per-module. Once I say > something like: > > from __future__ import indices_start_at_one > > afterwards I would expect *any* index from *any* module to start at 1. > To my understanding, Python is going to parse the content of modules > only as and when they are called. Modules are parsed when they are imported. And some modules are already imported before your module is imported because they are built-in or loaded to be able to import your module in the first place. And what about modules that are written in C? Ciao, Marc 'BlackJack' Rintsch From jstroud at mbi.ucla.edu Tue Apr 10 06:25:03 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Tue, 10 Apr 2007 10:25:03 GMT Subject: NLTK, Random Sentence Generators? In-Reply-To: <87slb8d3uj.fsf@localhost.localdomain> References: <87slb8d3uj.fsf@localhost.localdomain> Message-ID: <3CJSh.7608$u03.3757@newssvr21.news.prodigy.net> Passer By wrote: > Has any created or not of examples of random sentence generators using > n-gram models (or other models might be interesting). > > I know of one example from a course at MIT, but besides that nothing. > > Any help would be great. > > Best is to just cull text from your spam folder as these are often generated by similar means--but somehow I think you knew that. James From robert.kern at gmail.com Wed Apr 4 18:48:58 2007 From: robert.kern at gmail.com (Robert Kern) Date: Wed, 04 Apr 2007 17:48:58 -0500 Subject: Calling Fortran from Python In-Reply-To: <1175726427.114890.7990@y80g2000hsf.googlegroups.com> References: <1175640339.648190.207530@y66g2000hsf.googlegroups.com> <1175685841.847487.173440@w1g2000hsg.googlegroups.com> <1175718204.410453.29510@q75g2000hsh.googlegroups.com> <1175726427.114890.7990@y80g2000hsf.googlegroups.com> Message-ID: Mangabasi wrote: > Would Python 2.5 work with Visual Studio 6.6? No. -- 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 Jun.Jin.act at gmail.com Mon Apr 16 21:07:45 2007 From: Jun.Jin.act at gmail.com (Jun.Jin.act+group.python@gmail.com) Date: 16 Apr 2007 18:07:45 -0700 Subject: strange behaviour with keyword arguments and inheritance In-Reply-To: <1176771364.964642.209300@b75g2000hsg.googlegroups.com> References: <1176771364.964642.209300@b75g2000hsg.googlegroups.com> Message-ID: <1176772065.853443.50740@p77g2000hsh.googlegroups.com> On Apr 17, 8:56 am, "matthewperpick" wrote: > Check out this toy example that demonstrates some "strange" behaviour > with keyword arguments and inheritance. > > ================================= > > class Parent: > def __init__(self, ary = []): > self.ary = ary > > def append(self): > self.ary.append(1) > > class Child(Parent): > def __init__(self): > Parent.__init__(self) > self.append() > > def main(): > a = Child() > print a.ary > b = Child() > print b.ary > > main() > > ===================================== > > You would think the output of this program would be [1], [1]. But > strangely enough the output is [1,], [1,1]. I suppose that the > Parent.__class__ object is only created once and thus the keyword > argument always refers to the same thing, but I don't know. I have a > very rudimentary understading of python's guts, but I would still call > the behaviour unexpected. Or perhaps I should rtfm? > > Any thoughts would be much appreciated. Thanks. A slight modification of init-ing the parent can give you the expected output. class Child(Parent): def __init__(self): Parent.__init__(self, []) self.append() From jaywgraves at gmail.com Tue Apr 3 23:08:09 2007 From: jaywgraves at gmail.com (jay graves) Date: 3 Apr 2007 20:08:09 -0700 Subject: Where to find pywin32/win32all for Python 1.5.2? In-Reply-To: References: Message-ID: <1175656089.023440.286290@q75g2000hsh.googlegroups.com> On Apr 3, 7:52 pm, "Jack" wrote: > I searched around but could not find win32all source or binaries for earlier > versions of Python. Don't ask me why but I have to use Python 1.5.2 in this > project :) The sourceforget page only has latest versions. ActiveState does > not even have 1.5.2 for download. Is it still available somewhere? Thanks! I looked through my stash of old versions but I couldn't find it. I believe the filename you are looking for is 'win32all-128.exe' and Google has some references to it but the download links don't respond. Someone else has it stashed somewhere, hopefully having the filename will help. ... Jay Graves From subscriber123 at gmail.com Sun Apr 8 17:42:33 2007 From: subscriber123 at gmail.com (Subscriber123) Date: Sun, 8 Apr 2007 17:42:33 -0400 Subject: Python Web Servers and Page Retrievers Message-ID: <4c0048df0704081442w7a25ee2bqe2b13229dc37769e@mail.gmail.com> I wrote most of the following script, useful for retrieving pages from the web and serving web pages. Since it is so low level, it is much more customizable than simpleHTTPserver, cgiHTTPserver, urllib, or urllib2 for advanced users. For example, you can easily set your own headers when retrieving and serving pages, such as the User-Agent header which you cannot set in either urllib or urllib2. (sorry for not putting in any comments!) By the way, I just threw this together quickly, and haven't really had time to test retrieve() very much. Please let me know if it is buggy. I guess I should also write a dictToQuery() function. Oh well. import socket > > host,port='',80 > > sock=socket.socket(socket.AF_INET,socket.SOCK_STREAM) > sock.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1) > sock.bind((host,port)) > sock.listen(1) > > def serve(function=lambda *args:(args[2],200,'OK',{},'')): > """\ > def serve(function(method,filename,httpversion,headers,get,post)) > > Serves one request, calling function() with the above > parameters. function() must return (httpversion,code, > accepted,headers,content) in that order. If you don't > pass a function, then > function=lambda *args:(args[2],200,'OK',{},'') > """ > > csock,caddr=sock.accept() > rfile=csock.makefile('r',0) > wfile=csock.makefile('w',0) > > # Protocol exchange - read request > headers={} > line=rfile.readline().strip() > split1=line.find(' ') > method,remainder=line[:split1].strip(),line[split1+1:].strip() > split2=remainder.find(' ') > > filename,httpversion=remainder[:split2].strip(),remainder[split2+1:].strip() > while 1: > line=rfile.readline().strip() > print line > if line=='': > break > else: > split=line.find(':') > key,value=line[:split],line[split+1:] > headers[key.strip()]=value.strip() > > try: > post=rfile.read(int(headers['Content-Length'])) > except: > post='' > get=queryToDict(filename) > post=queryToDict(post) > loc=filename.find("?") > if loc>-1: > filename=filename[:loc] > print "get:",`get` > print "post:",`post` > > httpversion,code,accepted,headers,content=function(method,filename,httpversion,headers,get,post) > wfile.write("%s %s %s\n"%(httpversion,code,accepted)) > for header in list(headers): > wfile.write("%s: %s\n"%(header,headers[header])) > wfile.write("\n%s\n"%content) > wfile.close() > csock.close() > > def > retrieve(host,port=80,method='GET',filename='/',httpversion='HTTP/1.0',headers={},post=''): > """\ > Retrieves one web page from: > http://host:port/filename > with the headers > """ > sock.connect((host,port)) > rfile=sock.makefile('r',0) > wfile=sock.makefile('w',0) > wfile.write("%s %s %s\n"%(method,filename,httpversion)) > for header in list(headers): > wfile.write("%s: %s\n"%(header,headers[header])) > wfile.write('\n') > wfile.write("%s\n"%post) > > headers={} > line=rfile.readline().strip() > split1=line.find(' ') > httpversion,remainder=line[:split1].strip(),line[split1+1:].strip() > split2=remainder.find(' ') > code,accepted=remainder[:split2].strip(),remainder[split2+1:].strip() > while 1: > line=rfile.readline().strip() > if line=='': > break > else: > split=line.find(':') > key,value=line[:split],line[split+1:] > headers[key.strip()]=value.strip() > return httpversion,code,accepted,headers,rfile > > def queryToDict(query): > if '?' in query: > query=query[query.index('?')+1:] > kvpairs=query.split("&") > ret={} > for kvpair in kvpairs: > if '=' in kvpair: > loc=kvpair.index('=') > key,value=kvpair[:loc],kvpair[loc+1:] > ret[key]=value > return ret > > if __name__=='__main__': > i=0 > while True: > i+=1 > print "\nserve #%d:"%i > serve(lambda > *args:(args[2],200,'OK',{'Content-Type':'text/html'},'

Go Away!

')) > -------------- next part -------------- An HTML attachment was scrubbed... URL: From aleax at mac.com Sun Apr 8 11:56:13 2007 From: aleax at mac.com (Alex Martelli) Date: Sun, 8 Apr 2007 08:56:13 -0700 Subject: RFC: Assignment as expression (pre-PEP) References: <1175802680.021987.39220@p77g2000hsh.googlegroups.com> <1176035258.355141.221290@d57g2000hsg.googlegroups.com> Message-ID: <1hw8tyt.o3fd3h1fbcjfpN%aleax@mac.com> Dustan wrote: > >>> class Wrapper(object): > def __init__(self, obj): > self.obj = obj > def getit(self): > return self.obj > def setit(self, obj): > self.obj = obj > return obj Yeah, that's substantialy the same approach I posted as a Python Cookbook recipe almost six years ago, see . My specific use case for that recipe was when using Python to code a "reference algorithm" found in a book, so that deep restructuring was unwanted -- a similar but opposite case is using Python to explore prototype algorithms that would later be recoded e.g. in C (here, too, you don't really want to refactor the Python code to use dictionaries "properly", so assign-and-test is handy). Alex From cam.ac.uk at mh391.invalid Thu Apr 26 15:47:37 2007 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Thu, 26 Apr 2007 20:47:37 +0100 Subject: Generalized range In-Reply-To: <1177616211.476888.38360@r30g2000prh.googlegroups.com> References: <1177598743.352743.290730@t39g2000prd.googlegroups.com> <1177616211.476888.38360@r30g2000prh.googlegroups.com> Message-ID: tkpmep at hotmail.com wrote: > Thanks - you have covered a fair bit of gorund here - I will modify > myRange taking your suggestions into account. The one suggestion that > I'm going to have to think through is repeatedly incrementing res. > > I deliberately did not use this as repeated addition can cause > rounding errors to accumulate, making the loop run a little longer or > shorter than necessary. I thought I would be far less likely to run > into rounding issues with a multiplicative construct - hence my use of > epsilon, and my question about an appropriate value for it You are right about rounding issues--with a sufficiently small step, the way I have done it, it could become an infinite loop. But you can still do it with multiplication, without using an epsilon constant. How about something like this: index = 0 while res < maximum: yield minimum + (step * index) index += 1 -- Michael Hoffman From skip at pobox.com Tue Apr 3 13:44:24 2007 From: skip at pobox.com (skip at pobox.com) Date: Tue, 3 Apr 2007 12:44:24 -0500 Subject: How can I kill a running thread when exiting from __main__ In-Reply-To: References: <1175620919.478708.292150@p77g2000hsh.googlegroups.com> Message-ID: <17938.37496.3294.776762@montanaro.dyndns.org> Steve> The only way to do this is to have the thread regularly examine a Steve> "please quit" flag that is set from the main thread when Steve> termination is required. I thought the process would terminate when only daemon threads were left. Skip From aleax at mac.com Sun Apr 15 23:12:07 2007 From: aleax at mac.com (Alex Martelli) Date: Sun, 15 Apr 2007 20:12:07 -0700 Subject: Calling private base methods References: <1176374675.347453.89340@n76g2000hsh.googlegroups.com> <1176404325.211501.26610@w1g2000hsg.googlegroups.com> <1176435087.708516.66470@o5g2000hsb.googlegroups.com> <1176650850.211487.294690@y80g2000hsf.googlegroups.com> Message-ID: <1hwmmq4.n76p2d1k88mz5N%aleax@mac.com> Isaac Rodriguez wrote: > > The fact that I had > > to resort to this trick is a big indication of course that genuinely > > private members (as opposed to a 'keep off' naming convention) are a bad > > idea in general. > > The fact that you had to resort to this trick is a big indication that > the library you were using is bad designed; it has nothing to do with > private members being a bad idea. You were using a library which This is just like the airlines invariably concluding "human error" in just about every instance of an airplane crash or similar problem... Don Norman has some choice reflection about that issue from the point of view of a user-experience specialist, or, one could try Charles Perrow's classic "Normal Accidents" for more of a systems-level view from a sociologist's viewpoint. C++'s and Java's approaches are vitiated by an unspoken assumption that the library's designer is some kind of demigod, while the writer of code that uses the library is presumably still struggling with the challenge of opposable thumbs. In real life, the skills of the two people in question are likely to be much closer, and since designing libraries for use in all kinds of applications is a really hard task, it's likelier than the library designer will make an error in designing his or her library, rather than the application programmer in using that library. Purely-advisory encapsulation approaches, like Python's, even the odds. Actually, I'd argue that even double-leading-underscores are overkill more often than not (and single-leading-underscores the compromise that is generally prefereable). Alex From larry.bates at websafe.com Tue Apr 24 10:32:29 2007 From: larry.bates at websafe.com (Larry Bates) Date: Tue, 24 Apr 2007 09:32:29 -0500 Subject: getting scancodes In-Reply-To: <596hp5F2jf49qU1@mid.uni-berlin.de> References: <132r2hb2gltbf4d@corp.supernews.com> <596hp5F2jf49qU1@mid.uni-berlin.de> Message-ID: <-4udnQQIc_KaiLPbnZ2dneKdnZydnZ2d@comcast.com> Diez B. Roggisch wrote: > andmarti at gmail.com wrote: > >> On Tue, Apr 24, 2007 at 04:40:11AM -0000, Grant Edwards wrote: >>> On 2007-04-24, andmarti at gmail.com wrote: >>> >>>> Anyone knows if its possible to get scan codes ??? >>> What hardware? What OS? >> Debian Sarge/Etch, i386.. >> >> :P > > Greeeeeaaaat. Now we only need to guess what scan code reader you use.... > > > I believe he his referring to keyboard scancodes not a scanner. -Larry From duncan.booth at invalid.invalid Fri Apr 6 05:04:12 2007 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 6 Apr 2007 09:04:12 GMT Subject: RFC: Assignment as expression (pre-PEP) References: <1175802680.021987.39220@p77g2000hsh.googlegroups.com> <1175807326.466842.219820@p77g2000hsh.googlegroups.com> Message-ID: "Gabriel Genellina" wrote: > You have to build the handlers list, containing (regex, handler) items; > the "unknown" case might be a match-all expression at the end. > Well, after playing a bit with decorators I got this: That's a nice class, and more maintainable with the separate handler methods than a long function. Here's a completely untested variation. I hope the intent is clear: def handle_this(regex, handlers=handlers): # A decorator; associates the function to the regex # (Not intended to be used as a normal method! # not even a static method!) def register(function, regex=regex): handlers.append((function.__name__, regex)) return function return register ... insert handlers here ... def parse(self): regex = '|'.join(['(?P<%s>%s)' % pair for pair in self.handlers]) fields = str.split(self.name) for field in fields: match = regex.match(field) if match: handler = getattr(self, match.lastgroup, self.handle_unknown) handler(self, field, match) The handler functions themselves would have to be constrained to also use only named groups, but you gain by only having a single regex.match call on each field which could (if there are a lot of handlers) be significant. The calculation of regex could also of course be pulled out of parse to somewhere it only happens once for the class instead of once per instance. From anglozaxxon at gmail.com Mon Apr 9 09:07:00 2007 From: anglozaxxon at gmail.com (anglozaxxon) Date: 9 Apr 2007 06:07:00 -0700 Subject: "Plugin" architecture - how to do? In-Reply-To: <1175867963.727762.321170@l77g2000hsb.googlegroups.com> References: <1175785055.668181.308140@b75g2000hsg.googlegroups.com> <1175867963.727762.321170@l77g2000hsb.googlegroups.com> Message-ID: <1176124020.074341.144740@o5g2000hsb.googlegroups.com> On Apr 6, 9:59 am, "Nate Finch" wrote: > On Apr 5, 10:57 am, anglozax... at gmail.com wrote: > > > I'm making a program that consists of a main engine + plugins. Both > > are in Python. My question is, how do I go about importing arbitrary > > code and have it be able to use the engine's functions, classes, etc? > > For a truepluginarchitecture, you don't have the main engine calling > methods on theplugin. What you do is have an API on your engine with > methods theplugincan call and events it can hook into. The events > are how the engine communicates state to any plugins, without having > to know who they are or what they do. Your engine has a configuration > that tells it what plugins to load (which the plugins presumably > modified when they installed themselves) or otherwise has some > standard way that the engine can figure out what plugins need to be > loaded. > > Now granted, I don't specifically know how to do this via python.. > but, maybe what I've said will send you in the right direction. > > -Nate Alright that's a good suggestion. But the problem I'm having is that I don't know how to execute the plugin. I think I know how to do the architecture, just that there needs to be some crazy circular importing going on and I was wondering if there was a smarter way to attack the problem. Thanks, Nick From nobody at invalid.com Wed Apr 11 18:26:27 2007 From: nobody at invalid.com (Erik Johnson) Date: Wed, 11 Apr 2007 16:26:27 -0600 Subject: recec & Bastion ? Message-ID: <461d6064$1@nntp.zianet.com> The documentation for these two modules says that they were disabled in Python 2.3 due to security holes not easily fixable. I have not worked with them, but I can still import them under Python 2.4, so I'm not clear on whether the security problems were fixed in Python itself, or whether the modules remain deprecated (disabled?)? How are/were they actually disabled? Any place that documents what the problems are? Any alternatives? Thanks, -ej From michael at jedimindworks.com Thu Apr 12 19:50:17 2007 From: michael at jedimindworks.com (Michael Bentley) Date: Thu, 12 Apr 2007 18:50:17 -0500 Subject: VB6 To Python In-Reply-To: <2FAA57395C1F914DB27CAA4C376058F202434C96@S0-OTT-X2.nrn.nrcan.gc.ca> References: <2FAA57395C1F914DB27CAA4C376058F202434C96@S0-OTT-X2.nrn.nrcan.gc.ca> Message-ID: On Apr 12, 2007, at 1:11 PM, Sampson, David wrote: > Any experience or insight would be great. It has been my experience that when migrating to a dissimilar system, avoiding the rewrite is a mistake. And futile. hth, Michael -------------- next part -------------- An HTML attachment was scrubbed... URL: From chris at mccormick.cx Mon Apr 2 06:36:08 2007 From: chris at mccormick.cx (Chris McCormick) Date: Mon, 2 Apr 2007 18:36:08 +0800 Subject: Proxying object memory for synchronous update. Message-ID: <20070402103608.GA15515@mccormick.cx> Hi, I'm looking for a solution to a concurrency problem I have. I would like to have multiple objects with an Update() method. This Update method might access the contents of other objects. I would like there to be a proxy so that if object A's Update method is run before object B, and object A modifies a few of it's own variables, arrays, whatever, then when object B's Update is run and it tries to read object A's variables, arrays or whatever, it gets the old values as if A's Update method had not yet run. Once all of the update methods have been run on each object (in an array), the actual values of each object's variables, arrays, etc will be updated (possibly using another method). I'd like this to be automatic so that i can just add a Mixin to a class to give it this property, or a decorator or something. I am thinking this might be possible to do using __getattr__ and copy.copy() or pickle or something, but so far the solutions I have tried don't work very well. they especially don't work if in the situation where A has an array and it modifies an element of that array (how would I proxy that access?). Links, solutions, tutorials, whatever are very welcome. Please reply to me off (and on) list as I am not subscribed. Thank you very much for your help. Best regards, Chris. ------------------- chris at mccormick.cx http://mccormick.cx From steve at holdenweb.com Wed Apr 4 07:43:39 2007 From: steve at holdenweb.com (Steve Holden) Date: Wed, 04 Apr 2007 07:43:39 -0400 Subject: how to build a forum? In-Reply-To: <1175671911.485478.137090@q75g2000hsh.googlegroups.com> References: <1175671911.485478.137090@q75g2000hsh.googlegroups.com> Message-ID: kath wrote: > Hi everybody, > > I am planning to build a web portal, which is mainly a discussion > forum for our corporate environment. I want to implement it with > Python. Because this project is very new to me and I have no idea > about how to go about this. I searched in google for getting some tuts/ > guidelines about this but ended up in getting tuts for building > website. > > I would like to know some useful links to learn or some usefull > guidelines. > > I would appreciate your help, > Thanks in advance, Without wishing to dampen your enthusiasm, it seems like you are putting the cart before the horse here if the goal is "build a web portal". Could it be that the real goal is to learn Python, and the web portal is a vehicle for that? If not then you should use one of many already-extant web portals (you could surely find one written in Python if necessary) rather than developing one from scratch? Nuxeo comes to mind, but they've now switched from Python to Java ... 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 Apr 11 15:23:50 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 11 Apr 2007 16:23:50 -0300 Subject: Nested dictionaries trouble References: <1176317876.917874.58040@n59g2000hsh.googlegroups.com> Message-ID: En Wed, 11 Apr 2007 15:57:56 -0300, IamIan escribi?: > I'm writing a simple FTP log parser that sums file sizes as it runs. I > have a yearTotals dictionary with year keys and the monthTotals > dictionary as its values. The monthTotals dictionary has month keys > and file size values. The script works except the results are written > for all years, rather than just one year. I'm thinking there's an > error in the way I set my dictionaries up or reference them... > monthTotals = dict.fromkeys(months, 0) > # Nest monthTotals dictionary in yearTotals dictionary > yearTotals = {} > for year in years: > yearTotals.setdefault(year, monthTotals) All your years share the *same* monthTotals object. This is similar to this FAQ entry: You have to create a new dict for each year; replace the above code with: yearTotals = {} for year in years: yearTotals[year] = dict.fromkeys(months, 0) -- Gabriel Genellina From joshua at eeinternet.com Thu Apr 26 14:54:38 2007 From: joshua at eeinternet.com (Joshua J. Kugler) Date: Thu, 26 Apr 2007 10:54:38 -0800 Subject: Dedicated CPU core for Python? References: <1177607759.916727.180950@t39g2000prd.googlegroups.com> Message-ID: <4630e90c$0$16272$88260bb3@free.teranews.com> On Thursday 26 April 2007 09:16, Louise Hoffman wrote: > Dear readers, > > I was wondering, if Python in the foerseeable future will allocate one > CPU core just for the interpreter, so heavy Python operations does > slow down the OS? > > It seams to me like a perfect use for a CPU core =) Are you talking about CPU affinity (http://en.wikipedia.org/wiki/Processor_affinity) or an actual CPU that can directory execute Python byte code? If the former, CPython only uses one CPU core right now because it's threads are all internal, and do not spawn system threads (IIRC). If the latter, I don't think that would work very well because then, e.g., C extensions wouldn't work very well as they could not be executed by a Python Byte-code CPU. 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 torriem at chem.byu.edu Sun Apr 1 01:13:49 2007 From: torriem at chem.byu.edu (Michael Torrie) Date: Sat, 31 Mar 2007 23:13:49 -0600 Subject: Shed Skin Python-to-C++ Compiler 0.0.21, Help needed In-Reply-To: <7x8xdcrc13.fsf@ruckus.brouhaha.com> 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> <7x8xdcrc13.fsf@ruckus.brouhaha.com> Message-ID: <1175404429.25928.40.camel@enterprise> On Sat, 2007-03-31 at 20:47 -0700, Paul Rubin wrote: > Michael Torrie writes: > > The no-service contract version of the GPL is not the same as the > > standard GPLv2. > > I don't see how that can be--we're talking about a GCC-based compiler, > right? I found the real reason why the GPL'd GNAT compiler's produced executables are required to be GPL'd, and it has nothing to do with the license of the compiler: "What is the license of the GNAT GPL Edition? Everything (tools, runtime, libraries) in the GNAT GPL Edition is licensed under the General Public License (GPL). This ensures that executables generated by the GNAT GPL Edition are Free Software and that source code is made available with the executables, giving the freedom to recepients to run, study, modify, adapt, and redistribute sources and execuatbles under the terms of the GPL."[1] Note that it says the runtime *and* the libraries are GPL. Thus the linking clause in the GPL requires that programs that link against them (the executable in other words) must be GPL'd. Note that GLibC, while being GPL, has an exception clause in it, allowing linking to it by code of any license. Hence it's a red herring as far as the discussion and Shed Skin is concerned, although the licensing of any Shed Skin runtime libraries should be a concern to folks. [1] https://libre.adacore.com/ From clajo04 at mac.com Wed Apr 4 16:25:37 2007 From: clajo04 at mac.com (John Clark) Date: Wed, 4 Apr 2007 16:25:37 -0400 Subject: calling super() In-Reply-To: <461405D9.8040203@designaproduct.biz> References: <1175714555.413502.77390@o5g2000hsb.googlegroups.com> <461405D9.8040203@designaproduct.biz> Message-ID: <00f301c776f7$6b8a1680$fefea8c0@haengma> Please be aware that super() has it's own set of gotchas - it's not as clean as you would hope. For more info: http://fuhm.org/super-harmful/ (I'm not the author, I was referred to this article while struggling with wxPython and super()) -John Clark -----Original Message----- From: python-list-bounces+clajo04=mac.com at python.org [mailto:python-list-bounces+clajo04=mac.com at python.org] On Behalf Of Laszlo Nagy Sent: Wednesday, April 04, 2007 4:09 PM To: Jarek Zgoda; python-list at python.org; Finger.Octopus at gmail.com Subject: Re: calling super() Jarek Zgoda wrote: >> Hello, I have been trying to call the super constructor from my >> derived class but its not working as expected. See the code: >> >> class HTMLMain: >> def __init__(self): >> self.text = ""; >> print(self.text); >> def __del__(self): >> self.text = ""; >> print(self.text); >> >> class NewPage(HTMLMain): >> def __init__(self): >> print 'derive2 init' >> super(NewPage, self).__init__(); >> > > This should read: super(HTMLMain, self).__init__() > Definitely, this is not true. Well, it depends what the OP wanted to do here, but in 99.9% of the cases, you want to use class B(A): def method(self,*args): super(B,self).method(*args) Look at here: http://www.python.org/doc/2.3.5/lib/built-in-funcs.html#l2h-66 It tells that super(type,[self]) will """Return the superclass of type.""". So super(B) will return the superclass of B, that is A. The built-in function "super" is very useful when you have diamond-shaped inheritance and you only want each inherited method to be called only once, IN THE CORRECT ORDER. If you only have single inheritance class trees, then super(B,self).method(*args) is identical to A.method(self,*args). You only need to worry about method calling order when you use multiple inheritance. However, using super is much nicer than calling the method of the base class directly, and it is syntactically cleaner, since you will only have a single reference to the base class, in the class definition header. (E.g. you can change the base class by replacing one word in the source code...) Best, Laszlo -- http://mail.python.org/mailman/listinfo/python-list From oliphant.travis at ieee.org Tue Apr 3 19:17:48 2007 From: oliphant.travis at ieee.org (Travis E. Oliphant) Date: Tue, 03 Apr 2007 17:17:48 -0600 Subject: ANN: NumPy 1.0.2 Message-ID: We are pleased to announce the release of NumPy 1.0.2 NumPy is a Python extension that provides a general-purpose multi-dimensional array that can act as a container of arbitrary raw-data formats (including bools, integers, floats, complex, Python objects, string, unicode, and general C-structures). NumPy also provides fast array processing and mathematics on these multi-dimensional arrays. In addition, NumPy provides tools that allows these arrays to form the foundation for basic image and signal processing, linear algebra and Fourier transforms, and random number generation. NumPy also includes easy integration with ctypes and Fortran allowing seamless use of NumPy arrays with extensions written in either C/C++ or Fortran. The new support in NumPy for completely general (including nested structure) data-types allows it to be used as a container object for any number of applications where memory efficiency and speed are critical. For example, the ability to handle general data-formats means that NumPy could be used as an interface to general databases (see PyTables for one example). Get the latest version of NumPy by clicking on the Download link at http://numpy.scipy.org Enjoy!! -NumPy Developers From eugene.vandenbulke at gmail.com Fri Apr 27 02:23:27 2007 From: eugene.vandenbulke at gmail.com (EuGeNe Van den Bulke) Date: Fri, 27 Apr 2007 08:23:27 +0200 Subject: EuroPython vs PyconUK References: <4630D480.7050308@gmail.com> <1177648588.208173.117060@t38g2000prd.googlegroups.com> Message-ID: Michele Simionato wrote: > I don't see the problem. In my view EuroPython is the big event in > Europe. If you can > go to only one conference and you have the possibility to travel to > Vilnius, then go to EuroPython. > The national conferences are of interest primarily for people of that > national (of course, not > exclusively). Thanks, I didn't see it that way but that was ignorance on my behalf. I was WRONGLY under the impression that we were in front of a classical European pattern named "what WE can do collectively I can do better alone" - known use : European constitution :P (but I am digressing :D). > BTW, this year I will go both to PyCon It and EuroPython, last year I > went both to > PyUK and EuroPython. The more, the better ;) The more the merrier indeed in that respect! I learnt a lot from your "Using decorators" talk last year. Thanks. EuGeNe -- http://www.3kwa.com From martin at v.loewis.de Wed Apr 25 16:34:33 2007 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Wed, 25 Apr 2007 22:34:33 +0200 Subject: conditional print statement ? In-Reply-To: <2c923$462fb3e0$d443bb3a$18429@news.speedlinq.nl> References: <2c923$462fb3e0$d443bb3a$18429@news.speedlinq.nl> Message-ID: <462FBB59.4020405@v.loewis.de> Stef Mientki schrieb: > hello, > > > As part of a procedure I've a number sequences like this: > > > if Print_Info: print Datafile.readline() > else: Datafile.readline() > > > Is there a more compressed way to write such a statement, > especially I dislike the redundancy "Datafile.readline()". d=Datafile.readline() if Print_info: print d It's still two lines, but only has a single call to .readline(). HTH, Martin From aboudouvas at panafonet.gr Thu Apr 19 08:06:33 2007 From: aboudouvas at panafonet.gr (king kikapu) Date: 19 Apr 2007 05:06:33 -0700 Subject: About installing new Python version. In-Reply-To: References: <1176973387.967130.27370@y80g2000hsf.googlegroups.com> <1176975545.693682.51870@q75g2000hsh.googlegroups.com> <1176976568.438207.253120@d57g2000hsg.googlegroups.com> <1176977440.265263.186450@n76g2000hsh.googlegroups.com> <1176978617.299033.37250@n59g2000hsh.googlegroups.com> Message-ID: <1176984393.620727.56330@b58g2000hsg.googlegroups.com> On Apr 19, 1:51 pm, Steve Holden wrote: > Good question. kk is right - with a change in *major* version (such as > 2.4 to 3.5, 3.5 to 3.6) the compiled extensions will be incompatible, > and will need to be recompiled. This can take a while, as extension > authors frequently have other things to do besides maintain their > extensions. > > As you have found out, though, when only the *minor* version changes you > can just frop the new version in over the old and all your installed > extensions and packages continue to work just fine. > > 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 Thanks Steve, it is just the way i understood this, after seeing what the installer did. From bbxx789_05ss at yahoo.com Sun Apr 8 22:35:30 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: 8 Apr 2007 19:35:30 -0700 Subject: python, wxpython and Mac OS X Message-ID: <1176086130.330795.268590@n76g2000hsh.googlegroups.com> Hi, I'm using an intel imac which came with python 2.3.5 pre-intstalled on OS 10.4.7. I was able run a hello world wxPython script in Terminal by typing: $pythonw wxPythonTest.py Yesterday, I installed python 2.4.4 which I downloaded from the MacPython website, and it seems to have installed correctly: $python Python 2.4.4 (#1, Oct 18 2006, 10:34:39) [GCC 4.0.1 (Apple Computer, Inc. build 5341)] on darwin Type "help", "copyright", "credits" or "license" for more information. However, now when I try to run my hello world wxPython script in Terminal, I get the error message: Traceback (most recent call last): File "wxPythonTest.py", line 1, in ? import wx ImportError: No module named wx Does that mean I need to install a newer version of wxPython? If so, I'm not sure how to proceed. The wxPython download page says: ----- The Max OSX version of wxPython is distributed as a set of mountable disk images. The runtime verisons contain Installer packages, as well as a script that can perform an uninstall of previous installs of wxPython. (NOTE: If you have versions prior to 2.5.3.1 installed please do run the uninstaller to remove the older version.) ------ I looked around in Finder, but I can't tell what version of wxPython that came pre-installed on my imac, so I am not sure whether I need to uninstall it. Also, what wxPython download should I install? From mensanator at aol.com Thu Apr 12 23:28:57 2007 From: mensanator at aol.com (mensanator at aol.com) Date: 12 Apr 2007 20:28:57 -0700 Subject: Problem with algorithm In-Reply-To: <1176434160.047703.214600@q75g2000hsh.googlegroups.com> References: <1176434160.047703.214600@q75g2000hsh.googlegroups.com> Message-ID: <1176434937.258002.162220@p77g2000hsh.googlegroups.com> On Apr 12, 10:16???pm, "Jia Lu" wrote: > Hi all. > ?I want to create a large list like: > > aaaa ~ zzzz > > Is there any good algorithm to do this? Sure. test = '01' for m in test: for n in test: for o in test: for p in test: print m+n+o+p ## 0000 ## 0001 ## 0010 ## 0011 ## 0100 ## 0101 ## 0110 ## 0111 ## 1000 ## 1001 ## 1010 ## 1011 ## 1100 ## 1101 ## 1110 ## 1111 Now just change test='01' to test='abcdefghijklmnopqrstuvwxyz'. > > Thanx > > Jia Lu From lutz at rmi.net Thu Apr 19 17:02:18 2007 From: lutz at rmi.net (Mark Lutz) Date: 19 Apr 2007 14:02:18 -0700 Subject: Python training in Colorado, June 2007 Message-ID: <1177016538.712656.29890@n59g2000hsh.googlegroups.com> Python author and trainer Mark Lutz will be teaching another 3-day Python class at a conference center in Longmont, Colorado, on June 11-13, 2007. This is a public training session open to individual enrollments, and covers the same topics as the 3-day onsite sessions that Mark teaches, with hands-on lab work. For more information on this, and our other 2007 public classes, please visit this web page: http://home.earthlink.net/~python-training/longmont-public-classes.htm Thanks for your interest. --Python Training Services From cam.ac.uk at mh391.invalid Wed Apr 25 17:46:20 2007 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Wed, 25 Apr 2007 22:46:20 +0100 Subject: bitwise shift? In-Reply-To: References: Message-ID: Jean-Paul Calderone wrote: > On Wed, 25 Apr 2007 22:54:12 +0200, desktop wrote: >> I have found a code example with this loop. >> >> for k in range(10, 25): >> n = 1 << k; >> >> >> I have never read Python before but is it correct that 1 get multiplied >> with the numbers 10,11,12,12,...,25 assuming that 1 << k means "1 shift >> left by k" which is the same as multiplying with k. > > No. > > http://python.org/doc/ref/shifting.html "A right shift by n bits is defined as division by pow(2,n). A left shift by n bits is defined as multiplication with pow(2,n); for plain integers there is no overflow check so in that case the operation drops bits and flips the sign if the result is not less than pow(2,31) in absolute value. Negative shift counts raise a ValueError exception." >>> sys.maxint << 2 8589934588L >>> 2**31 2147483648L It looks like the limitation has been removed. This might be a nice optimization as well, as 1 << n is faster than 2**n for large enough n. Might be rare, although I have a friend who has been doing this all day. In Python. -- Michael Hoffman From flifus at gmail.com Wed Apr 25 18:50:53 2007 From: flifus at gmail.com (flifus at gmail.com) Date: 25 Apr 2007 15:50:53 -0700 Subject: My python annoyances so far Message-ID: <1177541453.471959.120830@c18g2000prb.googlegroups.com> Hi all. I'm learning python these days. I'm going to use this thread to post, from time to time, my annoyances with python. I hope someone will clarify things to me where I have misunderstood them. Annoyances: 1. Underscores! What's the deal with that? Especially those double underscores. The best answer I read on this is that the double underscores denotes special methods that the interpreter may automatically use. For example, 4+4 get expanded by the interpreter to 4.__add__(4). 2. There are modules, there are functions, and there are classes- methods! Wouldn't it have been easier had everything either been a function or a class method? From bbxx789_05ss at yahoo.com Thu Apr 19 01:45:15 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: 18 Apr 2007 22:45:15 -0700 Subject: What makes an iterator an iterator? In-Reply-To: <1hws6rd.u0a6hd78fhhpN%aleax@mac.com> References: <1hwr9pv.13v4ci6106qn0aN%aleax@mac.com> <1176936067.315082.17970@y80g2000hsf.googlegroups.com> <1hws6rd.u0a6hd78fhhpN%aleax@mac.com> Message-ID: <1176961515.450458.189530@p77g2000hsh.googlegroups.com> Hi, Thanks for the responses. > 7stud wrote: > > Can you explain some of the details of why this code fails: > --- > class Parrot(object): > def __iter__(self): > return self > def __init__(self): > self.next = self.next().next > def next(self): > for word in "Norwegian Blue's have beautiful > plumage!".split(): > yield word > > P = Parrot() > for word in P: > print word > ------ On Apr 18, 8:45 pm, a... at mac.com (Alex Martelli) wrote: > > ...a loop like "for x in y:" binds an unnamed temporary > variable (say _t) to iter(y) and then repeatedly calls _t.next() [or to > be pedantic type(_t).next(t)] until that raises StopIteration. Aiiii. Isn't this the crux: > repeatedly calls....[type(_t).next(t)] As far as I can tell, if the call was actually _t.next(), the code I asked about would work. However, the name look up for 'next' when you call: P.next() is entirely different from the name look up for 'next' when you call: type(P).next(). In the first lookup, the instance attribute "next" hides the class attribute "next". In the second lookup, the "next" attribute of the class is returned, i.e. the next() method. Yet, a generator-function- call returns an iterator object that wraps the generator function, so when the for loop makes repeated calls to type(P).next(), an iterator object is repeatedly returned--what you want is i.next() to be returned. I suspected next() might be called through the class, but after carefully parsing the section on iterators (Python in a Nutshell, p. 65) where it says iter() returns an object i, and then the for loop repeatedly calls i.next(), I dismissed that idea. I have to admit I'm still a little confused by why you only parenthetically noted that information and called it pedantic. On Apr 18, 8:38 pm, "Terry Reedy" wrote: > > One very good way to get an iterator from an iterable is for .__iter__ to > be a generator function. Ahhh. That eliminates having to deal with next().next constructs. Nice. > snip all examples of bad code that violate the iterator rule > by improperly writing .next as a generator function What iterator rule states that .next can't be a generator function? My book says an iterator is any object with a .next method that is callable without arguments (Python in a Nutshell(p.65) says the same thing). Also, my boos says an iterable is any object with an __iter__ method. As a result, next() and __iter__() don't have to be in the same object: lass MyIterator(object): def __init__(self, obj): self.toIterateOver = obj def next(self): for x in range(self.toIterateOver.age): print x raise StopIteration class Dog(object): def __init__(self, age): self.age = age def __iter__(self): return MyIterator(self) d = Dog(5) for year in d: print year I've read recommendations that an iterator should additionally contain an __iter__() method, but I'm not sure why that is. In particular PEP 234 says: ---------- Classes can define how they are iterated over by defining an __iter__() method; this should take no additional arguments and return a valid iterator object. A class that wants to be an iterator should implement two methods: a next() method that behaves as described above, and an __iter__() method that returns self. The two methods correspond to two distinct protocols: 1. An object can be iterated over with "for" if it implements __iter__() or __getitem__(). 2. An object can function as an iterator if it implements next(). Container-like objects usually support protocol 1. Iterators are currently required to support both protocols. The semantics of iteration come only from protocol 2; protocol 1 is present to make iterators behave like sequences; in particular so that code receiving an iterator can use a for-loop over the iterator. Classes can define how they are iterated over by defining an __iter__() method; this should take no additional arguments and return a valid iterator object. A class that wants to be an iterator should implement two methods: a next() method that behaves as described above, and an __iter__() method that returns self. The two methods correspond to two distinct protocols: 1. An object can be iterated over with "for" if it implements __iter__() or __getitem__(). 2. An object can function as an iterator if it implements next(). Container-like objects usually support protocol 1. Iterators are currently required to support both protocols. The semantics of iteration come only from protocol 2; protocol 1 is present to make iterators behave like sequences; in particular so that code receiving an iterator can use a for-loop over the iterator. -------- >The semantics of > iteration come only from protocol 2 My example demonstrates that. >protocol 1 is present to make > iterators behave like sequences; in particular so that code > receiving an iterator can use a for-loop over the iterator. I don't understand that part--it looks like my example is using a for loop over the iterator. From steveo at syslang.net Mon Apr 23 15:53:02 2007 From: steveo at syslang.net (Steven W. Orr) Date: Mon, 23 Apr 2007 15:53:02 -0400 (EDT) Subject: Shebang or Hashbang for modules or not? In-Reply-To: References: <1176308951.932721.197630@y80g2000hsf.googlegroups.com> Message-ID: On Monday, Apr 23rd 2007 at 17:31 +0100, quoth Michael Hoffman: =>Steven W. Orr wrote: =>> On Saturday, Apr 21st 2007 at 19:18 +0100, quoth Michael Hoffman: =>> =>> =>Chris Lasher wrote: =>> =>> Should a Python module not intended to be executed have shebang/ =>> =>> hashbang (e.g., "#!/usr/bin/env python") or not? I'm used to having a =>> =>> shebang in every .py file but I recently heard someone argue that =>> =>> shebangs were only appropriate for Python code intended to be =>> =>> executable (i.e., run from the command line). =>> => =>> =>Personally I include it in all of them, as part of boilerplate in a =>> =>template. =>> =>> I'd recommend againt it. The shebang doesn't do you any good unless it's =>> also in the presence of a file that has its executable bit set. => =>It doesn't do any bad either, so I don't understand why you would =>recommend against it. => =>And the bash function I use to create new files from the template also =>does chmod a+x. => =>Not to mention that I have emacs set such that things with shebangs at =>the top are automatically chmod a+x, so in my programming environment, =>having a shebang on files I create and being executable are one and the =>same. => =>> For example, let's leave python out for a second: I have a shell script. =>> And I also have lots of files which are not intended to be executed which =>> are also shell scripts, but which are sucked in by the shell "." or =>> "source" command (which is *somewhat* analogous to python's import). Lots =>> of these shell "library" scripts can't execute as standalone. The same =>> thing is possible with pything scripts. =>> =>> Of course, anything that has =>> if __name__ == "__main__": =>> in it should always have a shebang and be executable. => =>That's in my template as well. :) => =>I try to write all my modules so that they can easily be adapted to run =>as scripts, and all my scripts so that they can easily be adapted to use =>as modules. This has served me well many, many times. I see no reasons =>to create an artificial barrier to doing this by leaving the shebang out =>of files where it has no ill effect. We're going too far here. Anything that ever gets executed should obviously always be executable and have a shebang. I'm trying to point out to people who create scripts in any language, shell, python, farsi, whatever, that if it's intended to be read in as some sort of library then don't make it executable and don't add a shebang. To do so is to confuse future generations. -- 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 paul at boddie.org.uk Sun Apr 8 10:41:20 2007 From: paul at boddie.org.uk (Paul Boddie) Date: 8 Apr 2007 07:41:20 -0700 Subject: tuples, index method, Python's design In-Reply-To: <1175960990.140745.226360@b75g2000hsg.googlegroups.com> References: <1175867771.114540.61810@n76g2000hsh.googlegroups.com> <1175884427.779950.267220@y80g2000hsf.googlegroups.com> <1175953520.316208.241490@o5g2000hsb.googlegroups.com> <1175960990.140745.226360@b75g2000hsg.googlegroups.com> Message-ID: <1176043280.712239.116790@y80g2000hsf.googlegroups.com> bearophileHUGS at lycos.com wrote: > Carsten Haese: > > Adding useless features always makes a product worse. What's your use > > case for tuple.index? > > Ruby is a bit younger than Python, it has shown that few things may be > better done in a different way. I think the Ruby way is just to add a ton of methods to every class and to give them all aliases as well. Then you let the programmer "monkey patch" those classes in their own code, too. > An advantage of PyPy is that it allows faster and simpler ways to perform language experiments. So you can > even try things first and judge them later. You can find usercases later. This may help rejuvenate Python a bit :-) It's virtually a matter of copy and paste to do this with CPython. Here's a patch against the SVN trunk: http://sourceforge.net/tracker/index.php?func=detail&aid=1696444&group_id=5470&atid=305470 Paul From robert.rawlins at thinkbluemedia.co.uk Thu Apr 19 11:03:09 2007 From: robert.rawlins at thinkbluemedia.co.uk (Robert Rawlins - Think Blue) Date: Thu, 19 Apr 2007 16:03:09 +0100 Subject: Byte-Array to String In-Reply-To: <462782A5.5060000@timgolden.me.uk> References: <000f01c7828f$8b8ce770$a2a6b650$@rawlins@thinkbluemedia.co.uk> <462782A5.5060000@timgolden.me.uk> Message-ID: <001a01c78293$e5b58370$b1208a50$@rawlins@thinkbluemedia.co.uk> Thanks for getting back to me on this Tim, *pauses pulling his hair out for a moment. I'm back on this damn API and its driving me crazy I get three options really for returning a service record from the API, they look like this. array{uint32} GetRemoteServiceHandles(string address, string match) This method will request the SDP database of a remote device and retrieve the service record handles. To request service browse send an empty match string. Possible errors: org.bluez.Error.InvalidArguments org.bluez.Error.InProgress org.bluez.Error.ConnectionAttemptFailed org.bluez.Error.Failed array{byte} GetRemoteServiceRecord(string address, uint32 handle) This method will request the SDP database of a remote device for a service record and return the binary stream of it. Possible errors: org.bluez.Error.InvalidArguments org.bluez.Error.InProgress org.bluez.Error.Failed string GetRemoteServiceRecordAsXML(string address, uint32 handle) This method will request the SDP database of a remote device for a service record and return its data in XML format. Possible errors: org.bluez.Error.InvalidArguments org.bluez.Error.InProgress org.bluez.Error.Failed The first method, when I print its results just gives me dbus.Array([dbus.UInt32(65547L)], signature=dbus.Signature('u')) the method gives me that byte array and the third doesn't appear to work at all :-D Unfortunately nowhere seems to document what exactly those arrays contain, so I'm trying to crack one open and find out, but as you can see, I'm not having much luck. Perhaps this is a DBus thing, they do have a mailing list so I'll give them a go in a while. If you have any brain waves let me know mate, I'll add another beer to the tab, Rob -----Original Message----- From: python-list-bounces+robert.rawlins=thinkbluemedia.co.uk at python.org [mailto:python-list-bounces+robert.rawlins=thinkbluemedia.co.uk at python.org] On Behalf Of Tim Golden Sent: 19 April 2007 15:54 Cc: python-list at python.org Subject: Re: Byte-Array to String Robert Rawlins - Think Blue wrote: > I have a byte array passed to me by dbus and I'm looking to convert it into > a string? Is that possible? Sorry for seeming like a putts with these > questions, I'm not used to all these complex data types :-D > > dbus.Array([dbus.Byte(54), dbus.Byte(0), dbus.Byte(24), dbus.Byte(9), > dbus.Byte(0), dbus.Byte(0), dbus.Byte(10), dbus.Byte(0), dbu > s.Byte(0), dbus.Byte(0), dbus.Byte(0), dbus.Byte(9), dbus.Byte(0), > dbus.Byte(1), dbus.Byte(53), dbus.Byte(3), dbus.Byte(25), dbus. > Byte(16), dbus.Byte(0), dbus.Byte(9), dbus.Byte(2), dbus.Byte(0), > dbus.Byte(53), dbus.Byte(3), dbus.Byte(9), dbus.Byte(1), dbus.By > te(1)], signature=dbus.Signature('y')) No idea, but what happens when you iterate over it? for i in array_thingy: print i Or does it support the buffer interface? for i in buffer (array_thingy): print i If it did then you can at least get access to its innards and construct some kind of string representation. I've no idea what the numbers are supposed to represent, so I don't know what "convert it to a string" is likely to imply. This looks rather more like a dbus question than a strictly Python one. Is there a DBus mailing list or what-have-you? TJG -- http://mail.python.org/mailman/listinfo/python-list From cginboston at hotmail.com Tue Apr 17 09:44:05 2007 From: cginboston at hotmail.com (Chaz Ginger) Date: Tue, 17 Apr 2007 13:44:05 GMT Subject: Using X509 (and TLSlite) authentication Message-ID: I have been looking for a server application as an example of how to use TLSLite or PyOpenSSL X509 certificates for authentication. Does any one have a pointer or two? Peace, Chaz From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Fri Apr 27 08:18:54 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Fri, 27 Apr 2007 14:18:54 +0200 Subject: My python annoyances so far References: <1177541453.471959.120830@c18g2000prb.googlegroups.com> <59bf34F2k27v5U1@mid.individual.net> <1177603623.774892.230390@t38g2000prd.googlegroups.com> Message-ID: <59e81fF2k81ikU1@mid.individual.net> Steven D'Aprano wrote: > Perhaps you should read about the Kingdom of Nouns: > > execution-in-kingdom-of-nouns.html> Really cool. :) Thanks for sharing the link. Regards, Bj?rn -- BOFH excuse #118: the router thinks its a printer. From carsten at uniqsys.com Sat Apr 28 22:03:03 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Sat, 28 Apr 2007 22:03:03 -0400 Subject: Platform-dependent module search order? In-Reply-To: <1177797278.380434.145410@n59g2000hsh.googlegroups.com> References: <1177766565.118899.232620@e65g2000hsc.googlegroups.com> <1177797278.380434.145410@n59g2000hsh.googlegroups.com> Message-ID: <1177812183.3625.9.camel@localhost.localdomain> On Sat, 2007-04-28 at 14:54 -0700, John Machin wrote: > Very interesting. My first reaction to Theo's posting was to make a > confident declaration like Carsten did, but I couldn't simulate this > behaviour on Windows with Python 2.5.1 (or 2.1.3 for that matter) and > moreover the docs say: > """ > Details of the module searching and loading process are implementation > and platform specific. It generally involves searching for a ``built- > in'' module with the given name and then searching a list of locations > given as sys.path. My "confident declaration" was a lucky guess based on the available evidence. You couldn't reproduce the OP's problem because array is a built-in module on Windows, but on Linux it's an external module: Python 2.5 (r25:51908, Oct 28 2006, 12:26:14) [GCC 4.1.1 20060525 (Red Hat 4.1.1-1)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import array >>> array -Carsten From larry.bates at websafe.com Wed Apr 25 13:51:29 2007 From: larry.bates at websafe.com (Larry Bates) Date: Wed, 25 Apr 2007 12:51:29 -0500 Subject: File not read to end In-Reply-To: <1177522730.327454.121120@s33g2000prh.googlegroups.com> References: <1177522730.327454.121120@s33g2000prh.googlegroups.com> Message-ID: <-LWdnRS04OCCCLLbnZ2dnUVZ_uSgnZ2d@comcast.com> andrew.jefferies at gmail.com wrote: > Hi, > > I'm trying to write a simple log parsing program. I noticed that it > isn't reading my log file to the end. > > My log is around 200,000 lines but it is stopping at line 26,428. I > checked that line and there aren't any special characters. > > This is the file reading code segment that I'm using: > sysFile=open(sysFilename,'r') > lineCount = 0 > for line in sysFile: > lineCount +=1 > print str(lineCount) + " -- " + line > > I also stuck this same code bit into a test script and it was able to > parse the entire log without problem. Very quirky. > > This is my first foray from Perl to Python so I appreciate any help. > > Thanks in advance. > > --Andrew > Show us more of your surrounding code so we have some chance of figuring out why this working code stops. There's nothing wrong with this code, the problem is somewhere else. Suggestion: lineCount = 0 for line in sysFile: lineCount +=1 print str(lineCount) + " -- " + line can be written: for lineCount, line in enumerate(sysFile): print "%i--%s" % (lineCount, line) -Larry From bj_666 at gmx.net Wed Apr 4 02:41:01 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Wed, 04 Apr 2007 08:41:01 +0200 Subject: How can I time how much each thread takes? References: <1175662835.758899.13340@o5g2000hsb.googlegroups.com> Message-ID: In <1175662835.758899.13340 at o5g2000hsb.googlegroups.com>, silverburgh.meryl at gmail.com wrote: > I have the following code which spawn a number of thread and do > something (in the run method of MyThread). > how can I record how much time does EACH thread takes to complete the > 'run'? > > for j in range(threadCount): > t = MyThread(testNo) > threads.append(t) > t.start() > testNo += 1 > > > for t in threads: > print "len = %d", len(threads) > t.join() > > > I have read example of timeit.Timer() funcion, but I don' t know how > can i use it in a multiple thread program? If you want wall time then use `time.time()` in the `run()` method of the threads to calculate the difference between start and end and set an attribute with the elapsed time on the `MyThread` objects. Ciao, Marc 'BlackJack' Rintsch From gagsl-py2 at yahoo.com.ar Thu Apr 26 01:38:47 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 26 Apr 2007 02:38:47 -0300 Subject: kwarg references References: Message-ID: En Tue, 24 Apr 2007 22:31:59 -0300, Calvin Spealman escribi?: > In the internal API when a C function is called and passed a kwarg > dictionary, is there any case where anything else has a reference to > it? I checked with the following code and it looks like even if you > explicitly pass a dictionary with **kwargs, it still copies the > dictionary anyway. See the Python Reference Manual, 5.3.4 Calls http://docs.python.org/ref/calls.html Unfortunately it does not explicitely *guarantee* it will be a new dictionary. At least the way I read the docs, on a function call like this: def foo(**kwargs): pass d = {'a':1, 'b':2) foo(**d) Python could bind the existing d object to the formal parameter kwargs and still comply with the documented behavior. Some of my own code would break if that happened... :( -- Gabriel Genellina From c.c.wood at gmail.com Thu Apr 26 06:53:42 2007 From: c.c.wood at gmail.com (ChrisW) Date: 26 Apr 2007 03:53:42 -0700 Subject: How does Jython compile python modules that can be used by the JVM? Message-ID: <1177584822.083670.123950@b40g2000prd.googlegroups.com> Hi, I need a relatively technical answer to the above question - I've looked through the Jython docs / FAQs and Googled it but to no avail... if anyone can let me know I'd be most grateful, Thanks, Chris From kelvin.you at gmail.com Sun Apr 29 07:15:13 2007 From: kelvin.you at gmail.com (=?utf-8?B?5Lq66KiA6JC95pel5piv5aSp5rav77yM5pyb5p6B5aSp5rav5LiN6KeB5a62?=) Date: 29 Apr 2007 04:15:13 -0700 Subject: Could zipfile module process the zip data in memory? Message-ID: <1177845313.798239.71580@o5g2000hsb.googlegroups.com> I made a C/S network program, the client receive the zip file from the server, and read the data into a variable. how could I process the zipfile directly without saving it into file. In the document of the zipfile module, I note that it mentions the file-like object? what does it mean? class ZipFile( file[, mode[, compression[, allowZip64]]]) Open a ZIP file, where file can be either a path to a file (a string) or a file-like object. Thanks! From g.brandl at gmx.net Tue Apr 10 04:24:13 2007 From: g.brandl at gmx.net (Georg Brandl) Date: Tue, 10 Apr 2007 10:24:13 +0200 Subject: RFC: Assignment as expression (pre-PEP) In-Reply-To: <1hwbp28.xpul1y1vyggigN%aleax@mac.com> References: <1175802680.021987.39220@p77g2000hsh.googlegroups.com> <1176171797.184061.196520@b75g2000hsg.googlegroups.com> <1hwbp28.xpul1y1vyggigN%aleax@mac.com> Message-ID: Alex Martelli schrieb: > Adam Atlas wrote: > >> Hasn't this been discussed many many times before? I think Guido has >> been favourable to the idea of allowing :=, but that was a long time >> ago, and I don't think anything ever came of it. >> >> Personally, if anything, I'd like to see more use of the 'as' keyword >> as in Python 2.5's new 'with' statement. Assignment is basically what >> it adds to the statement, so if anything we should reuse it in other >> statements for consistency. >> >> if my_re1.match(exp) as temp: >> # do something with temp >> elif my_re2.match(exp) as temp: >> # do something with temp >> elif my_re3.match(exp) as temp: >> # do something with temp >> elif my_re4.match(exp) as temp: >> # do something with temp >> >> As others have mentioned, your particular instance is probably >> evidence that you need to restructure your code a little bit, but I do >> agree that "x = y; if x: ..." is a common enough idiom that it >> warrants a shortcut. And reusing "as", I think, is nice and readable, >> and it's an advantage that it doesn't require adding any new keywords >> or symbols. > > Actually, I agree with you. Unfortunately, I doubt python-dev will, but > the chance is good enough that it's probably worth proposing there > (ideally together with a patch to implement it, just to avoid any > [otherwise likely] whines about this being difficult to implement:-). The patch is already done -- I have it lying around here :) Georg -- Thus spake the Lord: Thou shalt indent with four spaces. No more, no less. Four shall be the number of spaces thou shalt indent, and the number of thy indenting shall be four. Eight shalt thou not indent, nor either indent thou two, excepting that thou then proceed to four. Tabs are right out. From nagle at animats.com Sat Apr 21 15:22:13 2007 From: nagle at animats.com (John Nagle) Date: Sat, 21 Apr 2007 19:22:13 GMT Subject: Python "robots.txt" parser broken since 2003 Message-ID: This bug, "[ 813986 ] robotparser interactively prompts for username and password", has been open since 2003. It killed a big batch job of ours last night. Module "robotparser" naively uses "urlopen" to read "robots.txt" URLs. If the server asks for basic authentication on that file, "robotparser" prompts for the password on standard input. Which is rarely what you want. You can demonstrate this with: import robotparser url = 'http://mueblesmoraleda.com' # this site is password-protected. parser = robotparser.RobotFileParser() parser.set_url(url) parser.read() # Prompts for password That's the tandard, although silly, "urllib" behavior. This was reported in 2003, and a patch was uploaded in 2005, but the patch never made it into Python 2.4 or 2.5. A temporary workaround is this: import robotparser def prompt_user_passwd(self, host, realm): return None, None robotparser.URLopener.prompt_user_passwd = prompt_user_passwd # temp patch John Nagle From dek at oliver.lbl.gov Wed Apr 11 11:07:28 2007 From: dek at oliver.lbl.gov (David E. Konerding DSD staff) Date: Wed, 11 Apr 2007 15:07:28 +0000 (UTC) Subject: No zlib in Python 2.4.4 References: <1176278576.196716.104760@p77g2000hsh.googlegroups.com> <1176281332.740637.219950@q75g2000hsh.googlegroups.com> Message-ID: On 2007-04-11, shamzz at gmail.com wrote: > On Apr 11, 9:14 am, Marc 'BlackJack' Rintsch wrote: >> In <1176278576.196716.104... at p77g2000hsh.googlegroups.com>, shamzz wrote: >> > Shouldn't zlib be compiled as a Python module automatically in Python >> > 2.4.4. I'm guessing Python is doing some kind of check and not >> > compiling zlib for some reason? >> >> It only gets compiled if the header files can be found. Is the zlib-dev >> or zlib-devel package installed? > > Thanks for the fast reply... this seems to be going off topic from > Python so sorry about that. > > But yep, I've just installed (through YAST) the zlib-devel and zlib- > devel-32 packages (zlib and zlib-32bit are already installed). > > I then did a make clean/configure/make/make install with the Python > source, but it's still not compiling with zlib. carefully inspect the configure output. Where it gets to the zlib output, it should print a message about whether it found the libraries or not. Usually, in these situations, I find myself looking closely at the output in config.log to see exactly what gcc command it tried to run. If that doesn't help, take a look at the 'make' output. It might be that there is no check for zlib in configure, but Python goes to build the module and fails due to missing headers or libraries. Dave From iansan at gmail.com Wed Apr 18 15:16:12 2007 From: iansan at gmail.com (IamIan) Date: 18 Apr 2007 12:16:12 -0700 Subject: Nested dictionaries trouble In-Reply-To: <1176325715.951076.4790@w1g2000hsg.googlegroups.com> References: <1176317876.917874.58040@n59g2000hsh.googlegroups.com> <1176325715.951076.4790@w1g2000hsg.googlegroups.com> Message-ID: <1176923772.011976.116190@p77g2000hsh.googlegroups.com> I am using the suggested approach to make a years list: years = ["199%s" % x for x in range(0,10)] years += ["200%s" % x for x in range(0,10)] I haven't had any luck doing this in one line though. Is it possible? Thanks. From tinaweb at bestemselv.com Sat Apr 14 02:16:31 2007 From: tinaweb at bestemselv.com (Tina I) Date: Sat, 14 Apr 2007 08:16:31 +0200 Subject: Append data to a list within a dict In-Reply-To: References: Message-ID: Michael Bentley wrote: > > On Apr 14, 2007, at 12:39 AM, Tina I wrote: > >> Say I have the following dictionary: >> >> ListDict = { >> 'one' : ['oneone' , 'onetwo' , 'onethree'], >> 'two' : ['twoone' , 'twotwo', 'twothree'], >> 'three' : ['threeone' , 'threetwo', threethree']} >> >> Now I want to append 'twofour' to the list of the 'two' key but I can't >> figure out how to that? >> Some pointers would be greatly appreciated. > > ListDict['two'].append('twofour') > > But you'll have to insert the missing single quote before "threethree" > first. > > hope this helps, > Michael Great! Thanks! And the missing singlequote was just a typo, my actual dictionary is way bigger so I just made up this as an example. Tina From deets at nospam.web.de Wed Apr 25 07:31:39 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 25 Apr 2007 13:31:39 +0200 Subject: trinary operator - if then else References: <1177484290.449378.93720@t38g2000prd.googlegroups.com> Message-ID: <598sgrF2jq0usU1@mid.uni-berlin.de> Michael >> >> Does Python 2.4 support it? > > Not precisely, but you can *usually* get away with: > > a and b or c This is really bad advice, as long as you don't explain why it "usually" works (and often enough not). This for example won't work: >>> False or '' and 0 '' The reason is that the if-value has to be bool(v) == True, otherwise the short-circuiting of the and will prevent the 0 from being returned. So in general, _don't_ use this! Diez From jjl at pobox.com Sun Apr 1 11:35:21 2007 From: jjl at pobox.com (John J. Lee) Date: Sun, 01 Apr 2007 15:35:21 GMT Subject: how to remove specified cookie in cookie jar? References: <1175313590.516509.232500@y66g2000hsf.googlegroups.com> Message-ID: <87ejn4cdl1.fsf@pobox.com> "ken" writes: > How to remove specified cookie (via a given name) in cookie jar? > > I have the following code, but how can I remove a specified cookie in > the cookie jar? > cj = cookielib.LWPCookieJar() > > if cj is not None: > if os.path.isfile(COOKIEFILE): > print 'Loading Cookie--------------' > cj.load(COOKIEFILE) cj.clear('example.com', '/', 'cookiename') Note that the domain arg must match the cookie domain exactly (and the domain might, for example, start with a dot). You may want to iterate over the Cookie objects in the CookieJar to find the one(s) you want to remove, but it's not supported to remove them at the same time as iterating, so (UNTESTED): remove = [] for cookie in cj: if is_to_be_removed(cookie): remove.append(cookie) for cookie in remove: cj.clear(cookie.domain, cookie.path, cookie.name) http://docs.python.org/lib/cookie-jar-objects.html """ clear( [domain[, path[, name]]]) Clear some cookies. If invoked without arguments, clear all cookies. If given a single argument, only cookies belonging to that domain will be removed. If given two arguments, cookies belonging to the specified domain and URL path are removed. If given three arguments, then the cookie with the specified domain, path and name is removed. Raises KeyError if no matching cookie exists. """ John From steve at holdenweb.com Thu Apr 19 15:39:33 2007 From: steve at holdenweb.com (Steve Holden) Date: Thu, 19 Apr 2007 15:39:33 -0400 Subject: HTTP getreply() never returns In-Reply-To: <1177009226.847229.34210@n76g2000hsh.googlegroups.com> References: <1177009226.847229.34210@n76g2000hsh.googlegroups.com> Message-ID: Marko.Cain.23 at gmail.com wrote: > Hi, > > I have the following code which send/receive HTTP request/response: > > # where sampleUrl is '127.0.0.1' and > # url is 'www.cnn.com' > > h = httplib.HTTP(self.sampleUrl, 8080) > h.putrequest('GET', '/sample?url=' + self.url) > h.endheaders() > > errcode, errmsg, headers = h.getreply() > > But it never returns from h.getreply(). > > I am using python 2.3.4. Can you please tell me what am I missing? > I am sure the url is correctly. I try putting this 'http:// > 127.0.0.1:8080/sample?url=www.cnn.com' and it works. > > Thank you for any help. > >>> h = httplib.HTTP("www.cnn.com", 80) >>> h.putrequest('GET', "/") >>> h.endheaders() >>> c, m, h = h.getreply() >>> c 200 >>> m 'OK' >>> h >>> h.getheaders("content-type") ['text/html'] The above shows you the basics of using httplib - if your own server isn't responding that's probably not the library's fault. What is the server? Perhaps its implementation of the HTTP protocol is slightly off, but not so far off that browsers can't work with it. For what it's worth you *do* appear to have formed the calls correctly, so something a little more complex is going on here. You might consider using WireShark (nee Ethereal) to look at the data passing across the wire when you use the browser and when you use httplib then comparing the data. That won't work on Windows because it disobligingly refuses to let you tap into the loopback (127) network. 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 Sat Apr 7 15:14:52 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: 7 Apr 2007 12:14:52 -0700 Subject: Mail not setting timestamp In-Reply-To: References: <1175923152.762487.273780@n76g2000hsh.googlegroups.com> Message-ID: <1175973291.952880.78970@y80g2000hsf.googlegroups.com> Lorenzo Thurman wrote: > Gabriel Genellina wrote: > > Lorenzo Thurman wrote: > > > >> I'm using the Mimewriter and mimetools modules to create html messages. > >> They work OK, except that when the messages are received, they always > >> have the timestamp of 12/31/1969. I've looked through both packages and > >> > > The date goes into the message headers, like From, To, Subject... > > message.add_header("Date", "Thu, 22 Jun 2006 23:18:15 -0300") > > > Thanks for the reply. When I try this though, I get an error: > AttributeError: 'datetime.datetime' object has no attribute 'split' > I'm trying to use a variable for the date, since of course, it should > always be 'now'. You have to convert the date into a string, using the right format. The docs for the time module have a recipe: http://www.python.org/doc/current/lib/module-time.html (look for RFC 2822) -- Gabriel Genellina From m.elston at advantest-ard.com Tue Apr 10 16:30:26 2007 From: m.elston at advantest-ard.com (Mark Elston) Date: Tue, 10 Apr 2007 13:30:26 -0700 Subject: About Eggs Message-ID: <131nspji8t6559b@corp.supernews.com> This is probably a *really* stupid question but... I have looked at all the documentation I have for 2.4.3 and all the docs I can download for 2.5 and I simply cannot find anything, anywhere that documents what egg files are. I have read posts referring to them and have been able to deduce that they are some form of zip file for the distribution of modules but beyond that I cannot find *any* docs for them anywhere. Where are they documented and how do I take advantage of them? Mark From tinaweb at bestemselv.com Sat Apr 14 02:13:28 2007 From: tinaweb at bestemselv.com (Tina I) Date: Sat, 14 Apr 2007 08:13:28 +0200 Subject: Append data to a list within a dict In-Reply-To: <7xejmnbj0x.fsf@ruckus.brouhaha.com> References: <7xejmnbj0x.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > Tina I writes: >> ListDict = { >> 'one' : ['oneone' , 'onetwo' , 'onethree'], >> 'two' : ['twoone' , 'twotwo', 'twothree'], >> 'three' : ['threeone' , 'threetwo', threethree']} >> >> Now I want to append 'twofour' to the list of the 'two' key but I >> can't figure out how to that? > > Is this a class exercise? Hint: > 1) figure out how to access the list of the 'two' key > 2) append 'twofour' to it. He he... at the age of 40 I'm well beyond school work ;) But thanks anyway Tina From sjmachin at lexicon.net Sat Apr 14 18:14:56 2007 From: sjmachin at lexicon.net (John Machin) Date: 14 Apr 2007 15:14:56 -0700 Subject: treating str as unicode in legacy code? In-Reply-To: <1176407869.541038.212410@p77g2000hsh.googlegroups.com> References: <1176407869.541038.212410@p77g2000hsh.googlegroups.com> Message-ID: <1176588896.359629.276060@l77g2000hsb.googlegroups.com> On Apr 13, 5:57 am, "Ben" wrote: > I'm left with some legacy code using plain oldstr, and I need to make > sure it works withunicodeinput/output. I have a simple plan to do > this: > > - Run the code with "python -U" so all the string literals becomeunicodelitrals. Requiring that the code is always run with a non-default argument doesn't seem very robust/portable to me. > - Add this statement > > str=unicode > > to all .py files so the type comparison (e.g., type('123') ==str) > would work. > IMVHO (1) doing that merely changes "legacy code" to "kludged legacy code" (2) there is no substitute for reading the code and trying to nut out what it is doing. Do you mean that those two things are the ONLY changes you plan to make? > Did I miss anything? Does this sound like a workable plan? Do you need to make sure it still works with ASCII input? With input in some other encoding e.g. cp1252? What do you mean by "unicode input"? Bear in mind that if you want to work with Python unicode objects internally, input from a file / socket / whatever will need to be decoded i.e. you will have to read the code and make appropriate changes. Data stored in (say) utf_16_le encoding is not "unicode" in the sense that you need; it still has to be decoded. What do you mean by "unicode output"? You are going to need to encode your output. This doesn't work; the output is not "unicode" in any meaningful sense: >>> f = open(u'uout', u'w') ### Warning: you need to hope that all builtins etc that you are calling cope with unicode arguments as well as the above one does. >>> f.write(u'abcde\n') >>> f.close() >>> open(u'uout', u'rb').read() 'abcde\r\n' This doesn't work; it crashes. >>> f = open('uout2', u'w') >>> f.write(u'abcde\xff\n') Traceback (most recent call last): File "", line 1, in UnicodeEncodeError: 'ascii' codec can't encode character u'\xff' in position 5: ordinal not in range(128) >>> Some object methods work differently with unicode; e.g. (1) str.translate and unicode.translate. (2) >>> 'abc\xA0def'.split() ['abc\xa0def'] >>> u'abc\xA0def'.split() [u'abc', u'def'] NameError: name 'isspace' is not defined >>> '\xA0'.isspace() False >>> u'\xA0'.isspace() True >>> HTH, John From aleax at mac.com Sat Apr 14 00:58:13 2007 From: aleax at mac.com (Alex Martelli) Date: Fri, 13 Apr 2007 21:58:13 -0700 Subject: how to strip the domain name in python? References: <1176526155.679721.159870@l77g2000hsb.googlegroups.com> Message-ID: <1hwj3lu.1psusuy14nbgxxN%aleax@mac.com> wrote: > Hi, > > I have a list of url names like this, and I am trying to strip out the > domain name using the following code: > > http://www.cnn.com > www.yahoo.com > http://www.ebay.co.uk > > pattern = re.compile("http:\\\\(.*)\.(.*)", re.S) > match = re.findall(pattern, line) > > if (match): > s1, s2 = match[0] > > print s2 > > but none of the site matched, can you please tell me what am i > missing? You're using reverse slashes in your RE pattern, to start with, while the URLs contain plain slashes (or don't have any slashes, in the case of the second one). Anyway, forget REs, and use standard library module urlparse, specifically its urlparse.urlsplit function. Alex From malkarouri at gmail.com Wed Apr 11 17:01:47 2007 From: malkarouri at gmail.com (malkarouri at gmail.com) Date: 11 Apr 2007 14:01:47 -0700 Subject: run function in separate process In-Reply-To: <1hweao8.1t99a5vdqygvbN%aleax@mac.com> References: <1176301427.183706.321920@n76g2000hsh.googlegroups.com> <1hweao8.1t99a5vdqygvbN%aleax@mac.com> Message-ID: <1176325307.190858.217560@q75g2000hsh.googlegroups.com> After playing with Alex's implementation, and adding some support for exceptions, this is what I came up with. I hope I am not getting too clever for my needs: import os, cPickle def run_in_separate_process_2(f, *args, **kwds): pread, pwrite = os.pipe() pid = os.fork() if pid > 0: os.close(pwrite) with os.fdopen(pread, 'rb') as f: status, result = cPickle.load(f) os.waitpid(pid, 0) if status == 0: return result else: raise result else: os.close(pread) try: result = f(*args, **kwds) status = 0 except Exception, exc: result = exc status = 1 with os.fdopen(pwrite, 'wb') as f: try: cPickle.dump((status,result), f, cPickle.HIGHEST_PROTOCOL) except cPickle.PicklingError, exc: cPickle.dump((2,exc), f, cPickle.HIGHEST_PROTOCOL) f.close() os._exit(0) Basically, the function is called in the child process, and a status code is returned in addition to the result. The status is 0 if the function returns normally, 1 if it raises an exception, and 2 if the result is unpicklable. Some cases are deliberately not handled, like a SystemExit or a KeyboardInterrupt show up as EOF errors in the unpickling in the parent. Some cases are inadvertently not handled, these are called bugs. And the original exception trace is lost. Any comments? Regards, Muhammad Alkarouri From apardon at forel.vub.ac.be Wed Apr 4 04:12:55 2007 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 4 Apr 2007 08:12:55 GMT Subject: how can I clear a dictionary in python References: <1175121525.261424.72350@n76g2000hsh.googlegroups.com> <4_SdndYI-pFUbZfbnZ2dnUVZ_hzinZ2d@comcast.com> Message-ID: On 2007-04-03, Aahz wrote: > In article , > Larry Bates wrote: >>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. > > Then you should explain why you didn't answer the question that was > asked. Answering a different question without explanation makes your > answer irrelevant at best, wrong at worst. This is not true. If this different question was in fact the intended question instead of the one actually asked. Anwering this different question can be more usefull than answering the one actually asked. People are often enough not very exact in their communication and that goes double for people who are new in a particular subject. So I think it is entirely appropiate to think about the real question the person is strugling with that hides between the question actually asked. Yes sometimes those who try to guess the intentions of the OP are going totally off in the wrong direction. But I have also seen those people providing very helpfull information, while those that would stick to the "actual" question didn'y provide very usefull information. -- Antoon Pardon From dickinsm at gmail.com Sun Apr 15 16:58:38 2007 From: dickinsm at gmail.com (Mark Dickinson) Date: 15 Apr 2007 13:58:38 -0700 Subject: combination function in python In-Reply-To: <1176665609.470089.211190@y80g2000hsf.googlegroups.com> References: <1176615838.830315.160210@b75g2000hsg.googlegroups.com> <1176629911.409257.149780@l77g2000hsb.googlegroups.com> <1176654363.696340.283330@d57g2000hsg.googlegroups.com> <1176665609.470089.211190@y80g2000hsf.googlegroups.com> Message-ID: <1176670718.329927.288920@l77g2000hsb.googlegroups.com> On Apr 15, 3:33 pm, bearophileH... at lycos.com wrote: > With few tests, it seems this is faster than the version by Jussi only > with quite big n,k. > True---and for large n and k it's difficult to imagine any real-world applications that wouldn't be better served by using the lngamma function instead. That is, the natural log of n choose k can be computed much more quickly as lngamma(n+1) - lngamma(k+1) - lngamma(n-k+1) I assume that lngamma is implemented somewhere in either numpy or scipy, but right now I can't find it... Mark From skip at pobox.com Mon Apr 16 10:11:24 2007 From: skip at pobox.com (skip at pobox.com) Date: Mon, 16 Apr 2007 09:11:24 -0500 Subject: Writing Log CSV (Efficiently) In-Reply-To: <000c01c7802a$08e42660$1aac7320$@rawlins@thinkbluemedia.co.uk> References: <000c01c7802a$08e42660$1aac7320$@rawlins@thinkbluemedia.co.uk> Message-ID: <17955.33804.728841.190687@montanaro.dyndns.org> Rob> I'm looking to write a Log file which will be CSV based, and there Rob> is a good possibility that it'll get quite busy once its up and Rob> running, so I'm looking for the most efficient way to achieve Rob> it. In addition to Tim's advice, if you're worried about possible loss of data you can set a timer to flush the file object every second or so. myfile = open("Logs/Application.txt", "wb") # note "b"inary mode! writer = csv.writer(myfile) set_a_timer(1.0, myfile.flush) ... You didn't indicate your platform so I can't be more specific about set_a_timer(). In my work environment we use Gtk a lot, so gobject.timeout_add works for us. You could also call signal.alarm on Unixoid systems. I'm sure there's something similar in Win32. Skip From kay.schluehr at gmx.net Sat Apr 7 04:12:49 2007 From: kay.schluehr at gmx.net (Kay Schluehr) Date: 7 Apr 2007 01:12:49 -0700 Subject: Custom Python Runtime In-Reply-To: <2NudnVn5jsm2QIvbnZ2dnUVZ_vqpnZ2d@comcast.com> References: <2NudnVn5jsm2QIvbnZ2dnUVZ_vqpnZ2d@comcast.com> Message-ID: <1175933569.660842.305030@o5g2000hsb.googlegroups.com> On Apr 7, 1:52 am, "Jack" wrote: > Since the full installation of Python (from either the standard installer or > ActiveState installer) is too big for my intended use, I'd like to build a > custom distribution of Python for Windows platform, omitting some lib files, > such as audio, tk, printing, testing units, etc. > > Is there a way to customize the Windows build? In my case, there is no need > to build an installer. The best way is to have everything in a directory, as > long as I know where to find Python and Python knows where to find the > necessary libs. Any online docs describing this? Thanks! In principle it suffices to drop in just the pythonxx.dll. If you want to isolate those scripts and additional libraries your project requires you might try out the py2exe even when you don't finally plan to deliver an executable. py2exe factors and copies everything needed for a complete application. For builds you can comment out includes in the header file python.h but this won't usually buy you that much. From Karsten.G.Weinert at googlemail.com Mon Apr 30 13:08:42 2007 From: Karsten.G.Weinert at googlemail.com (Karsten.G.Weinert at googlemail.com) Date: 30 Apr 2007 10:08:42 -0700 Subject: Cgi File Upload without Form In-Reply-To: <1177943490.669714.176360@y5g2000hsa.googlegroups.com> References: <1177708242.553577.226530@n15g2000prd.googlegroups.com> <1177943490.669714.176360@y5g2000hsa.googlegroups.com> Message-ID: <1177952922.186209.233210@n76g2000hsh.googlegroups.com> OK, I think I have a simple solution now. I am going to use FTP in my VBA-Client (it's possible) and don't need to do any server-side programming. Kind regards, Karsten. From marco at waven.com Mon Apr 2 04:45:13 2007 From: marco at waven.com (Marco) Date: Mon, 2 Apr 2007 16:45:13 +0800 Subject: frame of Qt program Message-ID: <5c62a320704020145q246e94cq4f3084fda6af8813@mail.gmail.com> Hi, I want to write a PyQt4 program, which like a graph-ssh. One side user choose server moder, and other side(s) user choose client mode. Both of them have a GUI, they can connect via socket. I have study PyQt4 for a while and learn a little socket(from W.R Stevens Unix Networking Programming). But I donot know how to integer both of them. What the frame of this kind of program looked like? Or is there some example? Thank you !! -- LinuX Power From ramashish.lists at gmail.com Fri Apr 20 04:17:09 2007 From: ramashish.lists at gmail.com (Ramashish Baranwal) Date: 20 Apr 2007 01:17:09 -0700 Subject: setDaemon problem. Message-ID: <1177057029.688992.160020@o5g2000hsb.googlegroups.com> Hi, I am facing an issue in daemonizing a thread using setDaemon method. Here is my code- import time from threading import Thread class MThread(Thread): def run(self): f = open('/tmp/t.log', 'w') for i in range(10): f.write('Iteration %d\n' % i) time.sleep(1) f.close() if __name__ == "__main__": t = MThread() t.setDaemon(True) print 'Starting thread' t.start() The scripts runs all fine, but nothing gets logged to "/tmp/t.log". However when I run the same script without setting thread as daemon (no call to t.setDaemon), everything works fine. Am I missing anything? Thanks in advance, Ram From misterwang at gmail.com Wed Apr 18 16:07:00 2007 From: misterwang at gmail.com (Peter Wang) Date: 18 Apr 2007 13:07:00 -0700 Subject: Python crash after using weave inline In-Reply-To: <1176900343.605337.42230@y5g2000hsa.googlegroups.com> References: <1176900343.605337.42230@y5g2000hsa.googlegroups.com> Message-ID: <1176926820.627494.13260@o5g2000hsb.googlegroups.com> Soren, For future reference, you might want to direct weave-related questions to the scipy-user at scipy.org mailing list. > def cartPolFast(xlen, ylen, x_c, y_c): > > res = zeros((xlen,ylen)) > > code = """ > { > int xlen, ylen, x_c, y_c; This line is unnecessary, because weave exposes those variables inside the local scope of your code. This also makes the braces at the top and bottom of the code block unnecessary. > for( x = 0; x == xlen; x++) > for( y = 0; y == ylen; y++) > rel_x = x-x_c; > rel_y = y_c-y; > > res(x,y) = rel_y*rel_y; > } Two things: 1. You need to put curly braces around the three lines of the inner loop. 2. You need to change "x == xlen" and "y == ylen" to "x < xlen" and "y < ylen". I made these modifications to your code and it runs fine on my machine (macbook pro, OS 10.4, scipy 0.5.2.dev2314). -peter From jzgoda at o2.usun.pl Sun Apr 1 16:02:15 2007 From: jzgoda at o2.usun.pl (Jarek Zgoda) Date: Sun, 01 Apr 2007 22:02:15 +0200 Subject: I18n issue with optik In-Reply-To: References: Message-ID: Thorsten Kampe napisa?(a): >>> Under Windows I get " File "G:\program files\python\lib\encodings >>> \cp1252.py", line 12, in encode >>> return codecs.charmap_encode(input,errors,encoding_table)" >> I'm not very experienced with internationalization, but if you change:: >> >> gettext.install('test') >> >> to:: >> >> gettext.install('test', unicode=True) >> >> what happens? > > No traceback anymore from optparse but the non-ascii umlauts are > displayed as question marks ("?"). And this is expected behaviour of encode() with errors set to 'replace'. I think this is the solution to your problem. I was a bit surprised I never saw this error, but I always use the unicode=True setting to gettext.install()... -- Jarek Zgoda http://jpa.berlios.de/ From gigs at hi.t-com.hr Fri Apr 6 13:19:38 2007 From: gigs at hi.t-com.hr (Gigs_) Date: Fri, 06 Apr 2007 19:19:38 +0200 Subject: tkinter canvas In-Reply-To: References: Message-ID: gigs wrote: > I have made drawing area and few butons. > How can I make when i click my fill button that later when i click on > oval oval gets filled with chousen color? when later click on my oval that is drawn in to change oval color, or to fill color in oval if click in oval with mouse From sbassi at clubdelarazon.org Tue Apr 3 10:52:55 2007 From: sbassi at clubdelarazon.org (Sebastian Bassi) Date: Tue, 3 Apr 2007 11:52:55 -0300 Subject: Problem installing Python 2.5 Message-ID: <9e2f512b0704030752h6079b365xa3a60a1b0411d33a@mail.gmail.com> I was trying to install Python 2.5 compiling from sources. I used: ./compile It run OK. Then: make altintall After a lot of output, got this: Listing /usr/local/lib/python2.5/xml/sax ... Compiling /usr/local/lib/python2.5/xml/sax/__init__.py ... Compiling /usr/local/lib/python2.5/xml/sax/_exceptions.py ... Compiling /usr/local/lib/python2.5/xml/sax/expatreader.py ... Compiling /usr/local/lib/python2.5/xml/sax/handler.py ... Compiling /usr/local/lib/python2.5/xml/sax/saxutils.py ... Compiling /usr/local/lib/python2.5/xml/sax/xmlreader.py ... Compiling /usr/local/lib/python2.5/xmllib.py ... Compiling /usr/local/lib/python2.5/xmlrpclib.py ... Compiling /usr/local/lib/python2.5/zipfile.py ... make: *** [libinstall] Error 1 It seems I am not the only one with this error: http://www.thescripts.com/forum/thread613458.html http://www.megasolutions.net/python/Python-installation-problem-(sorry-if-this-is-a-dup)-22624.aspx http://ubuntuforums.org/showthread.php?p=1912370 System: Freespire 1.0.13 (based on Debian). From kyosohma at gmail.com Fri Apr 6 23:15:04 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: 6 Apr 2007 20:15:04 -0700 Subject: Database Timestamp conversion error In-Reply-To: <1175901654.390331.150420@e65g2000hsc.googlegroups.com> References: <1175892527.110813.26570@n76g2000hsh.googlegroups.com> <1175901654.390331.150420@e65g2000hsc.googlegroups.com> Message-ID: <1175915704.435784.213830@b75g2000hsg.googlegroups.com> On Apr 6, 6:20 pm, "John Machin" wrote: > On Apr 7, 6:48 am, kyoso... at gmail.com wrote: > > > Hi, > > > I am populating a mySQL database with data from the MS Access > > database. I have successfully figured out how to extract the data from > > Access, and I can insert the data successfully into mySQL with Python. > > My problem is that I keep hitting screwy records with what appears to > > be a malformed dbiDate object when I insert certain records. I get the > > following traceback: > > Ummm ... I didn't start using Python on databases till after DB API > 2.0 came out (1999) so please pardon my ignorance, but isn't dbiDate > something that was in API 1.0 but vanished in API 2.0 [e.g. its > mentioned only briefly in the history section of the current mxODBC > docs]? > > If that's what you are still using: > (a) I can't imagine how printing a dbiDate object would give such a > garbled result -- try: > > print type(obj) > print repr(obj) > for both a "bad" obj and a "good" obj. > > (b) The API 1.0 docs give a clue: > """ > dbiDate(value) > > This function constructs a 'dbiDate' instance that holds a > date value. The value should be specified as an integer > number of seconds since the "epoch" (e.g. time.time()). > """ > and googling brought up a few hits mentioning that not handling dates > earlier that the "epoch" (1970-01-01T00:00:00) was a limitation. > > So: if you are calling dbiDate yourself, you can inspect its input > argument; presumably a date in the year 112 will show up as negative. > > > > > > > Traceback (most recent call last): > > File "\\someServer\Development\collectiveFleet.py", line 68, in - > > toplevel- > > mycursor.execute(sql) > > TypeError: argument 1 must be string without null bytes, not str > > > When I print the timestamp variable, I get this output: > > > (I31 > > (S'OK' > > p1 > > Nttp2 > > . > > > If I look in the MS Access database, I see the timestamp as "5/6/112". > > Obviously some user didn't enter the correct date and the programmer > > before me didn't give Access strict enough rules to block bad dates. > > How do I test for a malformed date object so I can avoid this? > > There > > are thousands of records to transfer. > > > I am using the odbc module for connection purposes with Python 2.4 on > > Windows XP SP2. > > If this is the odbc module that comes in the win32all package: > 1. There are much better options available on Windows e.g. mxODBC. > 2. Doesn't document dbiDate objects AFAICT. > > If your SELECT from the Access db is returning you "seconds since the > epoch" values, proceed as I suggested earlier. > > If it is returning you dbiDate objects directly, find out if the > dbiDate obj has any useful attributes or methods e.g. > > obj.date_as_tuple() -> (2007, 4, 7, ...) > or > obj.year -> 2007 > obj.month -> 4 > etc > > How to find out: insert code like > print dir(obj) > in your script and inspect the output for likely attribute/method > names. > > And if that doesn't help, abandon the odbc module and use e.g. mxODBC > or Python adodb. > > Hope some of this helps, > John I did find a workaround that I implemented right before it was quitting time, but I want to look into both of your guy's answers. I have used the adodb module and I can't recall why I switched to the odbc one. I think one of my co-workers said that the adodb wouldn't work with mySQL on Linux or something. The quick-fix I used included using the datetime module and the time module with the strftime() method. The type that was returned said it was a dbiDate object (which is what I think I get in one of my other programs that does use the adodb module!) John - when I tried printing a dir() on the returned object, I got and empty list. Thanks for the suggestions. I won't get to try them until Monday. Mike From boris.dusek at gmail.com Thu Apr 19 16:57:16 2007 From: boris.dusek at gmail.com (=?utf-8?B?Qm9yaXMgRHXFoWVr?=) Date: 19 Apr 2007 13:57:16 -0700 Subject: Significance of "start" parameter to string method "endswith" In-Reply-To: <1177014971.167843.293190@n76g2000hsh.googlegroups.com> Message-ID: <1177016236.700474.16170@n59g2000hsh.googlegroups.com> On Apr 19, 10:36 pm, subscriber123 wrote: > On Apr 19, 3:58 pm, Boris Du?ek wrote: > > > > > Hello, > > > what is the use-case of parameter "start" in string's "endswith" > > method? > def foo(function,instance,param): > if function(instance,param,2,4): > return True > else: return False > > The function must work whether you pass it > foo(str.endswith,"blaahh","ahh"), or > foo(str.startswith,"blaahh","aah"). This is a really bad example, but > it gets the point across that similar functions must have similar > parameters in order to be Pythonic. Thanks for explanation, this point makes sense. And I agree that I can hardly imagine any use of both parameters :-). From mail at microcorp.co.za Thu Apr 26 02:42:14 2007 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Thu, 26 Apr 2007 08:42:14 +0200 Subject: Now() References: <000301c78728$ba634ce0$2f29e6a0$@rawlins@thinkbluemedia.co.uk> Message-ID: <033801c787ce$f7a755a0$03000080@hendrik> Robert Rawlins - Think Blue wrote: >With time depicted to the nearest second, from my background in ColdFusion development we used to have a >datetimeformat() function that I could use as > >DateTimeFormat(now(), ?yyyy-mm-dd HH:mm:ss?) > >Which would give the current time a mask. Here is a hack that does more or less what you want: import time # function to return time as a string def time_string(): """Get the time as a string YYYY/MM/DD HH:MM:SS - with trailing space""" y = time.localtime() # get the current time - a tuple of ints t = '' # start with empty string for x in y[0:6]: # move first 6 values over z = str(x) # first make a string if len(z) < 2: # formatting them t = t + '0' # pad to at least two chars t = t + z # as string values u = t[0:4] + '/' + t[4:6] + '/' + t[6:8] + ' ' + t[8:10] + ':' + t[10:12] + ':' + t[12:14] + ' ' return u # done! hth - Hendrik From Robert.Katic at gmail.com Wed Apr 11 03:40:28 2007 From: Robert.Katic at gmail.com (goodwolf) Date: 11 Apr 2007 00:40:28 -0700 Subject: Does python have the static function member like C++ In-Reply-To: <461c895f$0$2128$426a74cc@news.free.fr> References: <1176260903.362329.59370@o5g2000hsb.googlegroups.com> <1176261542.704649.240350@n76g2000hsh.googlegroups.com> <1176273559.047449.263710@n76g2000hsh.googlegroups.com> <461c895f$0$2128$426a74cc@news.free.fr> Message-ID: <1176277228.056538.268290@o5g2000hsb.googlegroups.com> On Apr 11, 9:09 am, Bruno Desthuilliers wrote: > goodwolf a ?crit : > (snip) > > > 1. In this case you will prefer a classmethod instead a staticmethod. > > 2. If counter is the number of instances of class AAA then you will > > incrase counter inside __init__ method. > > > class AAA (object): > > counter = 0 > > def __init__(self): > > type(self).counter_increase() > > You can call a class method on an instance: > self.counter_increase() > > And FWIW, this is probably something I'd put in the constructor (the > __new__ method), not in the initializer. > > > @classmethod > > def counter_increase(cls): > > cls.counter += 1 > > > or > > > class AAA (object): > > counter = 0 > > def __init__(self): > > type(self).counter += 1 > > Instances have a reference to their class, so you can also write this: > self.__class__.counter += 1 OK, you will use something like this: class AAA (object): counter = 0 def __new__(cls): cls.counter += 1 return super(cls, cls).__new__(cls) but I think that __new__ is more "low level" and not necessary here, so I will use: class AAA (object): counter = 0 def __init__(self): self.counter_increase() @classmethod def counter_increase(cls): cls.counter += 1 with yours correction invoking self.counter_increase() instead of more explicit type(self).counter_increase() From bbxx789_05ss at yahoo.com Fri Apr 13 14:37:37 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: 13 Apr 2007 11:37:37 -0700 Subject: function/method assigment In-Reply-To: <1176480852.643836.121930@p77g2000hsh.googlegroups.com> References: <1176480852.643836.121930@p77g2000hsh.googlegroups.com> Message-ID: <1176489457.103834.266610@d57g2000hsg.googlegroups.com> On Apr 13, 10:14 am, viscr... at gmail.com wrote: > I have a confusion when I do some practice, the code and output are as > following, > > >>> def fun(): > > print 'In fun()....' > > >>> testfun = fun() > In fun().... > >>> print testfun > None > >>> testfun2 = fun > >>> print testfun2 > > >>> print testfun2() > > In fun().... > None > > > > what is 'testfun'? Why it is 'None'? And print testfun2(), what is the > meaning of 'None'? > > Thanks! Start with these rules: 1) all function calls in your code are replaced by the function's return value. 2) if a function doesn't have a return statement, it automatically returns None. 3 The '()' symbols make the function execute. Without those the function won't execute. From michael at jedimindworks.com Wed Apr 25 07:02:53 2007 From: michael at jedimindworks.com (Michael Bentley) Date: Wed, 25 Apr 2007 06:02:53 -0500 Subject: trinary operator - if then else In-Reply-To: <1177484290.449378.93720@t38g2000prd.googlegroups.com> References: <1177484290.449378.93720@t38g2000prd.googlegroups.com> Message-ID: On Apr 25, 2007, at 1:58 AM, Alchemist wrote: > What is Python's version for the trinary if..then..else operator? > > I want a one-liner such as > a?b:c > for the if..then..else control structure > if a > then b > else c > > Does Python 2.4 support it? Not precisely, but you can *usually* get away with: a and b or c From bdesth.quelquechose at free.quelquepart.fr Wed Apr 4 19:24:37 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Thu, 05 Apr 2007 01:24:37 +0200 Subject: Why NOT only one class per file? In-Reply-To: <1175721799.714907.52770@o5g2000hsb.googlegroups.com> References: <1175721799.714907.52770@o5g2000hsb.googlegroups.com> Message-ID: <46142acc$0$7532$426a34cc@news.free.fr> Chris Lasher a ?crit : > A friend of mine with a programming background in Java and Perl places > each class in its own separate file in . I informed him that keeping > all related classes together in a single file is more in the Python > idiom than one file per class. He asked why, Why not ? > and frankly, his valid > question has me flummoxed. > > I tried to rationalize this Python idiom by claiming a file--a single > module--makes for a great container of code which is logically tied > together, such as a class and its subclasses. He posited that > directories (packages) can tie the files together just as well, With much more verbosity and boilerplate code... > and by > having the classes as separate files, he can "diff" them to see how > they differ, something he wouldn't be able to do with the code all in > one file. Bullshit. diff used to exist way before Java. And it's still used for languages that have no notion of 'class'. I use it on an almost daily basis, FWIW. > I also offered that having related classes under one file gives more > direct access to those classes, e.g.: (snip) > He doesn't find my arguments convincing, Then he's a bit on the masochist side. > so I thought I'd ask here to > see why the Python idiom is the way it is: why should we NOT be > placing classes in their own separate files? Because it just sucks. Ok, let's have an example: I'm currently working on adding ActiveRecord-like validation to Elixir, and here's one of my classes: """ class ValidatePresenceOfStatement(ValidateWithStatement): def __init__(self, entity, column, when='on_save'): validator = validators.not_empty super(ValidateWithStatement, self).__init__(entity, column, validator, when) validate_presence_of = Statement(ValidatePresenceOfStatement) """ Four (4) lines of code. Should I really consider putting this in a separate file ? And what about my functions, then ? Should they all live in a separate file too? FWIW, I'm also currently working on a Plone application developped by a (somewhat braindead) Java programmer, who of course did the 'one-class-per-file' dance. *It's a pure nightmare*. I constantly have to switch between dozens of files to find things that are so obviously tied together that they should belong to a single module. In some cases, there's more import statements than effective code. Talk about a waste of time. > Thoughts, comments, and insight much appreciated, Just ask him why Java insists on 'one-(public)-class-per-file', and why it's considered good form in C++. I mean, the real *technical* reasons... From bj_666 at gmx.net Wed Apr 11 04:14:32 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Wed, 11 Apr 2007 10:14:32 +0200 Subject: No zlib in Python 2.4.4 References: <1176278576.196716.104760@p77g2000hsh.googlegroups.com> Message-ID: In <1176278576.196716.104760 at p77g2000hsh.googlegroups.com>, shamzz wrote: > Shouldn't zlib be compiled as a Python module automatically in Python > 2.4.4. I'm guessing Python is doing some kind of check and not > compiling zlib for some reason? It only gets compiled if the header files can be found. Is the zlib-dev or zlib-devel package installed? Ciao, Marc 'BlackJack' Rintsch From kyosohma at gmail.com Tue Apr 3 14:57:54 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: 3 Apr 2007 11:57:54 -0700 Subject: how to remove multiple occurrences of a string within a list? In-Reply-To: <1175626164.428718.267670@w1g2000hsg.googlegroups.com> References: <1175624433.206953.214290@n59g2000hsh.googlegroups.com> <1175625098.269660.184790@o5g2000hsb.googlegroups.com> <1175626164.428718.267670@w1g2000hsg.googlegroups.com> Message-ID: <1175626674.836668.293850@b75g2000hsg.googlegroups.com> On Apr 3, 1:49 pm, kyoso... at gmail.com wrote: > On Apr 3, 1:31 pm, "Matimus" wrote: > > > It depends on your application, but a 'set' might really be what you > > want, as opposed to a list. > > > >>> s = set(["0024","haha","0024"]) > > >>> s > > > set(["0024","haha"])>>> s.remove("0024") > > >>> s > > > set(["haha"]) > > If you want, you can also loop over the list, like so: > > counter = 0 > your_list = ["0024","haha","0024"] > for i in your_list: > if i == '0024': > your_list.pop(counter) > counter += 1 > > Mike If you want to get really fancy, you could do a list comprehension too: your_list = ["0024","haha","0024"] new_list = [i for i in your_list if i != '0024'] Mike From skip at pobox.com Tue Apr 3 14:05:39 2007 From: skip at pobox.com (skip at pobox.com) Date: Tue, 3 Apr 2007 13:05:39 -0500 Subject: How can I kill a running thread when exiting from __main__ In-Reply-To: References: <1175620919.478708.292150@p77g2000hsh.googlegroups.com> <17938.37496.3294.776762@montanaro.dyndns.org> Message-ID: <17938.38771.423297.950299@montanaro.dyndns.org> Steve> Maybe, then, the real answer is "just exit from the main thread"? Yes, I believe so. If that's not what's happening I would look to see if there is another thread which wasn't marked as a daemon. Skip From redtiger84 at googlemail.com Fri Apr 6 10:23:53 2007 From: redtiger84 at googlemail.com (Christoph Krammer) Date: 6 Apr 2007 07:23:53 -0700 Subject: Using os.popen3() to get binary data In-Reply-To: References: <1175857372.585042.239310@y80g2000hsf.googlegroups.com> Message-ID: <1175869433.044366.58650@l77g2000hsb.googlegroups.com> Just got the solution... After sending the image data with "si.write(image)", I have to close the pipe to tell the program to convert the image with "si.close()". Now everything works fine. Christoph From robert.kern at gmail.com Sun Apr 15 23:47:51 2007 From: robert.kern at gmail.com (Robert Kern) Date: Sun, 15 Apr 2007 22:47:51 -0500 Subject: working of round() In-Reply-To: References: <1176682019.215351.114560@y80g2000hsf.googlegroups.com> Message-ID: Steven Bethard wrote: > I'm not sure why you would have expected 2.62 for the latter when:: > > >>> 5.25 / 2 > 2.625 Round-to-nearest-even is a valid, and oft-recommended rounding mode for numbers exactly halfway between two round numbers. -- 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 viscroad at gmail.com Fri Apr 13 12:14:12 2007 From: viscroad at gmail.com (viscroad at gmail.com) Date: 13 Apr 2007 09:14:12 -0700 Subject: function/method assigment Message-ID: <1176480852.643836.121930@p77g2000hsh.googlegroups.com> I have a confusion when I do some practice, the code and output are as following, >>> def fun(): print 'In fun()....' >>> testfun = fun() In fun().... >>> print testfun None >>> testfun2 = fun >>> print testfun2 >>> print testfun2() In fun().... None >>> what is 'testfun'? Why it is 'None'? And print testfun2(), what is the meaning of 'None'? Thanks! From Emile.Boudreau at cognos.com Mon Apr 9 09:12:20 2007 From: Emile.Boudreau at cognos.com (Boudreau, Emile) Date: Mon, 9 Apr 2007 09:12:20 -0400 Subject: Using/finding ODBC and DBI Message-ID: <09042D621CD4AA479C678463F3A646D0F7466B@sottemail1.ent.ad.cognos.com> Hello all, I'm trying to use ODBC and DBI but I don't seem to have the right files on my system. I have looked around and I can't find what I'm looking for. From the information I have been able to find these are not part of the standard python library. True?? Where can I find the modules that I'm missing to be able to import the modules correctly and run my script? Thanks, Here is the code that I'm using. import odbc, dbi Query = "select jobs.trakkerid, fixes.change as change, from jobs, fixes where trakkerid <> 'na' and trakkerid <> '' and jobs.job = fixes.job and fixes.change = 28339 order by change desc" db = odbc.odbc( "UDAP4" ) cursor = db.cursor() cursor.execute( Query ) Emile Boudreau x5754 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 guido at python.org Sun Apr 1 16:14:57 2007 From: guido at python.org (Guido van Rossum) Date: Sun, 1 Apr 2007 13:14:57 -0700 Subject: [Python-Dev] Python 3000 PEP: Postfix type declarations In-Reply-To: <43aa6ff70704010949v5d38ccb2pa2c183594124267c@mail.gmail.com> References: <43aa6ff70704010949v5d38ccb2pa2c183594124267c@mail.gmail.com> Message-ID: +18446744073709551616 from me too. This also fits nicely in with my plan to abandon the python-dev and python-3000 mailing lists. Mailing lists are so 20th century! I propose that from now on, all Python development should be carried out on blogs, so that readers can use customized RSS feeds to read only those contributions they are interested in. I note that all the key developers already have a blog, e.g.: Aahz - http://www.artima.com/weblogs/index.jsp?blogger=aahz Neal Norwitz - http://nnorwitz.blogspot.com/ Fredrik Lundh - http://effbot.org/pyref/blog.htm Jeremy Hylton - http://www.python.org/~jeremy/weblog/ Anthony Baxter - http://codingweasel.blogspot.com/ Phillip Eby - http://dirtsimple.org/programming/index.html Talin - http://www.advogato.org/person/Talin/diary.html David Ascher - http://ascher.ca/blog/ Fred Drake - http://www.advogato.org/person/fdrake/diary.html (and myself, of course - http://www.artima.com/weblogs/index.jsp?blogger=guido) --Guido On 4/1/07, Collin Winter wrote: > On 4/1/07, Georg Brandl wrote: > [snip several pages of excellent ideas] > > > > The mapping between types and declarators is not static. It can be completely > > customized by the programmer, but for convenience there are some predefined > > mappings for some built-in types: > > > > ========================= =================================================== > > Type Declarator > > ========================= =================================================== > > ``object`` ? (REPLACEMENT CHARACTER) > > ``int`` ? (DOUBLE-STRUCK CAPITAL N) > > ``float`` ? (ESTIMATED SYMBOL) > > ``bool`` ? (CHECK MARK) > > ``complex`` ? (DOUBLE-STRUCK CAPITAL C) > > ``str`` ? (LOWER RIGHT PENCIL) > > ``unicode`` ? (BLACK NIB) > > ``tuple`` ? (PARENTHESIZED LATIN SMALL LETTER T) > > ``list`` ? (HOT SPRINGS) > > ``dict`` ? (DOUBLE-ENDED MULTIMAP) > > ``set`` ? (EMPTY SET) (*Note:* this is also for full sets) > > ``frozenset`` ? (SNOWMAN) > > ``datetime`` ? (WATCH) > > ``function`` ? (LATIN SMALL LETTER LAMBDA WITH STROKE) > > ``generator`` ? (ATOM SYMBOL) > > ``Exception`` ? (ELECTRIC ARROW) > > ========================= =================================================== > > > > The declarator for the ``None`` type is a zero-width space. > > > > These characters should be obvious and easy to remember and type for every > > programmer. > > > [snip] > > > > Example > > ======= > > > > This is the standard ``os.path.normpath`` function, converted to type declaration > > syntax:: > > > > def normpath?(path?)?: > > """Normalize path, eliminating double slashes, etc.""" > > if path? == '': > > return '.' > > initial_slashes? = path?.startswith?('/')? > > # POSIX allows one or two initial slashes, but treats three or more > > # as single slash. > > if (initial_slashes? and > > path?.startswith?('//')? and not path?.startswith?('///')?)?: > > initial_slashes? = 2 > > comps? = path?.split?('/')? > > new_comps? = []? > > for comp? in comps?: > > if comp? in ('', '.')?: > > continue > > if (comp? != '..' or (not initial_slashes? and not new_comps?)? or > > (new_comps? and new_comps?[-1]? == '..')?)?: > > new_comps?.append?(comp?) > > elif new_comps?: > > new_comps?.pop?()? > > comps? = new_comps? > > path? = '/'.join(comps?)? > > if initial_slashes?: > > path? = '/'*initial_slashes? + path? > > return path? or '.' > > > > As you can clearly see, the type declarations add expressiveness, while at the > > same time they make the code look much more professional. > > My only concern is that this doesn't go far enough. While knowing that > some object is a ? is a good start, it would be so much more helpful > to know that it's a ? of ?s. I think something like ???3? to indicate > a 3-? of ?s would be nice. This would change the line in the above > from "if comp? in ('', '.')?:" to "if comp? in ('', '.')??2?:", which > I think is a nice win in terms of readability, EIBTI and all that. > > (Sidebar: I think the PEP should feature a section on how these new > type declarations will cut down on mailing list volume and > documentation size.) > > In light of this PEP, PEP 3107's function annotations should be > rejected. All that hippie feel-good crap about "user-defined > annotations" and "open-ended semantics" and "no rules, man" was just > going to get us into trouble. This PEP's more modern conception of > type annotations give the language a power and expressiveness that my > PEP could never hope to match. > > This is clearly a move in the right direction. +4 billion. > > Collin Winter > _______________________________________________ > Python-Dev mailing list > Python-Dev at python.org > http://mail.python.org/mailman/listinfo/python-dev > Unsubscribe: http://mail.python.org/mailman/options/python-dev/guido%40python.org > -- --Guido van Rossum (home page: http://www.python.org/~guido/) From bdesth.quelquechose at free.quelquepart.fr Tue Apr 3 17:06:31 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Tue, 03 Apr 2007 23:06:31 +0200 Subject: Need help on reading line from file into list In-Reply-To: <1175630106.220186.107900@y66g2000hsf.googlegroups.com> References: <1175630106.220186.107900@y66g2000hsf.googlegroups.com> Message-ID: <4612b8f2$0$28546$426a74cc@news.free.fr> bahoo a ?crit : > Hi, > > I have a text file containing a single line of text, such as > 0024 > > How should I read it into a "list"? You mean ['0024'], or ['0', '0', '2', '4'] ? > I tried this, but the "join" did not work as expected. What did you expect ? help(str.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. > Any > suggestions? Honestly, the first would be to learn to ask questions, and the second to pay more attention to what's written in the doc. But let's try : > infile = open('my_file.txt','r') > for line in infile: > line.join(line) > my_list.extend( line ) > If you have a single line of text, you don't need to iterate. file has a readlines() method that will return a list of all lines. It also has a read() method that reads the whole content. Notice that none of these methods will strip newlines characters. Also, str has a strip() method that - by default - strip out any 'whitespace' characters - which includes newline characters. And finally, passing a string as an argument to list's constructor gives you a list of the characters in the string. This is all you need to know to solve your problem - or at least the two possible definitions of it I mentionned above. >>> open('source.txt').readlines() ['0024\n'] >>> map(str.strip, open('source.txt').readlines()) ['0024'] >>> open('source.txt').read() '0024\n' >>> list(open('source.txt').read().strip()) ['0', '0', '2', '4'] >>> From aleax at mac.com Wed Apr 18 10:40:14 2007 From: aleax at mac.com (Alex Martelli) Date: Wed, 18 Apr 2007 07:40:14 -0700 Subject: python - dll access (ctypes or swig) References: <1hwq9na.98800513op6liN%aleax@mac.com> Message-ID: <1hwr93q.ym0vh4baceh6N%aleax@mac.com> Larry Bates wrote: ... > I guess I was the only one it wasn't "obvious" to . I've always > written my COM servers as .EXE files even though they cannot be run > independently. What I find is "odd" is that I can create a .DLL or an > .EXE of my COM server and after I register it, my application doesn't > appear to know the difference. The difference seems to be hidden from > the actual application and doesn't affect it (at least that I can > determine). Yes, except for performance (a DLL affords within-process communication without the overhead of IPC, so it can be much faster when appropriate) and some technical issues such as threading (if COM client and server are in separate processes, their threading models are independent from each other; if they are in the same process, they'd better have compatible threading approaches -- a thread-unsafe DLL server can make a single-threaded client happy but would cause problems and crashes if a freely-threaded client tried using it). Alex From mail at timgolden.me.uk Wed Apr 18 08:29:40 2007 From: mail at timgolden.me.uk (Tim Golden) Date: Wed, 18 Apr 2007 13:29:40 +0100 Subject: X root Operator help In-Reply-To: <1176898887.530470.222830@p77g2000hsh.googlegroups.com> References: <1176898887.530470.222830@p77g2000hsh.googlegroups.com> Message-ID: <46260F34.7080102@timgolden.me.uk> lucidparadox wrote: > I'm currently new to Python and I haven't been able to find the > operator/math function to find the square root or even the x root of a > number. Without ever having used it, I would guess it's the sqrt function in the math module. (Possibly also of interest: the pow function in that same module) TJG From bdesth.quelquechose at free.quelquepart.fr Thu Apr 5 20:10:32 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Fri, 06 Apr 2007 02:10:32 +0200 Subject: Why NOT only one class per file? In-Reply-To: References: <1175721799.714907.52770@o5g2000hsb.googlegroups.com> <46142acc$0$7532$426a34cc@news.free.fr> <4614b40e$0$26843$426a74cc@news.free.fr> <46154952$0$23907$426a74cc@news.free.fr> Message-ID: <46158702$0$18849$426a74cc@news.free.fr> Sherm Pendley a ?crit : > Bruno Desthuilliers writes: > > >>Sherm Pendley a ?crit : >> >>In my book, it's huge classes and methods that are usually a smell of >>a design problem. > > > Obviously we're reading different books. Obviously. But I didn't gain this knowledge from books. FWIW, I'd be interested if you'd let us know about any book pretending that monster classes are good design !-) > But that's OK - I'm not on a crusade to convince everyone to work my way. > If "one class per file" doesn't work well for you, don't write that way. > All I'm saying is, what works well for you isn't necessarily what works > well for everyone. It seems that it works well for almost anyone having some real-world experience with languages like Python. Experience with C++, Java, ObjectPascal, (insert your favorite verbose low-level language here) may not apply here. From gandalf at designaproduct.biz Tue Apr 10 11:00:16 2007 From: gandalf at designaproduct.biz (Laszlo Nagy) Date: Tue, 10 Apr 2007 17:00:16 +0200 Subject: convert html entities into real chars Message-ID: <461BA680.7050805@designaproduct.biz> Hi, I would like to have a function that can convert '>' into '>', '&' into '&' etc. I could not find how to do it easily (I have a code snippet for the opposite). Thanks, Laszlo From rhamph at gmail.com Fri Apr 20 02:44:53 2007 From: rhamph at gmail.com (Rhamphoryncus) Date: 19 Apr 2007 23:44:53 -0700 Subject: Python's handling of unicode surrogates In-Reply-To: <4628532B.5060104@v.loewis.de> References: <4628532B.5060104@v.loewis.de> Message-ID: <1177051493.468698.176740@b75g2000hsg.googlegroups.com> (Sorry for the dupe, Martin. Gmail made it look like your reply was in private.) On 4/19/07, "Martin v. L?wis" wrote: > > Thoughts, from all you readers out there? For/against? > > See PEP 261. This things have all been discussed at that time, > and an explicit decision against what I think (*) your proposal is > was taken. If you want to, you can try to revert that > decision, but you would need to write a PEP. I don't believe this specific variant has been discussed. The change I propose would make indexes non-contiguous, making unicode technically not a sequence. I say that's a case for "practicality beats purity". Of course I'd appreciate any clarification before I bring it to python-3000. > Regards, > Martin > > (*) I don't fully understand your proposal. You say that you > want "gaps in [the string's] index", but I'm not sure what > that means. If you have a surrogate pair on index 4, would > it mean that s[5] does not exist, or would it mean that > s[5] is the character following the surrogate pair? Is > there any impact on the length of the string? Could it be > that len(s[k]) is 2 for some values of s and k? s[5] does not exist. You would get an IndexError indicating that it refers to the second half of a surrogate. The length of the string will not be changed. s[s.find(sub):] will not be changed, so long as sub is a well-formed unicode string. Nothing that properly handles unicode surrogates will be changed. len(s[k]) would be 2 if it involved a surrogate, yes. One character, two code units. The only code that will be changed is that which doesn't handle surrogates properly. Some will start working properly. Some (ie random.choice(u'\U00100000\uFFFF')) will fail explicitly (rather than silently). -- Adam Olsen, aka Rhamphoryncus From rNOSPAMon at flownet.com Sun Apr 22 14:42:10 2007 From: rNOSPAMon at flownet.com (Ron Garret) Date: Sun, 22 Apr 2007 11:42:10 -0700 Subject: Select weirdness References: Message-ID: I think I've figured out what's going on. First, here's the smoking gun: I changed the code as follows: class myHandler(StreamRequestHandler): def handle(self): print '>>>>>>>>>>>' while 1: sl = select([self.rfile],[],[],1)[0] print sl l = self.rfile.readline() if len(l)<3: break print l, pass (Rest of code is unchanged.) In other words, I select on the rfile object and added a timeout. Here's the result when I cut-and-paste an HTTP request: >>>>>>>>>>> [] GET /foo/baz HTTP/1.1 [] Accept: */* [] Accept-Language: en [] Accept-Encoding: gzip, deflate [] Cookie: c1=18:19:55.042196; c2=18:19:55.042508 [] User-Agent: Mozilla/5.0 (Macintosh; U; Intel Mac OS X; en) AppleWebKit/419 (KHTM [] L, like Gecko) Safari/419.3 [] Connection: keep-alive [] Host: localhost:8081 [] <<<<<<<<<<<< As you can see, the select call shows input available for a while (five lines) and then shows no input available despite the fact that there is manifestly still input available. The answer is obvious: select is looking only at the underlying socket, and not at the rfile buffers. So... is this a bug in select? Or a bug in my code? rg From maxime.p at gmail.com Sun Apr 1 17:31:23 2007 From: maxime.p at gmail.com (Ulysse) Date: 1 Apr 2007 14:31:23 -0700 Subject: Clean "Durty" strings Message-ID: <1175463083.135907.128480@y80g2000hsf.googlegroups.com> Hello, I need to clean the string like this : string = """ bonne mentalité mec!:) \n
bon pour info moi je suis un serial posteur arceleur dictateur ^^* \n
mais pour avoir des resultats probant il faut pas faire les mariolles, comme le "fondateur" de bvs krew \n mais pour avoir des resultats probant il faut pas faire les mariolles, comme le "fondateur" de bvs krew \n """ into : bonne mentalit? mec!:) bon pour info moi je suis un serial posteur arceleur dictateur ^^* mais pour avoir des resultats probant il faut pas faire les mariolles, comme le "fondateur" de bvs krew mais pour avoir des resultats probant il faut pas faire les mariolles, comme le "fondateur" de bvs krew To do this I wold like to use only strandard librairies. Thanks From beliavsky at aol.com Fri Apr 20 09:40:03 2007 From: beliavsky at aol.com (Beliavsky) Date: 20 Apr 2007 06:40:03 -0700 Subject: Python Feature Request: Explicit variable declarations In-Reply-To: <1176546078.934340.253810@y5g2000hsa.googlegroups.com> References: <1176546078.934340.253810@y5g2000hsa.googlegroups.com> Message-ID: <1177076403.252004.127640@p77g2000hsh.googlegroups.com> On Apr 14, 6:21 am, samj... at gmail.com wrote: > Hello. Please tell me whether this feature request is sane (and not > done before) for python so it can be posted to the python-dev mailing > list. I should say first that I am not a professional programmer with > too much technical knowledge. > > I would like to have something like the "option explicit" statement in > Visual Basic which turns on C-like checking for declaration of > variables. The thoughts of the inventor of Python on "Adding Optional Static Typing to Python" are at http://www.artima.com/weblogs/viewpost.jsp?thread=86641 . I wonder if the idea will be implemented in Python 3.0. From robert.rawlins at thinkbluemedia.co.uk Wed Apr 18 03:39:23 2007 From: robert.rawlins at thinkbluemedia.co.uk (Robert Rawlins - Think Blue) Date: Wed, 18 Apr 2007 08:39:23 +0100 Subject: Signals Message-ID: <002001c7818c$af280ab0$0d782010$@rawlins@thinkbluemedia.co.uk> Hello Chaps, I posted about this the other day but I'm still struggling to get any form of result from it. Basically I have the following piece of code, and according to its API is produces singals when particular events occur, but i have no idea how to list for events, I've tried all sorts of combinations using the signal module but haven't been able to get it working. #!/usr/bin/python import dbus, signal bus = dbus.SystemBus() obj = bus.get_object('org.bluez', '/org/bluez') obj = bus.get_object('org.bluez', '/org/bluez/hci0') adapter = dbus.Interface(obj, 'org.bluez.Adapter') adapter.DiscoverDevices() Now here is a copy of the API documentation that lists the signals thrown by the API, this is the one I'm trying to listen for. void RemoteDeviceFound(string address, uint32 class, int16 rssi) This signal will be send every time an inquiry result has been found by the service daemon. In general they only appear during a device discovery. Basically I'm just looking to run a function that will print those details to screen. Can anyone help with working out how to listen for this signal? I'd also like to know how i can keep the application running until I decided to stop it manually, as the DiscoverDevices() can take a while to complete and send out several RemoteDeviceFound() signals in that period. Thanks guys Rob -------------- next part -------------- An HTML attachment was scrubbed... URL: From irmen.NOSPAM at xs4all.nl Mon Apr 9 12:08:03 2007 From: irmen.NOSPAM at xs4all.nl (Irmen de Jong) Date: Mon, 09 Apr 2007 18:08:03 +0200 Subject: [offtopic?] problem with UDP broadcast on Windows XP In-Reply-To: References: <461a271c$0$323$e4fe514c@news.xs4all.nl> Message-ID: <461a6523$0$327$e4fe514c@news.xs4all.nl> Gabriel Genellina wrote: > Try running the service impersonating another user (not LOCAL_SERVICE, > the default). > You can change that from the service control panel. Alas, that didn't change anything. I made it run as a user account that has admin privileges even, and it still doesn't respond to the broadcasts. :-( --Irmen From mad.vijay at gmail.com Thu Apr 12 08:05:51 2007 From: mad.vijay at gmail.com (SamG) Date: 12 Apr 2007 05:05:51 -0700 Subject: Capturing the entry point of a script Message-ID: <1176379551.176232.272400@n76g2000hsh.googlegroups.com> If a function does not have main function defined and there is only a if __name__="__main__": how do i make a call to that using profile.runcall( ...) in my profiling script. Is there a way to find the entry point of a script and indentify it with module method. From kyosohma at gmail.com Wed Apr 11 10:34:07 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: 11 Apr 2007 07:34:07 -0700 Subject: run function in separate process In-Reply-To: <1176301427.183706.321920@n76g2000hsh.googlegroups.com> References: <1176301427.183706.321920@n76g2000hsh.googlegroups.com> Message-ID: <1176302047.122464.156680@o5g2000hsb.googlegroups.com> On Apr 11, 9:23 am, malkaro... at gmail.com wrote: > Hi everyone, > > I have written a function that runs functions in separate processes. I > hope you can help me improving it, and I would like to submit it to > the Python cookbook if its quality is good enough. > > I was writing a numerical program (using numpy) which uses huge > amounts of memory, the memory increasing with time. The program > structure was essentially: > > for radius in radii: > result = do_work(params) > > where do_work actually uses a large number of temporary arrays. The > variable params is large as well and is the result of computations > before the loop. > > After playing with gc for some time, trying to convince it to to > release the memory, I gave up. I will be happy, by the way, if > somebody points me to a web page/reference that says how to call a > function then reclaim the whole memory back in python. > > Meanwhile, the best that I could do is fork a process, compute the > results, and return them back to the parent process. This I > implemented in the following function, which is kinda working for me > now, but I am sure it can be much improved. There should be a better > way to return the result that a temporary file, for example. I > actually thought of posting this after noticing that the pypy project > had what I thought was a similar thing in their testing, but they > probably dealt with it differently in the autotest driver [1]; I am > not sure. > > Here is the function: > > def run_in_separate_process(f, *args, **kwds): > from os import tmpnam, fork, waitpid, remove > from sys import exit > from pickle import load, dump > from contextlib import closing > fname = tmpnam() > pid = fork() > if pid > 0: #parent > waitpid(pid, 0) # should have checked for correct finishing > with closing(file(fname)) as f: > result = load(f) > remove(fname) > return result > else: #child > result = f(*args, **kwds) > with closing(file(fname,'w')) as f: > dump(result, f) > exit(0) > > To be used as: > > for radius in radii: > result = run_in_separate_process (do_work, params) > > [1]http://codespeak.net/pipermail/pypy-dev/2006q3/003273.html > > Regards, > > Muhammad Alkarouri I found a post on a similar topic that looks like it may give you some ideas: http://mail.python.org/pipermail/python-list/2004-October/285400.html http://www.artima.com/forums/flat.jsp?forum=106&thread=174099 http://www.nabble.com/memory-manage-in-python-fu-t3386442.html http://www.thescripts.com/forum/thread620226.html Mike From soren.skou.nielsen at gmail.com Mon Apr 16 07:22:06 2007 From: soren.skou.nielsen at gmail.com (Soren) Date: 16 Apr 2007 04:22:06 -0700 Subject: Boost Problem! Boost.Build not found In-Reply-To: <1176720813.976821.237610@w1g2000hsg.googlegroups.com> References: <1176719740.525832.132610@e65g2000hsc.googlegroups.com> <1176720813.976821.237610@w1g2000hsg.googlegroups.com> Message-ID: <1176722526.231494.79730@l77g2000hsb.googlegroups.com> On 16 Apr., 12:53, "Rob Wolfe" wrote: > Soren wrote: > > Unable to load Boost.Build: could not find "boost-build.jam" > > --------------------------------------------------------------- > > Attempted search from C:\boost\boost_1_33_1\libs\python\example > > \tutorial up to t > > he root and in these directories from BOOST_BUILD_PATH and BOOST_ROOT: > > C:\boost\boost_1_ > > 33_1. > > Please consult the documentation at 'http://www.boost.org'. > > > Can anyone please tell me what I am doing wrong?? Theres no tutorial > > on how to make a boost-build.jam file.. and as I understand I don't > > need one as long as I set BOOST_BUILD_PATH .. > > Try to create boost-build.jam file like this: > > # boost-build.jam > boost-build C:\boost\boost_1_33_1\tools\build\v1 ; > > -- > HTH, > Rob Hi Rob, Thanks for answer! It did solve the error... but created a new one: C:\boost\boost_1_33_1\libs\python\example\tutorial>bjam -sTOOLS=vc-8_0 Unable to load Boost.Build: could not find build system. --------------------------------------------------------- C:\boost\boost_1_33_1\libs\python\example\boost-build.jam attempted to load the build system by invoking 'boost-build C:/boost/boost_1_33_1/tools/build/v1 ;' but we were unable to find "bootstrap.jam" in the specified directory or in BOOST_BUILD_PATH (searching C:\boost\boost_1_33_1, C:/boost/ boost_1_33_1/t ools/build/v1). What is boostrap.jam? I haven't seen that one mentioned in the short tutorial... Thanks!, Soren From gil.horen at gmail.com Wed Apr 4 07:24:43 2007 From: gil.horen at gmail.com (Gil_H) Date: 4 Apr 2007 04:24:43 -0700 Subject: Pexpect: SSH, Command and Password Message-ID: <1175685883.565899.282450@q75g2000hsh.googlegroups.com> Hi, I'm trying to run a script over unix on a remote machine. In order to automate it, the procedure requests the following: 1. Using SSH connection. 2. Operating a command on the remote machine. 3. Expecting password or (yes/no) request and authorize it. I get an error (I thing that it occures at the last part (3) of the password request). I don't have any errors when trying to operate the script without the last password. Here is the script: import pexpect import sys import re import os import getopt PROMPT = "\$|\%|\>" class SSH: def __init__(self, user, password, host): self.child = pexpect.spawn("ssh %s@%s"%(user, host)) i = self.child.expect(['assword:', r'yes/no'], timeout=120) if i==0: self.child.sendline(password) elif i==1: self.child.sendline("yes") self.child.expect("assword:", timeout=120) self.child.sendline(password) self.child.expect(PROMPT) def command(self, command, password): """send a command and return the response""" self.child.expect(PROMPT) self.child.sendline(command) j = self.child.expect(['assword:', r'yes/no'], timeout=120) if j==0: self.child.sendline(password) elif j==1: self.child.sendline("yes") self.child.expect("assword:", timeout=120) self.child.sendline(password) self.child.expect(PROMPT) # response = self.child.before # return response def close(self): """close the connection""" self.child.close() if __name__=="__main__": ssh = SSH(sys.argv[1], sys.argv[2], sys.argv[3]) command=sys.argv[4] print command print "Password: " + sys.argv[2] responce=ssh.command(command, sys.argv[2]) ssh.close() print responce I'm waiting for your ideas. Thanks, Gil H. From gagsl-py2 at yahoo.com.ar Thu Apr 12 18:58:11 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 12 Apr 2007 19:58:11 -0300 Subject: Custom Python Runtime References: <2NudnVn5jsm2QIvbnZ2dnUVZ_vqpnZ2d@comcast.com> Message-ID: En Thu, 12 Apr 2007 19:02:53 -0300, Jack escribi?: > It seems that pywintypes24.dll and pythoncom24.dll have to be in > C:\Windows\System32 directory. Otherwise I get an error. > Any way to get around that? Both are part of the pywin32 extensions, better ask on the python-win32 list: http://mail.python.org/mailman/listinfo/python-win32 You don't say which error you got, but abusing again my crystall ball, try this: http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnsetup/html/dlldanger1.asp -- Gabriel Genellina From attn.steven.kuo at gmail.com Thu Apr 19 19:26:17 2007 From: attn.steven.kuo at gmail.com (attn.steven.kuo at gmail.com) Date: 19 Apr 2007 16:26:17 -0700 Subject: multirember&co In-Reply-To: References: <1176768854.720234.23320@w1g2000hsg.googlegroups.com> <1176790588.024371.119360@n76g2000hsh.googlegroups.com> <1176850352.999231.79260@n59g2000hsh.googlegroups.com> <1176921030.330467.76860@o5g2000hsb.googlegroups.com> <1176925857.535835.130010@b58g2000hsg.googlegroups.com> <1177010211.252779.83620@y5g2000hsa.googlegroups.com> Message-ID: <1177025176.943890.252910@b75g2000hsg.googlegroups.com> On Apr 19, 3:37 pm, Anton Vredegoor wrote: > Anton Vredegoor wrote: > > Maybe this one is better? > > No, this one keeps generating output. > > But this one stops at least: > > from collections import deque > from itertools import chain, repeat > > def xsplitter(seq, pred): > Q = deque(),deque() > sentinel = object() > it = chain(seq,repeat(sentinel)) > def gen(p): > for x in it: > if x is sentinel: > while Q[p]: yield Q[p].popleft() > break > elif pred(x) == p: > while Q[p]: yield Q[p].popleft() > yield x > else: > Q[~p].append(x) > for x in gen(p): yield x > return gen(1),gen(0) > > def test(): > L = 1, 2, 3, 'a', 'a' > # L = 'a', 1, 2, 'a' > # L = 1, 'a', 3, 'a', 4, 5, 6, 'a' > it1, it2 = xsplitter(L, lambda x: x == 'a') > print it1.next() > print it2.next() > print it1.next() > print it2.next() > > if __name__=='__main__': > test() > > Are there any other cases this doesn't cover? > > A. This one gets the order wrong. With def test(): L = 1, 2, 3, 'a', 4, 'a', 5, 'a', 6, 'a' it1, it2 = xsplitter(L, lambda x: x == 'a') print it1.next() print it2.next() print it1.next() print it2.next() print it1.next() print it2.next() print it1.next() print it2.next() 5 will appear before 4. -- Regards, Steven From nagle at animats.com Fri Apr 20 15:19:18 2007 From: nagle at animats.com (John Nagle) Date: Fri, 20 Apr 2007 19:19:18 GMT Subject: Python un-plugging the Interpreter In-Reply-To: References: <005f01c782a3$ae84d710$fa936540@cisco.com> Message-ID: Steve Holden wrote: > Marc 'BlackJack' Rintsch wrote: > >> In , John Nagle wrote: >> >>> Many cases are easy. If a smart compiler sees >>> >>> for i in range(n) : >>> ... # something >>> >>> and there are no other assignments to "i", then it's clear that >>> "i" can be represented as an integer, without "boxing" into a >>> general object. >> >> >> How is it clear that `i` is restricted to integers? That works only if >> you assume `range` refers to the built-in `range()` function. So the >> smart compiler has to check all possible control flows up to this point >> and be sure `range` was not bound to something different. >> > That is, of course, exactly what a smart compiler would do. Only > nowadays it would quite possibly do it just-in-time (so I suppose you > might call it the run-time, though the boundary is continually getting > more blurred) rather than as the result of static analysis, so it would > *know* that the built-in generator had been called. That's always a question in compiler implementation. 99.99% of the time, "range" isn't redefined, and the optimization is a big win, so it's worth doing. With enough heavy machinery, you can make the hard cases work. Or you can disallow some things that aren't really that useful. Generally, this sort of thing is necessary if there's a legacy code base which uses that feature, and otherwise not. Scanning big databases of code for uses of wierd features is useful when making that decision. A good example at the CPU level is the ability to store into the code of a program that's running. This was a popular programming technique among some DOS programmers in the 1980s, and there's still some legacy code that uses it. Every IA-32 CPU supports this. And it wasn't easy to make that work. What happens when you store into code just about to be executed in a modern superscalar CPU is something like this. Execution is going along, with the instruction pipeline filled perhaps ten instructions ahead, with the next ten or so instructions decoded and ready to go. Several operations are in progress, perhaps a floating point operation or two and some integer operations, a few memory fetches are underway, and some memory stores are queued waiting for confirmation that everything is OK for them to be committted. "Commitment" works like a database commit; only when everything is clear for the results of an instruction to be accepted, and no bad cases have occured like an exception or a page fault, do the actual writes to memory occur. If some exception occurs, the state of the CPU has to be rolled back to just before the exception. So there's a back end on the CPU called the "retirement unit" that handles this finishing and cleanup process. So that's the basic architecture, incredibly oversimplified. So what happens when code stores into itself? The code stores into an instruction about to be executed, one that's already in the pipeline. The "retirement unit" detects a conflict between the store and the addresses in the instruction pipeline. There's hardware to handle this, but since it's a very rare event, it's not an optimized path in the CPU. So the retirement unit orders most of the CPU to do a stop and flush. Instruction fetching stops. The CPU stalls while all floating point operations and loads run to completion. The pipeline is run out, but none of its results are committed. Then the pipeline and all intermediate results are flushed, losing any pending work. Pending stores after the store into the code are flushed. Predecoded instructions are flushed (a big cost on an AMD CPU, which decodes a whole cache line at once). The whole CPU is backed up to just before the store into the code occurs. Only then can the store into the code be allowed to occur. That store is committed, done, and pushed out to cache. Next, the CPU execution engine restarts, as if from an interrupt. Instructions are reloaded from cache and decoded. The pipeline is refilled. The superscaler units crank up again, and finally, normal execution resumes. The whole thing has cost about as much time as handling an interrupt. Now, that's the x86 approach - allow all this to support legacy DOS code. On PowerPC, IBM simply disallowed it. You can't store into code; it's under memory protection. To change code, the OS must remove the executable mode from the page, load the memory with new code, reset the executable mode, and explictly tell the CPU to invalidate the instruction cache. This simplifies the CPU, and since there was no legacy code base, it wasn't a problem. You have to look at the legacy code base to decide if features like that are worth keeping. John Nagle From gagsl-py2 at yahoo.com.ar Thu Apr 26 02:00:10 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 26 Apr 2007 03:00:10 -0300 Subject: override settrace References: <1177477557.493519.124620@u32g2000prd.googlegroups.com> Message-ID: En Wed, 25 Apr 2007 02:05:57 -0300, Raja escribi?: > I want to override the sys.settrace() call, create a way to trace > the execution of a python program. Keep track of all objects created > and destroyed. Keep track of the call pattern throughout the execution > of the program and output a simplified "call graph" to standard out. > Please help me in this regard. Maybe you find easier to use one of the existing profiling tools: http://docs.python.org/lib/profile.html -- Gabriel Genellina From sgeiger at ncee.net Sun Apr 1 17:47:47 2007 From: sgeiger at ncee.net (Shane Geiger) Date: Sun, 01 Apr 2007 16:47:47 -0500 Subject: [Python-Dev] Python 3000 PEP: Postfix type declarations In-Reply-To: <460FAC2C.5020105@mediamonger.ch> References: <460FAC2C.5020105@mediamonger.ch> Message-ID: <46102883.4000704@ncee.net> OMG, I was starting to reconsider Ruby. Ma?l Benjamin Mettler wrote: >> Is this supposed to be a joke? >> > > First of April? Likely. > -- 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 cam.ac.uk at mh391.invalid Mon Apr 30 05:55:36 2007 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Mon, 30 Apr 2007 10:55:36 +0100 Subject: While we're talking about annoyances In-Reply-To: <1hxcm3o.19dhbys1wllx20N%aleax@mac.com> References: <1177837565.317999.244420@c35g2000hsg.googlegroups.com> <1177857049.938363.166170@p77g2000hsh.googlegroups.com> <1hxchgp.7sw7efb72rh2N%aleax@mac.com> <1hxcm3o.19dhbys1wllx20N%aleax@mac.com> Message-ID: Alex Martelli wrote: > Michael Hoffman wrote: > >> Alex Martelli wrote: >>> Arnaud Delobelle wrote: >>> ... >>>>>>> decorated.sort() >>> ... >>>>> def index(sequence): >>>>> return sorted(range(len(sequence)), key=sequence.__getitem__) >>> ... >>>> But really these two versions of rank are slower than the original one >>>> (as sorting a list is O(nlogn) whereas filling a table with >>>> precomputed values is O(n) ). >>> Wrong, because the original one also had a sort step, of course, so it >>> was also, inevitably, O(N log N) -- I've quoted the .sort step above. >> Well, counting the index() function that is called in both cases, the >> original rank() had one sort, but my version has two sorts. > > That doesn't affet the big-O behavior -- O(N log N) holds whether you > have one sort, or three, or twentyseven. I've taught programming classes before, and I would have had to fail anybody who misunderstood speed badly enough to claim that something repeating an O(N log N) algorithm 27 times was no faster than doing it once. ;-) As Arnaud points out, asymptotic behavior is not the same as speed. His original statement that the more recently proposed definitions of rank() are slower than the OP's may be correct. And if it's not, it's not because they're all O(N log N). -- Michael Hoffman From gagsl-py2 at yahoo.com.ar Wed Apr 18 20:01:27 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 18 Apr 2007 21:01:27 -0300 Subject: converting currency using locals References: <1a6pqx9mwzy6n$.1up65mccv8fm.dlg@40tude.net> Message-ID: En Wed, 18 Apr 2007 15:08:24 -0300, Grzegorz ?lusarek escribi?: > Hi all. I have situation that I have value that holds price and I must > show > this price using national specification(e.g. thousands_sep). Any idea how > this can be done under python 2.4.4? I saw that function format from > module > locals can format value with national specification, but this could be > done > only in python 2.5. Any solution for 2.4? > example what I want achieve: > value 24500.50 > Hungarian Price 24 500.50 > Romaniam Price 24.500.50 > Thanks for any help > Gregor Python 2.4.4 can handle thousands separator and grouping but not *specific* settings for monetary values. That is, when thousands_sep==mon_thousands_sep and grouping==mon_grouping and decimal_point==mon_decimal_point the following code works also for monetary values: (I've checked the 'hu' and 'ro' locales on my system and both have that property) Python 2.4.4 (#71, Oct 18 2006, 08:34:43) [MSC v.1310 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. py> import locale py> locale.setlocale(locale.LC_ALL, '') 'Spanish_Argentina.1252' py> help(locale.format) Help on function format in module locale: format(f, val, grouping=0) Formats a value in the same way that the % formatting would use, but takes the current locale into account. Grouping is applied if the third parameter is true. py> locale.format('%.2f', 1234567.1234, True) '1.234.567,12' -- Gabriel Genellina From bdesth.quelquechose at free.quelquepart.fr Fri Apr 13 17:45:07 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Fri, 13 Apr 2007 23:45:07 +0200 Subject: vocab question In-Reply-To: References: <461fe3d0$0$11935$426a74cc@news.free.fr> Message-ID: <461ff0ae$0$29118$426a74cc@news.free.fr> Steven Bethard a ?crit : > Bruno Desthuilliers wrote: > >> Alan G Isaac a ?crit : >> >>> Pardon the vocab question; >>> I'm not a computer science type. >>> According to the Reference Manual, >>> a class defintion has the structure:: >>> >>> classdef ::= "class" classname [inheritance] ":" suite >>> >>> What is the entire part before the suite called? >> >> >> A statement. In this case, a 'class' statement. > > > Actually, the class statement includes the suite as well. Well, technically, yes, but from a practical POV I'd say the "suite" is the class's body. Hmmm... Well, ok, you're right. Me go to bed. > As far as I > know, there's no official term for the first four elements of a class > statement. I'd probably call it the class statement header. > > STeVe From jstroud at mbi.ucla.edu Sun Apr 29 16:09:57 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Sun, 29 Apr 2007 13:09:57 -0700 Subject: Counting In-Reply-To: <1177873864.502180.283390@u30g2000hsc.googlegroups.com> References: <1177873864.502180.283390@u30g2000hsc.googlegroups.com> Message-ID: Andy wrote: > Hi, the file below will print all the keywords in a file and also the > line # of the keyword. What I couldn't figure out is to count those > keywords per line. For example - "Line #1 has 3 keywords" > > Can I do like - > > total[j] = total[j] + numwords(k) > "Line number %d has %d keywords" % (j, total[j]) > > Seems sort of "illegal" in Python? > > > > ------------------------------------------------- > import keyword, sys, string, fileinput > def numwords(s): > list = string.split(s) > return len(list) > > # Get the file name either from the command-line or the user > if len(sys.argv) != 2: > name = raw_input("Enter the file name: ") > else: > name = sys.argv[1] > > inp = open(name,"r") > linelist = inp.readlines() > total, words,lines = 0, 0, 0 > > for i in range(len(linelist)): > line = linelist[i] > tempwords = line.split() > for k in tempwords: > if keyword.iskeyword(k): > total = total + numwords(k) > j = i + 1 > print" The word * %s * belongs in line number: %d" % (k, > j) > > print "Total keywords in this file are: %d" %(total) > You probably want something that goes a little like this: for i,line in enumerate(linelist): for k in line.split(): if keyword.iskeyword(k): total += line.count(k) print "The word '%s' belongs in line num: %d" % (k, i+1) print "Total keyords are: %d" % total James From fuzzyman at gmail.com Wed Apr 4 18:48:46 2007 From: fuzzyman at gmail.com (Fuzzyman) Date: 4 Apr 2007 15:48:46 -0700 Subject: Why NOT only one class per file? In-Reply-To: <1175721799.714907.52770@o5g2000hsb.googlegroups.com> References: <1175721799.714907.52770@o5g2000hsb.googlegroups.com> Message-ID: <1175726926.150272.113420@d57g2000hsg.googlegroups.com> On Apr 4, 10:23 pm, "Chris Lasher" wrote: > A friend of mine with a programming background in Java and Perl places > each class in its own separate file in . I informed him that keeping > all related classes together in a single file is more in the Python > idiom than one file per class. He asked why, and frankly, his valid > question has me flummoxed. > Only tightly coupled (and short) classes and functions. It is better to keep modules as short as possible (and classes to), without being ridiculous. It is kind of obvious that keeping stub classes (exceptions for example) in the same file is a good thing. Diffing classes doesn't seem like a terribly good use-case: classes that are *that* similar badly need refactoring into less classes... Fuzzyman http://www.voidspace.org.uk/python/articles.shtml From kw at codebykevin.com Sat Apr 21 11:43:23 2007 From: kw at codebykevin.com (Kevin Walzer) Date: Sat, 21 Apr 2007 11:43:23 -0400 Subject: Tkinter wiki down? Message-ID: <462A311B.9070206@codebykevin.com> Jeff Epler's Tkinter wiki has been down for several days now: http://tkinter.unpythonic.net/wiki/FrontPage Anyone heard about when, or if, it will be restored? I've tried to contact Mr. Epler but have not yet heard back. The site has been the target of some heavy spam/spidering recently; I've taken a few hours to clean up lots of pages. My own concern is that I had posted some resources there on the assumption that it would be reasonably stable/permanent home for them; if that's not the case, I will being looking into other resources. -- Kevin Walzer Code by Kevin http://www.codebykevin.com From deets at nospam.web.de Tue Apr 24 07:10:38 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 24 Apr 2007 13:10:38 +0200 Subject: adjust References: <1177412489.683970.45320@u32g2000prd.googlegroups.com> Message-ID: <5966teF2ijvk7U1@mid.uni-berlin.de> saif.shakeel at gmail.com wrote: > Hi, > How do i right adjust my output using python.I need a output > something like this: > DID= 0x01,0x02,0x03,0x05,0x06,0x07,0x2B,0x30,0x31,0x4D,0x4E, > 0x51,0x52,0x53,0x55, > minlength= 3, 3, 4, 2, 10, 10, 40, 2, 150, 4, 1, > 2, 2, 1, 2, 1, 6, 3, 17, 1, > maxlength= 3, 3, 4, 2, 10, 10, 40, 2, 150, 4, 1, > 2, 2, 1, 2, 30, 6, 3, 17, 20 > > I am printing from a list, and the values shld print below each id > like shown. > Thx http://docs.python.org/lib/typesseq-strings.html Diez From fakeaddress at nowhere.org Sun Apr 1 16:16:35 2007 From: fakeaddress at nowhere.org (Bryan Olson) Date: Sun, 01 Apr 2007 20:16:35 GMT Subject: socket read timeout In-Reply-To: References: <17930.25631.86693.827473@montanaro.dyndns.org> <000e01c771d2$2f3dd240$03000080@hendrik> Message-ID: Steve Holden wrote: > Hendrik van Rooyen wrote: >> Are sockets full duplex? >> > Yes. But you have to use non-blocking calls in your application to use > them as full-duplex in your code. Hmmm... I'm missing something. Suppose I have one thread (or process) reading from a blocking-mode socket while another is writing to it? What stops it from being full duplex? -- --Bryan From horpner at yahoo.com Mon Apr 23 14:21:41 2007 From: horpner at yahoo.com (Neil Cerutti) Date: 23 Apr 2007 20:21:41 +0200 Subject: When are immutable tuples *essential*? Why can't you just use lists *everywhere* instead? References: <1177088796.622928.224890@d57g2000hsg.googlegroups.com> <1177089206.550423.288670@q75g2000hsh.googlegroups.com> <58sf33F2b1q8tU1@mid.individual.net> <1177103370.022138.110320@n59g2000hsh.googlegroups.com> <1177108560.660288.171890@n76g2000hsh.googlegroups.com> Message-ID: On 2007-04-23, Steve Holden wrote: > Neil Cerutti wrote: >> So the question becomes: Why do Python dictionaries require >> keys to be of an immutable type? > > Because otherwise people would expect to be able to use a list > to select a dictionary entry even after they'd modified > elements of the list after creating the dictionary entry. Which > they couldn't. So Python doesn't let them use lists. The interpreter explains it: "A list is not a hashable object." Choosing a hash table instead of some kind of balanced tree seems to be just an optimization. ;) -- Neil Cerutti From gagsl-py2 at yahoo.com.ar Wed Apr 11 16:10:50 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 11 Apr 2007 17:10:50 -0300 Subject: Reading the first line of a file (in a zipfile) References: <1176318822.811661.115730@q75g2000hsh.googlegroups.com> Message-ID: En Wed, 11 Apr 2007 16:13:42 -0300, escribi?: > Hi folks, > I am trying to read the first occurence of non-whitespace in a file, > within a zipfile. Here is my code: > > zipnames = glob.glob("*") > for zipname in zipnames: > z = zipfile.ZipFile(zipname, "r") > for filename in z.namelist(): > count = len(z.read(filename).split('\n')) > if fnmatch.fnmatch(filename, "*AUDIT*"): > test = filename.split(' ') > print 'File:', test[0], > bytes = z.read(filename) > print 'has', len(bytes), 'bytes' > print 'and', count, 'lines' > > The first line in the file I am examining will be a number followed by > more whitespace. Looks like I cannot split by whitespace? Your code does nothing with the first line on the file; you only split the *filename* on whitespace. And you extract the file twice. You don't even try to find "the first occurence of non-whitespace". Surely an example of file contents and what output you really expect from it would be adequate. -- Gabriel Genellina From max at alcyone.com Sun Apr 22 16:53:04 2007 From: max at alcyone.com (Erik Max Francis) Date: Sun, 22 Apr 2007 13:53:04 -0700 Subject: Vector classes In-Reply-To: <1177245233.573675.274580@n59g2000hsh.googlegroups.com> References: <1177245233.573675.274580@n59g2000hsh.googlegroups.com> Message-ID: Mizipzor wrote: > During my coding Ive found two vector classes on the internet. Ive > modified them both a little but the do both have advantages and > disadvantages. > > vector1: http://rafb.net/p/4FVdh699.html > vector2: http://rafb.net/p/0KShGu30.html > > With 1, I can typ vec.x and vec.y, very nice. With 2, I need to do > vec.vals[0] and vec.vals[1], which makes my eyes bleed. > > But with 2, I can create a vector by supplying a list of numbers as > arguments. And I can also do maths with numbers (ints/floats) and not > just vectors (something 1 forces me to do). > > Is there any way to combine the two? The ultimate would be if I > somehow could take vector2 and hook the member self.vals[0] to self.x > or something. There are also full-featured Vector and Matrix classes in the la.py module of ZOE: http://www.alcyone.com/software/zoe/ -- 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 Stretch a bow to the very full, / And you will wish you had stopped in time. -- Laotse, ca. 6th C. BC From python at rcn.com Mon Apr 30 03:37:41 2007 From: python at rcn.com (Raymond Hettinger) Date: 30 Apr 2007 00:37:41 -0700 Subject: fastest way to find the intersection of n lists of sets In-Reply-To: <1177890102.708578.70460@y5g2000hsa.googlegroups.com> References: <1177883328.835058.138990@p77g2000hsh.googlegroups.com> <1177890102.708578.70460@y5g2000hsa.googlegroups.com> Message-ID: <1177918661.205983.280140@e65g2000hsc.googlegroups.com> [Prateek] > The reason why I'm casting to a list first is because I found that > creating a long list which I convert to a set in a single operation is > faster (although probably less memory efficient - which I can deal > with) than doing all the unions. That would be a surprising result because set-to-set operations do not have to recompute hash values. Also, underneath-the-hood, both approaches share the exact same implementation for inserting new values one the hash value is known. If you've seen an unfavorable speed comparison, then you most likely had code that built new intermediate sets between step: common = s1 | s2 | s3 | s4 | s5 | s6 | s7 | s8 | s9 Instead, it is faster to build-up a single result set: common = set() for s in s1, s2, s3, s4, s5, s6, s7, s8, s9: common |= s Raymond Hettinger From schpok at gmail.com Fri Apr 20 10:54:13 2007 From: schpok at gmail.com (schpok at gmail.com) Date: 20 Apr 2007 07:54:13 -0700 Subject: pydoc and imported modules Message-ID: <1177080853.261895.224440@q75g2000hsh.googlegroups.com> When I "from foo import *" in my __init__.py, sometimes module foo's docs will be expanded in the pydocs. It seems to depend in what language foo was implemented. For example, if you "from math import *" in your __init__.py, you will see math's members will appear in the resulting pydocs, as though it's part of your module. The behavior is consistent across the C modules I am writing. However, if you "from foo import *" in your __init__.py, and foo is a python file (not a module written in C), foo's members don't appear in the resulting pydocs. This also seems to occur in some boost::python bindings. What is expected behavior? How do ensure foo's docs do or don't appear in help, regardless of their implementation language? Thanks, Schpok From bdesth.quelquechose at free.quelquepart.fr Thu Apr 5 19:58:58 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Fri, 06 Apr 2007 01:58:58 +0200 Subject: Why NOT only one class per file? In-Reply-To: References: <1175721799.714907.52770@o5g2000hsb.googlegroups.com> <46142acc$0$7532$426a34cc@news.free.fr> <4614b40e$0$26843$426a74cc@news.free.fr> <1175778276.603838.86500@l77g2000hsb.googlegroups.com> <2O9Rh.24647$uo3.24013@newssvr14.news.prodigy.net> <46154b8c$0$14532$426a34cc@news.free.fr> Message-ID: <4615844b$0$7529$426a74cc@news.free.fr> Steve Holden a ?crit : > Bruno Desthuilliers wrote: > >> John Nagle a ?crit : >> >>> Nate Finch wrote: > > [...] > >> >>> Interestingly, PHP breaks this model; PHP programs are web pages. >> >> >> Err... Actually, "web pages" *are* text files. And FWIW, in most php >> programs (at least the clean ones), the application logic is in >> separate files, and the 'rendering' code (views, templates, call them >> what you like) are seldom full html documents. > > > And it's perfectly possible to write a PHP program that isn't a web > page. It's just that PHP is such an awful language nobody chooses to do it. > > Perhaps I'm not being fair to PHP. It's just been pushed so far beyond > its original design limits that it's screamingly uncomfortable to use. original design ? Which original design ?-) From erikwickstrom at gmail.com Thu Apr 5 21:03:41 2007 From: erikwickstrom at gmail.com (erikcw) Date: 5 Apr 2007 18:03:41 -0700 Subject: Extract zip file from email attachment In-Reply-To: <65fge4-j15.ln1@athlon.my> References: <1175815907.434721.274190@w1g2000hsg.googlegroups.com> <65fge4-j15.ln1@athlon.my> Message-ID: <1175821421.265541.120440@w1g2000hsg.googlegroups.com> On Apr 5, 8:00 pm, hlubenow wrote: > erikcw wrote: > > Hi all, > > > I'm trying to extract zip file (containing an xml file) from an email > > so I can process it. But I'm running up against some brick walls. > > I've been googling and reading all afternoon, and can't seem to figure > > it out. > > > Here is what I have so far. > > > p = POP3("mail.server.com") > > print p.getwelcome() > > # authentication, etc. > > print p.user("USER") > > print p.pass_("PASS") > > print "This mailbox has %d messages, totaling %d bytes." % p.stat() > > msg_list = p.list() > > print msg_list > > if not msg_list[0].startswith('+OK'): > > # Handle error > > exit(1) > > > for msg in msg_list[1]: > > msg_num, _ = msg.split() > > resp = p.retr(msg_num) > > if resp[0].startswith('+OK'): > > #print resp, '=======================\n' > > #extract message body and attachment. > > parsed_msg = email.message_from_string('\n'.join(resp[1])) > > payload= parsed_msg.get_payload(decode=True) > > print payload #doesn't seem to work > > else: > > pass# Deal with error retrieving message. > > > How do I: > > a) retrieve the body of the email into a string so I can do some > > processing? (I can get at the header attributes without any trouble) > > b) retrieve the zip file attachment, and unzip into a string for xml > > processing? > > > Thanks so much for your help! > > Erik > > Hi, > > some weeks ago I wrote some code to extract attachments from emails. > It's not that long, so maybe it could be of help for you: > > ------------------------------------------- > > #!/usr/bin/env python > > import poplib > import email > import os > import sys > import string > > # > # attsave.py > # Check emails at PROVIDER for attachments and save them to SAVEDIR. > # > > PROVIDER = "pop.YourMailProvider.de" > USER = "YourUserName" > PASSWORD = "YourPassword" > > SAVEDIR = "/home/YourUserDirectory" > > def saveAttachment(mstring): > > filenames = [] > attachedcontents = [] > > msg = email.message_from_string(mstring) > > for part in msg.walk(): > > fn = part.get_filename() > > if fn <> None: > filenames.append(fn) > attachedcontents.append(part.get_payload()) > > for i in range(len(filenames)): > fp = file(SAVEDIR + "/" + filenames[i], "wb") > fp.write(attachedcontents[i]) > print 'Found and saved attachment "' + filenames[i] + '".' > fp.close() > > try: > client = poplib.POP3(PROVIDER) > except: > print "Error: Provider not found." > sys.exit(1) > > client.user(USER) > client.pass_(PASSWORD) > > anzahl_mails = len(client.list()[1]) > > for i in range(anzahl_mails): > lines = client.retr(i + 1)[1] > mailstring = string.join(lines, "\n") > saveAttachment(mailstring) > > client.quit() > > ------------------------------------------- > > See you > > H. Thanks H! I'm now able to get the name of the zip file, and the contents (is it still encoded?). I now need to be able to unzip the zip file into a string and get the body of the email into a string. Here is my updated code: p = POP3("mail.**********.com") print p.getwelcome() # authentication, etc. print p.user("USER") print p.pass_("PASS") print "This mailbox has %d messages, totaling %d bytes." % p.stat() msg_list = p.list() print msg_list if not msg_list[0].startswith('+OK'): # Handle error in listings exit(1) for msg in msg_list[1]: msg_num, _ = msg.split() resp = p.retr(msg_num) if resp[0].startswith('+OK'): #print resp, '=======================\n' parsed_msg = email.message_from_string('\n'.join(resp[1])) for part in parsed_msg.walk(): fn = part.get_filename() if fn <> None: fileObj = StringIO.StringIO() fileObj.write( part.get_payload() ) #attachment = zlib.decompress(part.get_payload()) #print zipfile.is_zipfile(fileObj) attachment = zipfile.ZipFile(fileObj) print fn, '\n', attachment payload= parsed_msg.get_payload(decode=True) print payload else: pass# Deal with error retrieving message. I get this error: Traceback (most recent call last): File "wa.py", line 208, in attachment = zipfile.ZipFile(fileObj) File "/usr/lib/python2.5/zipfile.py", line 346, in __init__ self._GetContents() File "/usr/lib/python2.5/zipfile.py", line 366, in _GetContents self._RealGetContents() File "/usr/lib/python2.5/zipfile.py", line 378, in _RealGetContents raise BadZipfile, "File is not a zip file" zipfile.BadZipfile: File is not a zip file Is the zip file still encoded? Or am I passing in the wrong arguments to the zipfile module? Thanks for your help! Erik From paddy3118 at googlemail.com Mon Apr 23 11:34:56 2007 From: paddy3118 at googlemail.com (Paddy) Date: 23 Apr 2007 08:34:56 -0700 Subject: python style guide inconsistencies In-Reply-To: References: Message-ID: <1177342496.421017.165960@y5g2000hsa.googlegroups.com> On Apr 22, 8:27 pm, Darren Dale wrote: > I was just searching for some guidance on how to name packages and modules, > and discovered some inconsistencies on thewww.python.org.http://www.python.org/doc/essays/styleguide.htmlsays "Module names can be > either MixedCase or lowercase." That page also refers to PEP 8 athttp://www.python.org/dev/peps/pep-0008/, which says "Modules should have > short, all-lowercase names. ... Python packages should also have short, > all-lowercase names ...". > > Which is most up to date? Is this the right place to point out that one of > those pages needs to be updated? > > Thanks, > Darren In addition to the other replies on your direct question, it is also not a good idea to have modules whose names only differ by case. - Paddy. From aisaac at american.edu Thu Apr 26 10:12:09 2007 From: aisaac at american.edu (Alan Isaac) Date: Thu, 26 Apr 2007 14:12:09 GMT Subject: Preferred Random Library References: Message-ID: "Robert Kern" wrote in message news:mailman.6978.1177567043.32031.python-list at python.org... > numpy.random does not implement jumpahead(). Which may be removed from the random API: http://www.python.org/dev/peps/pep-3100/#standard-library Cheers, Alan Isaac From carsten at uniqsys.com Fri Apr 27 15:52:41 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Fri, 27 Apr 2007 15:52:41 -0400 Subject: Memory addressing In-Reply-To: <1177702902.156596.52510@n35g2000prd.googlegroups.com> References: <1177702902.156596.52510@n35g2000prd.googlegroups.com> Message-ID: <1177703561.3416.27.camel@dot.uniqsys.com> On Fri, 2007-04-27 at 12:41 -0700, Simon Berube wrote: > Hi, > > I have a rather simple question for which I couldn't find an > answer. I noticed how a significant number of objects in Python return > a __repr__() string along the lines of : > > < Object at 0xXXXXXX> > > I find this notation quite convenient to avoid out of control > strings when using large arrays but I was wondering how you can use > the memory address for assigning a new object. You can't. > In c, one could simple have a pointer to that memory address and > voila, you have a new object you can analyze however it seems like > python is allergic to direct memory manipulation. For good reason. Python is not C. > Hence, I was wondering what is the correct way to go about obtaining > objects returned in such a fashion? What am I going wrong or what am I > not getting? What is the actual problem you're trying to solve? -Carsten From bdesth.quelquechose at free.quelquepart.fr Mon Apr 2 15:36:36 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Mon, 02 Apr 2007 21:36:36 +0200 Subject: How can i compare a string which is non null and empty In-Reply-To: <1175469766.979636.65020@e65g2000hsc.googlegroups.com> References: <1175469766.979636.65020@e65g2000hsc.googlegroups.com> Message-ID: <46115267$0$2104$426a74cc@news.free.fr> Plissken.s at gmail.com a ?crit : > Hi, > > how can i compare a string which is non null and empty? Compare with what ?-) > > i look thru the string methods here, but cant find one which does it? > > http://docs.python.org/lib/string-methods.html#string-methods > > In java,I do this: > if (str != null) && (!str.equals("")) .... > > how can i do that in python? > 1/ don't use 'str' as an identifier as it will shadow the builtin str type. 2/ just test: if some_str: # code here In a boolean context, both the None object (the closer equivalent to Java's 'null') and an empty string will eval to False (FWIW, so will do an empty list, an empty tuple, an empty set, an empty dict, and a numeric zero). FWIW, Python allows (and encourage where it makes sens) operator overloading. cf: http://docs.python.org/ref/specialnames.html HTH From cam.ac.uk at mh391.invalid Fri Apr 27 04:39:37 2007 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Fri, 27 Apr 2007 09:39:37 +0100 Subject: List objects are un-hashable In-Reply-To: <1177660237.470851.170200@s33g2000prh.googlegroups.com> References: <1177660237.470851.170200@s33g2000prh.googlegroups.com> Message-ID: Andy wrote: > Hi, I'm trying to search and print any no# of Python keywords present > in a text file (say - foo.txt), and getting the above error. Sad for > not being able to decipher such a simple problem (I can come up with > other ways - but want to fix this one FFS). It helps a lot of if you post the traceback with your problem. The line it occurred on is crucial for debugging. But I will use my psychic debugger which tells me that the error is here: > if keyword.iskeyword(tempwords): tempwords is a list. You need to iterate over the contents of the list and run keyword.iskeyword() for each one. Here's an example for Python 2.5. I've cleaned up some extra lines of code that didn't have any eventual effects in your current implementation from __future__ import with_statement import keyword INFILENAME = "foo.txt" with open(INFILENAME) as infile: for line in infile: words = line.split() for word in words: if keyword.iskeyword(word): print word This will print multiple lines per input line. If you wanted one line per input line then try: with open(INFILENAME) as infile: for line in infile: words = line.split() print " ".join(word for word in words if keyword.iskeyword(word)) -- Michael Hoffman From al at taslab.com Wed Apr 25 11:53:57 2007 From: al at taslab.com (Alex Taslab) Date: Wed, 25 Apr 2007 17:53:57 +0200 Subject: key detect Message-ID: <1177516437.6587.21.camel@pktbl> Hi everybody, does anyone know how to detect a key press from a keyboard. Well I do know how to do that, but i need to detect just one press and ignore the others. I mean, my program checks an input from the outside (a sensor) and i emulate that signal as a keypress, but the sensor doesn`t send the signal as a unique pulse y just keeps sending signal during some seconds, so that is like to be pressing one key for a period of time. How can i take that first press of a key and ignore the others? I am using pygtk. thanks everybody! From gagsl-py2 at yahoo.com.ar Thu Apr 12 00:50:00 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 12 Apr 2007 01:50:00 -0300 Subject: python regular expression help References: <138221.90891.qm@web58906.mail.re1.yahoo.com> Message-ID: En Wed, 11 Apr 2007 23:14:01 -0300, Qilong Ren escribi?: > Thanks for reply. That actually is not what I want. Strings I am dealing > with may look like this: > s = 'a = 4.5 b = 'h' 'd' c = 4.5 3.5' > What I want is > a = 4.5 > b = 'h' 'd' > c = 4.5 3.5 That's a bit tricky. You have LHS = RHS where RHS includes all the following text *except* the very next word before the following = (which is the LHS of the next expression). Or something like that :) py> import re py> s = "a = 4.5 b = 'h' 'd' c = 4.5 3.5" py> r = re.compile(r"\w+\s*=\s*.*?(?=\w+\s*=|$)") py> for item in r.findall(s): ... print item ... a = 4.5 b = 'h' 'd' c = 4.5 3.5 -- Gabriel Genellina From bcwhite at pobox.com Fri Apr 20 15:51:49 2007 From: bcwhite at pobox.com (bcwhite at pobox.com) Date: 20 Apr 2007 12:51:49 -0700 Subject: How To Find Currently Selected Tile.Notebook Tab? In-Reply-To: <315d0$46282bdf$4275d90a$28375@FUSE.NET> References: <1177035392.983733.68240@n76g2000hsh.googlegroups.com> <315d0$46282bdf$4275d90a$28375@FUSE.NET> Message-ID: <1177098709.188440.103610@e65g2000hsc.googlegroups.com> > > How can I determine what tab is currently selected in a Tile.Notebook > > widget? > > > The best suggestion I've been able to find via Google is > > "mynotebook.index('current')", but that gets an exception from Tcl. > > How about > > mynotebook.index.current() No good: AttributeError: 'function' object has no attribute 'current' I tried "mynotebook.index().current()", too, but get a different error. -- Brian From jstroud at mbi.ucla.edu Thu Apr 5 01:19:14 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Wed, 04 Apr 2007 22:19:14 -0700 Subject: Prevent Modification of Script? In-Reply-To: <1175743177.489242.214700@w1g2000hsg.googlegroups.com> References: <1175735097.856840.177510@e65g2000hsc.googlegroups.com> <1175743177.489242.214700@w1g2000hsg.googlegroups.com> Message-ID: ts-dev wrote: > On Apr 4, 6:10 pm, Michael Ekstrand wrote: > >>One significant factor: are you worried about other >>users on your systems (or other users who share systems with you under a >>third party's control), or are you worried about what people will do on >>their own systems? > > > Michael, Ben & others: > The short answer is others on a shared system, or malware that could > modify the scripts. > > I'm new to python programming and there are just some paradigms I'm > having trouble grasping. > If the scripts can be modified (very easily), how can the application > be trusted? > > i.e. If its an address book, then it would be trivial for malware to > modify the script to override data or send it somewhere else... > It would also seem like it makes user authentication through a > password/ username, or encryption useless. The script could easily be > modified to by-pass authentication and encryption could be disabled. > > Please correct any wrong assumptions that I might be making.. > > In a compiled application its not impossible to by pass the code.. but > its not so easy. Perhaps this is just a side-effect of being a > scripted language - not a flaw, just me trying to use it for something > its not well suited for. > > - Kiel > You are worrying a little too much. Lets say you are genuinely worried about malware, for example. To justify this worry, answer these questions: 1. Who in the world would take the time to write malware targeted at your application specifically? 2. What value does your application have that would warrant such effort? 3. Would it not be worth a malware writer's troubles to focus on an easy target that offers more rewards, like say, Microsoft Crapware 3000, or whatever they are selling these days? 4. Are you so technically proficient at writing streamlined and transparent code that a malware author will find your code an easy target, especially if you distribute it as bytecode? 5. Could you not just md5sum the bytecode and check it from within a launcher against a value on a server somewhere? How many barriers would a malware writer need to circumvent to foil this protection scheme? Again, would it be worth his troubles in fame, fortune, or the knowledge that he did a good job? 6-7000. Etc. Write your program in the language most suited for it and, when you hit it big, hire some security experts. James From kyosohma at gmail.com Thu Apr 19 13:38:04 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: 19 Apr 2007 10:38:04 -0700 Subject: Relative import problem In-Reply-To: References: Message-ID: <1177004284.859778.161970@l77g2000hsb.googlegroups.com> On Apr 19, 11:54 am, "Jorgen Bodde" wrote: > Hi all, > > I want to structure my app so that I have two dirs like; > > obj/{object files} > > gui/{gui files} > > Here comes the catch. From the GUI dir, I would like to access the obj > submodule path. I need to go one dir back.. I read there was something > like from .. import x in python 2.5 so that I could access my obj dir > from a lower level, but I have problems getting this to work. > > Example; > > In the main dir I have; > > main.py: > -------- > import gui > > gui.gui.startme() > -------- > > In the obj dir I have; > > obj/obj.py > --------- > > def start(): > print 'Started OBJ' > --------- > > In the GUI dir I have > > gui/gui.py > --------- > from .. import obj > > def start(): > obj.obj.start() > --------- > > This does not work. It gives me; > > D:\personal\src\GuitarPortfolio\tmp>python start.py > Traceback (most recent call last): > File "start.py", line 4, in > gui.gui.start() > AttributeError: 'module' object has no attribute 'gui' > > Am I shooting myself in the foot by trying to structure? Or are there > better more elegant ways? > > Regards, > - Jorgen I'm not finding much info on this subject. But here's the most interesting links I've found as of yet: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/456362 http://www.thescripts.com/forum/thread549516.html http://www.thescripts.com/forum/thread42319.html http://docs.python.org/tut/node8.html Dunno if any of these will help you though. Sorry. Mike From matthiasjanes at gmx.net Wed Apr 11 08:58:25 2007 From: matthiasjanes at gmx.net (matthiasjanes at gmx.net) Date: 11 Apr 2007 05:58:25 -0700 Subject: THREADS use 100 % CPU all the time In-Reply-To: <1176291417.888693.107050@w1g2000hsg.googlegroups.com> References: <1176284321.528102.112740@o5g2000hsb.googlegroups.com> <1176291417.888693.107050@w1g2000hsg.googlegroups.com> Message-ID: <1176296305.384526.266350@y80g2000hsf.googlegroups.com> On Apr 11, 1:36 pm, "A.B., Khalid" wrote: > On Apr 11, 2:38 am, matthiasja... at gmx.net wrote: > > > > > Hi all, > > > I have a application where I use different threads. actually all is > > working - BUT I just discovered that the [b]CPU is always 100 % [/ > > b]used. > > > on the 32-bit machine athlon XP, as well as on the amd 64-bit AMD > > Athlon(TM) 64 X2 Dual-Core. > > > I have to admit I'm not used to threads. I actually use a thirdparty > > scheduler [url]http://www.webwareforpython.org/TaskKit/Docs/Source/ > > Docs/TaskKit.Scheduler.html[/url] > > but I checked and a very simple exampe with threading gives me also > > all the time 100% CPU. > > > [code] > > > import threading, time > > > class TestThread ( threading.Thread ): > > def run ( self ): > > print 'TEST' > > > t = TestThread() > > t.start() > > > while (True): > > pass > > > [/code] > > > Does anyone know how to run this without consuming all CPU. > > > regards, > > > MJ > > You need your program to sleep a while to allow a switch to other > tasks. Like so: > > ### > import threading, time > > class TestThread(threading.Thread): > def run(self): > print 'TEST' > > t = TestThread() > t.start() > > while (True): > time.sleep(0.01) > pass > ### > > Regards Thanks a lot both of you. MJ From antroy at gmail.com Fri Apr 27 04:27:47 2007 From: antroy at gmail.com (Ant) Date: 27 Apr 2007 01:27:47 -0700 Subject: List objects are un-hashable In-Reply-To: <1177662217.626642.60610@r3g2000prh.googlegroups.com> References: <1177660237.470851.170200@s33g2000prh.googlegroups.com> <1177661758.725027.101430@r30g2000prh.googlegroups.com> <1177662217.626642.60610@r3g2000prh.googlegroups.com> Message-ID: <1177662467.140335.165050@c18g2000prb.googlegroups.com> > I think it should be: > > if keyword.iskeyword(k): > print k Whoops - yes of course! From mcfletch at vrplumber.com Thu Apr 5 14:08:47 2007 From: mcfletch at vrplumber.com (Mike C. Fletcher) Date: Thu, 05 Apr 2007 14:08:47 -0400 Subject: PyDispatcher question In-Reply-To: <11e49df10704051046p65ac623fqcae6d3a010a7e415@mail.gmail.com> References: <11e49df10704051046p65ac623fqcae6d3a010a7e415@mail.gmail.com> Message-ID: <46153B2F.5020305@vrplumber.com> Jorgen Bodde wrote: > Hi all, > > Hopefully someone can help me. I am fairly new to Python, and I am > looking into PyDispatcher. I am familiar with the C++ sigslot variant, > and I wonder how similar PyDispatches is. I run in to the following > 'problem' (pseudo code, untested here) > Here's some real code... from pydispatch import dispatcher import gc class X(object): def __init__( self ): dispatcher.connect( self.someSignal, signal=1 ) def someSignal( self ): print 'hello world' obj = X() dispatcher.send( signal= 1 ) del obj #gc.collect() dispatcher.send( signal= 1 ) This will print out only one "hello world" on my Python 2.5 Gentoo machine (it should work the same on any recent Python). Basically your python shell will tend to keep around an extra copy of the X instance until you get rid of it explicitly, and that's what keeps the object "live" and receiving signals if you try the code in the shell. PyDispatcher is designed so that, by default, when the object goes away the registration is removed. It uses the weakref module to do this, rather than __del__ methods, to avoid garbage cycles, btw. HTH, Mike -- ________________________________________________ Mike C. Fletcher Designer, VR Plumber, Coder http://www.vrplumber.com http://blog.vrplumber.com From titogarcia_nospamplease_ at gmail.com Mon Apr 9 11:32:43 2007 From: titogarcia_nospamplease_ at gmail.com (=?ISO-8859-2?Q?Ernesto_Garc=EDa_Garc=EDa?=) Date: Mon, 09 Apr 2007 17:32:43 +0200 Subject: Cascading ifs In-Reply-To: References: Message-ID: > tbl = [(my_regex, doSomething), (my_regex2, doSomething2), (my_regex3, > doSomething3)] > for regex, fun in tbl: > match = regexp.match(line) > if match: > fun(line) > break Thank you for the idea. This is a bit more difficult when functions need to work with a common context, but in that case I could store the context in an object and use the object's methods. Thanks, Ernesto From aleax at mac.com Tue Apr 24 10:56:50 2007 From: aleax at mac.com (Alex Martelli) Date: Tue, 24 Apr 2007 07:56:50 -0700 Subject: Would You Write Python Articles or Screencasts for Money? References: <462DCCE6.9060908@taupro.com> Message-ID: <1hx2dvj.10ek1v51noh1otN%aleax@mac.com> Steve Holden wrote: ... > used to provide incentives to improve the available information about > Python, and possibly even the software that's available in Python. I > have undertaken to make a proposal to the PSF Board for an incentive > scheme. So please let me have your ideas. My main suggestion here is to declare PSF members to be "not eligible" for these cash awards (although it would be perfectly fine to award ourselves nice pieces of parchment, or PSF hats or other schwag, in recognition of such good work, I'd suggest giving cash awards only to non-members). When cash is involved, it's important to avoid even the slightest hint of a suggestion of a suspicion of a conflict of interest; that, I guess, is why firms that run contests with cash prizes always declare employees and their families "not eligible", and why I think the PSF should do likewise in this case. Alex From steven.bethard at gmail.com Tue Apr 17 11:25:00 2007 From: steven.bethard at gmail.com (Steven Bethard) Date: Tue, 17 Apr 2007 09:25:00 -0600 Subject: rewrite for achieving speedup In-Reply-To: References: <1176821334.217154.36350@y80g2000hsf.googlegroups.com> Message-ID: <4umdnWdZhZNVe7nbnZ2dnUVZ_gGdnZ2d@comcast.com> Steve Holden wrote: > Johnny Blonde wrote: >> Hello Group! >> >> I really tried hard for two hours to rewrite the following expression >> (python 2.4): >> -------------------------- >> teilnehmer = [] >> for r in Reisen.select(AND(Reisen.q.RESVON <= datum, Reisen.q.RESBIS >>> = datum)): >> for g in r.BUCHUNGEN: >> for t in g.aktiveTeilnehmer: >> teilnehmer.append(t) >> -------------------------- >> >> to something like >> -------------------------- >> teilnehmer = [x for x in ........] >> -------------------------- >> >> Reisen is a SQLObject class, Reisen.select(...), aktiveTeilnehmer and >> BUCHUNGEN all are of the type SelectResults. >> >> unfortunately i just can?t figure it out to make it work. >> i hope someone maybe can help me? >> >> I hope to gain performance by rewriting it... >> >> Thanks a lot for your help! >> > >>> lt = [[[1,2,3], [2,3,4]], [[3,4,5], [4,5,6]]] > >>> lf = [c for a in lt for b in a for c in b] > >>> lf > [1, 2, 3, 2, 3, 4, 3, 4, 5, 4, 5, 6] > >>> > > Untested: > > teilnehmer = [t for r in Reisen.select(AND(Reisen.q.RESVON <= datum, > reisen.q.RESBIS >= datum)) for g in r.BUCHUNGEN for t in > g.aktiveTeilnehmer] Note also that you can probably get most of the speedup above by binding the append method to a function-local name:: teilnehmer = [] append = teilnehmer.append for r in Reisen.select(...): for g in r.BUCHUNGEN: for t in g.aktiveTeilnehmer: append(t) That's pretty much all a list comprehension is doing anyway. STeVe From duncan.booth at invalid.invalid Mon Apr 30 07:21:18 2007 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 30 Apr 2007 11:21:18 GMT Subject: if __name__ == 'main': & passing an arg to a class object References: <1177708104.277756.245360@t38g2000prd.googlegroups.com> Message-ID: Bart Willems wrote: > gtb wrote: >> appear at the end of many examples I see. Is this to cause a .class >> file to be generated? > This might be obvious, but no one else mentioned it: the Python > interpreter cannot execute code that it hasn't compiled yet, which is > why the "if __name__ ..." code is always at the end of the module - to > guarantee that the entire file is scanned first. This is somewhat misleading: the entire file is always compiled before any of it is executed (to see this try putting a syntax error on the last line: the syntax error will prevent any lines in the file being executed). A more accurate statement would be to say that executing code cannot access any names which have not yet been defined. The code for functions and classes is compiled first with everything else, but the function or class objects are not created, and the relevant names are not bound until the appropriate 'def' or 'class' statement is executed. From syedamjad_a at yahoo.com Tue Apr 24 10:43:35 2007 From: syedamjad_a at yahoo.com (CSUIDL PROGRAMMEr) Date: 24 Apr 2007 07:43:35 -0700 Subject: defining user exceptions Message-ID: <1177425815.272197.258400@t39g2000prd.googlegroups.com> I am trying to write a user defined exception that will catch for failed dependencies when a rpm is installed try: rpm -ivh xxx.rpm --force; except RPMError: print RPM failed dependency Can some one tell me how to define this RPMError. I looked at python docs but they were not useful. From cfriedalek at gmail.com Thu Apr 19 19:13:43 2007 From: cfriedalek at gmail.com (cfriedalek at gmail.com) Date: 19 Apr 2007 16:13:43 -0700 Subject: matplotlib basic question In-Reply-To: <1177016327.543985.34500@o5g2000hsb.googlegroups.com> References: <1177016327.543985.34500@o5g2000hsb.googlegroups.com> Message-ID: <1177024423.742103.194750@p77g2000hsh.googlegroups.com> > So, first off, what's up with the [ at 0x017C38C8>] line that shows up after my plot command? And second, > when I call show(), a new figure pops up with my sin wave -- seems all > right, yes? But I'm not given another >>> prompt in IDLE until or > unless I close the figure that popped up with the show() call. This may not be strictly correct but thats a reference to the plot instance which is subsequently passed to show(). If you don't want to see it put a semicolon at the end of your command eg. plot(range(5)); The issue with IDLE is to due with lack of connection between the python interpreter event loop and the event loop of matplotlib (I think). For me the solution was to install the ipython shell (http:// ipython.scipy.org/moin/). If you run ipython with the -pylab flag then you can matplotlib interactively. For example plot(range(5),'bo') show() clf() plot([1,2,3,4,5],range(0,10,2),'r-') (no need for another show() command since the graphics display is already visible ... unless of course I deleted it in between plot commands) hth From S.Mientki-nospam at mailbox.kun.nl Sat Apr 28 16:08:32 2007 From: S.Mientki-nospam at mailbox.kun.nl (Stef Mientki) Date: Sat, 28 Apr 2007 22:08:32 +0200 Subject: My Python annoyances In-Reply-To: <1177790269.523160.276060@l77g2000hsb.googlegroups.com> References: <1177790269.523160.276060@l77g2000hsb.googlegroups.com> Message-ID: <31af9$4633a930$d443bb3a$15803@news.speedlinq.nl> > Programming should be more difficult than this - otherwise, how can > programmers be respected by the common folks? the answer is very simple (even more simple than Python ;-) ... ... create what common folks ask for !! cheers, Stef Mientki From dsampson at NRCan.gc.ca Thu Apr 12 14:11:38 2007 From: dsampson at NRCan.gc.ca (Sampson, David) Date: Thu, 12 Apr 2007 14:11:38 -0400 Subject: VB6 To Python Message-ID: <2FAA57395C1F914DB27CAA4C376058F202434C96@S0-OTT-X2.nrn.nrcan.gc.ca> Hey Folks, I'm working towards understanding python and one of my hopes is to convert an internal program from VB6 to python. Partialy to learn python more, and partialy because VB6 is a dead language and partialy because I am trying to encourage the use of open source solutions. I am wondering if anyone out there has personal experience converting VB6 code to Python code. I have come across some old and defunct projects that created scripts and such. Unfortunately this often relies on complete separation of logic from GUI. Unfortunately the software was inherrited and secondly I am not that good of a programmer to know how to separate the two all the time. MY DREAM: In an ideal world I would like * the code and logic to be python * The GUI to by Gnome 2 * I would like to use the GLADE Gui toolkit (and libs) for the GUI. * I would like to avoid a code rewrite. Any experience or insight would be great. Cheers -------------- next part -------------- An HTML attachment was scrubbed... URL: From aleax at mac.com Fri Apr 27 01:15:48 2007 From: aleax at mac.com (Alex Martelli) Date: Thu, 26 Apr 2007 22:15:48 -0700 Subject: Python keywords References: <1177599386.204340.65680@r35g2000prh.googlegroups.com> Message-ID: <1hx76wb.nfgwat181d8goN%aleax@mac.com> gtb wrote: > Have done some searching but have not found a place where I can look > up python keywords. >>> import keyword >>> keyword.kwlist ['and', 'as', 'assert', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'exec', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'not', 'or', 'pass', 'print', 'raise', 'return', 'try', 'while', 'with', 'yield'] call help(kw) from an interpreter prompt for any one of these values for more information. E.g., >>> help('and') will give you section 5.1 (Boolean operations), all the way to help('yield') giving 6.8 (The yield statement). Some of the keywords have no specific info, e.g. help('as') will not be very informative:-). Alex From dillonco at comcast.net Thu Apr 19 17:55:46 2007 From: dillonco at comcast.net (DillonCo) Date: Thu, 19 Apr 2007 17:55:46 -0400 Subject: Python un-plugging the Interpreter In-Reply-To: <005f01c782a3$ae84d710$fa936540@cisco.com> References: <005f01c782a3$ae84d710$fa936540@cisco.com> Message-ID: <200704191755.46237.dillonco@comcast.net> On Thursday 19 April 2007, S.Mohideen wrote: > 2) Making the program to run at par with the compiled version of C/C++ > program- this is the main benefit which can be derived out of this. Python is a rather slow language because of how it works. Even if you got rid of the VM (as noted by others, Python compiles into VM code), Python would still be slower than C, and probably by a large margin. Look at the "+" operator for instance. In C, this translates directly to and add instruction that takes something like 1 cycle. Very fast. In python, it translates (very) roughly to: def add(a,b): if issubclass(b,a): try: return b.__dict__['__radd__'](a) catch: return a.__dict__['__add__'](b) else: try: return a.__dict__['__add__'](b) catch: return b.__dict__['__radd__'](a) So for 2+2, you'll have to go through "issubclass", then look up '__add__' from 2.__dict__ (it's there), then execute the function before you finally get to the "add" instruction. So ultimately, you pay for he flexibility. Sure, you can kind of optimize builtin operations (like "2+2"), but even with something like a 'PPU' (Python Processing Unit) that had hardware dictionary support (<5ish cycles per lookup) you'll still be an order of magnitude off C easily. It's not hopeless though. With an insanely clever JIT VM and lots of caching, it could be possible to get Python within an order of magnitude of C, but the demand isn't really there. Things that need to be fast can be written easily enough in C libraries. I think Pypy, which is an implementation of Python in Python, may be headed in that direction (clever JIT), but it's a long way off to say the least. From ivlenin at gmail.com Wed Apr 18 02:13:39 2007 From: ivlenin at gmail.com (I V) Date: Wed, 18 Apr 2007 06:13:39 +0000 (UTC) Subject: What makes an iterator an iterator? References: Message-ID: On Wed, 18 Apr 2007 15:39:22 +1000, Steven D'Aprano wrote: > I thought that an iterator was any object that follows the iterator > protocol, that is, it has a next() method and an __iter__() method. ... > class Parrot(object): ... > def __init__(self): > self.next = self._next() self.next isn't a method here, it's a generator. You could do: def __init__(self): self.next = self._next().next But, having tested, that doesn't appear to work either - I think this is because, again, self.next is not strictly a method, it's an attribute that happens to be callable. The python manual gives you a possible solution: ---QUOTE http://docs.python.org/lib/typeiter.html --- Python's generators provide a convenient way to implement the iterator protocol. If a container object's __iter__() method is implemented as a generator, it will automatically return an iterator object (technically, a generator object) supplying the __iter__() and next() methods. ---END QUOTE--- i.e., just rename your _next function to __iter__ . Your class won't itself be an iterator, but it will be usable in for statements and so one, and convertable to an iterator with the iter builtin. From steve at holdenweb.com Tue Apr 3 13:32:47 2007 From: steve at holdenweb.com (Steve Holden) Date: Tue, 03 Apr 2007 13:32:47 -0400 Subject: How can I kill a running thread when exiting from __main__ In-Reply-To: <1175620919.478708.292150@p77g2000hsh.googlegroups.com> References: <1175620919.478708.292150@p77g2000hsh.googlegroups.com> Message-ID: care02 at gmail.com wrote: > Hi! > > I have the following problem: I have written a short Python server > that creates an indefinite simulation thread that I want to kill when > quitting (Ctrl-C) from Python. Googling around has not given me any > hints on how to cleanly kill running threads before exiting. Any help > is appreciated! > > Carl > > ### CODE EXTRACT ### > > import pythoncom > > class QueueThread( threading.Thread): > def __init__(self, command): > threading.Thread.__init__(self) > self.command = command > > def run(self): > pythoncom.CoInitialize() > try: > object = Dispatch('application') > execute = getattr(object, 'Execute') > execute(self.command ) > finally: > object = None > pythoncom.CoUnitialize() > > queuethread = QueueThread("queuehandler") > queuethread.setDaemon(True) > queuethread.start() > > ## How can I kill "queuethread" when exiting (Ctrl-C)? > The only way to do this is to have the thread regularly examine a "please quit" flag that is set from the main thread when termination is required. There have been many suggestions to allow external forced termination of threads, but this is impossible to specify in a clean way that is both platform-independent and reliable, so it's not likely to happen. 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 tim.leslie at gmail.com Sun Apr 15 08:23:27 2007 From: tim.leslie at gmail.com (Tim Leslie) Date: Sun, 15 Apr 2007 22:23:27 +1000 Subject: function with list argument defaulting to [] - what's going on here??? In-Reply-To: <1176607242.441196.140310@n76g2000hsh.googlegroups.com> References: <46217e8f$0$19437$4c368faf@roadrunner.com> <1176607242.441196.140310@n76g2000hsh.googlegroups.com> Message-ID: On 14 Apr 2007 20:20:42 -0700, Paddy wrote: > On Apr 15, 3:58 am, Steven D'Aprano > wrote: > > On Sat, 14 Apr 2007 17:33:11 -0800, Troy Melhase wrote: > > > On 4/14/07, Mike wrote: > > >> While trying to write a recursive function involving lists, I came > > >> across some (to me) odd behavior which I don't quite understand. Here's > > >> a trivial function showing the problem. > > > > > fromhttp://docs.python.org/ref/function.html: > > > > > Default parameter values are evaluated when the function definition is > > > executed. This means that the expression is evaluated once, when the > > > function is defined, and that that same ``pre-computed'' value is used > > > for each call. This is especially important to understand when a > > > default parameter is a mutable object, such as a list or a dictionary: > > > if the function modifies the object (e.g. by appending an item to a > > > list), the default value is in effect modified. > > > > This comes up so often that I wonder whether Python should issue a warning > > when it sees [] or {} as a default argument. > > > > What do people think? A misuse or good use of warnings? > > > > -- > > Steven. > > I wonder if it is a check done by Pylint or PyChecker? It is a check done by pylint Tim > > - Paddy. > > -- > http://mail.python.org/mailman/listinfo/python-list > From syedamjad_a at yahoo.com Fri Apr 20 16:48:10 2007 From: syedamjad_a at yahoo.com (CSUIDL PROGRAMMEr) Date: 20 Apr 2007 13:48:10 -0700 Subject: getting from command line options to file In-Reply-To: References: <1176748372.685762.169820@w1g2000hsg.googlegroups.com> Message-ID: <1177102090.716465.133610@d57g2000hsg.googlegroups.com> On Apr 16, 1:08 pm, Michael Hoffman wrote: > CSUIDL PROGRAMMEr wrote: > > hi folks > > I am new to python. I have a module does call a os.command(cmd) where > > cmd is a rpm command. > > Instead of using os.command and getting the results on command line , > > i would like to dump the output in a file. Is os.command(cmd > > > filename) the most efficient command?? > > I think the best thing to do would be something like this (Python 2.5): > > from __future__ import with_statement > import subprocess > > with file("test.out", "w") as outfile: > subprocess.check_call(["ls", "/etc"], stdout=outfile) > -- > Michael Hoffman but what if i have python which is 2.4?? From hat at se-126.se.wtb.tue.nl Thu Apr 12 07:30:52 2007 From: hat at se-126.se.wtb.tue.nl (A.T.Hofkamp) Date: Thu, 12 Apr 2007 13:30:52 +0200 Subject: parsing text in blocks and line too References: <1176370200.947603.314500@d57g2000hsg.googlegroups.com> Message-ID: On 2007-04-12, flyzone at technologist.com wrote: > Goodmorning people :) > I have just started to learn this language and i have a logical > problem. > I need to write a program to parse various file of text. > Here two sample: > > --------------- > trial text bla bla bla bla error > bla bla bla bla bla > bla bla bla on more lines > trial text bla bla bla bla warning bla > bla bla more bla to be grouped with warning > bla bla bla on more lines > could be one two or ten lines also withouth the tab beginning > again text > text can contain also blank lines > text no delimiters.... > -------------- > Apr 8 04:02:08 machine text on one line > Apr 8 04:02:09 machine this is an error > Apr 8 04:02:10 machine this is a warning > -------------- I would first read groups of lines that belong together, then decide on each group whether it is an error, warning, or whatever. To preserve order in a group of lines, you can use lists. >From your example you could first compute a list of lists, like [ [ "trial text bla bla bla bla error", " bla bla bla bla bla", " bla bla bla on more lines" ], [ "trial text bla bla bla bla warning bla", " bla bla more bla to be grouped with warning", " bla bla bla on more lines", " could be one two or ten lines also withouth the tab beginning" ], [ "again text" ], [ "text can contain also blank lines" ], [ ], [ "text no delimiters...." ] ] Just above the "text no delimiters...." line I have added an empty line, and I translated that to an empty group of lines (denoted with the empty list). By traversing the groups (ie over the outermost list), you can now decide for each group what type of output it is, and act accordingly. > Hope someone could give me some tips. Sure, however, in general it is appreciated if you first show your own efforts before asking the list for a solution. Albert From fuzzyman at gmail.com Sat Apr 21 19:18:15 2007 From: fuzzyman at gmail.com (Fuzzyman) Date: 21 Apr 2007 16:18:15 -0700 Subject: No speedup on multi-processor machine? In-Reply-To: References: <1177189332.916296.205280@d57g2000hsg.googlegroups.com> Message-ID: <1177197495.821701.140390@b58g2000hsg.googlegroups.com> On Apr 21, 10:53 pm, Dennis Lee Bieber wrote: > On 21 Apr 2007 14:02:12 -0700, danfan1... at yahoo.com declaimed the > following in comp.lang.python: > > > Hi, > > I am using Python Thread library for my parallel processing course > > project. I am doing matrix convolution on a multi-processor machine > > running Solaris. I just found out that no speed-up is obtained with > > threading. It is probably because of something called GIL in Python. > > How can I get around > > that GIL and get speed-up? > > Threading in Python is optimized for I/O bound processing, wherein > the threads spend most of their lives sleeping (blocked waiting for some > I/O to complete, or some lock/event/condition to change state). It is > not optimized for parallel number crunching. > > Options: > > Don't use the common "CPython" (eg, the Python built from C-language > source using the C-runtime library). Jython (a version that runs on the > JVM, using Java libraries) may not be afflicted with the GIL. > IronPython is *definitely* not restricted by the GIL. Fuzzyman http://www.voidspace.org.uk/ironpython/index.shtml From slevitus at gmail.com Fri Apr 27 19:13:43 2007 From: slevitus at gmail.com (Stephen Levitus) Date: Fri, 27 Apr 2007 18:13:43 -0500 Subject: gmail.py (WAS: Re: [ANN] libgmail 0.0.1 -- Gmail access via Python) Message-ID: <047c01c78921$b3c9c760$6801a8c0@sil1> I saw some material about exporting archived emails from gmail to outlook on the web that had your name in them. I'm looking for a way to export about 200 messages with about 250 or so attachments into an Outlook. Or preferably, I'd like to simply save all of the attachments that are in the gmail archive to a specific windows xp folder. Can you help? Stephen I. Levitus Mobile Telephone 612.751.3200 -------------- next part -------------- An HTML attachment was scrubbed... URL: From dmc5010 at psu.edu Wed Apr 4 07:16:51 2007 From: dmc5010 at psu.edu (Dillon Collins) Date: Wed, 4 Apr 2007 07:16:51 -0400 Subject: Why NOT only one class per file? In-Reply-To: <1175721799.714907.52770@o5g2000hsb.googlegroups.com> References: <1175721799.714907.52770@o5g2000hsb.googlegroups.com> Message-ID: <200704040716.51493.dmc5010@psu.edu> On Wednesday 04 April 2007, Chris Lasher wrote: > He doesn't find my arguments convincing, so I thought I'd ask here to > see why the Python idiom is the way it is: why should we NOT be > placing classes in their own separate files? Because it really just provides as an artificial limitation that could only be annoying at best? After all, programmers can put one class per file if the want anyway. I know I would like Python less if I had to make a directory of files each with somehing like: class MyError(Exception): pass Of course, there are other cases as well where logically grouping classes is much nicer. However, at the end of the day the question is almost meaningless because of the way Python treats classes. Examples: class A(object): class B: pass C=A.B class A(object): pass A=1 class A(object): pass B=type('B', (object,), {}) The first creates a class with a contained class, but then "exports" the contained class as C. The second creates class A, but then destroys it by writing over it with the value 1. The third also creates a class A, but this time creates a top-level class B. You'll note that the method of construction allows for B to be created dynamically. So the idea of one class per file is almost meaningless. From joshua at eeinternet.com Wed Apr 18 15:01:17 2007 From: joshua at eeinternet.com (Joshua J. Kugler) Date: Wed, 18 Apr 2007 11:01:17 -0800 Subject: Wanted: Email Client with GUI References: Message-ID: <46265e98$0$16353$88260bb3@free.teranews.com> On Wednesday 18 April 2007 05:07, Franz Steinhaeusler wrote: > Hi, although I have googled, I didn't find a Python > email client program fitting to my needs. > > What I want is a program (it doesn't have to be so sophisticated > as thunderbird) written totally in python and using a gui > toolkit like pyqt, pygtk, wxpyhton or tkinter. > > Who knows such a program? ;) Why not give Chandlar a try? It's mostly python, with some parts written in C (for speed, I assume). http://chandler.osafoundation.org/ 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 steveo at syslang.net Wed Apr 18 15:34:42 2007 From: steveo at syslang.net (Steven W. Orr) Date: Wed, 18 Apr 2007 15:34:42 -0400 (EDT) Subject: Nested dictionaries trouble In-Reply-To: <1176923772.011976.116190@p77g2000hsh.googlegroups.com> References: <1176317876.917874.58040@n59g2000hsh.googlegroups.com> <1176325715.951076.4790@w1g2000hsg.googlegroups.com> <1176923772.011976.116190@p77g2000hsh.googlegroups.com> Message-ID: On Wednesday, Apr 18th 2007 at 12:16 -0700, quoth IamIan: =>I am using the suggested approach to make a years list: => =>years = ["199%s" % x for x in range(0,10)] =>years += ["200%s" % x for x in range(0,10)] => =>I haven't had any luck doing this in one line though. Is it possible? I'm so green that I almost get a chubby at being able to answer something. ;-) years = [str(1990+x) for x in range(0,20)] Yes? -- 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 gagsl-py2 at yahoo.com.ar Sun Apr 29 18:51:11 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sun, 29 Apr 2007 19:51:11 -0300 Subject: Beginner Ping program References: <1177739647.737759.32610@u30g2000hsc.googlegroups.com> <1177755579.454423.35590@n59g2000hsh.googlegroups.com> <59jdncF2jhibgU1@mid.individual.net> Message-ID: En Sun, 29 Apr 2007 08:26:36 -0300, Bjoern Schliessmann escribi?: > Linus Cohen wrote: >> It will be called inettools, and the ping function is >> what I'm working on first. It should be a simple enough job to >> code in the features the Unix and DOS ping programs have(never >> stop, change size, change timeout). > > IIRC, MS ping has no "never stop", you can only say "repeat 99999 > times". ping -t hostname -- Gabriel Genellina From kelvin.you at gmail.com Mon Apr 30 05:08:35 2007 From: kelvin.you at gmail.com (=?utf-8?B?5Lq66KiA6JC95pel5piv5aSp5rav77yM5pyb5p6B5aSp5rav5LiN6KeB5a62?=) Date: 30 Apr 2007 02:08:35 -0700 Subject: What's the life time of the variable defined in a class function? Message-ID: <1177924115.659293.185880@q75g2000hsh.googlegroups.com> Please see the followed example: class A: def __init__(self): pass class X: def __init__(self): n = 200 if True: j = 200 m = j k = A() print m, j a = X() # ?? what about the m, n and j? is it still alive? del a -------------------------- In C/C++, the life time of m,n and j was the nearest block. but obviously, python doen't have this syntax, but I would like to know that whether the life time of m, n, j is base on function range or the object range. We can not access the m, n, and j from the outside of class X. Now I'm writing a program base on the wxpython. In the __init__ function of wx.Panel, I use normal varable(just like the m,n and j) created some widgets. It could be show in the window. Does it indicated the life time of varable m,n,j is base on the object range? Sorry for my poor english! It seems From hg at nospam.org Mon Apr 23 06:01:48 2007 From: hg at nospam.org (hg) Date: Mon, 23 Apr 2007 12:01:48 +0200 Subject: pyserial ... timeout on write Message-ID: Hi, I notice that pyserial will hang on a write (even with timeout on) if rts/cts are one. Anyway to get around that ? Thanks hg From michael at jedimindworks.com Sun Apr 1 08:20:20 2007 From: michael at jedimindworks.com (Michael Bentley) Date: Sun, 1 Apr 2007 07:20:20 -0500 Subject: Generic logic/conditional class or library for classification of data In-Reply-To: <1175403286.809692.100080@n59g2000hsh.googlegroups.com> References: <1175403286.809692.100080@n59g2000hsh.googlegroups.com> Message-ID: <434F050D-7AF9-4C16-BD71-E4A99B18EDA8@jedimindworks.com> On Mar 31, 2007, at 11:54 PM, Basilisk96 wrote: > This topic is difficult to describe in one subject sentence... > > Has anyone come across the application of the simple statement "if > (object1's attributes meet some conditions) then (set object2's > attributes to certain outcomes)", where "object1" and "object2" are > generic objects, and the "conditions" and "outcomes" are dynamic run- > time inputs? Typically, logic code for any application out there is > hard-coded. I have been working with Python for a year, and its > flexibility is nothing short of amazing. Wouldn't it be possible to > have a class or library that can do this sort of dynamic logic? > > The main application of such code would be for classification > algorithms which, based on the attributes of a given object, can > classify the object into a scheme. In general, conditions for > classification can be complex, sometimes involving a collection of > "and", "or", "not" clauses. The simplest outcome would involve simply > setting a few attributes of the output object to given values if the > input condition is met. So each such "if-then" clause can be viewed as > a rule that is custom-defined at runtime. > > As a very basic example, consider a set of uncategorized objects that > have text descriptions associated with them. The objects are some type > of tangible product, e.g., books. So the input object has a > Description attribute, and the output object (a categorized book) > would have some attributes like Discipline, Target audience, etc. > Let's say that one such rule is "if ( 'description' contains > 'algebra') then ('discipline' = 'math', 'target' = 'student') ". Keep > in mind that all these attribute names and their values are not known > at design time. > > Is there one obvious way to do this in Python? > Perhaps this is more along the lines of data mining methods? > Is there a library with this sort of functionality out there already? > > Any help will be appreciated. You may be interested in http://divmod.org/trac/wiki/DivmodReverend -- it is a general purpose Bayesian classifier written in python. hope this helps, Michael From xah at xahlee.org Sun Apr 15 12:25:19 2007 From: xah at xahlee.org (Xah Lee) Date: 15 Apr 2007 09:25:19 -0700 Subject: is laziness a programer's virtue? Message-ID: <1176654319.273907.167280@q75g2000hsh.googlegroups.com> Laziness, Perl, and Larry Wall Xah Lee, 20021124 In the unix community there's quite a large confusion and wishful thinking about the word laziness. In this post, i'd like to make some clarifications. American Heritage Dictionary third edition defines laziness as: ?Resistant to work or exertion; disposed to idleness.? When the sorcerer Larry Wall said ?The three chief virtues of a programmer are: Laziness, Impatience and Hubris?, he used the word ?laziness? to loosely imply ?natural disposition that results in being economic?. As you can see now, ?Resistant to work or exertion? is clearly not positive and not a virtue, but ?natural disposition that results in economy? is a good thing if true. When Larry Wall said one of programer's virtue is laziness, he wants the unix morons to conjure up in their brains the following proposition as true: ?Resistant to work or exertion is a natural human disposition and such disposition actually results behaviors being economic?. This statement may be true, which means that human laziness may be intuitively understood from evolution. However, this statement is a proposition on all human beings, and is not some ?virtue? that can be applied to a group of people such as programers. Demagogue Larry Wall is smart in creating a confusion combined with wishful thinking. By making subtle statements like this, he semi- intentionally confuses average programers to think that it is OK to be not thorough, it is OK to be sloppy, it is OK to disparage computer science. (like the incompetent unixers and perlers are) Can you see the evil and its harm in not understanding things clearly? This laziness quote by Wall is a tremendous damage to the computing industry. It is a source among others that spurs much bad fashion trends and fuckups in the industry. It is more damaging than any single hack or virus. It is social brain-washing at work, like the diamond company De Beers' tremendously successful sales slogan: ?A Diamond is Forever? or Apple's grammatically fantastic ?Think Different?. The most fundamental explanation of why Larry Wall's sophistry are damaging to society is simply this: What he said is not true and they are widely spread and conceived as worthwhile. This is a form of mis- information. This is a manifestation of Love without Knowledge as i expounded before, with subtle but disastrous consequences (already). [DISCLAIMER: all mentions of real persons are opinion only.] ---- This post is archived at: http://xahlee.org/UnixResource_dir/writ/perl_laziness.html Xah xah at xahlee.org ? http://xahlee.org/ From steve at holdenweb.com Mon Apr 23 10:12:00 2007 From: steve at holdenweb.com (Steve Holden) Date: Mon, 23 Apr 2007 10:12:00 -0400 Subject: Can __init__ not return an object? In-Reply-To: References: Message-ID: <462CBEB0.60702@holdenweb.com> Steven W. Orr wrote: > On Sunday, Apr 22nd 2007 at 21:01 -0400, quoth Steve Holden: [let's keep it on the list so everything gets indexed] > =>Steven W. Orr wrote: > =>> When I go to create an object I want to be able to decide whether the > =>> object is valid or not in __init__, and if not, I want the constructor to > =>> return something other than an object, (like maybe None). I seem to be > =>> having problems. At the end of __init__ I say (something like) > =>> > =>> if self.something < minvalue: > =>> del self > =>> return None > =>> > =>> and it doesn't work. I first tried just the return None, then I got crafty > =>> and tried the del self. Is what I'm trying to do possible in the > =>> constructor or do I have to check after I return? Or would raising an > =>> exception in the constructor be appropriate? > =>> > =>> Am I even being clear? > =>> > =>The trouble you have is that it's too late by the time you get to > =>__init__. The object has been created. The reason that "del self" > =>doesn't work is that all it does is remove the local name "self" from > =>the namespace of the method - you will find that if __init__ returns > =>anything *except* None you get an exception. > => > =>Don't think of __init__ as a constructor - that's __new__, which *is* > =>expected to return a newly-created instance. > => > =>Raising an exception in __init__ is perfectly permissible, but adopting > =>the new-style classes (inheriting from object) might give you a more > =>efficient solution to your problem. > > Thanks Steve. I'm new but I do now understand that __init_ is an > initializer and that new is a constructor. I don't understand your last > sentence about new-style classes inheriting from an object. The object is > question is mine and doesn't inherit from anything. Can you explain what > you mean? > Not "an object" but "object", the root of all Python types. If you are very new you may not appreciate that Python currently implements two different class declaration mechanisms. The original classes, often now called "classic classes", couldn't be used to subclass Python's built-in types because they formed an independent and parallel class hierarchy. Among other things the instances don't have an accessible __new__ method: >>> class X: pass ... >>> type(X) >>> At present the so-called "new-style" classes must specifically inherit from object (or, more correctly, must have a metaclass that is conformant with the protocol implemented by the type type, but the easiest way to do this is just to subclass object or one of the other built-in types): >>> class X(object): pass ... >>> type(X) >>> So, all I was saying is that you might prefer to implement your solution as a new-style class, since that gives you access to your class's instance creation mechanism through the __new__ method. __new__ doesn't *have* to return an instance of the class whose __new__ method is called, and this might allow you to return exactly what your application needs without having to handle exceptions at the application code level. regards Steve -- Steve Holden +1 571 484 6266 +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.co From carsten at uniqsys.com Tue Apr 10 11:47:05 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Tue, 10 Apr 2007 11:47:05 -0400 Subject: tuples, index method, Python's design In-Reply-To: <1176219856.3430.76.camel@dot.uniqsys.com> References: <1175867771.114540.61810@n76g2000hsh.googlegroups.com> <1175884427.779950.267220@y80g2000hsf.googlegroups.com> <1176210960.3430.20.camel@dot.uniqsys.com> <740c3aec0704100810g5f962e8eu614fbaedecf3608e@mail.gmail.com> <1176219856.3430.76.camel@dot.uniqsys.com> Message-ID: <1176220025.3430.77.camel@dot.uniqsys.com> On Tue, 2007-04-10 at 11:44 -0400, Carsten Haese wrote: > On Tue, 2007-04-10 at 17:10 +0200, BJ?rn Lindqvist wrote: > > On 4/10/07, Carsten Haese wrote: > > > i = p.index(current_player) > > > opponents = p[:i-1] + p[i+1:] > > > > > > An alternative is this: > > > > > > opponents = tuple(x for x in p if x is not current_player) > > > > > > You may disagree, but in my opinion, the alternative is better because > > > it is a more natural translation of the concept that the opponents of > > > the current player are all players that are not the current player. > > > > Your alternative is wrong because it wont raise ValueError if > > current_player is not present in the tuple. Please revise your > > "solution." > > You have a point. Here is my revised solution: > > assert current_player in p > opponents = tuple(x for x in p if x is not current_player) > > The added advantage is that AssertionError is better than IndexError for > conveying that a severe program bug has occurred. _.replace("IndexError", "ValueError"), of course. -Carsten From kar1107 at gmail.com Sat Apr 14 23:55:54 2007 From: kar1107 at gmail.com (Karthik Gurusamy) Date: 14 Apr 2007 20:55:54 -0700 Subject: optparse -- anyway to find if the user entered an option? In-Reply-To: References: <1176594561.971801.211710@y80g2000hsf.googlegroups.com> Message-ID: <1176609354.841749.275210@p77g2000hsh.googlegroups.com> On Apr 14, 7:54 pm, Steven D'Aprano wrote: > On Sat, 14 Apr 2007 16:49:22 -0700, Karthik Gurusamy wrote: > > I'm wondering if there is a cleaner approach -- something like > > parser.opt_seen("-i") > > What do dir(parser) and help(parser) say? They don't seem to convey existence of a routine like the one I'm looking for. I did check the lib reference - I guess such a support is not available. Most likely the 'None' solution will work for me. I will go ahead with it. Karthik >>> dir(parser) ['__doc__', '__init__', '__module__', '_add_help_option', '_add_version_option', '_check_conflict', '_create_option_list', '_create_option_mappings', '_get_all_options', '_get_args', '_get_encoding', '_init_parsing_state', '_long_opt', '_match_long_opt', '_populate_option_list', '_process_args', '_process_long_opt', '_process_short_opts', '_share_option_mappings', '_short_opt', 'add_option', 'add_option_group', 'add_options', 'allow_interspersed_args', 'check_values', 'conflict_handler', 'defaults', 'description', 'destroy', 'disable_interspersed_args', 'enable_interspersed_args', 'epilog', 'error', 'exit', 'expand_prog_name', 'format_description', 'format_epilog', 'format_help', 'format_option_help', 'formatter', 'get_default_values', 'get_description', 'get_option', 'get_option_group', 'get_prog_name', 'get_usage', 'get_version', 'has_option', 'largs', 'option_class', 'option_groups', 'option_list', 'parse_args', 'print_help', 'print_usage', 'print_version', 'process_default_values', 'prog', 'rargs', 'remove_option', 'set_conflict_handler', 'set_default', 'set_defaults', 'set_description', 'set_process_default_values', 'set_usage', 'standard_option_list', 'usage', 'values', 'version'] >>> >>> print sys.version 2.5 (r25:51908, Sep 29 2006, 12:35:59) [GCC 3.2.3 20030502 (Red Hat Linux 3.2.3-54)] help(parser) just gives info on a generic instance. > > -- > Steven. From usenet423.4.fms at neverbox.com Wed Apr 25 12:49:51 2007 From: usenet423.4.fms at neverbox.com (Frank Stajano) Date: Wed, 25 Apr 2007 17:49:51 +0100 Subject: q: how to output a unicode string? In-Reply-To: <598prcF2ihs92U1@mid.uni-berlin.de> References: <596qd4F2k129kU1@mid.uni-berlin.de> <598prcF2ihs92U1@mid.uni-berlin.de> Message-ID: Diez B. Roggisch wrote: >> So why is it that in the first case I got UnicodeEncodeError: 'ascii' >> codec can't encode? Seems as if, within Idle, a utf-8 codec is being >> selected automagically... why should that be so there and not in the >> first case? > > I'm a bit confused on what you did when.... the error appears if you try to > output a unicode-object without prior encoding - then the default encoding > (ascii) is used. Here's a minimal example for you. I put these four lines into a utf-8 file. # -*- coding: utf-8 -*- # this file is called t3.py s1 = u"h?ll? w?rld" print s1 If I invoke "python t3.py" at the cygwin/rxvt/bash prompt, I get: Traceback (most recent call last): File "t3.py", line 4, in print s1 UnicodeEncodeError: 'ascii' codec can't encode character u'\xe9' in position 1: ordinal not in range(128) If I load the exact same file in Idle and press F5 (for Run), I get: h?ll? w?rld So obviously "the system" is not behaving in the same way in the two cases. Maybe Python senses that it can do utf-8 when it's inside Idle and sets the default to utf-8 without me asking for it, and senses that it can't do (or more precisely output) utf-8 when it's in cygwin/rxvt/bash so there it sets the default codec to ascii. That's my best guess so far... I find the encode/decode terminology somewhat confusing, because arguably both sides are "encoded". For example, a unicode-encoded string (I mean a sequence of unicode code points) should count as "decoded" in the terminology of this framework, right? Anyway, thanks again for your help, for deepening my modest understanding of the issue and for solving my original problem! From rhamph at gmail.com Fri Apr 20 22:12:29 2007 From: rhamph at gmail.com (Rhamphoryncus) Date: 20 Apr 2007 19:12:29 -0700 Subject: Python's handling of unicode surrogates In-Reply-To: References: <4628532B.5060104@v.loewis.de> <1177051493.468698.176740@b75g2000hsg.googlegroups.com> Message-ID: <1177121549.348204.189840@y5g2000hsa.googlegroups.com> On Apr 20, 5:49 pm, Ross Ridge wrote: > Rhamphoryncus wrote: > >The only code that will be changed is that which doesn't handle > >surrogates properly. Some will start working properly. Some (ie > >random.choice(u'\U00100000\uFFFF')) will fail explicitly (rather than > >silently). > > You're falsely assuming that any code that doesn't support surrogates > is broken. Supporting surrogates is no more required than supporting > combining characters, right-to-left languages or lower case letters. No, I'm only assuming code which would raise an error with my change is broken. My change would have minimal effect because it's building on the existing correct way to do things, expanding them to handle some additional cases. -- Adam Olsen, aka Rhamphoryncus From zefria at gmail.com Sun Apr 15 04:33:50 2007 From: zefria at gmail.com (Daniel Gee) Date: 15 Apr 2007 01:33:50 -0700 Subject: Python editor/IDE on Linux? In-Reply-To: References: <1176575715.649316.130430@n76g2000hsh.googlegroups.com> Message-ID: <1176626030.729710.321520@d57g2000hsg.googlegroups.com> In Linux I just use Gedit. In windows I settle for Notepad2. With python having help built into the interpreter, anything more than line numbering, simple syntax highlighting, and auto-indent when you hit enter just doesn't seem necessary. Vim has b and c, but not a. Using Kate for Python would probably be very similar to using Gedit (from my limited experience with Kate). From john at baumanfamily.com Thu Apr 19 17:40:27 2007 From: john at baumanfamily.com (John Bauman) Date: Thu, 19 Apr 2007 17:40:27 -0400 Subject: Better dict of dicts In-Reply-To: <1177018181.493650.297900@e65g2000hsc.googlegroups.com> References: <1177018181.493650.297900@e65g2000hsc.googlegroups.com> Message-ID: <-cudnX2k8KPLfLrbnZ2dnUVZ_uvinZ2d@ptd.net> Adam Atlas wrote: > On Apr 19, 5:24 pm, Bill Jackson wrote: >> I have a dictionary of dictionaries where the keys are typically very >> long tuples and repeated in each inner dictionary. The dictionary >> representation is nice because it handles sparseness well...and it is >> nice to be able to look up values based on a string rather than a >> number. However, since my keys are quite long, I worry that I am >> wasting a lot of memory. > > I wouldn't worry about it. Try doing hash('string_2') in the > interpreter -- the output thereof is what's really being used as the > key. It doesn't use up any more memory than the integer 2. > Are you sure about that? Most dictionaries need to store the actual key, in case of a collision, so when you lookup a key they can tell which you're really looking for. From nagle at animats.com Sun Apr 15 02:07:20 2007 From: nagle at animats.com (John Nagle) Date: Sun, 15 Apr 2007 06:07:20 GMT Subject: proposed PEP: iterator splicing In-Reply-To: <7xirbyi5d7.fsf_-_@ruckus.brouhaha.com> References: <7xirbyi5d7.fsf_-_@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > Less clutter, and avoids yet another temp variable > polluting the namespace. Are we in danger of running out of temp variables? John Nagle From gagsl-py2 at yahoo.com.ar Sat Apr 7 01:19:12 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: 6 Apr 2007 22:19:12 -0700 Subject: Mail not setting timestamp In-Reply-To: References: Message-ID: <1175923152.762487.273780@n76g2000hsh.googlegroups.com> Lorenzo Thurman wrote: > I'm using the Mimewriter and mimetools modules to create html messages. > They work OK, except that when the messages are received, they always > have the timestamp of 12/31/1969. I've looked through both packages and > can't find anything that would allow me to manually set it. Can someone > help me out? The date goes into the message headers, like From, To, Subject... message.add_header("Date", "Thu, 22 Jun 2006 23:18:15 -0300") -- Gabriel Genellina From tim at tdw.net Thu Apr 5 19:21:09 2007 From: tim at tdw.net (Tim Williams) Date: Fri, 6 Apr 2007 00:21:09 +0100 Subject: way to extract only the message from pop3 In-Reply-To: <9afea2ac0704051614l738f8e06j2380c787b2bfcfc@mail.gmail.com> References: <1175628970.874615.127020@y80g2000hsf.googlegroups.com> <9afea2ac0704051614l738f8e06j2380c787b2bfcfc@mail.gmail.com> Message-ID: <9afea2ac0704051621n3c35a8fct12efe84823a7e294@mail.gmail.com> On 06/04/07, Tim Williams wrote: > Content: ['text/plain', 'text/html', 'message/delivery-status', > 'text/plain', 'text/plain', 'text/plain', 'unknown', 'message/rfc822', > 'text/plain', 'text/html'] I should explain that this was the content in a single email > > # part.get_content_maintype() requires a further call > # to get_content_subtype() , so use > # part.get_content_type() instead. > > required = ['text/plain', 'text/tab-separated-values'] > for part in EMAIL_OBJ.walk(): > text_parts = [] > if part.get_content_type() in required: > text_parts.append(part) > > print ('\r\n' + '='*76 +'\r\n').join(text_parts) > # print all the text parts seperated by a line of '=' > # end Content: ['text/plain', 'text/html', 'message/delivery-status', 'text/plain', 'text/plain', 'text/plain', 'unknown', 'message/rfc822', 'text/plain', 'text/html'] Is text/html a text part or an html part for this exercise ? :) You need to walk the parts and use something like # part.get_content_maintype() requires a further call # to get_content_subtype() , so use # part.get_content_type() instead. required = ['text/plain', 'text/tab-separated-values'] for part in EMAIL_OBJ.walk(): # text_parts = [] <== oops, this should be above the for..... if part.get_content_type() in required: text_parts.append(part) print ('\r\n' + '='*76 +'\r\n').join(text_parts) # print all the text parts seperated by a line of '=' # end From weinhand at unileoben.ac.at Fri Apr 13 03:39:25 2007 From: weinhand at unileoben.ac.at (WEINHANDL Herbert) Date: Fri, 13 Apr 2007 09:39:25 +0200 Subject: Databases with python In-Reply-To: References: Message-ID: <461f3480$0$10578$3b214f66@aconews.univie.ac.at> Anthony Irwin wrote: > Hi All, > > I am interested in playing with python some more and am looking at > writing an app with data stored in a database. I have experience with > mysql but thought that their may be other better databases that can be > more easily distributed with the program does anyone have any > suggestions here? with SQLObject ( http://www.sqlobject.org/ ) or SQLAlchemy ( http://www.sqlalchemy.org/ ) you can use any of the supported (sqlite, mysql, postgresql, firebird) databases in an object oriented way without worrying about the details of the database you use. sqlite ( http://www.sqlite.org/ ) is a database which stores its data directly into a file, while all other databases require a server to be installed prior to using it, so if you want to distribute your application it might be the easiest way to use sqlite as your database. Python 2.5 and newer has sqlite already included, thus it seems the database of choice. > I only use linux myself but I can foresee some windows people wanting to > use what I create and if I am going to support windows then I might as > well support mac too. (this is to say that the database should support > the 3 main platforms in use) > > Also is wxpython the best cross platform gui library it seems to be the > best I have seen so far. Happy pythoning Herbert ps: if you want to create a web-application i can recommend TurboGears ( http://www.turbogears.org/ ) From steve at holdenweb.com Thu Apr 26 07:59:06 2007 From: steve at holdenweb.com (Steve Holden) Date: Thu, 26 Apr 2007 07:59:06 -0400 Subject: Tutorial creates confusion about slices In-Reply-To: References: <1177496078.319400.324720@r30g2000prh.googlegroups.com> Message-ID: Antoon Pardon wrote: > On 2007-04-25, Steve Holden wrote: [...] >>> >> Most people reading a tutorial are aware that they are being given the >> knowledge they need to put the subject matter to immediate use, and that >> there may well be refinements that are glossed over or covered in detail >> later or elsewhere. > > I agree with that. > > However there is a difference between information that will help you > on the way now that will be refined later and information that will > help you on the way now and will be contradicted later. > > I also understand that the line between the two is rather fuzzy. > > In my opinion the text in the tutorial as it stands now, is more > of the latter than of the former type and that is why I would > prefer a change. > I had already deduced that from your arguments so far in this thread. Do you *have* to make every trivial conclusion explicit? Warning: this is an explicit test to see whether you can sit on your hands and refrain from replying. It's hard to find a thread where you don't make the last comment on every branch you get involved in. regards Steve -- Steve Holden +1 571 484 6266 +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 zhonghua.m.yang at gmail.com Tue Apr 3 13:46:18 2007 From: zhonghua.m.yang at gmail.com (ZMY) Date: 3 Apr 2007 10:46:18 -0700 Subject: python installation destination directory In-Reply-To: <1175606767.236264.184830@e65g2000hsc.googlegroups.com> References: <1175574838.705561.203310@n76g2000hsh.googlegroups.com> <1175606767.236264.184830@e65g2000hsc.googlegroups.com> Message-ID: <1175622378.147163.92270@w1g2000hsg.googlegroups.com> On Apr 3, 6:26 am, "Kushal Kumaran" wrote: > On Apr 3, 9:33 am, "ZMY" wrote: > > > > > Hi all, > > > I am installing python 2.2 on QNX4.25 but can't get it into /usr/local/ > > bin/ directory. Here is what I did: > > > 1) untar Python-2.2 into directory /openqnx/Python-2.2/ > > > 2) use command: > > CONFIG_SHELL=/usr/local/bin/bash CC=cc RANLIB=: > > ./configure --verbose --without-gcc --with-libm="" > > > 3) Enabled array, math, os, struct, time, cmath modules > > > 4) use command: > > make SHELL=/usr/local/bin/bash > > > and I got a python excutable in directory > > /openqnx/Python-2.2/ > > > which works well with all the modules. But I really want to have it > > at /usr/local/bin > > > I checked the Makefile, and it seems python should be installed in / > > usr/local/bin instead, since I got following lines in Makefile: > > > # Install prefix for architecture-independent files > > prefix= /usr/local > > > # Install prefix for architecture-dependent files > > exec_prefix= ${prefix} > > > Do any of you know what the problem is? > > You need to do a make install. > > -- > Kushal Thanks. It works. -ZMY From someguywithoutanemailaddress Sun Apr 29 20:27:58 2007 From: someguywithoutanemailaddress (Alvin Bruney [MVP]) Date: Sun, 29 Apr 2007 20:27:58 -0400 Subject: SEO - Search Engine Optimization - Seo Consulting References: <1177808356.681710.42980@n76g2000hsh.googlegroups.com> Message-ID: >Top posting Did not. I replied to the message at the bottom of the thread. >Call yourself an MVP, that's a joke Slick. Yup, I do call myself an MVP, it's not a joke either. -- Regards, Alvin Bruney ------------------------------------------------------ Shameless author plug Excel Services for .NET is coming... OWC Black book on Amazon and www.lulu.com/owc Professional VSTO 2005 - Wrox/Wiley "Spin Dryer" wrote in message news:r8b9339u19tf8n3plqg32jc1g7i0ma4s5u at 4ax.com... > On Sat, 28 Apr 2007 21:21:39 -0400, ["Alvin Bruney [MVP]" without an email address>] said :- > >>Please don't spam this group > > Top posting and without removing the spamvertised site, you are as bad > as the spammer. Call yourself an MVP, that's a joke Slick. > > Indeed the spam was not even seen by probably many servers until you > decided to reply. From jstroud at mbi.ucla.edu Tue Apr 24 21:33:13 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Tue, 24 Apr 2007 18:33:13 -0700 Subject: gotcha or bug? random state reset on irrelevant import In-Reply-To: <33yXh.5839$Fc1.4387@trnddc05> References: <33yXh.5839$Fc1.4387@trnddc05> Message-ID: Alan Isaac wrote: > Running test.py will print False. > Is this expected/desirable? > Thanks, > Alan Isaac > > > %%%%%%% test.py %%%%%%%%%%% > from random import seed, getstate > seed(217) > x = getstate() > from test2 import Trivial > y = getstate() > print x == y > > > %%%%% test2.py %%%%%%%%%%%%% > from random import seed > seed(314) > class Trivial: > pass > > > Yes. To circomvent this, use from random import seed class Trivial: pass if __name__ == "__main__": seed(314) From bcwhite at pobox.com Wed Apr 18 20:06:09 2007 From: bcwhite at pobox.com (bcwhite at pobox.com) Date: 18 Apr 2007 17:06:09 -0700 Subject: Future Python Gui? In-Reply-To: <46267C84.8040505@codebykevin.com> References: <1176859699.906386.326720@b75g2000hsg.googlegroups.com> <1176923448.998078.170760@e65g2000hsc.googlegroups.com> <46267C84.8040505@codebykevin.com> Message-ID: <1176941169.750013.216660@e65g2000hsc.googlegroups.com> > On Windows, the easiest way to install Tile is to grab it from > ActiveState's Tcl distribution > (http://www.activestate.com/products/activetcl/) and then place it with > the Tcl/Tk bits that come with Python. The Tcl/Tk build for Windows that > python.org provides doesn't ship with Tile. You'll also have to install > the Tile wrapper at the site I referenced earlier in your site-packages > directory. For posterity's sake, here's what I did... - install python http://www.python.org/download/ (use the Windows MSI install package) - go to http://bruno.thoorens.free.fr/ and do the download - instructions say to copy "tty.py" to "Tkinter" folder, but that doesn't exist - copy instead to C:\Python25\Lib - copy folders as directed (to C:\Python25\Tcl) This should also work with the ActivePython download at http://www.activestate.com/products/activepython/ . Within your program, you need: # Import "Tile" theming engine tkroot.tk.call('package', 'require', 'tile') tkroot.tk.call('namespace', 'import', '-force', 'ttk::*') tkroot.tk.call('tile::setTheme', 'xpnative') after your call to "tkroot = Tk()" (or "tkroot = Tkinter.Tk()" if you just "import Tkinter"). The frustrating part is that the main reason I wanted this is because it says it wraps a "Notebook" widget. If it does, I can't find it! -- Brian From g.brandl at gmx.net Mon Apr 9 02:10:26 2007 From: g.brandl at gmx.net (Georg Brandl) Date: Mon, 09 Apr 2007 08:10:26 +0200 Subject: Exec Statement Question In-Reply-To: <312cfe2b0704082231p53fe2605laf3cfef732eaff61@mail.gmail.com> References: <312cfe2b0704082231p53fe2605laf3cfef732eaff61@mail.gmail.com> Message-ID: Gregory Pi?ero schrieb: > I'm curious why this code isn't working how I expect it to: > > import sys > d=3 > > def func1(a,b,c): > print a,b,c,d > print sys.path > > exec "func1(1,2,3)" in {'func1':func1} > > ---- > returns: > 1 2 3 3 > [ sys.path stuff ....] > > Since I'm telling exec to operate only within the context of the > dictionary I give it, why does it still see sys.path and d? I figured > it would throw a NameError. > > Is there a way to call exec such that it won't have access to any more > objects than I explicitly give it? The function f has a func_globals attribute which points to the globals it will use for execution. This is of course set at definition time so that functions from, e.g., another module, have the globals of that module available. Georg From claird at lairds.us Tue Apr 24 11:23:30 2007 From: claird at lairds.us (Cameron Laird) Date: Tue, 24 Apr 2007 15:23:30 +0000 Subject: Python Screen Scraper References: Message-ID: In article , Michael Bentley wrote: > >On Apr 24, 2007, at 11:50 AM, James Stroud wrote: > >> Hello, >> >> Does anyone know of an example, however modest, of a screenscraper >> authored in python? I am using Firefox. >> >> Basically, I am answering problems via my browser and being scored for >> each problem. I have a tendency to go past my peak for training >> efficiency, so I would like to scrape the result page for each >> problem I >> answer, compile statistics, and have a program alert me when I should >> stop (based on score and accuracy--assuming training value is >> related to >> changes in these metrics). >> >> I have no idea how to go about writing such a beast and I am hoping >> that >> I could get some pointers or an example that could get me going in the >> right direction. >> >> Parsing, etc, is not a problem, but I'm not exactly sure how I might >> interface python with Firefox, forwarding scraped pages to my browser >> (or forwarding from the browser to the scraper). >> >> Thanks in advance for any help or advice. > >Possibly the easiest thing will be to read from firefox' cache. >Otherwise I think your only real options are to either build a proxy >or sniff the wire... > > Oh, there are *lots* of ways to go about this. How crucial is the role of Firefox in all this? might be the right answer. Are you open to use of languages other than Python? From nagle at animats.com Fri Apr 27 15:03:19 2007 From: nagle at animats.com (John Nagle) Date: Fri, 27 Apr 2007 12:03:19 -0700 Subject: More urllib timeout issues. Message-ID: I thought I had all the timeout problems with urllib worked around, but no. socket.setdefaulttimeout is useful, but not always effective. I'm setting that to 15 seconds. If the host end won't open the connection within 15 seconds, urllib times out. But if the host end opens the connection, then never sends anything, urllib waits for many minutes before timing out. Any idea how to deal with this? And don't just say "use urllib2" unless you KNOW it works better there and can explain why. I finally have M2Crypto and urllib playing well together, and don't want to mess with that. For some wierd reason, several UK academic sites have this behavior, including "soton.ac.uk". If you try to open that in a browser, the browser just sits there, and eventually, after several minutes, displays "The site is taking too long to respond". What's the current status in this area? Some patches to sockets were proposed a while back. There's a long history of trouble in this area, and some fixes, but nothing that just works. The sockets module has two timeout settings (socket.setdefaulttimeout and sock.settimeout, the M2Crypto module has two (sock.set_socket_read_timeout and sock.set_socket_write_timeout), and none of them play well together or with the urllib/urllib2/httplib level and the blocking/non blocking socket distinction. What we really should have is something like this: Sockets should have set_socket_connect_timeout set_socket_read_timeout set_socket_write_timeout which set an upper limit on how long a socket can go with a request for a connect, read or write pending but without progress on the connection. This needs to be independent of select poll timeouts, and these timeouts should work on blocking sockets. The existing socket function settimeout should set all of the above, and socket.setdefaulttimeout should set the default value for settimeout to be used on new sockets. SSL and M2Crypto, which wrap socket functionality, should understand all the above functions. HTTPlib, urllib, and urllib2 objects should understand settimeout Making the connect/read/write timeout distinction at that level probably isn't worth the trouble. Then we'd have a reasonable network timeout system. We have about half of the above now, but it's not consistent. Comments? John Nagle From khemkaamit at gmail.com Wed Apr 4 03:08:50 2007 From: khemkaamit at gmail.com (Amit Khemka) Date: Wed, 4 Apr 2007 12:38:50 +0530 Subject: how to remove multiple occurrences of a string within a list? In-Reply-To: <1175624433.206953.214290@n59g2000hsh.googlegroups.com> References: <1175624433.206953.214290@n59g2000hsh.googlegroups.com> Message-ID: <1360b7230704040008q6c716eaat941d5081cfd6bd5@mail.gmail.com> On 3 Apr 2007 11:20:33 -0700, bahoo wrote: > Hi, > > I have a list like ['0024', 'haha', '0024'] > and as output I want ['haha'] > > If I > myList.remove('0024') > > then only the first instance of '0024' is removed. To remove all items with multiple occurances in myList: list(set(myList) - set([x for x in myList if myList.count(x)>1])) 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 larry.bates at websafe.com Wed Apr 25 19:59:22 2007 From: larry.bates at websafe.com (Larry Bates) Date: Wed, 25 Apr 2007 18:59:22 -0500 Subject: My python annoyances so far In-Reply-To: <1177541453.471959.120830@c18g2000prb.googlegroups.com> References: <1177541453.471959.120830@c18g2000prb.googlegroups.com> Message-ID: <4tKdncgjI-HKdrLbnZ2dnUVZ_ruknZ2d@comcast.com> flifus at gmail.com wrote: > Hi all. I'm learning python these days. I'm going to use this thread > to post, from time to time, my annoyances with python. I hope someone > will clarify things to me where I have misunderstood them. > > Annoyances: > > 1. Underscores! What's the deal with that? Especially those double > underscores. The best answer I read on this is that the double > underscores denotes special methods that the interpreter may > automatically use. For example, 4+4 get expanded by the interpreter to > 4.__add__(4). > > 2. There are modules, there are functions, and there are classes- > methods! Wouldn't it have been easier had everything either been a > function or a class method? > 1. Underscores. __add__ is a special method that gets called when you want to add two objects together. __init__ is the initalizer method that gets called when a class is instantiated. Special methods begin and end with double underlines. __variable is a class (or instance) variable that shouldn't be manipulated outside the class that is somewhat equivalent to private variables in other languages. I say somewhat because there is always a way to get to any variable, even the double underline ones. _variable is a class (or instance) variable that is internal to the class an normally shouldn't depended upon or manipulated from the outside unless the caller really knows what they are doing. 2. Modules are collections of code. They can be functions or classes. Functions are functions, classes are classes, you need both in an object oriented language. Functions alone will not suffice. If you want to ignore classes at the beginning, please do so. Suggestion: if you are just starting please accept that there is a reason for Python being different from almost all "traditional" compiled languages. If you take some time you will come to understand and, if you are like most, love the differences. I've been creating a cross-language COM object and after writing unit tests in VB, Delphi, and Python I am once again reminded why I love Python. I have more lines of declarations in the Delphi version than in the Python program for some tests. -Larry From duncan.booth at invalid.invalid Tue Apr 10 03:56:08 2007 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 10 Apr 2007 07:56:08 GMT Subject: exec statement Syntax Error on string pulled from MySQL References: <1176191064.840339.247160@d57g2000hsg.googlegroups.com> Message-ID: "gregpinero at gmail.com" wrote: > To really get a picture of what is coming out of the DB I had the > program print out everything about this string using this code: > print code > print repr(code) > print type(code) > for char in code: > print ord(char),char > > To which I got: > > print 'greg' print 'greg2' > "print 'greg'\r\nprint 'greg2'" >>> exec "1\n2" >>> exec "1\r\n2" Traceback (most recent call last): File "", line 1, in exec "1\r\n2" File "", line 1 1 ^ SyntaxError: invalid syntax >>> Get rid of the carriage return. From paul at boddie.org.uk Thu Apr 12 06:06:02 2007 From: paul at boddie.org.uk (Paul Boddie) Date: 12 Apr 2007 03:06:02 -0700 Subject: tuples, index method, Python's design In-Reply-To: References: <1176210960.3430.20.camel@dot.uniqsys.com> <740c3aec0704100810g5f962e8eu614fbaedecf3608e@mail.gmail.com> <1176219856.3430.76.camel@dot.uniqsys.com> <740c3aec0704101021i1fd79ef2l99eac4ced1e252d9@mail.gmail.com> <1176226682.3430.86.camel@dot.uniqsys.com> <4866bea60704101104r4600d281h135286b66378f4d4@mail.gmail.com> <740c3aec0704101534y3c65f5a7je382f97e1f6301b7@mail.gmail.com> <1176305859.581010.199600@n76g2000hsh.googlegroups.com> Message-ID: <1176372362.350332.216710@b75g2000hsg.googlegroups.com> On 12 Apr, 09:37, Antoon Pardon wrote: > > Why then does python itself provide immutables? I find this reasoning > more than baffling. There has been all these arguments about why > it is best to use immutables as dictionary keys. You've answered your own question. If you had a mutable dictionary key, stored something in a dictionary using that key, then modified the key and tried to retrieve the stored item using that same key object, you might never find that item again. This is something of a simplification (you'd have to look into details of things like __hash__ and __eq__, I imagine), but this is just one area where immutability is central to the operation of the feature concerned. Other languages provide some control over immutability with things like "const", and there are good reasons for having such things, although you do need to know what you're doing as a programmer when using them. Some people might argue that the dictionary key example given above is contrived: "Of course it won't work if you modify the key!" they might say. Having some idea of which objects are immutable can provide some protection from inadvertent mutation, however. > But the moment the topic changes, someone else comes with the comment that > wanting your sequence to be immuatble is unpythonic. As soon as "unpythonic" is mentioned we enter subjective territory. Paul From steve at REMOVEME.cybersource.com.au Wed Apr 18 04:32:15 2007 From: steve at REMOVEME.cybersource.com.au (Steven D'Aprano) Date: Wed, 18 Apr 2007 18:32:15 +1000 Subject: What makes an iterator an iterator? References: Message-ID: On Wed, 18 Apr 2007 06:13:39 +0000, I V wrote: > On Wed, 18 Apr 2007 15:39:22 +1000, Steven D'Aprano wrote: >> I thought that an iterator was any object that follows the iterator >> protocol, that is, it has a next() method and an __iter__() method. [snip] > i.e., just rename your _next function to __iter__ . Your class won't > itself be an iterator, but it will be usable in for statements and so one, > and convertable to an iterator with the iter builtin. Thanks to all those who helped, this fixed my problem. For the record, this is what I actually wanted: a four-line self-sorting dictionary: class SortedDict(dict): def __iter__(self): for key in sorted(self.keys()): yield key Note that using sorted(self) does not work. Iterating over a SortedDictionary returns the keys in sorted order. This minimalist implementation doesn't sort the values, items or string representation of the dict, but they should be easy to implement. -- Steven D'Aprano From kw at codebykevin.com Wed Apr 18 20:24:37 2007 From: kw at codebykevin.com (Kevin Walzer) Date: Wed, 18 Apr 2007 20:24:37 -0400 Subject: Future Python Gui? In-Reply-To: <1176941350.215908.310760@n59g2000hsh.googlegroups.com> References: <1176859699.906386.326720@b75g2000hsg.googlegroups.com> <1176863948.526051.186210@n76g2000hsh.googlegroups.com> <1176909848.455264.174730@e65g2000hsc.googlegroups.com> <1176941350.215908.310760@n59g2000hsh.googlegroups.com> Message-ID: <4626B6C5.6090602@codebykevin.com> bcwhite at pobox.com wrote: >> "Tile" has already been mentioned in this thread, and I know >> there'll be at least one more follow-up on the subject. Tile >> includes a ("native"!) notebook, as well as a combobox, tree- >> view, ... . > > It seems that Tile does include a "notebook" widget but it's pure Tcl > code and so isn't available via the Python wrapper. > > -- Brian > That's not correct. When the Tkinter wiki is back up, see the page I referred to. -- Kevin Walzer Code by Kevin http://www.codebykevin.com From jeff at jmcneil.net Mon Apr 9 13:32:55 2007 From: jeff at jmcneil.net (Jeff McNeil) Date: Mon, 9 Apr 2007 13:32:55 -0400 Subject: output of top on a linux box In-Reply-To: <80628d680704091026u7e98719co3d63a7913832475a@mail.gmail.com> References: <80628d680704072342r60b57995mad6c505505a919a8@mail.gmail.com> <80628d680704091026u7e98719co3d63a7913832475a@mail.gmail.com> Message-ID: <82d28c40704091032p3c5fcc35p38ee9509ca3fa7c0@mail.gmail.com> Can you pull the same information from /proc/stat as opposed to using a pipe to top? The first line(s) should contain (at least): cpu usermode, lowprio, system, idle, hz. The 2.6 kernel adds iowait, irq, and soft irq. It seems that this might be a better solution than executing that additional command. Take a look at proc(5). Thanks, Jeff On 4/9/07, Pradnyesh Sawant wrote: > Hello, > I need the cpu usage of a linux box, for which i capture the output of > "top" using "popen". However, i am facing problems during string > handling. The code snippet is:- > > top = os.popen("top -n 1") > rd = top.read().split("\n") > splt = rd[2].split() > # cpu = splt[2][:-4] # why ain't this working ??? > cpu = splt[2] > print "cpu usage: %s, %s" % (cpu, type(cpu)) > > the "print" statement prints, "cpu usage: 0.5%sy, ". i > tried my best to get rid of the "%sy" after the "0.5", but couldn't > succeed (even though the type of "cpu" is "string"). > > Also, one weird thing that was happening was that if i still "split" > the cpu string (removed the last 4 characters), the output of the next > print statement was wrong (specifically, the first 2 characters got > chipped off). This output is totally unexpected, and wrong... > > Can anyone kindly help me in understanding what exactly is going on here. > > Thanks a lot! > -- > http://mail.python.org/mailman/listinfo/python-list > From ptmcg at austin.rr.com Wed Apr 18 04:45:10 2007 From: ptmcg at austin.rr.com (Paul McGuire) Date: 18 Apr 2007 01:45:10 -0700 Subject: What makes an iterator an iterator? In-Reply-To: References: Message-ID: <1176885910.102141.39750@p77g2000hsh.googlegroups.com> On Apr 18, 3:32 am, Steven D'Aprano wrote: > On Wed, 18 Apr 2007 06:13:39 +0000, I V wrote: > > On Wed, 18 Apr 2007 15:39:22 +1000, Steven D'Aprano wrote: > >> I thought that an iterator was any object that follows the iterator > >> protocol, that is, it has a next() method and an __iter__() method. > > [snip] > > > i.e., just rename your _next function to __iter__ . Your class won't > > itself be an iterator, but it will be usable in for statements and so one, > > and convertable to an iterator with the iter builtin. > > Thanks to all those who helped, this fixed my problem. > > For the record, this is what I actually wanted: a four-line self-sorting > dictionary: > > class SortedDict(dict): > def __iter__(self): > for key in sorted(self.keys()): > yield key > > Note that using sorted(self) does not work. > > Iterating over a SortedDictionary returns the keys in sorted order. This > minimalist implementation doesn't sort the values, items or string > representation of the dict, but they should be easy to implement. > > -- > Steven D'Aprano Very neat. Why not this? class SortedDict(dict): def __iter__(self): return iter(sorted(self.keys())) -- Paul From edfialk at gmail.com Mon Apr 16 13:49:33 2007 From: edfialk at gmail.com (edfialk) Date: 16 Apr 2007 10:49:33 -0700 Subject: script for seconds in given month? In-Reply-To: <1176744505.863580.182390@e65g2000hsc.googlegroups.com> References: <1176740556.859125.221980@l77g2000hsb.googlegroups.com> <1176744505.863580.182390@e65g2000hsc.googlegroups.com> Message-ID: <1176745773.092500.47600@w1g2000hsg.googlegroups.com> Jim: I need years too, basically from 1960-2000. Don't want to hardcode all those days :) Matt: Thanks, I will try this out. Paul: I don't believe we need leap seconds. Leap days definitely. I'll let you know how Matt's code works. Any other suggestions feel free to let me know. Thanks all! -Ed From ptmcg at austin.rr.com Wed Apr 11 21:39:12 2007 From: ptmcg at austin.rr.com (Paul McGuire) Date: 11 Apr 2007 18:39:12 -0700 Subject: ANN: pyparsing-1.4.6 released Message-ID: <1176341952.369727.237770@w1g2000hsg.googlegroups.com> I'm happy to announce v1.4.6 of pyparsing has been released. This latest version of pyparsing has a few minor bug-fixes and enhancements, and another performance improvement for recursive grammars (those that use the Forward class). The salient features of this new release are: Simplified the ParseException constructor, to better support the standard exception idiom: raise ParseFatalException, "unexpected text: 'Spanish Inquisition'" Modified cyclic object references within ParseResults objects to use weakrefs, to be gentler on the garbage collector. Added method getTokensEndLoc(), to be called from within a parse action, for those parse actions that need both the starting *and* ending location of the parsed tokens within the input text. Various bug-fixes: - tuple as named result now reports entire tuple, not just first element - SkipTo with include=True now returns the skipped-to tokens properly - makeHTMLTags/makeXMLTags and anyOpenTag and anyCloseTag helpers now recognize attributes and tags with namespaces - countedArray now matches when defined within an Or expression - keepOriginalText now preserves named results fields - fixed Unicode bug in upcase and downcase methods - corrected typo in OnceOnly reset() method - enhanced documentation to describe behavior when parsing input strings containing tabs - cleaned up internal decorators to preserve function names, docstrings, etc. This release also includes some new examples: - holaMundo.py - Spanish translation of HelloWorld - sexpParser.py - S-exp parser - jsonParser.py (update) - minor bug-fixes to previously released example for parsing JSON (JavaScript Object Notation) object serialization strings - macroExpander.py - macro preprocessor to substitute defined macros Download pyparsing 1.4.6 at http://sourceforge.net/projects/pyparsing/. The pyparsing Wiki is at http://pyparsing.wikispaces.com -- Paul ======================================== Pyparsing is a pure-Python class library for quickly developing recursive-descent parsers. Parser grammars are assembled directly in the calling Python code, using classes such as Literal, Word, OneOrMore, Optional, etc., combined with operators '+', '|', and '^' for And, MatchFirst, and Or. No separate code-generation or external files are required. Pyparsing can be used in many cases in place of regular expressions, with shorter learning curve and greater readability and maintainability. Pyparsing comes with a number of parsing examples, including: - "Hello, World!" (English, Korean, Greek, and Spanish(new)) - chemical formulas - configuration file parser - web page URL extractor - 5-function arithmetic expression parser - subset of CORBA IDL - chess portable game notation - simple SQL parser - Mozilla calendar file parser - EBNF parser/compiler - Python value string parser (lists, dicts, tuples, with nesting) (safe alternative to eval) - HTML tag stripper - S-expression parser (new) - macro substitution preprocessor (new) From bbxx789_05ss at yahoo.com Tue Apr 3 19:08:14 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: 3 Apr 2007 16:08:14 -0700 Subject: heap doesn't appear to work as described Message-ID: <1175641694.226975.258820@n76g2000hsh.googlegroups.com> My book says that in a heap, a value at position i will be smaller than the values at positions 2*i and 2*i + 1. To test that, I ran this program: ---------- from heapq import * from random import shuffle data = range(10) shuffle(data) heap = [] for n in data: heappush(heap, n) print heap heappush(heap, .5) print heap -----output:------ [0, 1, 3, 4, 2, 6, 7, 9, 8, 5] [0, 0.5, 3, 4, 1, 6, 7, 9, 8, 5, 2] ---------- In the second heap, at position i=2 there is the value 3. At position 2*i=4, there is the value 1. 3 is not less than 1, which my book claims should be the case. From olsonas at gmail.com Thu Apr 12 16:17:27 2007 From: olsonas at gmail.com (Drew) Date: 12 Apr 2007 13:17:27 -0700 Subject: Code Explaination: Spelling correction code In-Reply-To: References: <1176345676.300560.78020@n59g2000hsh.googlegroups.com> <_tqdnfpprqGxOoDbnZ2dnUVZ_uTinZ2d@comcast.com> <1176381680.678201.233880@b75g2000hsg.googlegroups.com> Message-ID: <1176409047.870796.159290@y80g2000hsf.googlegroups.com> On Apr 12, 10:28 am, Steven Bethard wrote: > Drew wrote: > > On Apr 11, 11:27 pm, Steven Bethard wrote: > >> Drew wrote: > >>> def known_edits2(word): > >>> return set(e2 for e1 in edits1(word) for e2 in edits1(e1) if e2 in > >>> NWORDS) > > >> This is the same as: > > >> result = set() > >> for e1 in edits1(word): > >> for e2 in edits1(e1): > >> if e2 in NWORDS: > >> result.add(e2) > >> return result > > >> The thing between the ``set(`` and ``)`` is called a generator > >> comprehension if you'd like to look into it further. > > > Thanks for the response. I'm somewhat familiar with generator/list > > comprehension but was unsure how multiple statements were evaluated > > when chained together. From your explanation, I'm assuming they are > > evaluated from the "inside out" rather than left to right or right to > > left. > > > Does the mean that the comprehension on the inside is always evaluated > > first? > > Not really (at least for the most literal interpretation of ``evaluated > first``). I find it easiest to think of translating them into regular > for loops by adding the appropriate indentation. > > Starting with: > > (e2 for e1 in edits1(word) for e2 in edits1(e1) if e2 in NWORDS) > > Adding newlines: > > (e2 > for e1 in edits1(word) > for e2 in edits1(e1) > if e2 in NWORDS) > > Adding indentation: > > (e2 > for e1 in edits1(word) > for e2 in edits1(e1) > if e2 in NWORDS) > > Moving the add/append to the bottom: > > for e1 in edits1(word) > for e2 in edits1(e1) > if e2 in NWORDS > e2 > > Adding the remaining boiler-plate: > > result = set() > for e1 in edits1(word): > for e2 in edits1(e1): > if e2 in NWORDS: > result.add(e2) > > So multiple for- and if-expressions are evaluated in the same order that > they would normally be in Python, assuming the proper whitespace was added. > > HTH, > > STeVe Wow, thanks for having the patience to write that out. This makes perfect sense now. -Drew From rampeters at gmail.com Sat Apr 28 21:55:56 2007 From: rampeters at gmail.com (johnny) Date: 28 Apr 2007 18:55:56 -0700 Subject: Any Good tools to create CSV Files? Message-ID: <1177811756.255774.315260@q75g2000hsh.googlegroups.com> Any Good tools to create CSV Files? ReportLab only creates pdf files. I need something to create CSV files. Thank you. From bbxx789_05ss at yahoo.com Wed Apr 11 06:03:15 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: 11 Apr 2007 03:03:15 -0700 Subject: __file__ In-Reply-To: References: <1176250851.946892.273550@l77g2000hsb.googlegroups.com> Message-ID: <1176285795.667520.120230@l77g2000hsb.googlegroups.com> Hi, Thanks for the response. On Apr 11, 12:49 am, "Gabriel Genellina" wrote: > > __file__ corresponds to the filename used to locate and load the module, > whatever it is. When the module is found on the current directory > (corresponding to '' in sys.path), you get just the filename; if sys.path > contains a relative path, that's what you get; the same for any absolute > path. > Whatever path worked to find and load the module, that's stored as > __file__. > > If you plan to use it, it's a good idea to make it early into an absolute > path (using os.path.abspath(__file__)) just in case the current directory > changes. > That last part doesn't seem to fit with your description above. What does the current working directory have to do with the path that was used to load a module? I would think the path that was used to load a module is constant. From python.technofreak at gmail.com Sun Apr 1 09:09:44 2007 From: python.technofreak at gmail.com (Parthan SR) Date: Sun, 1 Apr 2007 18:39:44 +0530 Subject: help with dates In-Reply-To: <1175376083.763091.128700@b75g2000hsg.googlegroups.com> References: <1175376083.763091.128700@b75g2000hsg.googlegroups.com> Message-ID: <9d6d3deb0704010609x7ebabec1maad13aa89f0afd75@mail.gmail.com> On 31 Mar 2007 14:21:23 -0700, rustybear at gmail.com wrote: > > > 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: > I have a small program for you, hope this helps. dutycycle.py ---------------- #!/usr/bin/env python """Data Cycle Finder The input date is of the form dd/mm/yyyy. """ from datetime import date import sys def dutyfinder(_date): start = date(2007,1,1) # the duty cycle started on 1st jan 2007 return (date.toordinal(_date)-date.toordinal(start))%4 indate = sys.argv[1].split('/') enddate = date(int(indate[2]),int(indate[1]),int(indate[0])) onduty = int(dutyfinder(enddate)) + 1 print onduty --------------------------- Now, call this program with your input date in dd/mm/yyyy format. You can modify the code to suit mm/dd/yyyy format . Also modify the start date which is now 1st January 2007. The output will be the number of the group. Ex: $ python dutycycle.py 10/1/2007 output: 2 -- With Regards Parthan "Technofreak" http://technofreakatchennai.wordpress.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From bbxx789_05ss at yahoo.com Wed Apr 18 18:41:07 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: 18 Apr 2007 15:41:07 -0700 Subject: What makes an iterator an iterator? In-Reply-To: <1hwr9pv.13v4ci6106qn0aN%aleax@mac.com> References: <1hwr9pv.13v4ci6106qn0aN%aleax@mac.com> Message-ID: <1176936067.315082.17970@y80g2000hsf.googlegroups.com> On Apr 18, 8:50 am, a... at mac.com (Alex Martelli) wrote: > The special methods need to be on the type -- having attributes of those > names on the instance doesn't help (applies to all special methods in > the normal, aka newstyle, object model; legacy, aka classic, classes, > work by slightly different and not entirely self-consistent semantics). > > Alex Can you explain some of the details of why this code fails: --- class Parrot(object): def __iter__(self): return self def __init__(self): self.next = self.next().next def next(self): for word in "Norwegian Blue's have beautiful plumage!".split(): yield word P = Parrot() for word in P: print word ------ It causes an infinite loop that just prints out the iterator object returned when you call the generator function. If I try this: ----- class Parrot(object): def __iter__(self): return self def __init__(self): print self.next() print self.next().next #self.next = self.next().next def next(self): for word in "Norwegian Blue's have beautiful plumage!".split(): yield word P = Parrot() ''' for word in P: print word ''' ---------- the output is: Based on that output, self.next() is the iterator object that wraps the generator function, and it has a next() method. If 'i' is the iterator object, then the statement: self.next = self.next().next is equivalent to: self.next = i.next and therefor calling P.next() is equivalent to i.next(), which appears to be exactly what you want. As I understand it, this is how the for loop works: 1) The for loop causes the built in, global iter() function to be called with P as an argument: iter(P). That calls P's __iter__() method, which just returns P. 2) The for loop repeatedly calls next() on whatever object is returned by 1), so that results in calls to P.next(). 3) P.next() is equivalent to i.next() I don't understand at which step does the code fail. From someguywithoutanemailaddress Sat Apr 28 21:21:39 2007 From: someguywithoutanemailaddress (Alvin Bruney [MVP]) Date: Sat, 28 Apr 2007 21:21:39 -0400 Subject: SEO - Search Engine Optimization - Seo Consulting References: <1177808356.681710.42980@n76g2000hsh.googlegroups.com> Message-ID: Please don't spam this group -- Regards, Alvin Bruney ------------------------------------------------------ Shameless author plug Excel Services for .NET is coming... OWC Black book on Amazon and www.lulu.com/owc Professional VSTO 2005 - Wrox/Wiley wrote in message news:1177808356.681710.42980 at n76g2000hsh.googlegroups.com... > Free Seo Consulting http://seo-optimizer.blogspot.com/ > From gagsl-py2 at yahoo.com.ar Thu Apr 5 15:39:08 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 05 Apr 2007 16:39:08 -0300 Subject: Trouble w/ 'create table' sql on mx.ODBC References: <9860747.post@talk.nabble.com> Message-ID: En Thu, 05 Apr 2007 16:25:08 -0300, Greg Corradini escribi?: > Lately I've been using the mx.ODBC module to query Access (mdb) tables. > For > the life of me, I can't get the 'create table' sql command to work. I use > this command in Oracle and I've seen other mx.ODBC users weave into their > scripts for Access. But I still can't get this simple test run below to > work And the error is...? Please copy the full exception traceback. -- Gabriel Genellina From elguavas at users.sourceforge.net Thu Apr 19 21:54:26 2007 From: elguavas at users.sourceforge.net (Stephen M. Gava) Date: Fri, 20 Apr 2007 01:54:26 -0000 Subject: using tkinter to display html References: <1176988173.015892.273660@e65g2000hsc.googlegroups.com> Message-ID: On Thu, 19 Apr 2007 06:09:33 -0700, kyosohma wrote: > On Apr 19, 6:29 am, "Stephen M. Gava" > wrote: >> Hi all, >> >> I prefer using tkinter to wxpython (so sue me :) and i need to display >> a lot of html in a particular app. does anyone know if one of the >> existing add on tk html widgets have been wrapped for tkinter already? >> >> TIA for any reply, >> Stephen > > The following thread has various ideas in it: > http://mail.python.org/pipermail/python-list/2001-October/107989.html thanks mike, i found that thread before i posted here, it doesn'rt answer my question though. > > I know wxpython has widgets specifically made to display html or even > wrap Internet Explorer, ActiveX and more. yeah. i feel like i'm being forced to use wxwidgets/wxpython just because i need pretty good html display though. oh well. stephen. > > Good luck! > > Mike From bbxx789_05ss at yahoo.com Thu Apr 5 14:53:35 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: 5 Apr 2007 11:53:35 -0700 Subject: defining functions In-Reply-To: <1175798327.249407.129860@o5g2000hsb.googlegroups.com> References: <1175798327.249407.129860@o5g2000hsb.googlegroups.com> Message-ID: <1175799215.335755.137220@n76g2000hsh.googlegroups.com> On Apr 5, 12:38 pm, "Andre P.S Duarte" wrote: > How do I define a function, then import it, without having to save it > in lib; like "C:\python25\lib". ? ...or permanently set your PYTHONPATH environment variable to the folders you want python to look in for the modules you import. That way you won't have to use sys.path.append() to temporarily append the path in all your programs. From steve at REMOVEME.cybersource.com.au Thu Apr 19 23:34:09 2007 From: steve at REMOVEME.cybersource.com.au (Steven D'Aprano) Date: Fri, 20 Apr 2007 13:34:09 +1000 Subject: What makes an iterator an iterator? References: <1hwr9pv.13v4ci6106qn0aN%aleax@mac.com> <1176936067.315082.17970@y80g2000hsf.googlegroups.com> <1hws6rd.u0a6hd78fhhpN%aleax@mac.com> <1176961515.450458.189530@p77g2000hsh.googlegroups.com> <1hwu1em.1tnjyg91wzltipN%aleax@mac.com> Message-ID: On Thu, 19 Apr 2007 20:00:31 -0700, Alex Martelli wrote: > class sane(object): > def __init__(self, sentence='four scores and twenty years ago'): > def agenerator(): > for word in sentence.split(): yield word > self._thegen = agenerator() > def __iter__(self): return self > def next(self): return self._thegen.next() Nice technique! I always forget about nesting functions like that. I should use it more often. -- Steven D'Aprano From ianare at gmail.com Fri Apr 6 15:37:42 2007 From: ianare at gmail.com (=?iso-8859-1?B?aWFuYXLp?=) Date: 6 Apr 2007 12:37:42 -0700 Subject: real time updating of popen, bufsize=0 problems In-Reply-To: <1175887330.532994.30840@d57g2000hsg.googlegroups.com> References: <1175885074.694737.261430@e65g2000hsc.googlegroups.com> <1175887330.532994.30840@d57g2000hsg.googlegroups.com> Message-ID: <1175888262.359961.53520@e65g2000hsc.googlegroups.com> On Apr 6, 3:22 pm, kyoso... at gmail.com wrote: > On Apr 6, 1:44 pm, "ianar?" wrote: > > > > > hey all, I'm trying to get real time updates of batch file output. > > > Here is my batch file: > > @echo off > > echo 1 > > @ping 127.0.0.1 -n 2 -w 1500 > nul > > echo 2 > > @ping 127.0.0.1 -n 2 -w 1500 > nul > > echo 3 > > > If I run it in cmd.exe it will print "1", wait 15sec, print "2", wait > > 15sec, print "3". > > > I tried doing it like this: > > > r, w, e = popen2.popen3('"C:/path/to/test.bat"',bufsize=0) > > for line in r: > > self.display.WriteText(line) > > > ... but get: ValueError: popen3() arg 3 must be -1 > > > If I use -1, then it waits for the batch file to complete, and prints > > out all 3 lines at once. > > > So I tried subprocess: > > proc = subprocess.Popen('"C:/path/to/test.bat"', bufsize=0, > > stdout=subprocess.PIPE) > > for line in proc.stdout: > > self.display.WriteText(line) > > > No error message, but no real time printing either. > > > info: > > self.display is a wx.TextCtrl - not that it should matter,as > > 'WriteText()' behaves basically like 'print' > > winXP pro SP2, python 2.5, wxPython 2.6.3.3 > > > You help is appreciated. > > Hi, > > I think this script on another post will help: > > http://groups.google.com/group/comp.lang.python/msg/9fa3a3c287e8e2a3?... > > The 4 line code example (from Daniel) in one of the posts at this link > worked with your batch file:http://www.velocityreviews.com/forums/t350573-redirect-ossystem-outpu... > > Mike Thanks but it doesn't work. Still prints it out all at once. It is supposed to print, then wait 15sec for the next line to print. From aleax at mac.com Thu Apr 19 23:39:57 2007 From: aleax at mac.com (Alex Martelli) Date: Thu, 19 Apr 2007 20:39:57 -0700 Subject: Python un-plugging the Interpreter References: Message-ID: <1hwu415.1yyvbo61efn1uqN%aleax@mac.com> Steve Holden wrote: > A long time ago Greg Stein produced a patch that removed the need for > the GIL, but nobody seemed to want to pay the penalty it extracted in > speed reduction, so it languished unadopted. Perhaps the current wave of dual-core and quad-core CPUs in cheap consumer products would change people's perceptions -- I wonder... Alex From steve at REMOVE.THIS.cybersource.com.au Sun Apr 1 06:55:30 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Sun, 01 Apr 2007 20:55:30 +1000 Subject: Generic logic/conditional class or library for classification of data References: <1175403286.809692.100080@n59g2000hsh.googlegroups.com> Message-ID: On Sat, 31 Mar 2007 21:54:46 -0700, Basilisk96 wrote: > As a very basic example, consider a set of uncategorized objects that > have text descriptions associated with them. The objects are some type > of tangible product, e.g., books. So the input object has a > Description attribute, and the output object (a categorized book) > would have some attributes like Discipline, Target audience, etc. > Let's say that one such rule is "if ( 'description' contains > 'algebra') then ('discipline' = 'math', 'target' = 'student')". Keep > in mind that all these attribute names and their values are not known at > design time. Easy-peasy. rules = {'algebra': {'discipline': 'math', 'target': 'student'}, 'python': {'section': 'programming', 'os': 'linux, windows'}} class Input_Book(object): def __init__(self, description): self.description = description class Output_Book(object): def __repr__(self): return "Book - %s" % self.__dict__ def process_book(book): out = Output_Book() for desc in rules: if desc in book.description: attributes = rules[desc] for attr in attributes: setattr(out, attr, attributes[attr]) return out book1 = Input_Book('python for cheese-makers') book2 = Input_Book('teaching algebra in haikus') book3 = Input_Book('how to teach algebra to python programmers') >>> process_book(book1) Book - {'section': 'programming', 'os': 'linux, windows'} >>> process_book(book2) Book - {'discipline': 'math', 'target': 'student'} >>> process_book(book3) Book - {'discipline': 'math', 'section': 'programming', 'os': 'linux, windows', 'target': 'student'} I've made some simplifying assumptions: the input object always has a description attribute. Also the behaviour when two or more rules set the same attribute is left undefined. If you want more complex rules you can follow the same technique, except you'll need a set of meta-rules to decide what rules to follow. But having said that, I STRONGLY recommend that you don't follow that approach of creating variable instance attributes at runtime. The reason is, it's quite hard for you to know what to do with an Output_Book once you've got it. You'll probably end up filling your code with horrible stuff like this: if hasattr(book, 'target'): do_something_with(book.target) elif hasattr(book, 'discipline'): do_something_with(book.discipline) elif ... # etc. Replacing the hasattr() checks with try...except blocks isn't any less icky. Creating instance attributes at runtime has its place; I just don't think this is it. Instead, I suggest you encapsulate the variable parts of the book attributes into a single attribute: class Output_Book(object): def __init__(self, name, data): self.name = name # common attribute(s) self.data = data # variable attributes Then, instead of setting each variable attribute individually with setattr(), simply collect all of them in a dict and save them in data: def process_book(book): data = {} for desc in rules: if desc in book.description: data.update(rules[desc]) return Output_Book(book.name, data) Now you can do this: outbook = process_book(book) # handle the common attributes that are always there print outbook.name # handle the variable attributes print "Stock = %s" % output.data.setdefault('status', 0) print "discipline = %s" % output.data.get('discipline', 'none') # handle all the variable attributes for key, value in output.data.iteritems(): do_something_with(key, value) Any time you have to deal with variable attributes that may or may not be there, you have to use more complex code, but you can minimize the complexity by keeping the variable attributes separate from the common attributes. -- Steven. From see_signature at nospam.nowire.org Thu Apr 26 04:25:21 2007 From: see_signature at nospam.nowire.org (=?ISO-8859-15?Q?Thomas_Kr=FCger?=) Date: Thu, 26 Apr 2007 10:25:21 +0200 Subject: str() and repr() question In-Reply-To: <1177575127.034458.243760@t38g2000prd.googlegroups.com> References: <1177575127.034458.243760@t38g2000prd.googlegroups.com> Message-ID: adima schrieb: > str = DoTestTime(EachFile) ^^^ > print type(str) > for s in str: > print s > out.write(str(s)) ^^^ > Where is the problem here? > Thanks in advance. > You have overwritten the built-in str function some lines above. Thomas -- sinature: http://nospam.nowire.org/signature_usenet.png From steve at holdenweb.com Sun Apr 15 20:48:41 2007 From: steve at holdenweb.com (Steve Holden) Date: Sun, 15 Apr 2007 20:48:41 -0400 Subject: Getting started with python In-Reply-To: <%LyUh.10121$YL5.5753@newssvr29.news.prodigy.net> References: <1176598011.463543.96990@q75g2000hsh.googlegroups.com> <1176608302.928513.274400@y5g2000hsa.googlegroups.com> <%LyUh.10121$YL5.5753@newssvr29.news.prodigy.net> Message-ID: <4622C7E9.5020802@holdenweb.com> James Stroud wrote: > Gabriel Genellina wrote: >> En Sun, 15 Apr 2007 10:46:54 -0300, Army1987 escribi?: >> >>> "Paddy" ha scritto nel messaggio >>> news:1176608302.928513.274400 at y5g2000hsa.googlegroups.com... >>> >>>> On a different tack, from: >>>> http://tickletux.wordpress.com/2007/01/24/using-fizzbuzz-to-find-developers-who-grok-coding/ >>>> >>>> It seems you need to learn how to write a Fizz-Buzz >>>> program to get a job now-a-days :-) >>> Something less idiotic? I took longer to type a program to do that >>> than to >>> figure out how to do that. >> We've used it as part of a test a few weeks ago. You'd be surprised on >> how many guys couldn't write anything remotely sensible. >> >> --Gabriel Genellina > > py> for i in xrange(1,101): > ... if not i % 15: > ... print 'fizzbuzz' > ... continue > ... if not i % 5: > ... print 'buzz' > ... continue > ... if not i % 3: > ... print 'fizz' > ... else: > ... print i > ... > > I typed this without so much as hitting delete. Didn't time it but I'm > guessing less than 2 minutes. How much am I worth a year? (Hopefully > capitalization is not important for this exercise.) > You'd be worth more if you'd used elif and omitted the continue statements, but for a first solution it's acceptable. For better readability I'd have used if i % 5 == 0 rather than if not i % 5 but that's mostly a stylistic matter. regards Steve 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 aahz at pythoncraft.com Sun Apr 22 12:18:27 2007 From: aahz at pythoncraft.com (Aahz) Date: 22 Apr 2007 09:18:27 -0700 Subject: Flat DB seeking speed References: <1177216068.518970.29470@o5g2000hsb.googlegroups.com> Message-ID: In article <1177216068.518970.29470 at o5g2000hsb.googlegroups.com>, Jia Lu wrote: > > I see there are lots of flat db or db-like modules in the standard >python modules. > What about the keywords seeking speed of them ? > > (I want to put about 10000 articles with 10000 IDs, and I can do >searching keywords with them) > > The db-like modules are : > dbm, gdbm, dbhash,anydbm, > pickle(cPickle), shelve, marshal Another option would be to use a real database, such as SQLite. Then you could easily create an inverted index with your keywords. This is a good alternative to full-text indexing when you otherwise want DB capabilities (such as for storing other information with your articles). -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Help a hearing-impaired person: http://rule6.info/hearing.html From steve at REMOVEME.cybersource.com.au Mon Apr 30 04:41:33 2007 From: steve at REMOVEME.cybersource.com.au (Steven D'Aprano) Date: Mon, 30 Apr 2007 18:41:33 +1000 Subject: Qustion about struct.unpack References: Message-ID: On Mon, 30 Apr 2007 00:45:22 -0700, OhKyu Yoon wrote: > Hi! > I have a really long binary file that I want to read. > The way I am doing it now is: > > for i in xrange(N): # N is about 10,000,000 > time = struct.unpack('=HHHH', infile.read(8)) > # do something > tdc = struct.unpack('=LiLiLiLi',self.lmf.read(32)) I assume that is supposed to be infile.read() > # do something > > Each loop takes about 0.2 ms in my computer, which means the whole for loop > takes 2000 seconds. You're reading 400 million bytes, or 400MB, in about half an hour. Whether that's fast or slow depends on what the "do something" lines are doing. > I would like it to run faster. > Do you have any suggestions? Disk I/O is slow, so don't read from files in tiny little chunks. Read a bunch of records into memory, then process them. # UNTESTED! rsize = 8 + 32 # record size for i in xrange(N//1000): buffer = infile.read(rsize*1000) # read 1000 records at once for j in xrange(1000): # process each record offset = j*rsize time = struct.unpack('=HHHH', buffer[offset:offset+8]) # do something tdc = struct.unpack('=LiLiLiLi', buffer[offset+8:offset+rsize]) # do something (Now I'm just waiting for somebody to tell me that file.read() already buffers reads...) -- Steven D'Aprano From bbxx789_05ss at yahoo.com Sat Apr 14 04:22:10 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: 14 Apr 2007 01:22:10 -0700 Subject: reading from sys.stdin In-Reply-To: References: <1176366058.261031.111870@p77g2000hsh.googlegroups.com> <1176387908.406115.270630@w1g2000hsg.googlegroups.com> <1176438754.995753.50190@d57g2000hsg.googlegroups.com> <1176454871.538968.176620@n76g2000hsh.googlegroups.com> <1176457007.589050.285400@d57g2000hsg.googlegroups.com> Message-ID: <1176538930.891355.230880@n59g2000hsh.googlegroups.com> On Apr 13, 6:20 am, Michael Hoffman wrote: > 7stud wrote: > > On Apr 13, 3:13 am, Michael Hoffman wrote: > >> 7stud wrote: > >>> I assume all input is buffered by default, so I'm not sure how it > >>> explains things to say that input from sys.stdin is buffered. > >> The difference with sys.stdin is that it has indeterminate length until > >> you signal EOF. I believe you'd get the same problem reading from, say, > >> a named pipe. > > > Couldn't you say the same thing about a file you are iterating over? > > Only if the file has indeterminate length. Regular files have a length. > > >>>> This should be f = iter(raw_input,"") and this will end in a EOFError > >>>> and stop on blank line. So you need a wrapper > >>> Why a wrapper? > >> Because without a wrapper you'll get EOFError, while the file iterator > >> would ordinarily give you StopIteration. > > > Did you run my example? Did you get an error? I don't get an error. > > Yes I did. I did get an error. > > >>> lst = [] > >>> f = iter(raw_input, "") > >>> for line in f: > ... lst.append(line) > ... > abc > def > Traceback (most recent call last): > File "", line 1, in > EOFError > -- > Michael Hoffman But if you hit return on a blank line, there is no error. In other words, will stop on a blank line and not return EOFError. Anyway, it seems everyone is saying that when you iterate over a file, the whole file is first read into memory. Therefore iterating over sys.stdin is consistent: you have to type Ctrl+D to signal EOF before the iteration can start. Is that about right? From bj_666 at gmx.net Tue Apr 3 11:45:48 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Tue, 03 Apr 2007 17:45:48 +0200 Subject: raw_input just continues anyway? References: <1175606844.249364.290060@o5g2000hsb.googlegroups.com> <57f489F2c787iU1@mid.individual.net> <1175611910.685578.246780@w1g2000hsg.googlegroups.com> Message-ID: In <1175611910.685578.246780 at w1g2000hsg.googlegroups.com>, oliver at obeattie.com wrote: > if __name__ == "__main__": > bucket_name = raw_input('Name of the bucket you wish the files to be > placed into? ') > update_s3() > > > Basically I pipe some files into the script - so would this cause a > linebreak? Yes of course. `raw_input()` is reading from `stdin` so the very first line you pipe in will be assigned to `bucket_name`. Ciao, Marc 'BlackJack' Rintsch From Roka100 at gmail.com Thu Apr 12 23:16:00 2007 From: Roka100 at gmail.com (Jia Lu) Date: 12 Apr 2007 20:16:00 -0700 Subject: Problem with algorithm Message-ID: <1176434160.047703.214600@q75g2000hsh.googlegroups.com> Hi all. I want to create a large list like: aaaa ~ zzzz Is there any good algorithm to do this? Thanx Jia Lu From bdesth.quelquechose at free.quelquepart.fr Sun Apr 22 12:30:32 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sun, 22 Apr 2007 18:30:32 +0200 Subject: Dictionaries and dot notation In-Reply-To: <23087554.X5dcTmlj7P@beaureve.gmx.net> References: <23087554.X5dcTmlj7P@beaureve.gmx.net> Message-ID: <462b842e$0$28548$426a74cc@news.free.fr> Martin Drautzburg a ?crit : > This may be pretty obvious for most of you: > > When I have an object (an instance of a class "Foo") I can access > attributes via dot notation: > > aFoo.bar > > however when I have a dictionary > > aDict = {"bar":"something"} > > I have to write > > aDict["bar"] > > What if I want to create a datastructure that can be used in dot > notation without having to create a class, i.e. because those objects > have no behavior at all? A class inheriting from dict and implementing __getattr__ and __setattr__ should do the trick... From michael at jedimindworks.com Tue Apr 24 16:48:54 2007 From: michael at jedimindworks.com (Michael Bentley) Date: Tue, 24 Apr 2007 15:48:54 -0500 Subject: Blank rows resulting from simple csv script In-Reply-To: <1177446930.186383.213470@r35g2000prh.googlegroups.com> References: <1177446930.186383.213470@r35g2000prh.googlegroups.com> Message-ID: <1803D940-95F7-4337-83FE-B44461DACD1E@jedimindworks.com> On Apr 24, 2007, at 3:35 PM, Drew wrote: > Hi all - > > I've written a simple script to read a .csv file and then write out > rows to a new file only if the value in the 4th column is a 0. Here's > the code: > > import csv > > reader = csv.reader(open('table_export.csv','rb')) > > writer = csv.writer(open('new_jazz.csv','w')) > > for row in reader: > if row[3] == '0': > writer.writerow(row) > > This is writing out the correct rows, however it is writing a blank > row between each of the rows written out. Any ideas? Write in binary mode. From steve at REMOVE.THIS.cybersource.com.au Sat Apr 14 21:12:27 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Sun, 15 Apr 2007 11:12:27 +1000 Subject: Python Feature Request: Explicit variable declarations References: <1176546078.934340.253810@y5g2000hsa.googlegroups.com> <1176557734.456820.275780@p77g2000hsh.googlegroups.com> Message-ID: On Sat, 14 Apr 2007 15:55:03 +0000, Dennis Lee Bieber wrote: > Names are references to the RHS object itself. > > a = 5 > > means that somewhere in memory is an integer object with the value "5"; > the name "a" is now "pasted onto" that integer object. That's not correct, as it implies that the object 5 knows which names (if any) it is associated with. That's not the case: objects don't know which names point to them. What actually happens is that the current namespace gains an entry "a", which points to the existing object 5. > b = a > > finds the object that has the name "a" stuck to it, and sticks a second > name "b" onto the same object. It most certainly does not. What it does is add another name into the namespace, "b", and points it to the same object as "a" already points to. We shouldn't be frightened of introducing namespaces to newbies. They have to learn sooner or later, and they aren't hard to learn. Sometimes over-simplifying is worse than not simplifying at all. A namespace is just a thing in memory that the Python compiler looks up names. They are very important to Python. -- Steven. From carsten at uniqsys.com Thu Apr 26 01:05:06 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Thu, 26 Apr 2007 01:05:06 -0400 Subject: Feedback on Until recipe In-Reply-To: <1177553497.739324.135970@r35g2000prh.googlegroups.com> References: <1177430903.027128.86480@o40g2000prh.googlegroups.com> <1177553497.739324.135970@r35g2000prh.googlegroups.com> Message-ID: <1177563906.3210.27.camel@localhost.localdomain> On Wed, 2007-04-25 at 19:11 -0700, Paul McGuire wrote: > I moved the state into the Until instance vs. the Until class, so that > it now supports nesting. But the calling syntax is even uglier - but > necessary to avoid creating a new Until instance each time around. > That is "while Until(blah):" evaluates and constructs a new Until > instance each time around the loop, so that is why the state had to be > kept in a class-level variable in your original design (which is why > nesting doesn't work). > > class Until: > def __init__(self, mybool): > self.lastTest = True > self.mybool = mybool > > def __nonzero__(self): > ret,self.lastTest = self.lastTest,self.mybool() > return ret > > i = 0 > u1 = Until(lambda : i < 0 ) > while u1: > print "hello" > i += 1 > j = 0 > u2 = Until(lambda : j < 0 ) > while u2: > print "byebye" > j += 1 Using iterators is a way around the problem of making a new instance every time around the loop, but the calling syntax is not much nicer since it is shoehorned into a for-loop. Note that I've renamed the beast in order to reflect what it actually does: The loop body is repeated as long as the given condition is true. class RepeatAsLongAs(object): def __init__(self, cond): self.cond = cond self.previousTest = True def __iter__(self): return self def next(self): ret, self.previousTest = self.previousTest, self.cond() if not ret: raise StopIteration return ret i = 0 for _ in RepeatAsLongAs(lambda: i<0): print "hello" i += 1 j = 0 for _ in RepeatAsLongAs(lambda: j<0): print "byebye" j += 1 Having said that, I don't see myself ever using such a beast. The equivalent code while True: # do something if until_condition: break is much more concise, much easier to understand, and it shows explicitly that the condition is checked after the loop body is executed. -Carsten From carsten at uniqsys.com Tue Apr 3 13:41:51 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Tue, 03 Apr 2007 13:41:51 -0400 Subject: Extracting a file from a tarball In-Reply-To: <09042D621CD4AA479C678463F3A646D0F73DD5@sottemail1.ent.ad.cognos.com> References: <09042D621CD4AA479C678463F3A646D0F73DD5@sottemail1.ent.ad.cognos.com> Message-ID: <1175622111.3456.47.camel@dot.uniqsys.com> On Tue, 2007-04-03 at 13:26 -0400, Boudreau, Emile wrote: > I am trying to extract one file from a tarball, without success. This > is the code I'm using to open the tarball and extract the file: > > tar = tarfile.open(component+'-win32-app-'+bestVersion+'-dev.tar.gz', > 'r') > extractedFile = tar.extractfile('symbols.xml') > > And this is my error: > > Traceback (most recent call last): > File "C:\CognosInstalls\AutoTest\PollDir.py", line 121, in > main() > File "C:\CognosInstalls\AutoTest\PollDir.py", line 119, in main > extract('c:\\', 'I:\\daily\\'+components[i], components[i]) > File "C:\CognosInstalls\AutoTest\PollDir.py", line 27, in extract > filelike = tar.extractfile('symbols.xml') > File "C:\Python25\lib\tarfile.py", line 1488, in extract > tarinfo = self.getmember(member) > File "C:\Python25\lib\tarfile.py", line 1171, in getmember > raise KeyError("filename %r not found" % name) > KeyError: "filename 'symbols.xml' not found" > > I know that the tarball contants this file "symbols.xml" What does tar.getnames() return? -Carsten From bill.sloman at ieee.org Fri Apr 27 08:53:09 2007 From: bill.sloman at ieee.org (bill.sloman at ieee.org) Date: 27 Apr 2007 05:53:09 -0700 Subject: *** Dr G Polya BRILLIANTLY analyses the Virgina Shooting Incident *** In-Reply-To: <4631D78D.5050700@nospam.com> References: <1177266754.126153.202760@b58g2000hsg.googlegroups.com> <1177287460.376404.323520@b58g2000hsg.googlegroups.com> <1177416547.394200.314950@r3g2000prh.googlegroups.com> <1177447632.371289.38180@r30g2000prh.googlegroups.com> <4631D78D.5050700@nospam.com> Message-ID: <1177678387.922081.207280@t38g2000prd.googlegroups.com> On Apr 27, 12:59 pm, Fred Bloggs wrote: > bill.slo... at ieee.org wrote: > > On Apr 24, 2:09 pm, Quadibloc wrote: > > >>The Real Andy wrote: > > >>>Makes me wonder about the credibility of any statement Dr Gideon Polya > >>>makes. > > >>. > >>I never thought that I would feel the urge to call someone an > >>edelweiss-eating Tanzanian devil, but Dr. Polya proved that I lacked > >>imagination. > > >>(Note that "Tanzanian" is pronounced Tan.zan._ee_.yan, not > >>Tan._zayn_.ee.an; one wouldn't want to spoil the effect.) > > > What really spoils the effect is that Dr. Polya lives in Tasmania, a > > state of Australia, and not in Tanzania, which is a country in East > > Africa. > > > Semi-literate Americans do tend to confuse the two places, as they > > also tend confuse Australia and Austria. Oddly enough, edelweiss grows > > in Austria, so Dr. Polya would have to import it from Europe if he > > were in the habit of dining on edelweiss - which would be an eccentric > > habit, even in Austria, where the flower doesn't form part of the > > normal diet. > > > -- > > Bill Sloman, Nijmegen > > Is there any civilized life in Tasmania? It looks like just another > natural wonderland that was raped, pillaged, exploited for its > resources, and left behind. The pillaging and rapine continues. The Green Party has managed to protect some of the more interesting elements of the ecology, but the paper mills where my father was research manager for as long as we lived in Tasmania continues to chop down a lot of trees. They liked to claim that their wood felling was sustainable, but since the cycle of felling and regrowth they had in mind at the time worked on a 200 year cycle, and the business was set up in the late 1930s, there wasn't a lot of farmed timber going into the wood chippers at the time. How it works at the moment isn't clear - two hundred year old wood isn't ideal for making paper. >Even the official tourism site makes the > place seem dull and bereft of any kind of enthusiasm, warning the > prospective visitor that life is slow there. The population is only around 350,000 on an island the size of Ireland. The state has the highest fertility and the lowest rate of population growth of all the Australian states - anybody who is any good leaves, as I did, and pursues a career someplace where there are careers worth pursuing. > I did not know Erol Flynn was from there. He was born there, but left Tasmania fairly early (like everybody else) - his father, the "distinguished Australian marine biologist/ zoologist Prof. Theodore Thomson Flynn" was presumably working at the University of Tasmania in Hobart in 1909. >That's something anyway. They might consider making his > boyhood home a museum or something. And was that Gunn Forestry you know > so well. I don't know anything about Gunn Forestry. The Green Party obviously doesn't like it, but they do have a tendency to describe 25-year-old regrowth forests as "virgin primeval rainforest" because the lie plays better to their target audience than would the more nuanced truth. The paper mill where my father worked had to severely restrict the proportion of old-growth wood - trunks more than four feet (1,2 metres) in diameter - because the lignin in the older wood contained a relatively high proportion of some organic acid that messed up the caustic soda recovery cycle - and IIRR preferentially logged regrowth forests that had grown up in areas clear-felled after the first world war in order to provide cattle-raising farms for soldiers coming back from the First World War. The farms were not successful, and the land rapidly went back to forest. My father was the guy who worked out that a high proportion of old wood was what messed up the soda recovery process, and he hired the Norwegian chemist - Asbjorn Baklien - who worked out how the old wood caused the problem. Asbjorn went on to a brilliant career with ICI and Monash University. http://www.asap.unimelb.edu.au/bsparcs/biogs/P003354b.htm -- Bill Sloman, Nijmegen From gigs at hi.t-com.hr Tue Apr 24 16:58:26 2007 From: gigs at hi.t-com.hr (Gigs_) Date: Tue, 24 Apr 2007 22:58:26 +0200 Subject: tkinter paint program In-Reply-To: References: Message-ID: Wojciech Mu?a wrote: > Gigs_ wrote: >> I'm working on tkinter paint program, mostly to learn tkinter canvas. >> I have method which create buttons for oval, rectangle, line, polygon >> etc. >> How to make oval button to be sunken when i click it and to remain >> sunken until i click on another button (like rectangle and than is >> another button sunken)? > > You can use radiobuttons. If attribute indicatoron is 0, then > radiobuttons are drawn as regular buttons. With attribute > selectcolor you can set background color of selected button. > > w. thanks, thats exactly i need From apardon at forel.vub.ac.be Mon Apr 23 03:43:21 2007 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 23 Apr 2007 07:43:21 GMT Subject: Do other Python GUI toolkits require this? References: <462697A6.6010007@codebykevin.com> <462b3c76$0$10200$9b4e6d93@newsspool4.arcor-online.net> Message-ID: On 2007-04-22, Ren? Fleschenberg wrote: > Antoon Pardon schrieb: >>> Who says the axes are labeled "familiarity" and "learning period"? I >>> just assume they are labeled (y-axis) "Effort" and (x-axis) "Knowledge" >>> (or "skill" or ....). >> >> You can assume all you want, but no serious person processing numbers >> would choose axes like that. > > The vast majority of world population is not into "processing numbers", > so why should they care? They don't have to care at all. But if they don't care about how curves are usually organized, maybe they are better of not using curves to bring a message across, since it risks to bring the wrong message to those who are familiar with curves. -- Antoon Pardon From bdesth.quelquechose at free.quelquepart.fr Sat Apr 21 15:53:23 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sat, 21 Apr 2007 21:53:23 +0200 Subject: Do other Python GUI toolkits require this? In-Reply-To: <2163b$462a2d59$4275d90a$19243@FUSE.NET> References: <2163b$462a2d59$4275d90a$19243@FUSE.NET> Message-ID: <462a6241$0$31989$426a34cc@news.free.fr> Kevin Walzer a ?crit : (snip) > Thanks to all for an illuminating thread on the mathematical > implications of "learning curve" and other aspects. This thread has > wandered pretty far from my original question (above) Noticed this too ?-) From mvksagar at gmail.com Mon Apr 30 04:58:44 2007 From: mvksagar at gmail.com (sagar) Date: 30 Apr 2007 01:58:44 -0700 Subject: Importing a csv file Message-ID: <1177923524.747364.182460@h2g2000hsg.googlegroups.com> Hi all , I want to read data in a csv file using the python scripts. when i gave the following code : import csv reader = csv.reader(open("some.csv", "rb")) for row in reader: print row it is showing : Traceback (most recent call last): File "csv.py", line 1, in import csv File "C:\Documents and Settings\meesa02\csv.py", line 2, in reader = csv.reader(open("some.csv", "rb")) AttributeError: 'module' object has no attribute 'reader' im a total fresher to this python...SO can any one help me out in this... Thanks in advance Sagar Meesala From michael at jedimindworks.com Thu Apr 19 03:22:30 2007 From: michael at jedimindworks.com (Michael Bentley) Date: Thu, 19 Apr 2007 02:22:30 -0500 Subject: Do other Python GUI toolkits require this? In-Reply-To: <462697A6.6010007@codebykevin.com> References: <462697A6.6010007@codebykevin.com> Message-ID: <57C90994-391D-4350-A2F2-29C1590A3335@jedimindworks.com> On Apr 18, 2007, at 5:11 PM, Kevin Walzer wrote: > James Stroud wrote: > >> This appears more or less unique to Objective C. It looks that with >> PyObjC, you have to interact with the Objective C runtime to manage >> memory. This is not required, thankfully, with any other GUI tookits >> I've seen. >> >> I think the main difference is that PyObjC is not a GUI toolkit >> per se, >> but is simply a means to make the Objective C runtime (and hence >> Cocoa) >> available via a python layer. >> >> James > > That's kind of what I thought. Memory management? In Python? *shudder* > > I'm a Mac-only developer, and I keep telling myself I should drink the > Mac-only Kool-aid of PyObjC. But Tk is burned into my brain, and > anything else looks and feels weird to me. Tk is so flexible that it's > fairly easy to tweak it to look Mac-like, and it's simpler to do that > than learn a new tookit. PyObjC is pretty slick (and since Ronald hasn't made any commits in a while I'm nearly certain it'll show up in the next official distribution of the devtools). About the time you gave up on PyQt on the Mac and switched over to Tkinter, I switched to PyObjC. The learning curve is rather steep IMO, but worth it. One thing I think I should mention though is that if you move to PyObjC -- do some projects in Objective C first. Otherwise your brain will implode. hth, Michael From wojciech_mula at poczta.null.onet.pl.invalid Sat Apr 7 12:31:36 2007 From: wojciech_mula at poczta.null.onet.pl.invalid (=?ISO-8859-2?Q?Wojciech_Mu=B3a?=) Date: Sat, 07 Apr 2007 18:31:36 +0200 Subject: Saving output of Turtle Graphics? In-Reply-To: References: Message-ID: Dick Moores wrote: > What do I do to see this? For example Opera 9 and Firefox 1.5+ are able to view SVG files; there is a free plugin for IrfanView. w. From ptmcg at austin.rr.com Fri Apr 27 10:11:50 2007 From: ptmcg at austin.rr.com (Paul McGuire) Date: 27 Apr 2007 07:11:50 -0700 Subject: conditional print statement ? In-Reply-To: <1177590681.015153.67800@b40g2000prd.googlegroups.com> References: <2c923$462fb3e0$d443bb3a$18429@news.speedlinq.nl> <1177590681.015153.67800@b40g2000prd.googlegroups.com> Message-ID: <1177683110.005910.99250@t38g2000prd.googlegroups.com> On Apr 26, 7:31 am, Dustan wrote: > On Apr 26, 1:58 am, Antoon Pardon wrote: > > > > > > > On 2007-04-25, Stef Mientki wrote: > > > > hello, > > > > As part of a procedure I've a number sequences like this: > > > > > > > if Print_Info: print Datafile.readline() > > > else: Datafile.readline() > > > > > > > Is there a more compressed way to write such a statement, > > > especially I dislike the redundancy "Datafile.readline()". > > > > thanks, > > > Stef Mientki > > > You could consider the following > > > def Print(arg): > > print arg > > > def Noop(arg): > > pass > > or (untested): > > if Print_Info: > def printOrNot(arg): > print arg > else: > def printOrNot(arg): > pass > > printOrNot(Datafile.readline()) > > > > > (Print if Print_Info else Noop) (Datafile.readline()) > > > -- > > Antoon Pardon- Hide quoted text - > > - Show quoted text -- Hide quoted text - > > - Show quoted text - The Enable/Disable decorators on the Python wiki (http:// wiki.python.org/moin/PythonDecoratorLibrary?highlight=%28decorator %29#head-8298dbf9ac7325d9ef15e7130e676378bbbda572) help you do something very similar, without having to replicate the function being enabled/disabled. @(disabled,enabled)[Print_Info] def printOrNot(arg): print arg -- Paul From deets at nospam.web.de Thu Apr 12 04:34:10 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 12 Apr 2007 10:34:10 +0200 Subject: reading from sys.stdin In-Reply-To: <1176366058.261031.111870@p77g2000hsh.googlegroups.com> References: <1176366058.261031.111870@p77g2000hsh.googlegroups.com> Message-ID: <586984F2g0ejiU1@mid.uni-berlin.de> 7stud schrieb: > I can't break out of the for loop in this example: > > ------ > import sys > > lst = [] > for line in sys.stdin: > lst.append(line) > break > > print lst > ----------- Works for me. But only after the stdin is closed with a C-d. I presume this is an OS thing. The first lines aren't communicated to the process until either the file is closed - C-d - or the buffer the OS puts before the stream is filled. You can switch to unbuffered behviour somehow, google for it. Termios should be in your query. Either way, it's not python behaving differently. Diez From kw at codebykevin.com Wed Apr 4 12:06:27 2007 From: kw at codebykevin.com (Kevin Walzer) Date: Wed, 04 Apr 2007 12:06:27 -0400 Subject: os.popen--which one to use? In-Reply-To: <1175626813.785146.326220@n59g2000hsh.googlegroups.com> References: <1175626813.785146.326220@n59g2000hsh.googlegroups.com> Message-ID: danmcleran at yahoo.com wrote: > Check out subprocess. It's meant to be a replacement for all of the > above. OK, I've done this. What is the benefit of subprocess? Improved performance? It doesn't seem that way--in fact, os.popen has a non-blocking mode, which subprocess seems to lack. -- Kevin Walzer Code by Kevin http://www.codebykevin.com From carsten at uniqsys.com Mon Apr 9 13:36:20 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Mon, 09 Apr 2007 13:36:20 -0400 Subject: doubt with importing module, given module name In-Reply-To: <80628d680704091022k7c350045j4787430bf9e39012@mail.gmail.com> References: <80628d680704072327y43c349f5sf863807dea6bc345@mail.gmail.com> <80628d680704091022k7c350045j4787430bf9e39012@mail.gmail.com> Message-ID: <1176140180.3534.38.camel@dot.uniqsys.com> On Mon, 2007-04-09 at 22:52 +0530, Pradnyesh Sawant wrote: > Hello, > I have a string which in reality is the name of a module to be > imported. The name of the class contained in the module also has the > same (although with different capitalization). My requirement is to > import the module, and also create an instance of the class. eg: > > str = "module" #name of module is "module.py" > cls = str.capitalize() #name of class is "Module" > inst = cls() #create an instance of class "Module" > > how do i do this? 1) Don't use the name 'str', you're shadowing a built-in name. 2) Use __import__ to import a module with a variable name. 3) Use getattr to look up an attribute with a variable name. Putting 1-3 together, you get code something like this: module_name = "module" mod = __import__(module_name) class_name = module_name.capitalize() cls = getattr(mod, class_name) inst = cls() Hope this helps, Carsten. From rene at korteklippe.de Tue Apr 10 06:07:11 2007 From: rene at korteklippe.de (=?UTF-8?B?UmVuw6kgRmxlc2NoZW5iZXJn?=) Date: Tue, 10 Apr 2007 12:07:11 +0200 Subject: confirm password for logged in user In-Reply-To: References: Message-ID: <461b61cf$0$23141$9b4e6d93@newsspool1.arcor-online.net> Andr? Wyrwa schrieb: > I'm wondering, though, if there isn't ANY way to have the password > confirmed for the user that is already logged in. Please note the > difference, i don't want to write some kind of login functionality. The > user is already authenticated, i just want to have a typed in password > checked agains the already logged in users password. It is not possible to check a password against the shadow file without having root privileges. Neither with nor without PAM. Whyt you can do is install (or write yourself) a small program that checks the password for you. That program must run as root (be installed with suid root), but your daemon does not need to. The daemon calls the external program to do the password check. http://unixpapa.com/pwauth should work for your purposes. -- Ren? From gagsl-py2 at yahoo.com.ar Sun Apr 1 05:34:12 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sun, 01 Apr 2007 06:34:12 -0300 Subject: tag replacement in toxml() References: <812945.62887.qm@web23213.mail.ird.yahoo.com> Message-ID: En Sun, 01 Apr 2007 05:26:48 -0300, Manuel Ospina escribi?: > I am new on the list and I already have a question :-(. Welcome! > I have something like this: > > import xml.dom.minidom > from xml.dom.minidom import getDOMImplementation > impl = getDOMImplementation() > myDoc = impl.createDocument(None, "example", None) > myRoot = myDoc.documentElement > myNode1 = myDoc.createElement("node") > myNode2 = myDoc.createElement("nodeTwo") > myText = myDoc.createTextNode("Here is the problem") > myNode2.appendChild(myText) > myNode1.appendChild(myNode2) > myRoot.appendChild(myNode1) > print myDoc.toxml() > > The result is: > '\nHere is the > <b>problem</>' That's right... > My question is how I can avoid that toxml() replaces the tags? createTextNode is used to create a *text* node: its argument is interpreted as the node contents, and quoted as appropiate. What if you want it to say "Price<1000"? The < sign must be quoted. You need a text node AND a node, both children of nodeTwo. Note: Using ElementTree is a lot easier! -- Gabriel Genellina From bbxx789_05ss at yahoo.com Wed Apr 11 23:27:57 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: 11 Apr 2007 20:27:57 -0700 Subject: python regular expression help In-Reply-To: References: <402459.62579.qm@web58905.mail.re1.yahoo.com> Message-ID: <1176348477.733395.72920@y80g2000hsf.googlegroups.com> On Apr 11, 7:41?pm, liupeng wrote: > pattern = re.compile(r'\w+\s*=\s*[0-9]*.[0-9]*\s*') > lists = pattern.findall(s) > print lists > ['a=4 ', 'b=3.4 ', 'c=4.5'] > > On Wed, Apr 11, 2007 at 06:10:07PM -0700, Qilong Ren wrote: > > Hi, everyone, > > > I am extracting some information from a given string using python RE. The > > string is ,for example, > > ? ?s = 'a = 4 b =3.4 5.4 c = 4.5' > > What I want is : > > ? ?a = 4 > > ? ? b = 3.4 5.4 > > ? ?c = 4.5 > > Right now I use : > > ? ?pattern = re.compile(r'\w+\s*=\s*.*?\s+') > > ? ?lists = pattern.findall(s) > > It works for the string like 'a = 4 b = 3.4 c = 4.5', but does not work with > > strings like 'a=4 b=3.4 5.4 c = 4.5' > > > Any suggestion? > > > Thanks,Qilong > > > ??????????????????????????????????????????????????????????????????????????? ???? > > Don't get soaked. Take a quick peak at the forecast > > with theYahoo! Search weather shortcut. > > -- > >http://mail.python.org/mailman/listinfo/python-list > > ?signature.asc > 1KDownload Try this: import re s = 'a = 4 b =3.4 5.4 c = 4.5' r = re.compile("[a-z]+.*?(?=[a-z]|$)" ) l = r.findall(s) print l From thn at mail.utexas.edu Tue Apr 24 12:08:23 2007 From: thn at mail.utexas.edu (Thomas Nelson) Date: 24 Apr 2007 09:08:23 -0700 Subject: Feedback on Until recipe Message-ID: <1177430903.027128.86480@o40g2000prh.googlegroups.com> Occasionally someone posts to this group complaining about the lack of "repeat ... until" in python. I too have occasionally wished for such a construct, and after some thinking, I came up with the class below. I'm hoping to get some feedback here, and if people besides me think they might use it someday, I can put it on the python cookbook. I'm pretty happy with it, the only ugly thing is you have to use a lambda. Ideally i'd like to just see while Until(i<3) but that doesn't work. Please tell me what you think, and thanks for your time. Tom class Until: """ >>> i = 0 >>> while Until(lambda: i<3): ... print "hello" ... i += 1 hello hello hello >>> while Until(lambda: i<2): #note i still equals 3 here ... print "hello" hello """ yet = True def __init__(self, mybool): if self.__class__.yet or mybool(): self.__class__.yet = False self.ans = True else: self.__class__.yet = True self.ans = False def __nonzero__(self): return self.ans From Gregory.Bloom at gmail.com Fri Apr 27 00:09:35 2007 From: Gregory.Bloom at gmail.com (Gregory Bloom) Date: 26 Apr 2007 21:09:35 -0700 Subject: webbrowser.open works in IDLE and cmd shell but not from cygwin prompt Message-ID: <1177646975.285805.106920@b40g2000prd.googlegroups.com> I'm running Python 2.5 under Windows. If I fire up IDLE and enter: >>> import webbrowser >>> url = 'http://www.python.org' >>> webbrowser.open_new(url) it works like a champ, opening the page in Firefox. Same thing goes from a Windows cmd shell: it works as advertised. But if I open a cygwin bash shell and try the same thing from a python prompt, I get: >>> import webbrowser >>> url = 'http://www.python.org' >>> webbrowser.open_new(url) Traceback (most recent call last): File "", line 1, in File "C:\Python25\lib\webbrowser.py", line 60, in open_new return open(url, 1) File "C:\Python25\lib\webbrowser.py", line 55, in open if browser.open(url, new, autoraise): File "C:\Python25\lib\webbrowser.py", line 185, in open p = subprocess.Popen(cmdline, close_fds=True, preexec_fn=setsid) File "C:\Python25\lib\subprocess.py", line 551, in __init__ raise ValueError("close_fds is not supported on Windows " ValueError: close_fds is not supported on Windows platforms What's up with that? And, more to the point, how can I use webbrowser from scripts launched under cygwin? From paddy3118 at googlemail.com Wed Apr 11 05:37:36 2007 From: paddy3118 at googlemail.com (Paddy) Date: 11 Apr 2007 02:37:36 -0700 Subject: IPython 0.8.0 is out In-Reply-To: References: Message-ID: <1176284256.148233.157200@e65g2000hsc.googlegroups.com> On Apr 11, 6:18 am, Fernando Perez wrote: > Hi all, > > The IPython team is happy to release version 0.8.0, with a lot of new > enhancements, as well as many bug fixes. > > We hope you all enjoy it, and please report any problems as usual. > > WHAT is IPython? > ---------------- > > 1. An interactive shell superior to Python's default. IPython has many > features for object introspection, system shell access, and its own special > command system for adding functionality when working interactively. > > 2. An embeddable, ready to use interpreter for your own programs. IPython > can > be started with a single call from inside another program, providing access > to > the current namespace. > > 3. A flexible framework which can be used as the base environment for other > systems with Python as the underlying language. > > 4. A shell for interactive usage of threaded graphical toolkits. IPython has > support for interactive, non-blocking control of GTK, Qt and WX applications > via special threading flags. The normal Python shell can only do this for > Tkinter applications. > > Where to get it > --------------- > > IPython's homepage is at: > > http://ipython.scipy.org > > and downloads are at: > > http://ipython.scipy.org/dist > > We've provided: > > - Source download (.tar.gz) > - A Python Egg (http://peak.telecommunity.com/DevCenter/PythonEggs). > - A python 2.4 RPM. > - A native win32 installer. > > The egg is 'light', as it doesn't include documentation and other ancillary > data. If you want a full ipython installation, use the source tarball or > your > distribution's favorite system. > > We note that IPython is now officially part of most major Linux and BSD > distributions, so packages for this version should be coming soon, as the > respective maintainers have the time to follow their packaging procedures. > Many thanks to the distribution packagers for their work, which helps users > get > IPython more conveniently. > > Thanks to all the users who contributed bug reports, ideas and especially > patches. The ChangeLog has hopefully detailed acknowledgements, but please > let > us know if we've accidentally ommitted giving you due credit. > > Many thanks to Enthought for their continued hosting support for IPython. > > Release notes > ------------- > > As always, the full ChangeLog is athttp://ipython.scipy.org/ChangeLog. The > highlights of this release follow. Also see the "What's New" page at > > http://ipython.scipy.org/moin/WhatsNew > > * Support for KeyboardInterrupt (Ctrl-C) when running in multithreaded mode > with GUI support. This had been a long-requested feature that we had > never > quite been able to implement correctly. Many thanks to Tomer Filiba's > for > his ctypes-based trick:http://sebulba.wikispaces.com/recipe+thread2, > which > we used (any implementation mistakes are our own and not his fault). > Users > of Python 2.4 should note that they need to install ctypes separately to > access this feature; ctypes is part of Python 2.5 already. > > * Fully syntax-highlighted tracebacks and debugger listings. IPython used > to > color tracebacks, but only certain elements; now the source is actually > highlighted by the same engine that handles '??' source listings, both in > tracebacks and during interactive debugging. > > * Improved the ipipe system:http://ipython.scipy.org/moin/UsingIPipe, > including a new WX-based graphical browser. > > * Much improved unicode support. There may still be bugs remaining, but a > number of known-incorrect cases have been fixed. > > * Make the execution of 'from pylab import *' when -pylab is given be > otional. > A new flag (which can be set in your ipythonrc file), pylab_import_all > controls this behavior, the default is True for backwards compatibility. > > * Extensions for perforce support via a new magic (%p4) and custom command > completers. > > * Improved support for (X)Emacs under win32. > > * Several small fixes and improvements to the interactive demo module. > > * Add \N for the actual prompt number, without any coloring, as an escape > for > customized prompt definitions. This lets users write their own custom > prompts with arbitrary coloring schemes. > > * Many more bugfixes and small features everywhere (the ChangeLog linked > above > has the gory details). > > API changes: > > * genutils.clock() now returns user+system time. The new clocku/clocks > functions return respectively user and system time only. > > Enjoy, and as usual please report any problems. > > The IPython team. Just made a connection between the IPipe feature and Windows PowerShell http://en.wikipedia.org/wiki/PowerShell I can't find the link to the orignial PowerShell article but I do remember them talking about sending objects rather than text through pipes (as Unix does); and that their was a default printing format for objects coming out of a pipeline. From bbxx789_05ss at yahoo.com Wed Apr 4 15:53:12 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: 4 Apr 2007 12:53:12 -0700 Subject: operator overloading In-Reply-To: <1175712109.655293.296720@o5g2000hsb.googlegroups.com> References: <1175679412.741899.45990@l77g2000hsb.googlegroups.com> <1175712109.655293.296720@o5g2000hsb.googlegroups.com> Message-ID: <1175716392.209444.223830@w1g2000hsg.googlegroups.com> On Apr 4, 12:41 pm, "7stud" wrote: > According to Python in a Nutshell(p.102), a name that is a slot can > only be "bound"(i.e. assigned to) inside the class body. Upon closer reading, it actually says that the name "__slots__" has to be bound inside the class body for the slot restrictions to take effect. From khemkaamit at gmail.com Mon Apr 16 06:11:42 2007 From: khemkaamit at gmail.com (Amit Khemka) Date: Mon, 16 Apr 2007 15:41:42 +0530 Subject: newbie question: how to read back the dictionary from a file? In-Reply-To: <1176717819.937015.9890@y80g2000hsf.googlegroups.com> References: <1176717819.937015.9890@y80g2000hsf.googlegroups.com> Message-ID: <1360b7230704160311y5ba4f70cv65b4d418a5d7e661@mail.gmail.com> On 16 Apr 2007 03:03:40 -0700, lancered wrote: > Hi Dear all, > > I have some data here in the form of a dictionary, called "vdic". Then > I write them to a data file "f" using the write function as > f.write(str(vdic)). The keys of this dictionary are integers and > values are float numbers. Something like this: > > { 1: 0.00951486513347, 2: 0.0388123556019, ... ...} > > Now, I want to read these data back in another function. Of course, I > could parse the string little by little, e.g, first read a "{", then > loop read a int, then read a ":", then a float etc etc... Since it is > written out with standard python builtin functions, I guess there may > be some more direct method than this, say a function in some modules? > Could someone give me a hint? > Check out cPickle or shelve modules. 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 alisonken1 at gmail.com Fri Apr 27 18:20:30 2007 From: alisonken1 at gmail.com (alisonken1) Date: 27 Apr 2007 15:20:30 -0700 Subject: how to create/ref globals in an alternate namespace? In-Reply-To: References: Message-ID: <1177712430.150976.85950@t38g2000prd.googlegroups.com> On Apr 27, 2:33 pm, "Steven W. Orr" wrote: > On Friday, Apr 27th 2007 at 14:07 -0700, quoth James Stroud: > > I'm trying to see if by being clever, I can factor out the common code of > the four different functions and still end up with what they create ending > up in the namespaces where they are intended to reside in. Does this make > sense or am I way off base? You may be trying to get too clever. If what you're trying to do is what I think you're trying to do, I would suggest looking at how the logging module handles globals and functions for an example. From exarkun at divmod.com Mon Apr 16 18:35:11 2007 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Mon, 16 Apr 2007 18:35:11 -0400 Subject: unittest assertRaises Problem In-Reply-To: <1176761622.220741.261420@y80g2000hsf.googlegroups.com> Message-ID: <20070416223511.19381.1496669536.divmod.quotient.2278@ohm> On 16 Apr 2007 15:13:42 -0700, john wrote: >All: > >Hi. I am an experienced developer (15 yrs), but new to Python and have >a question re unittest and assertRaises. No matter what I raise, >assertRaises is never successful. Here is the test code: > > >class Foo: > def testException(self): > raise ValueError > >class FooTestCase(unittest.TestCase): > > testTryThis(self): > f = Foo() > self.assertRaises(ValueError, f.testException()) > The 2nd argument to assertRaises should be a callable. assertRaises will call it (so that it can do exception handling), so you shouldn't: self.assertRaises(ValueError, f.testException) Jean-Paul From tdelaney at avaya.com Tue Apr 10 19:36:17 2007 From: tdelaney at avaya.com (Delaney, Timothy (Tim)) Date: Wed, 11 Apr 2007 09:36:17 +1000 Subject: tuples, index method, Python's design Message-ID: <2773CAC687FD5F4689F526998C7E4E5FF1ED57@au3010avexu1.global.avaya.com> Carsten Haese wrote: > assert current_player in p > opponents = tuple(x for x in p if x is not current_player) That would perform better as: opponents = tuple(x for x in p if x is not current_player) assert opponents Tim Delaney From mccredie at gmail.com Tue Apr 3 12:21:23 2007 From: mccredie at gmail.com (Matimus) Date: 3 Apr 2007 09:21:23 -0700 Subject: Stack experiment In-Reply-To: <5QuQh.152$9L1.108@read3.inet.fi> References: <5QuQh.152$9L1.108@read3.inet.fi> Message-ID: <1175617283.607006.195420@y66g2000hsf.googlegroups.com> On Apr 3, 8:57 am, t... at finland.com wrote: > Hi! Im new to Python and doing exercise found from internet. It is > supposed to evaluate expression given with postfix operator using > Stack() class. > > class Stack: > def __init__(self): > self.items = [] > > def push(self, item): > self.items.append(item) > > def pop(self): > return self.items.pop() > > def isEmpty(self): > return (self.items == []) > > def evaluatePostfix(expr): > import re > tokenList = re.split(" ([^0-9])", expr) > stack = Stack() > for token in tokenList: > if token == '' or token == ' ': > continue > if token == '+': > sum = stack.pop() + stack.pop() > stack.push(sum) > elif token == '*': > product = stack.pop() * stack.pop() > stack.push(product) > else: > stack.push(int(token)) > return stack.pop() > > print evaluatePostfix("56 47 + 2 *") > > Errormsg: > Traceback (most recent call last): > File "C:\*\postfix1.py", line 31, in > print evaluatePostfix("56 47 + 2 *") > File "C:\*\postfix1.py", line 28, in evaluatePostfix > stack.push(int(token)) > ValueError: invalid literal for int() with base 10: '56 47' > > How can I avoid the error and get desired result? Two things: 1. The regular expression contains a space, so it is trying to split on a space character followed by a non number, when you really want to split on any nonnumber. Remove the space. tokenList = re.split(" ([^0-9])", expr) -> tokenList = re.split("([^0-9])", expr) 2. The return statement in evaluatePostfix is part of the for loop, it will exit on the first loop. This: for token in tokenList: if token == '' or token == ' ': continue if token == '+': sum = stack.pop() + stack.pop() stack.push(sum) elif token == '*': product = stack.pop() * stack.pop() stack.push(product) else: stack.push(int(token)) return stack.pop() Should Be: for token in tokenList: if token == '' or token == ' ': continue if token == '+': sum = stack.pop() + stack.pop() stack.push(sum) elif token == '*': product = stack.pop() * stack.pop() stack.push(product) else: stack.push(int(token)) return stack.pop() From dborne at gmail.com Mon Apr 16 10:00:42 2007 From: dborne at gmail.com (Dave Borne) Date: Mon, 16 Apr 2007 09:00:42 -0500 Subject: Writing Log CSV (Efficiently) In-Reply-To: <7554276584215132819@unknownmsgid> References: <7554276584215132819@unknownmsgid> Message-ID: <6e42ec490704160700i20469453j6af39db62dd6b427@mail.gmail.com> On 4/16/07, Robert Rawlins - Think Blue wrote: > I'm looking to write a Log file which will be CSV based, and there is a good > possibility that it'll get quite busy once its up and running, so I'm > looking for the most efficient way to achieve it. Whilst I'm sure i could do > something like this. Python has built in logging support. It's pretty flexible as far as formatting output. I can get a bit complicated to set up, but it will handle traffic well. more info here http://docs.python.org/lib/module-logging.html -Dave From newsgroups at nospam.nowire.org Fri Apr 6 06:21:30 2007 From: newsgroups at nospam.nowire.org (=?ISO-8859-15?Q?Thomas_Kr=FCger?=) Date: Fri, 06 Apr 2007 12:21:30 +0200 Subject: Python on MIPS In-Reply-To: <46160b35$0$36451$4fafbaef@reader5.news.tin.it> References: <46160b35$0$36451$4fafbaef@reader5.news.tin.it> Message-ID: Lorenzo Mainardi schrieb: > I bought a very small embedded card, with a MIPS processor, running > Linux. So, I would to use Python on that; I checked on python.org, but I > did'nt find any release for this architecture. Could you help me? How about compiling it from source? Thomas From tim at tdw.net Thu Apr 5 06:14:24 2007 From: tim at tdw.net (Tim Williams) Date: Thu, 5 Apr 2007 11:14:24 +0100 Subject: way to extract only the message from pop3 In-Reply-To: References: Message-ID: <9afea2ac0704050314t786174aepde6398cfd8eba1c3@mail.gmail.com> On 3 Apr 2007 12:36:10 -0700, flit wrote: > Hello All, > > Using poplib in python I can extract only the headers using the .top, > there is a way to extract only the message text without the headers? for i in range( M.stat()[0] ): # M.stat returns msg-count and mbox size msg = '\r\n'.join( M.retr(i+1)[1] ) # retrieve the email into string hdrs,body = msg.split('\r\n\r\n',1) # split it into hdrs & body HTH :) From seberino at spawar.navy.mil Fri Apr 20 13:06:36 2007 From: seberino at spawar.navy.mil (seberino at spawar.navy.mil) Date: 20 Apr 2007 10:06:36 -0700 Subject: When are immutable tuples *essential*? Why can't you just use lists *everywhere* instead? Message-ID: <1177088796.622928.224890@d57g2000hsg.googlegroups.com> Please help me think of an example where immutable tuples are essential. It seems that everywhere a tuple is used one could just as easily use a list instead. chris From amit_605 at yahoo.co.in Wed Apr 11 10:25:25 2007 From: amit_605 at yahoo.co.in (amit soni) Date: Wed, 11 Apr 2007 07:25:25 -0700 (PDT) Subject: A general question Message-ID: <363359.30232.qm@web8412.mail.in.yahoo.com> Hi, I am using Matlab, Python and Java for sometime. Matlab looks to be very easy and having specified methods for almost each and everything. Java on the other hand has a good object oriented structure and is very fast. What are the advantages of Python over these two or any other language in general? and what are the areas it lacks behind and what improvements will make it appealing to more and more people? Thank you, Amit --------------------------------- Don't get soaked. Take a quick peak at the forecast with theYahoo! Search weather shortcut. -------------- next part -------------- An HTML attachment was scrubbed... URL: From gene.tani at gmail.com Tue Apr 10 13:08:32 2007 From: gene.tani at gmail.com (gene tani) Date: 10 Apr 2007 10:08:32 -0700 Subject: NLTK, Random Sentence Generators? In-Reply-To: <87slb8d3uj.fsf@localhost.localdomain> References: <87slb8d3uj.fsf@localhost.localdomain> Message-ID: <1176224912.373928.326030@e65g2000hsc.googlegroups.com> On Apr 10, 1:36 am, Passer By wrote: > Has any created or not of examples of random sentence generators using > n-gram models (or other models might be interesting). > > I know of one example from a course at MIT, but besides that nothing. > > Any help would be great. Markov chains e.g. http://rubyquiz.com/quiz74.html From steve at REMOVE.THIS.cybersource.com.au Thu Apr 19 03:04:44 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Thu, 19 Apr 2007 17:04:44 +1000 Subject: comparison with None References: <_JAVh.1700$jR5.897@trnddc08> Message-ID: On Thu, 19 Apr 2007 02:46:18 +0000, Alan Isaac wrote: > However, Gary Herron's explanation makes sense: this provides a stable > sort when None is involved, and meets the criterion that objects of > different types must always compare unequal. That's only correct for "sensible" objects that don't do stupid things, like this one: class Mirror: # compares equal to just about everything def __eq__(self, other): return True > However this would also > be true if None always compared greater than any object, and the current > behavior does not seem to be guaranteed. > > Is that about right? Yes, that's about right. You shouldn't expect comparisons between types to sort the same from one version of Python to another, although they may, and in the future (Python 3) it is likely to become an error to compare incomparable objects. -- Steven. From rdm at rcblue.com Sat Apr 7 07:31:13 2007 From: rdm at rcblue.com (Dick Moores) Date: Sat, 07 Apr 2007 04:31:13 -0700 Subject: Welch essential for learning Tkinter well? In-Reply-To: <1BKRh.15054$Um6.13418@newssvr12.news.prodigy.net> References: <46151818.6080302@codebykevin.com> <1BKRh.15054$Um6.13418@newssvr12.news.prodigy.net> Message-ID: <20070407113117.27D501E4009@bag.python.org> At 03:43 AM 4/7/2007, James Stroud wrote: >Dick Moores wrote: > > At 10:36 AM 4/6/2007, Russell E. Owen wrote: > >> I find Welch's book and the on-line tcl/tk help very helpful for Tkinter > >> programming--especially some of the more obscure details. But to use > >> either of these resources comfortably you must learn the basics of > >> Tkinter first (including understanding the simple mapping between > >> Tkinter and Tcl/Tk). > > > > Where can I get this mapping spelled out? > >Grayson Appendix A. $25 pdf--well worth it in your time. Terrific! Thank you. Dick From hlubenow2 at gmx.net Tue Apr 10 13:04:47 2007 From: hlubenow2 at gmx.net (hlubenow) Date: Tue, 10 Apr 2007 19:04:47 +0200 Subject: Check for keypress on Linux xterm ? References: <131m56dsgr7or38@corp.supernews.com> <131ne1g8eq7d060@corp.supernews.com> Message-ID: Grant Edwards wrote: > I do make mistakes, but before telling somebody he's wrong, it > might be a good idea to actually try what he's suggested. ;) I completely agree. The script waited at first for key-input, so I thought, I was right. But I was not. I apologize ! H. From paul at boddie.org.uk Thu Apr 5 13:55:22 2007 From: paul at boddie.org.uk (Paul Boddie) Date: 5 Apr 2007 10:55:22 -0700 Subject: AttributeError: 'tuple' object has no attribute 'encode' In-Reply-To: References: <1175787095.862712.297480@n76g2000hsh.googlegroups.com> Message-ID: <1175795722.696801.149550@y66g2000hsf.googlegroups.com> Lenard Lindstrom wrote: > > > > I'm trying to build a SQL string > > > > sql = """INSERT INTO ag ('cid', 'ag', 'test') VALUES(%i, %s, %d)""", > > (cid, ag, self.data[parent][child]['results']['test']) > > I am guessing you want the string formatting operator here: > > sql = """...""" % (cid, ...) That's a superficial solution which encourages a bad practice: if any of that data can be subverted to modify the query, as opposed to merely providing a simple value, then you have a vulnerability in your code. Perhaps the %i and %d substitutions may prevent such things, but the %s substitution won't. Paul From zhonghua.m.yang at gmail.com Tue Apr 3 16:33:59 2007 From: zhonghua.m.yang at gmail.com (ZMY) Date: 3 Apr 2007 13:33:59 -0700 Subject: Numeric compiling problem under QNX 4.25 In-Reply-To: References: <1175578324.426293.21970@y80g2000hsf.googlegroups.com> <1175622049.939184.28670@d57g2000hsg.googlegroups.com> Message-ID: <1175632439.676454.21830@q75g2000hsh.googlegroups.com> On Apr 3, 10:51 am, Robert Kern wrote: > ZMY wrote: > > Is "ld" part of make command? I am not familiar with compiling with > > make in general. > > No, it's the linker. I takes the object files (.o) which are generated by the > compiler (cc, I imagine) and links them together into the shared library (.so). > make is a program that can automate builds given instructions, but Numeric > doesn't use it, nor do most other Python packages. > > > Most other extensions (including math, os, struct, cPickle) from > > Python 2.2 works when I install python on QNX. > > No, I was wondering if you could build any other third-party extension modules. > Did you install Python from source? When building extension modules, Python uses > whatever linker was used to build itself. > > -- > 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 E Dear Robert, Looks like you are right. Here is what I got when I compile the Python2.2 from source (or I believe so): $ sudo make SHELL=/usr/local/bin/bash Password: case $MAKEFLAGS in \ *-s*) CC='cc' LDSHARED='ld' OPT='-DNDEBUG -O' ./python -E //6/openqnx/ Python-2.2/setup.py -q build;; \ *) CC='cc' LDSHARED='ld' OPT='-DNDEBUG -O' ./python -E //6/openqnx/ Python-2.2/setup.py build;; \ esac running build running build_ext building 'regex' extension skipping //6/openqnx/Python-2.2/Modules/regexmodule.c (build/temp.qnx- O-PCI-2.2/regexmodule.o up-to-date) skipping //6/openqnx/Python-2.2/Modules/regexpr.c (build/temp.qnx-O- PCI-2.2/regexpr.o up-to-date) ld build/temp.qnx-O-PCI-2.2/regexmodule.o build/temp.qnx-O-PCI-2.2/ regexpr.o -L/usr/local/lib -o build/lib.qnx-O-PCI-2.2/regex.so unable to execute ld: No such file or directory .... If there is no 'ld' linker, what should be used instead?? BTW, the reason I am still using QNX4.25 is because I was trying to install python on this legacy system. We can't move to QNX6 unless we want to redo all other code as well, which took 3 years of a good programmer :-( - ZMY From http Sun Apr 15 03:51:57 2007 From: http (Paul Rubin) Date: 15 Apr 2007 00:51:57 -0700 Subject: proposed PEP: iterator splicing References: <7xirbyi5d7.fsf_-_@ruckus.brouhaha.com> Message-ID: <7xzm5am5wi.fsf@ruckus.brouhaha.com> John Nagle writes: > > Less clutter, and avoids yet another temp variable polluting the namespace. > Are we in danger of running out of temp variables? There is unfortunately no way to contain the scope of a loop index to the inside of the loop. Therefore introducing more useless loop indexes creates more scorekeeping work and bug attractants. Better to get rid of them. From kyosohma at gmail.com Tue Apr 24 13:32:34 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: 24 Apr 2007 10:32:34 -0700 Subject: Python Screen Scraper In-Reply-To: References: Message-ID: <1177435953.963634.86160@n35g2000prd.googlegroups.com> On Apr 24, 7:17 am, Michael Bentley wrote: > On Apr 24, 2007, at 11:50 AM, James Stroud wrote: > > > > > Hello, > > > Does anyone know of an example, however modest, of a screenscraper > > authored in python? I am using Firefox. > > > Basically, I am answering problems via my browser and being scored for > > each problem. I have a tendency to go past my peak for training > > efficiency, so I would like to scrape the result page for each > > problem I > > answer, compile statistics, and have a program alert me when I should > > stop (based on score and accuracy--assuming training value is > > related to > > changes in these metrics). > > > I have no idea how to go about writing such a beast and I am hoping > > that > > I could get some pointers or an example that could get me going in the > > right direction. > > > Parsing, etc, is not a problem, but I'm not exactly sure how I might > > interface python with Firefox, forwarding scraped pages to my browser > > (or forwarding from the browser to the scraper). > > > Thanks in advance for any help or advice. > > Possibly the easiest thing will be to read from firefox' cache. > Otherwise I think your only real options are to either build a proxy > or sniff the wire... You should be able to parse the html too. There are quite a few tools out there for that purpose, "Beautiful Soup" being a good example. Mike From mail at microcorp.co.za Sat Apr 14 03:07:52 2007 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Sat, 14 Apr 2007 09:07:52 +0200 Subject: Lists and Tuples and Much More References: <1176419437.278359.52800@q75g2000hsh.googlegroups.com> Message-ID: <011d01c77e63$9ea4a1c0$03000080@hendrik> "7stud" wrote: > .......... But using a tuple as a > key in a dictionary is probably something you will never do. Yikes! I do this all the time... Think of an address in any one town. It has a Street, and a number (could be more complex, like a sub number for an apartment in a block, but lets ignore that for now) so: addy = ("First Avenue", 10) Residents = {addy:"Frank Everyman",......} To make a thing where you can look up who lives at a place... (this is simplistic of course, for illustrative purposes - few people live completely alone. - it should be at least a list, or possibly a dict by surname...) I find that when I do this, I almost invariably also create the inverse dict: Addresses = {"Frank Everyman":addy,.....} So that you can get at stuff from all directions. If you keep it up you have a home made relational database if you are not careful... But if you limit it to one thing and its inverse, its quite useful, and it would be nice to have one "doubledict" that can be accessed as speedily from either end... Sort of an internally linked list of mixed hashed immutables, where: doubledict["Frank Everyman"] yields addy, and doubledict[addy] yields "Frank Everyman" It would have direct applicability in things like the label table in an assembler, for debugging and so on. - Hendrik From bdesth.quelquechose at free.quelquepart.fr Fri Apr 27 17:44:30 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Fri, 27 Apr 2007 23:44:30 +0200 Subject: My python annoyances so far In-Reply-To: References: <1177541453.471959.120830@c18g2000prb.googlegroups.com> <1177599046.406827.5210@t38g2000prd.googlegroups.com> <4631d5be$0$2132$426a74cc@news.free.fr> Message-ID: <46326519$0$20759$426a74cc@news.free.fr> Antoon Pardon a ?crit : > On 2007-04-27, Bruno Desthuilliers wrote: > >>7stud a ?crit : >> >>>flifus at gmail.com wrote: >>> >>>>Annoyances: >>>> >>> >>>Every language has annoyances. Python is no exception. >> >>Sure. But we may disagree on what are actually Python's annoyances !-) > > > That is probably why the subject says: "my annoyances" > May I suggest that before finding something annyoing, one has to use it? When I first discovered Python - and before having any experience with it - I thought that not having declarative static typing and access restriction was kind of an annoyement. Real world experience made me change my mind... From grante at visi.com Tue Apr 24 15:39:58 2007 From: grante at visi.com (Grant Edwards) Date: Tue, 24 Apr 2007 19:39:58 -0000 Subject: Generate report containing pdf or ps figures? References: <132pnp6r4qg0lc2@corp.supernews.com> <132sdmde3vg6kf3@corp.supernews.com> Message-ID: <132sn8eh1iphnf0@corp.supernews.com> On 2007-04-24, Grant Edwards wrote: > On 2007-04-24, Steve Holden wrote: > >>>> I've looked at ReportLab's documentation, but although it >>>> appears to be able to use bitmap images (e.g jpeg) it doesn't >>>> appear to be able to use vector images (EPS/PDF/SVG). >>>> >>>> Is there a PDF generation library that can place EPS or >>>> PDF figures on a page? >>> . >>> . >>> . >>> You're stuck. > [...] >> >> In fairness to ReportLab I'd like to say that their *commercial* >> products can do everything the OP asks for and more besides, but >> unfortunately they are mostly targeted at the "enterprise" (read: big >> money) market. > > This is just a smallish app for internal use by 1-2 people, so > I probably can't justify spending much cash. I'll check on > the ReportLab pricing. I can't even find any mention of a commercial version of ReportLab on the web site. The FAQ says ReportLib is available under the BSD license. Period. There are some other "projects" listed, but they don't appear to be relevent. -- Grant Edwards grante Yow! I want the presidency at so bad I can already taste visi.com the hors d'oeuvres. From kaoruangel at gmail.com Fri Apr 6 02:46:57 2007 From: kaoruangel at gmail.com (C.L.) Date: Fri, 6 Apr 2007 06:46:57 +0000 (UTC) Subject: No subject References: Message-ID: James Stroud mbi.ucla.edu> writes: > > C.L. wrote: > > I was looking for a function or method that would return the index to the > > first matching element in a list. ... > > ... __please don't be overly defensive__ ... > > The amount of typing wasted to defend design decisions such as this can > boggle one's mind. Just use lists unless you have on overwhelming reason > to do otherwise. > > James Read the quote. I *am* using a list. That doesn't change the fact that this is unfriendly design. It's an ugly inconsistent chunk of a Python's past in which built-in types didn't behave like objects. It sticks out like a sore thumb, maybe just not very often. Oh, and thanks for the insulting tone of your anticipated response. Have you anything better to do with your time than wasting bytes writing empty responses to what you already deem a waste of typing? *sighs* just what I expected: another idle troll defending something just for the sake of defending it. On the other hand, thanks 7stud, for the truly helpful response. From arkanes at gmail.com Thu Apr 19 12:42:23 2007 From: arkanes at gmail.com (Chris Mellon) Date: Thu, 19 Apr 2007 11:42:23 -0500 Subject: comparison with None In-Reply-To: <462792BE.906@gmail.com> References: <_JAVh.1700$jR5.897@trnddc08> <462709FB.9020607@gmail.com> <462792BE.906@gmail.com> Message-ID: <4866bea60704190942o316e3f20t1021d0464786030a@mail.gmail.com> On 4/19/07, Steven Howe wrote: > > Steven D'Aprano wrote: > On Thu, 19 Apr 2007 08:18:30 -0400, Steve Holden wrote: > > > > > Which is why I suggested using the explicit type(x) == types.NoneType as > opposed to > x is None > > > > This seems to go entirely against the spirit of the language. It's about > as sensible as writing > > (3 > 4) == True > > > Please! For extra certainty, you should write that as: > > ((int(3) > int(4)) == True) == True > > Explicit is better than sensible, yes? > > *wink* > > > > > Your example, even with the *wink*, is stupid. The language requires 3 to > be an integer, 4 to be an integer. > > > The point I was show is with respect to a returned variable (like from a > function or method? *wink* *wink*). > For example, if you expect an open file handle, but get a NoneType because > you didn't really open a file (having given a bad name or maybe didn't have > permission to open a file), This won't happen, because an exception will be thrown instead. But if it *did*, you'd test with "is None", not by type comparison. >then it would be best to test the type of return > object before using it. Then you program could handle the error gracefully > (*wink* *wink* *wink*). > > As much as I love Python, it's ability to morph an object type can be a > pain. Testing before using can prevent a program from Error-ing out. > This is contrary to the vast majority of Python philosophy. Embracing rather than fighting it will result in a much more pleasant Python experience. > Steven Howe > > -- > http://mail.python.org/mailman/listinfo/python-list > From vinay_sajip at yahoo.co.uk Thu Apr 19 05:12:25 2007 From: vinay_sajip at yahoo.co.uk (Vinay Sajip) Date: 19 Apr 2007 02:12:25 -0700 Subject: using the sysloghandler class In-Reply-To: References: Message-ID: <1176973945.216457.274330@b58g2000hsg.googlegroups.com> On Apr 18, 11:42 pm, "Nicholas Milkovits" wrote: > Hello all, > > I have a small script which attempts to write to the user.log syslog > > importlogging,logging.handlers > > logger =logging.getLogger('bender') > handler =logging.handlers.SysLogHandler(('localhost',logging.handlers.SYSLOG_UDP_PORT),logging.handlers.SysLogHandler.LOG_USER) > formatter =logging.Formatter('%(filename)s: %(levelname)s: %(message)s') > handler.setFormatter(formatter) > logger.addHandler(handler) > logger.error('what') > > but no log entries show up, however if I use the syslog module as such: > > >>> import syslog > >>> syslog.syslog('testing syslog') > > everything works fine. I am not sure what I am doing wrong. Any help > would be appreciated. The logging package's syslog handler attempts to use UDP to communicate with the syslog daemon; are you sure your system is set up with the daemon listening on SYSLOG_UDP_PORT? If it's not, then this could explain what you are seeing. Regards, Vinay Sajip From steve at holdenweb.com Fri Apr 6 09:12:55 2007 From: steve at holdenweb.com (Steve Holden) Date: Fri, 06 Apr 2007 09:12:55 -0400 Subject: Simple mx.ODBC prob seeks simple answer In-Reply-To: <9871804.post@talk.nabble.com> References: <9871804.post@talk.nabble.com> Message-ID: Greg Corradini wrote: > Hello all, > I'm having trouble inserting an SQL selection into a new MS Access table. I > get a parameter error on my insert statement when I try this (see below for > code and error msg). I'm not sure if 'insert' or 'update' is the route I > should be taking. > > CODE: > #Import Pythond Standard Library Modules > import win32com.client, sys, os, string, copy, glob > import mx.ODBC.Windows as odbc > > # Create the Geoprocessor Object > gp = win32com.client.Dispatch("esriGeoprocessing.GpDispatch.1") > gp.overwriteoutput = 1 > > # Variables > tempspace = "C:\Documents and Settings\corr1gre\Desktop\Workspace\DBFs & > Shapefiles\TEST.mdb" > workspace = string.replace(tempspace,"\\","/") > worksheet1 = "Mower_I" > worksheet2 = "Mower_II" > > #Conection to Access > driv = 'DRIVER={Microsoft Access Driver (*.mdb)};DBQ='+workspace > conn = odbc.DriverConnect(driv) > curse = conn.cursor() > > #Drop Tables if they already exist > try: > curse.execute('Drop table Table_I') > curse.execute('Drop table Table_II') > curse.execute('Drop table Checker') > except: > pass > #Create a New Tables > curse.execute('Create table Table_I (TISCODE TEXT(12), EXISTSIN > TEXT(4),STATUS TEXT(3),NOTES TEXT(50))') > curse.execute('Create table Table_II(TISCODE TEXT(12), EXISTSIN TEXT(4))') > curse.execute('Create table Checker (TISCODE TEXT(12), EXISTSIN > TEXT(4),STATUS TEXT(3),NOTES TEXT(50))') > conn.commit() > > #Upload DBF 1 as a List of Tuples: Returns tuple as ('1021500000','BMP') > sql = 'SELECT TISCODE,EXISTSIN from '+worksheet2 > curse.execute(sql) > x = curse.fetchall() > > #Put the fetched Data into Table_II > for i in x: > curse.execute('Insert into Table_II (TISCODE,EXISTSIN) values > (%s,%s)'%(i[0],i[1])) > conn.commit() > conn.close() > > TRACEBACK ERROR MSG: > Traceback (most recent call last): > File "C:/Documents and Settings/corr1gre/Desktop/Workspace/Python/ArcGIS > Python/ExistenceChecker and Update/Access Double Checker/Access_SQL.py", > line 40, in ? > curse.execute('Insert into Table_II (TISCODE,EXISTSIN) values > (%s,%s)'%(i[0],i[1])) > ProgrammingError: ('07001', -3010, '[Microsoft][ODBC Microsoft Access > Driver] Too few parameters. Expected 1.', 4612) That error usually occurs when you use a name that isn't defined int he database (typically I mistype a column name) - the JET engine then thinks it's missing a value for some parameter. In your case it's because you aren't surrounding the string literal value for TISCODE in your statement with the appropriate '' single quotes. The engine thus parses it as a name, hence the assumption that a parameter is missing. It's actually good that you have made this error, because it allows me to expound yet again on the dangers of constructing your own SQL statements instead of using parameterised statements. In the case of mxODBC the correct parameter mark to use is a question mark. You should then supply the data to be substituted for the parameter marks as a tuple argument to the cursor's execute() method. So what you really need is: #Put the fetched Data into Table_II for i in x: curse.execute("""Insert into Table_II (TISCODE,EXISTSIN) values (?, ?)""", i) conn.commit() conn.close() A couple of other points: 1. It would actually be better to put the commit() call outside the loop. This is not only more efficient but it defines the whole set of changes as a transaction. 2. It would be even more efficient not to use a loop at all but to use the cursor's executemany() method to perform all inserts with a single call as follows: #Put the fetched Data into Table_II curse.executemany("""Insert into Table_II (TISCODE,EXISTSIN) values (?, ?)""", x) conn.commit() conn.close() For more on using the DBI API, including something about the risks of SQL injection vulnerabilities, take a look at the notes from my PyCon tutorial at http://www.holdenweb.com/PyConTX2007/dbapi.tgz 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 gigs at hi.t-com.hr Thu Apr 19 08:24:26 2007 From: gigs at hi.t-com.hr (Gigs_) Date: Thu, 19 Apr 2007 14:24:26 +0200 Subject: tkinter canvas In-Reply-To: <1176931838.804999.186070@n59g2000hsh.googlegroups.com> References: <1176931838.804999.186070@n59g2000hsh.googlegroups.com> Message-ID: kyosohma at gmail.com wrote: > On Apr 18, 3:43 pm, Gigs_ wrote: >> how to write text on canvas. i know that i need to use canvas.create_text, but >> how to write text than when i create_text? >> or how to access object ID in canvas and change some options? >> >> thanks in advance! > > All you need to do is canvas.create_text(x, y, text='Hello World') > where x and y are coordinates on the canvas. You can also add fg and/ > or bg to set foreground and background colors, respectively. > > Mike > but is there any option to bind event? when i create text i want to write in text box on canvas so i think that i need to bind event From steve at holdenweb.com Thu Apr 26 08:01:41 2007 From: steve at holdenweb.com (Steve Holden) Date: Thu, 26 Apr 2007 08:01:41 -0400 Subject: Would You Write Python Articles or Screencasts for Money? In-Reply-To: <1177563297.609958.223070@b40g2000prd.googlegroups.com> References: <462DCCE6.9060908@taupro.com><462E0D93.3090705@holdenweb.com> <1177563297.609958.223070@b40g2000prd.googlegroups.com> Message-ID: placid wrote: > On Apr 25, 4:40 pm, "Tennessee Leeuwenburg" > wrote: >> Firstly, let me put up my hand and say that I would be happy to write >> Python articles for cash. >> > > I would be happy to write Python articles for a T-shirt with the > Python logo printed on it. Maybe each article entrant can receive a t- > shirt? > I suppose that might depend on the nomination procedure, but I think any entry with merit would deserve *some* acknowledgment, yes. Knowing how stretched our limited volunteer staff is, however, we might need to recruit people to support this process if there were to be a reasonable expectation that people would receive the promised gifts. ask-not-what-the-psf-can-do-for-you'ly y'rs - steve -- Steve Holden +1 571 484 6266 +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 Tue Apr 3 01:45:37 2007 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Tue, 3 Apr 2007 07:45:37 +0200 Subject: Mastering Python (OT) References: <1174045298.826137.262890@o5g2000hsb.googlegroups.com><1174052358.486071.163280@e65g2000hsc.googlegroups.com><46018fd8$0$18018$426a74cc@news.free.fr><46091cdf$0$19664$426a74cc@news.free.fr> <000f01c771d2$2fc41940$03000080@hendrik> <003301c7746f$859d0300$03000080@hendrik> Message-ID: <00ed01c775c8$1ce7a2c0$03000080@hendrik> "Steve Holden" wrote: > Speaking of which, here's a limerick To read it you need to know not > only that Hampshire is colloquially know as Hants, but also that > Salisbury's ancient Roman name is Sarum. > > There once was a young man of Salisbury > Whose manners were most halisbury-scalisbury > He visited Hampshire > Without any pampshire > Till somebody told him to walisbury. > > try-running-a-spell-checker-on-that-ly y'rs - steve Nice one! - Thanks Steve - Hendrik From bytecolor at yahoo.com Tue Apr 3 05:35:04 2007 From: bytecolor at yahoo.com (bytecolor) Date: 3 Apr 2007 02:35:04 -0700 Subject: Parsing Problems In-Reply-To: <1175591597.120154.240820@q75g2000hsh.googlegroups.com> References: <1175591597.120154.240820@q75g2000hsh.googlegroups.com> Message-ID: <1175592904.788661.196190@y80g2000hsf.googlegroups.com> On Apr 3, 5:13 am, saif.shak... at gmail.com wrote: > Hi, > > I have just started learning python.I need to parse an XML file > and present the contents in a particular format.The format is called > as "ini" file.I have written some code.A section of the format needs > the data to be present in format as given below: > > [Services] > supported=0x10,0x1A,0x3B,0x20,0x27,0x28,0x34,0x36,0x3E,0xA2,0xA5,0x2D, > 0x22,0xA9,0x04,0xAA,0xAE > > My code for this section parses the xml file and gives : > [Services] > Supported=['0x3e', '0x28', '0x3b', '0x22', '0x20', '0x27', '0xaa', > '0x10', '0xae', '0x34', '0x36', '0x2d', '0xa9', '0xa5', '0x4', '0xa2', > '0x1a'] > > {forget the numericals matching}.As you can see there > are single quotes around numericals ,which is not desired .I think the > problem lies in me using a list for storing and later printing out > values.I have attached few lines of code,not sure how clear it can be > to you: > > for l in range(0,len(ser_par), > 1): > if > ser_par[l].getAttribute('Semantics')==u'serviceId': > if > tag_exists(ser_par[l].childNodes,'VALUE'): > val = > ser_par[l].getElementsByTagName('VALUE') > value = > str(val[0].getAttribute('value')) > valu = hex(int(value)) > rval.append(valu) > ser_par_num = ser_par_num + 1 > prim_num = prim_num + 1 > > service_num = service_num + 1 > variant_num = variant_num + 1 > ser = list(set(rval)) > > print "\n[Services]" > print "Supported="+str(ser) > > How can i get rid of those single quotes. > > Thanking you > > shakeel >>> l = ['0x3e', '0x28', '0x3b', '0x22', '0x20', '0x27', '0xaa'] >>> ','.join(l) '0x3e,0x28,0x3b,0x22,0x20,0x27,0xaa' You may want to look at the ConfigParser package too. It's for reading/ writing .ini file. -- bytecolor From paddy3118 at netscape.net Wed Apr 25 23:54:48 2007 From: paddy3118 at netscape.net (Donald 'Paddy' McCarthy) Date: Thu, 26 Apr 2007 03:54:48 GMT Subject: Where did my post go? In-Reply-To: <1177550534.197992.263190@u32g2000prd.googlegroups.com> References: <1177550534.197992.263190@u32g2000prd.googlegroups.com> Message-ID: flifus at gmail.com wrote: > I posted to this newsgroup earlier about my annoyances with python and > now I can't find the post. What did you do with it? > I notice a gmail address. Google groups was not updated for over a day and is still 'behind'. Try another news reader. - Paddy From skip at pobox.com Wed Apr 4 13:56:28 2007 From: skip at pobox.com (skip at pobox.com) Date: Wed, 4 Apr 2007 12:56:28 -0500 Subject: try... except SyntaxError: unexpected EOF while parsing In-Reply-To: <1175708304.034078.139020@e65g2000hsc.googlegroups.com> References: <1175708304.034078.139020@e65g2000hsc.googlegroups.com> Message-ID: <17939.59084.94131.861520@montanaro.dyndns.org> (Are you Howard the Duck's lesser known cousin?) >>>>> "oscar" == oscartheduck writes: oscar> I have a small script for doing some ssh stuff for me. I could oscar> have written it as shell script, but wanted to improve my python oscar> skills some. oscar> RIght now, I'm not catching a syntax error as I'd like to. Well, you should probably never catch SyntaxError (unless you use exec or eval, both of which you should also probably never use), however... What you're describing is not a Python syntax error. In addition, if you're expecting to catch problems with the call to input("Please ...") you'll need to have it within the try block. Given that port numbers have to be ints I'd try something like: port = 2024 userport = raw_input("Please enter a port #: ").strip() if userport: try: port = int(userport) except ValueError: pass if port > 65535: blah blah blah ... Note that input("prompt") is equivalent to eval(raw_input("prompt")), so you should probably never use it. (It's going away in Python 3.0 anyway.) Skip From bbxx789_05ss at yahoo.com Wed Apr 11 21:28:08 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: 11 Apr 2007 18:28:08 -0700 Subject: Nested dictionaries trouble In-Reply-To: <1176339709.998807.32990@e65g2000hsc.googlegroups.com> References: <1176317876.917874.58040@n59g2000hsh.googlegroups.com> <461d427e$0$18058$426a74cc@news.free.fr> <1176339709.998807.32990@e65g2000hsc.googlegroups.com> Message-ID: <1176341288.631317.235660@y5g2000hsa.googlegroups.com> On Apr 11, 7:01 pm, "7stud" wrote: > On Apr 11, 2:57 pm, Bruno Desthuilliers > > wrote: > > IamIan a ?crit : > > > yearTotals = dict([(year, dict.fromkeys(months, 0)) for year in years]) > > > HTH > > List comprehensions without a list? What? Where? How? Ooops. I copied the wrong one. I was looking at this one: yearTotals = dict((year, monthTotals) for year in years) From steve at holdenweb.com Mon Apr 23 17:52:22 2007 From: steve at holdenweb.com (Steve Holden) Date: Mon, 23 Apr 2007 17:52:22 -0400 Subject: Socket exceptions aren't in the standard exception hierarchy In-Reply-To: References: Message-ID: John Nagle wrote: [socket.error bug report] >> >> Where did you get this information? If true it would certainly need to >> be logged as a bug, but under Windows on 2,4 I see >> >> >>> issubclass(socket.gaierror, Exception) >> True >> >>> >> >> and the same under Cygwin 2.5. I am presuming most other users will see >> the same thing. >> >> regards >> Steve > > Ah. "socket.error" is a subclass of "Exception", but not > of "StandardError". > > issubclass(socket.error,StandardError) > > is False. > Right, so this *is* a big, as long as Brett Cannon's upcoming (further) reorganization of the standard exception hierarchy doesn't stamp on it. It probably *was* overlooked in the reorganization of the hierarchy, and this implies there may be other extensions that also make the same error. It should be logged as a bug in the tracker - the fix is probably pretty simple, but it'll need some consideration of the forward compatibility considerations. regards Steve -- Steve Holden +1 571 484 6266 +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 mik3l3374 at gmail.com Wed Apr 4 05:20:00 2007 From: mik3l3374 at gmail.com (mik3l3374 at gmail.com) Date: 4 Apr 2007 02:20:00 -0700 Subject: how to remove multiple occurrences of a string within a list? In-Reply-To: <1175624433.206953.214290@n59g2000hsh.googlegroups.com> References: <1175624433.206953.214290@n59g2000hsh.googlegroups.com> Message-ID: <1175678400.712810.145330@y66g2000hsf.googlegroups.com> On Apr 4, 2:20 am, "bahoo" wrote: > Hi, > > I have a list like ['0024', 'haha', '0024'] > and as output I want ['haha'] > > If I > myList.remove('0024') > > then only the first instance of '0024' is removed. > > It seems like regular expressions is the rescue, but I couldn't find > the right tool. > > Thanks! > bahoo how about this: >>> target = "0024" >>> l = ["0024", "haha", "0024", "0024", "sfs"] >>> result = [ item for item in l if item != target] >>> result ['haha', 'sfs'] From steve at holdenweb.com Mon Apr 2 10:38:53 2007 From: steve at holdenweb.com (Steve Holden) Date: Mon, 02 Apr 2007 10:38:53 -0400 Subject: Problem with global variables In-Reply-To: <57ciafF2cf6qdU1@mid.individual.net> References: <1311u48bqkehk24@corp.supernews.com> <57ciafF2cf6qdU1@mid.individual.net> Message-ID: Bjoern Schliessmann wrote: > Laurent Pointal wrote: > >> And so the solution to add "global foo" before using it. > > Didn't you read his final question? > > | All of a sudden, tiny() can see the global variable "foo". Very > | confusing! Why is it that tiny() sometimes can, and sometimes > | can't, see the global variable "foo"? > > I have no explanation for this, but I'm interested in one, too. > It doesn't happen "all of a sudden", it happens when the assignment to foo is removed from the function definition. The interpreter therefore no longer regards foo as a local variable. 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 marco.minerva at gmail.com Wed Apr 4 12:02:49 2007 From: marco.minerva at gmail.com (marco.minerva at gmail.com) Date: 4 Apr 2007 09:02:49 -0700 Subject: String manipulation In-Reply-To: References: <1175699768.427986.210310@l77g2000hsb.googlegroups.com> Message-ID: <1175702569.161940.113040@y66g2000hsf.googlegroups.com> On 4 Apr, 17:39, Alexander Schmolck wrote: > All the code is untested, but should give you the idea. > > > > > > marco.mine... at gmail.com writes: > > Hi all! > > > I have a file in which there are some expressions such as "kindest > > regard" and "yours sincerely". I must create a phyton script that > > checks if a text contains one or more of these expressions and, in > > this case, replaces the spaces in the expression with the character > > "_". For example, the text > > > Yours sincerely, Marco. > > > Must be transformated in: > > > Yours_sincerely, Marco. > > > Now I have written this code: > > > filemw = codecs.open(sys.argv[1], "r", "iso-8859-1").readlines() > > filein = codecs.open(sys.argv[2], "r", "iso-8859-1").readlines() > > > mw = "" > > for line in filemw: > > mw = mw + line.strip() + "|" > > One "|" too many. Generally, use join instead of many individual string +s. > > mwfind_re_string = "(%s)" % "|".join(line.strip() for line in filemw) > > > mwfind_re = re.compile(r"^(" + mw + ")",re.IGNORECASE|re.VERBOSE) > > mwfind_re = re.compile(mwfind_re_string),re.IGNORECASE) > > > mwfind_subst = r"_" > > > for line in filein: > > That doesn't work. What about "kindest\nregard"? I think you're best of > reading the whole file in (don't forget to close the files, BTW). > > > line = line.strip() > > if (line != ""): > > line = mwfind_re.sub(mwfind_subst, line) > > print line > > > It correctly identifies the expressions, but doesn't replace the > > character in the right way. How can I do what I want? > > Use the fact that you can also use a function as a substitution. > > print mwfind_re.sub(lambda match: match.group().replace(' ','_'), > "".join(line.strip() for line in filein)) > > 'as- Nascondi testo tra virgolette - > > - Mostra testo tra virgolette - Hi Alexander! Thank you very much, your code works perfectly! -- Marco Minerva, marco.minerva at gmail.com http://blogs.ugidotnet.org/marcom From gilcneth at earthlink.net Thu Apr 12 22:51:22 2007 From: gilcneth at earthlink.net (Chris Nethery) Date: Fri, 13 Apr 2007 02:51:22 GMT Subject: Using python to delta-load files into a central DB References: Message-ID: Gabriel, Thank you for your reply. Yes, they are tab-delimited text files that will change very little throughout the day. But, this is messy, antiquated 80s junk, nonetheless. Rows are designated either by a row type or they contain a comment. Each row type has an identity value, but the 'comment' rows do not. The comment rows, however, are logically associated with the last occurring row type. When I generate my bulk insert file, I add the identity of the last occurring row type to the comment rows, and generate and populate an additional identity column in order to retain the order of the comments. Generally rows will either be added or changed, but sometimes rows will be removed. Typically, only 1-5 new rows will be added to a file in a given day, but users sometimes make manual corrections/deletions to older rows and sometimes certain column values are recalculated. Did I mention that the header contains another implied hierarchy? Fortunately, I can just ignore it and strip it off. Thank you, Chris Nethery "Gabriel Genellina" wrote in message news:mailman.6440.1176427176.32031.python-list at python.org... > En Thu, 12 Apr 2007 14:05:15 -0300, Chris Nethery > escribi?: > >> At present, users of the separate application can run recalculation >> functions that modify all 700 files at once, causing my code to take the >> whole ball of wax, rather than just the data that has changed. > > Are they text files, or what? > What kind of modifications? some lines changed/deleted/added? a column > recalculated along the whole file? > >> What I would like to do is spawn separate processes and load only the >> delta >> data. The data must be 100% reliable, so I'm leary of using something >> like >> difflib. I also want to make sure that my code scales since the number >> of >> files is ever-increasing. > > Why don't you like difflib? AFAIK it has no known bugs. > > -- > Gabriel Genellina > From michael at jedimindworks.com Wed Apr 18 10:41:13 2007 From: michael at jedimindworks.com (Michael Bentley) Date: Wed, 18 Apr 2007 09:41:13 -0500 Subject: Help on Shelve.... In-Reply-To: <1176902396.364403.134210@o5g2000hsb.googlegroups.com> References: <1176810739.765433.47470@n59g2000hsh.googlegroups.com> <1176902396.364403.134210@o5g2000hsb.googlegroups.com> Message-ID: <5C39BE6D-61A4-46DB-A0F0-EFD1DC4B7E9A@jedimindworks.com> On Apr 18, 2007, at 8:19 AM, Clement wrote: > On Apr 17, 5:52 pm, Michael Bentley wrote: >> On Apr 17, 2007, at 6:52 AM, Clement wrote: >> >>> Can i useShelvefor storing large amount of data around 6GB.. Is it >>> stable...? if any problems come, can i retrive the document.. >> >> Do you know for sure your filesystem handles files that big? > > I am using NTFS filesystem that can handle more than 500GB files Ye looks like your filesystem can theoretically handle 16tb files. I'm afraid I don't know the answer to your question -- seems like it should work ;-) How about trying it out and reporting back? From hayes.tyler at gmail.com Mon Apr 23 18:57:48 2007 From: hayes.tyler at gmail.com (Tyler) Date: 23 Apr 2007 15:57:48 -0700 Subject: vtkStructuredGrid usage question in MayaVi Message-ID: <1177369068.590404.3040@b58g2000hsg.googlegroups.com> Hello All: I hope this is a simple question, but I can't seem to figure it out. I am using MayaVi to visualize some data. I have finally manged to get the data to plot, but the axes are weird, and the scaling of the image is way off. I have been fooling around with the command below. grid = pyvtk.StructuredPoints((nex1,nex1,1), (0,s1high,0), (2, 2, 0.2)) This seems to be the key to having the data plotted nicely (scaled properly, axes numbered correctly, etc.). However, I cannot figure out what each of the tuples are for. Does anyone know? This would be a huge help for me. Thanks, Tyler From kirkjobsluder at gmail.com Wed Apr 18 08:00:50 2007 From: kirkjobsluder at gmail.com (kirkjobsluder) Date: 18 Apr 2007 05:00:50 -0700 Subject: Future Python Gui? In-Reply-To: <4625b5a2$0$22843$afc38c87@news.optusnet.com.au> References: <1176859699.906386.326720@b75g2000hsg.googlegroups.com> <1176863948.526051.186210@n76g2000hsh.googlegroups.com> <4625b5a2$0$22843$afc38c87@news.optusnet.com.au> Message-ID: <1176897649.940734.245620@o5g2000hsb.googlegroups.com> On Apr 18, 2:07 am, Richard Jones wrote: > kirkjobsluder wrote: > > I'd say that the best bet is to learn swig and similar > > bridging, expanding, and embedding mechanisms. > > For GUI programming this would seem overkill. Pick a GUI toolkit and it's > almost guaranteed to be wrapped for use in Python already. Perhaps a bit. I'm not saying that everyone should wrap their own code, but many of the currently existing wrappers are quite thin, and understanding how to use and debug wrapped GUI code might put one in a better position over knowing a particular toolkit. > > Richard From bbxx789_05ss at yahoo.com Sat Apr 28 16:05:36 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: 28 Apr 2007 13:05:36 -0700 Subject: how can I put an Exception as the key of a hash table In-Reply-To: <1177786431.935154.89510@y5g2000hsa.googlegroups.com> References: <1177786431.935154.89510@y5g2000hsa.googlegroups.com> Message-ID: <1177790736.107745.59430@e65g2000hsc.googlegroups.com> yinglcs at gmail.com wrote: > I want to keep track of the number of different exception happens in > my python program: > > ErrorHash = {} > > try: > > # come code ... > > except Exception, e: > print e > errcode = e > > if (ErrorHash.has_key(errcode)): > ErrorFailNo = ErrorHash[errcode] > > ErrorHash[errcode] = ErrorFailNo + 1 > > else: > ErrorHash[errcode] = 1 > > > But when i print out the ErrorHash like this: > > print ErrorHash > > i get an empty string. Can you please tell me how can I put an > Exception as the key of a hash table ? Or how can i dump out all the > content of the hashtable. > > Thank you. Apparently, the Exception class's __str__() method doesn't print anything about the exception. That doesn't mean the exception is an empty string though: ErrorHash = {} try: raise ValueError except Exception, e: print "the exception is:", e, "<----" if (ErrorHash.has_key(e)): ErrorFailNo = ErrorHash[e] ErrorHash[e] = ErrorFailNo + 1 else: ErrorHash[e] = 1 print ErrorHash From fairwinds at eastlink.ca Sun Apr 8 22:56:04 2007 From: fairwinds at eastlink.ca (David Pratt) Date: Sun, 08 Apr 2007 23:56:04 -0300 Subject: Python universal build, OSX 10.3.9 and undefined symbols when linking In-Reply-To: <1hw9lxy.ldrc541w507xyN%aleax@mac.com> References: <1175746456.995618.186190@e65g2000hsc.googlegroups.com> <1175746966.023613.178830@n76g2000hsh.googlegroups.com> <1175756092.643182.142420@n76g2000hsh.googlegroups.com> <1hw9lxy.ldrc541w507xyN%aleax@mac.com> Message-ID: <4619AB44.4090001@eastlink.ca> Hi. I am on a PPC and have been getting the same undefined symbols traceback when linking applications after compiling. A few weeks back I posted on a problem to pythonmac-sig at python.org after attempting to build mod_python, today its pylucene - same problem. I initially shrugged off the problem with mod_python as likely an issue with the mac port. Crazy thing is that I built the same version of pylucene successfully just before upgrading to universal build of 2.4.4 python for mac without problems. So I recompiled the same version of pylucene I had previously built with a PPC only build of python to evaluate whether my thoughts were right. I had a hunch universal python was causing my trouble with mod_python and a newer build of pylucene and it appears I was right. I am currently using Mac OSX 10.3.9 on a PPC with universal build of 2.4.4. I should say that other than linking problem I am experiencing, the python functions as it should. From mod_python build: ld: Undefined symbols: _fstatvfs referenced from Python expected to be defined in libSystem _lchown referenced from Python expected to be defined in libSystem _statvfs referenced from Python expected to be defined in libSystem apxs:Error: Command failed with rc=65536 . make[1]: *** [mod_python.so] Error 1 make: *** [do_dso] Error 2 From pylucene build: ld: Undefined symbols: _fstatvfs referenced from Python expected to be defined in libSystem _lchown referenced from Python expected to be defined in libSystem _statvfs referenced from Python expected to be defined in libSystem gmake: *** [release/_PyLucene.so] Error 1 I have googled to see there have been others with this issue however they have tended to communicate about the problem on software lists or forums specific to the software they were attempting to build. I did not see this resolved in any case that I have read. I am hoping someone may be able to advise a possible solution. I am planning on upgrading to OSX 10.4 within a week since mac is not making the JDK 1.5.0 available for OSX 10.3 users - so pretty much being forced into upgrading in any case. If you had the same linking issue with the universal build of python it would be good to hear from you - better yet would be some way of solving this or at least understanding what may be going on. I have posted to pythonmac-sig at python.org in the interim but there is very little traffic on this list. In the meantime I thought there may other OSX 10.3.9 users out there who may have run into the same fate. Many thanks. Regards, David From paddy3118 at googlemail.com Thu Apr 19 23:02:19 2007 From: paddy3118 at googlemail.com (Paddy) Date: 19 Apr 2007 20:02:19 -0700 Subject: Better dict of dicts In-Reply-To: References: <4627E28C.1050406@v.loewis.de> Message-ID: <1177038139.635788.10340@e65g2000hsc.googlegroups.com> On Apr 20, 1:38 am, DillonCo wrote: > On Thursday 19 April 2007, Bill Jackson wrote: > > > Martin v. L?wis wrote the following on 04/19/2007 02:43 PM: > > > Bill Jackson schrieb: > > >> I have a dictionary of dictionaries where the keys are typically very > > >> long tuples and repeated in each inner dictionary. > > > > What I don't understand here: you say the keys are tuples, yet later, > > > you show that the keys are strings. Which one is it? > > > Sorry, I was just lazy. The keys will always be tuples...tuple of > > strings, tuples of numbers, tuples of objects....simply tuples. > > That'll change things a bit because intern only works with strings. > > Of course, It's not so big a deal, but you will have to put together a class > to implement interning. > I wrote one for fun: > > class ITuple(tuple): > _interns={} > def __new__(cls, tup): > if tup not in cls._interns: > itup=tuple.__new__(cls, tup) > cls._interns[tup]=itup > return cls._interns[tup] > def __init__(self, *args): > #Prevent multiple calls to __init__ > if hasattr(self, "_inited"): return > tuple.__init__(self, *args) > self._inited=True > def __eq__(self, o): > #If the other is an ITuple, self==o iff self is o > if isinstance(o, ITuple): > return self is o > return tuple.__eq__(self, o) > > >>> t1=(1,2,3,4); t2=(1,2,3,4) > >>> ti1=ITuple(t1); ti2=ITuple(t2) > >>> print t1==t2, t1 is t2 > True False > >>> print ti1==ti2, ti1 is ti2 > > True True > > That seems to work. Something to note is that the call overhead of the __eq__ > function is large enough that unless you have a slow comparing tuple, > comparisons will be faster without it. Comparisons are fast if they are done > internally; so between builtin objects or identical (" is ") objects. > > For an example, suppose you have: > > class TTT(object): > def __eq__(self, o): return True > a,b=TTT(),TTT() > > Then the follow comparisons are fast: > (1,2,3)==(1,2,3) > (1,2,3,a)==(1,2,3,a) > (0,0,0,a)==(1,2,3,b) > > The following are slow: > (1,2,3,a)==(1,2,3,b) > > Note that the only slow case is the one where a.__eq__(b) is called. However, > a.__eq__(b) is assumed True is "a is b" is True. So chances are you'll want > to comment out the __eq__ function. Hi DillonCo, Martins earlier local_intern function would work for tuples as well as strings. - Paddy. From 12cc104 at gmail.com Sun Apr 22 22:13:31 2007 From: 12cc104 at gmail.com (proctor) Date: 22 Apr 2007 19:13:31 -0700 Subject: recursion depth problem In-Reply-To: References: <1177267774.416169.276780@e65g2000hsc.googlegroups.com> <1177275314.846022.249000@e65g2000hsc.googlegroups.com> <1177276111.720137.315710@b75g2000hsg.googlegroups.com> <1177286778.918119.7490@e65g2000hsc.googlegroups.com> Message-ID: <1177294411.144709.24650@l77g2000hsb.googlegroups.com> On Apr 22, 7:10 pm, Dennis Lee Bieber wrote: > On 22 Apr 2007 17:06:18 -0700, proctor <12cc... at gmail.com> declaimed the > following in comp.lang.python: > > > > else: > > > # only one of carry in, b1, or b2 is set > > #or none is set! Missed the 0,0,0 condition > > > > return (0, b1 + b2 + c) > > > thank you. you guys are keeping me busy! > > Heh... I'm sure what I scratched together could be optimized more > (make functions out of the input/output conversions; add some error > checking on input data, allow for non-list arguments in adder()...) > > After all, if one wants a binary counter, one should implement a > binary addition operation, and basic digital has ways... Unfortunately, > Python now has a Boolean type, so boolean AND/OR doesn't give the > desired results... And using bitwise seems wasteful However... > replace the badd() with the following obscure thing if you really want > to get close to hardware emulation... > > def badd(b1, b2, ci=0): > """ > badd(b1, b2, ci) => (co, sum) > """ > (co1, hs1) = (b1 & b2, b1 ^ b2) > (co2, hs2) = (ci & hs1, ci ^ hs1) > return (co1 | co2, hs2) > > A pair of "half-adders"; and the extra bit to make a "full-adder". > It wouldn't be efficient to do it as one long return, just due to > duplicated (b1 ^ b2) sub-terms > > return ( (b1 & b2) | (ci & (b1 ^ b2)), (ci ^ (b1 ^ b2))) > > but it does work > -- > 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/ :-) this is good stuff. for learning especially! thank you again! proctor. From __peter__ at web.de Mon Apr 9 03:00:10 2007 From: __peter__ at web.de (Peter Otten) Date: Mon, 09 Apr 2007 09:00:10 +0200 Subject: shelve error References: <1175746456.995618.186190@e65g2000hsc.googlegroups.com> <1175746966.023613.178830@n76g2000hsh.googlegroups.com> <1175756092.643182.142420@n76g2000hsh.googlegroups.com> <1hw9lxy.ldrc541w507xyN%aleax@mac.com> Message-ID: Alex Martelli wrote: > BTW, if you DO want to call shelve.open on a path f that may correspond > to an arbitrary existing file (and want to toss away the previous > contents of that file, if any) the correct way to call is then: > > s?=?shelve.open(whatever_path,?'n') > > since 'n' truncates an existing file, or creates a new one, as needed. It's not entirely arbitrary since you get an exception if that file is not a valid database: >>> open("tmp.db", "w").write("garbage") >>> import shelve >>> shelve.open("tmp.db", "n") Traceback (most recent call last): File "", line 1, in File "/usr/local/lib/python2.5/shelve.py", line 225, in open return DbfilenameShelf(filename, flag, protocol, writeback) File "/usr/local/lib/python2.5/shelve.py", line 209, in __init__ Shelf.__init__(self, anydbm.open(filename, flag), protocol, writeback) File "/usr/local/lib/python2.5/anydbm.py", line 80, in open raise error, "db type could not be determined" anydbm.error: db type could not be determined Peter From kwatch at gmail.com Mon Apr 30 19:19:54 2007 From: kwatch at gmail.com (kwatch) Date: 30 Apr 2007 16:19:54 -0700 Subject: [Q] module name available in 'from ... import ...' statement Message-ID: <1177975194.782804.155070@n76g2000hsh.googlegroups.com> What is the condition of module name which is available in 'from .. import ..' statement ? ---------------------------------------- import os print os.path # from posixpath import sep # (no errors) from os.path import sep # (no errors, wow!) path = os.path from path import sep # ImportError: No module named path ---------------------------------------- I found that library 'os.py' exists but 'os/path.py' doesn't exist in '/usr/local/lib/python2.5'. It means that file 'os/path.py' is not required to perform 'from os.path import sep' statement. Could you teach me the condition of module name which is available in 'from ... import ...' statement? The goal what I want to do is to create a module by 'new' module and specify that module name in 'from ...' statement. ---------------------------------------- # create a module import new foo = new.module('foo') foo.pi = 3.14159 foo.x2 = lambda x: 2*x # specify it in 'from' statement from foo import pi, x2 # ImportError: No module named foo ---------------------------------------- -- regards, kwatch From lobais at gmail.com Mon Apr 16 05:50:40 2007 From: lobais at gmail.com (Thomas Dybdahl Ahle) Date: Mon, 16 Apr 2007 11:50:40 +0200 Subject: Compare regular expressions Message-ID: Hi, I'm writing a program with a large data stream to which modules can connect using regular expressions. Now I'd like to not have to test all expressions every time I get a line, as most of the time, one of them having a match means none of the others can have so. But ofcource there are also cases where a regular expression can "contain" another expression, like in: "^strange line (\w+) and (\w+)$" and "^strange line (\w+) (?:.*?)$" in which case I'd like to first test the seccond and only if it mathces test the seccond. Do anybody know if such a test is possible? if exp0.contains(exp1): ... From manhhle at gmail.com Mon Apr 23 15:17:32 2007 From: manhhle at gmail.com (manhhle at gmail.com) Date: 23 Apr 2007 12:17:32 -0700 Subject: tftpy 0.41 errors Message-ID: <1177355851.998724.255140@p77g2000hsh.googlegroups.com> When trying to import the tftpy package, I've gotten the following error messages: 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 tftpy Traceback (most recent call last): File "", line 1, in ? File "/usr/lib/python2.4/site-packages/tftpy/__init__.py", line 18, in ? from TftpServer import * File "/usr/lib/python2.4/site-packages/tftpy/TftpServer.py", line 50 % (listenip if listenip else '0.0.0.0', listenport)) ^ SyntaxError: invalid syntax >>> What am I missing? Any pointer is much appreciated. I installed the tftpy package using the standard command line: sudo python setup.py install From spohle at gmail.com Mon Apr 30 11:02:58 2007 From: spohle at gmail.com (spohle) Date: 30 Apr 2007 08:02:58 -0700 Subject: import structures In-Reply-To: <1177945229.856966.309080@y80g2000hsf.googlegroups.com> References: <1177945012.753497.117630@o5g2000hsb.googlegroups.com> <1177945229.856966.309080@y80g2000hsf.googlegroups.com> Message-ID: <1177945378.731721.137080@o5g2000hsb.googlegroups.com> On Apr 30, 8:00 am, Paul McGuire wrote: > On Apr 30, 9:56 am, spohle wrote: > > > > > hi, > > > i have written a small project for myself all in seperate classes and > > each of the classes lives in a seperate file. now i am looking for an > > import structure something like import wx, and then have access to all > > my classes just like wx.Button or wx.BoxSizer etc. > > > as of now i have a __init__.py file in the directory with: > > from pkgutil import extend_path > > __path__ = extend_path(__path__, __name__) > > > but i still have to import each class by it's own. im really looking > > for something like import wx > > and then get all my access right away under this new namespace. > > > thank you in advance > > If it really is a small project, consider just putting all the classes > into a single module, say spohlePkg.py. Then your users would import > this module using "import spohlePkg", and would access the classes as > "spohlePkg.ClassA", "spohlePkg.ClassB", etc. > > -- Paul yeah i had that, but my classes grew really fast and i decided to split them up. but you're right that in one file that would solve my problem. still hoping to find a way for the seperate files. From pydecker at gmail.com Tue Apr 10 16:59:30 2007 From: pydecker at gmail.com (Peter Decker) Date: Tue, 10 Apr 2007 16:59:30 -0400 Subject: About Trolltech QT OpenSource license. In-Reply-To: <1176233376.712861.67160@o5g2000hsb.googlegroups.com> References: <1176233376.712861.67160@o5g2000hsb.googlegroups.com> Message-ID: On 10 Apr 2007 12:29:36 -0700, king kikapu wrote: > Hi to all, > > i am coming from the Microsoft (.net) world and at the quest of > finding the right GUI toolkit that i can use from Python, i have two > obvious choices to choose from: wxPython and Qt. > > Both are looking very good. Qt has Qt designer, a tool that really > reminds me of the forms designers that we have in VS.Net.The > productivity someone can gain from tools like these can be really > astonished. There is another alternative: Dabo, which wraps the wxPython toolkit. It has a GUI designer, although not as polished as the Qt Designer. Check out some of their screencasts to see their tools in action. You can find them at http://dabodev.com/documentation -- # p.d. From sjmachin at lexicon.net Sat Apr 21 20:26:53 2007 From: sjmachin at lexicon.net (John Machin) Date: 21 Apr 2007 17:26:53 -0700 Subject: Returning a date as string In-Reply-To: <1177189171.147254.35920@n76g2000hsh.googlegroups.com> References: <1177189171.147254.35920@n76g2000hsh.googlegroups.com> Message-ID: <1177201613.014645.72530@y80g2000hsf.googlegroups.com> On Apr 22, 6:59 am, Bj?rn Keil wrote: > Hello pythons, > > I have little problem with understanding conversions in python. I've > written a little class - nothing much, just to try out Python a little > - containing the following method: > > def __repr__(self): > """Serializes the note. > > Currently the format of notes isn't decided upon. XML output > is > projected.""" Insert here: print "Due: %r" % self.dateDue print "Created: %r" % self.dateCreated print "Subject: %r" % self.subject print "Content: %r % self.content > return "Due: " + str(self.dateDue) + \ > "\nDate: " + str(self.dateCreated) + \ > "\nSubject: " + self.subject + \ > "\n" + self.content > > The fields "dateDue" and "dateCreated" contain datetime.date objects. > Now when I try to serialize the whole thing: > > >>> myNote > > Traceback (most recent call last): > File "", line 1, in ? > File "notes.py", line 81, in __repr__ > return "Due: " + str(self.dateDue) + \ > TypeError: cannot concatenate 'str' and 'datetime.date' objects > > I tryed different variant before I wrapped "self.dateDue" in a str() > constructor: > I tried to put it in brackets, or call its .isoformat() method. > Nothing works. It still complains that I was trying to concatenate a > string with a date, but I really wanna concatenate a string with a > string! > > Could anyone please tell me what I am doing wrong? Not showing us the *whole* code that you are executing. Suggestions: (1) Maybe dates have crept into self.subject and self.content. The print statements above should show exactly what you've got. (2) Maybe you didn't save it before you ran it. Maybe you forgot to reload(yourModule). Try making up the smallest possible script that demonstrates your problem. Get out of whatever IDE you may be using and go to the OS command-line prompt. Use type (windows) or cat (*x) to print your script on the console. Run your script. Copy the console contents and paste it into your mail/news client. HTH, John From tom at finland.com Tue Apr 17 10:12:00 2007 From: tom at finland.com (tom at finland.com) Date: Tue, 17 Apr 2007 14:12:00 GMT Subject: The smallest and largest values of numeric types Message-ID: Hi! How can I determine the smallest and largest values of numeric types (for example int) possible in my system? I think there exists a function for this task but I don't know it. From attn.steven.kuo at gmail.com Wed Apr 4 20:36:07 2007 From: attn.steven.kuo at gmail.com (attn.steven.kuo at gmail.com) Date: 4 Apr 2007 17:36:07 -0700 Subject: Newbie Question about sequence multiplication In-Reply-To: <6cOdnVFCLMXxuYnbnZ2dnUVZ_rCsnZ2d@comcast.com> References: <6cOdnVFCLMXxuYnbnZ2dnUVZ_rCsnZ2d@comcast.com> Message-ID: <1175733367.100208.240610@p77g2000hsh.googlegroups.com> On Apr 4, 3:19 pm, "Scott" wrote: (snipped) > > print > print ' ' * left_margin + '+' + '-' * (box_width-2) + '+' > print ' ' * left_margin + '| ' + ' ' * text_width + ' |' > print ' ' * left_margin + '| ' + ' ' sentence + ' |' > print ' ' * left_margin + '| ' + ' ' * text_width + ' |' > print ' ' * left_margin + '+' + '-' * (box_width-2) + ' |' > print > > ****end code**** > > Now that, even though copied straight from "Beginning Python: From Novice to > Professional", returns : > There's an error in your program: invalid syntax > (snipped) Others have pointed out the mistake. I'll just add that in this particular case, one might want to pad lines with some whitespace and change the middle print statement to: print print ' ' * left_margin + '+' + '-' * box_width + '+' print ' ' * left_margin + '|' + '-' * box_width + '|' print ' ' * left_margin + '|' + sentence.center(box_width) + '|' print ' ' * left_margin + '|' + '-' * box_width + '|' print ' ' * left_margin + '+' + '-' * box_width + '+' to improve legibility. -- Hope this helps, Steven From jjl at pobox.com Sat Apr 14 05:59:22 2007 From: jjl at pobox.com (John J. Lee) Date: Sat, 14 Apr 2007 09:59:22 GMT Subject: "HTTP error -1" from urllib2 References: Message-ID: <873b33cm4f.fsf@pobox.com> John Nagle writes: > I'm getting a wierd error from urllib2 when opening certain > URLs. The code works for most sites, but not all of them. > Here's the traceback: [...] > InfoException: Problem with page "http://www.fourmilab.ch": HTTP error -1 - .. > > This fails identically using Python 2.4 on a Windows desktop and on Python 2.5 > on a Linux server. > > The site being accessed reads fine in a browser. It's not a redirect, > and it doesn't insist on cookies. > > See "http://mail.python.org/pipermail/python-list/2005-March/314301.html" > for another problem involving "HTTP error -1". Can you create an example (preferably small) that fails? Feel free to email it to me if it includes something you don't want to post. Simply fetching the URL you mention with urllib2.urlopen() works for me, so I guess something extra is needed to reproduce the bug: import urllib2 r = urllib2.urlopen("http://www.fourmilab.ch") print r.read() John From kalita at poczta.onet.pl Sat Apr 7 12:17:34 2007 From: kalita at poczta.onet.pl (kalita at poczta.onet.pl) Date: 7 Apr 2007 09:17:34 -0700 Subject: Debugging embedded python Message-ID: <1175962654.909909.218910@o5g2000hsb.googlegroups.com> I'm a Python newbie, and I'm looking for a way to debug Python scripts run from a C++ program by using PyRun_FileEx() function. So far I tried pdb, but it only raises bdb.BdbQuit exception in a line immediately after pdb.set_trace() is called. I guess it's because it is not running under normal Python interpreter, but just as well I may be doing something wrong. Can you please suggest what I may be doing wrong with pdb, or maybe another python debugger? cheers, Marcin From robert.kern at gmail.com Sun Apr 8 22:46:43 2007 From: robert.kern at gmail.com (Robert Kern) Date: Sun, 08 Apr 2007 21:46:43 -0500 Subject: python, wxpython and Mac OS X In-Reply-To: <1176086130.330795.268590@n76g2000hsh.googlegroups.com> References: <1176086130.330795.268590@n76g2000hsh.googlegroups.com> Message-ID: 7stud wrote: > Hi, > > I'm using an intel imac which came with python 2.3.5 pre-intstalled on > OS 10.4.7. I was able run a hello world wxPython script in Terminal > by typing: > > $pythonw wxPythonTest.py > > Yesterday, I installed python 2.4.4 which I downloaded from the > MacPython website, and it seems to have installed correctly: Why 2.4.4 instead of the official 2.5 binary from www.python.org? http://www.python.org/download/ > $python > Python 2.4.4 (#1, Oct 18 2006, 10:34:39) > [GCC 4.0.1 (Apple Computer, Inc. build 5341)] on darwin > Type "help", "copyright", "credits" or "license" for more information. > > However, now when I try to run my hello world wxPython script in > Terminal, I get the error message: > > Traceback (most recent call last): > File "wxPythonTest.py", line 1, in ? > import wx > ImportError: No module named wx > > Does that mean I need to install a newer version of wxPython? The packages that are installed (or you might install) for Python 2.3 are entirely separate from those that you would install for Python 2.4. It's not that you need a newer version of wxPython; it's that you need to install one for Python 2.4 period. > Also, what wxPython download should I install? For 2.4: http://prdownloads.sourceforge.net/wxpython/wxPython2.8-osx-unicode-2.8.3.0-universal10.4-py2.4.dmg For 2.5: http://prdownloads.sourceforge.net/wxpython/wxPython2.8-osx-unicode-2.8.3.0-universal10.4-py2.5.dmg -- 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 ladasky at my-deja.com Sat Apr 28 07:06:00 2007 From: ladasky at my-deja.com (John Ladasky) Date: 28 Apr 2007 04:06:00 -0700 Subject: Numeric + wxPython, can't understand a bug... In-Reply-To: References: <1177721777.885907.18780@n59g2000hsh.googlegroups.com> Message-ID: <1177758360.099242.314780@e65g2000hsc.googlegroups.com> On Apr 27, 9:40 pm, Robert Kern wrote: > wx.Point objects are being recognized as sequences by array(). Consequently, > reshape() thinks you are trying to reshape a (height*width, 2) array into a > (height, width) array. You might want to create an empty (height, width) > PyObject array first, and simply assign wx.Point values into it. That bypasses > array()'s attempt at intuiting the structure of the list. Thanks for the heads-up, Robert. I did as you suggested, and it works fine. I'll need to read more about Numeric's array init procedure -- what it does it not immediately obvious to a newcomer. +-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-+ | Ladasky Home Solar, Inc.: blowing sunshine up your | | power grid since March 24, 2005. Fiat lux! | +-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-+ | Uptime Downtime kWh generated kWh consumed | | 744 days 13 hours 12886 14321 | +-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-+ From aleax at mac.com Wed Apr 4 23:09:31 2007 From: aleax at mac.com (Alex Martelli) Date: Wed, 4 Apr 2007 20:09:31 -0700 Subject: compiling modules with VS 2008 for python 2.4 prepared with Visual Studio 2003 References: Message-ID: <1hw2ak4.1cxnvt81nzd971N%aleax@mac.com> alf wrote: > Hi, > > I want to add some library but it can not be comipled? Here is an output: If you don't have the needed compiler installed (in this case, VS 2003, while it looks like your installation has VS 2005 instead), sure. > D:\>cl > Microsoft (R) 32-bit C/C++ Optimizing Compiler Version 14.00.50727.42 > for 80x86 > Copyright (C) Microsoft Corporation. All rights reserved. > > usage: cl [ option... ] filename... [ /link linkoption... ] > > > D:\> python setup.py install > running install > running build > running build_ext > error: Python was built with Visual Studio 2003; > extensions must be built with a compiler than can generate compatible > binaries. > Visual Studio 2003 was not found on this system. If you have Cygwin > installed, > you can try compiling with MingW32, by passing "-c mingw32" to setup.py. I would think this error message is as clear as it can be, and then some! It even gives very practical advice on how to work around the problem. Either install VS2003, if you own it or can purchase it, or else install mingw32 (which is free and can be downloaded) and use the option which the error message tells you to. Alex From rajesh.radhakrishnan at gmail.com Fri Apr 27 00:40:05 2007 From: rajesh.radhakrishnan at gmail.com (Rajesh) Date: 26 Apr 2007 21:40:05 -0700 Subject: Command-line option equiv of PYTHONPATH Message-ID: <1177648804.947472.112830@s33g2000prh.googlegroups.com> Hi, The '-I' option adds the path to the list of directories that contains modules that can be included in a script. I can use it as "#!/ usr/bin/perl -I" thereby not asking the user of the script to set the in their environment. Is there any equivalent command-line option to the python binary or a command-line version of PYTHONPATH? Regards Rajesh From aleax at mac.com Sun Apr 8 22:14:11 2007 From: aleax at mac.com (Alex Martelli) Date: Sun, 8 Apr 2007 19:14:11 -0700 Subject: How do I get a slice of a string held in a tuple? References: <25ine4-rvt.ln1@Hedley.internal.thethurmans.com> <1176050876.835238.68560@d57g2000hsg.googlegroups.com> <1176056948.721586.48460@o5g2000hsb.googlegroups.com> Message-ID: <1hw9lgj.pm009qmr92l1N%aleax@mac.com> Lorenzo wrote: ... > > > elapsedTime = mydata[1] > > > index = elapsedTime.find("real") > > > # the index will have a value 0f 110 > > > totaltime = elapsedTime[index:] ... > Oops! I sent the wrong piece of code. The above is actually the work > around which actually works. The bad code is this: > index = mydata[0].find("real") > elapsedTime = mydata[0][index:] The only difference is that in the "workaround that works" you're mungling mydata[1], in the "bad code" mydata[0]. If you print or otherwise emit the value of index in each case, I think the cause of your problem will become clear (and it will probably be a value of index that's -1 for the "failing" case, and >= 0 for the "working" case, as other posts on this thread have already suggested). No connection can exist between your problem, and the string being "held in a tuple" or held in any other fashion. Alex From martin at v.loewis.de Thu Apr 26 07:12:46 2007 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Thu, 26 Apr 2007 13:12:46 +0200 Subject: Python not giving free memory back to the os get's me in real problems ... In-Reply-To: <1177510121.882503.145560@n15g2000prd.googlegroups.com> References: <1177510121.882503.145560@n15g2000prd.googlegroups.com> Message-ID: <4630892E.9050709@v.loewis.de> > The moment I close the application that launched the macro, my > ressources get freed. > > So is there a way to free my memory inside my nested loops? Yes. Most likely, it is your algorithm itself which is flawed (not Python, not the application that embeds Python): You keep, most likely, references to objects which you should release in order to be able to reuse the memory. Regards, Martin From anglozaxxon at gmail.com Thu Apr 5 10:57:35 2007 From: anglozaxxon at gmail.com (anglozaxxon at gmail.com) Date: 5 Apr 2007 07:57:35 -0700 Subject: "Plugin" architecture - how to do? Message-ID: <1175785055.668181.308140@b75g2000hsg.googlegroups.com> I'm making a program that consists of a main engine + plugins. Both are in Python. My question is, how do I go about importing arbitrary code and have it be able to use the engine's functions, classes, etc? First, here's how it's laid out on the filesystem: -mainstarterscript.py - -__init__.py -[whole bunch of files] - -__init__.py -main.py -[whole bunch of files] So you'd execute the whole thing with ./mainstarterscript.py, which imports engine. Engine initializes, then executes plugin somehow. Plugin needs to be able to call functions in engine, and vice versa. Although various IPC methods would probably work, I think there's gotta be an easier and more straightforward way to do it. I use execfile to execute the plugin's __init__.py script. I insert some globals from engine into it so that __init__ can use them. __init__.py also imports plugin/main.py, which uses functions the engine functions, and so must import __init__.py. The problem is, when main imports __init__, the inserted globals aren't there, so it dies. So I've tried to make some globals in __init__ that simply map them to the engine's globals. Here's roughly how: #plugin/__init__.py engine_globals = {} if __name__ == '__builtin__': #run via execfile global engine_globals engine_globals = globals() #I don't really want all the globals, but in my real code I go through them one by one else: #imported from one of the other scripts in plugin dir. pass import main #among other things # end __init__.py # plugins/main.py import __init__ __init__.engine_globals.['some_function'](args) #do other stuff #end main.py #engine/__init__.py def some_function(args): pass sys.argv.append('plugins') execfile('plugins/__init__.py') When main.py imports plungin/__init__, it reinitializes engine_globals to {}, of course. But I can't think of a way not to initialize it to something, thus overwriting the original, because it needs to be in the namespace.. Essentially, I want a global to not reset itself if it's already set. So how do I go about doing this? Am I on the right track? Should I be __import__'ing plugins instead of execfile'ing them? Thanks, Nick From yinglcs at gmail.com Fri Apr 6 14:05:09 2007 From: yinglcs at gmail.com (yinglcs at gmail.com) Date: 6 Apr 2007 11:05:09 -0700 Subject: HTML Parser in python Message-ID: <1175882709.295125.289820@y66g2000hsf.googlegroups.com> Hi, Is there a HTML parser (not xml) in python? I need a html parser which has the ability to handle mal-format html pages. Thank you. From gagsl-py2 at yahoo.com.ar Wed Apr 11 15:34:35 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 11 Apr 2007 16:34:35 -0300 Subject: is asynchat broken or just not intended to work like other dispatchers? [PATCH] References: Message-ID: En Wed, 11 Apr 2007 11:29:28 -0300, Martin Maney escribi?: > Simple asyncore application where I wanted to use an explicit map (1) > rather than the automagic default. Worked fine until I tried to use > asynchat to handle an interactive status and control connection (3) and > found it had no notion about using a non-default map. After convincing > myself that this must be a simple oversight in asynchat, I applied the > following patch to a local copy. Of course now I have to carry around > this hacked-up version of asynchat, which sort of defeats the > "batteries included" simplicity thing. :-( This is not a good place for reporting bugs - use http://sourceforge.net/bugs/?group_id=5470 -- Gabriel Genellina From tom at finland.com Sat Apr 14 11:19:34 2007 From: tom at finland.com (tom at finland.com) Date: Sat, 14 Apr 2007 15:19:34 GMT Subject: Simple integer comparison problem Message-ID: Hi! I ran in problem with simple exercise. I'm trying to get program to return grade when given points but no matter what, I always get F. def grader(): print "Insert points: " points = raw_input('> ') int(points) if points > 89 and points <= 100: return "A" elif points > 89 and points <= 89: return "B" elif points > 69 and points <= 79: return "C" elif points > 59 and points <= 69: return "D" else: return "F" grade = grader() print grade From paul at boddie.org.uk Tue Apr 10 12:14:20 2007 From: paul at boddie.org.uk (Paul Boddie) Date: 10 Apr 2007 09:14:20 -0700 Subject: tuples, index method, Python's design In-Reply-To: References: <1175867771.114540.61810@n76g2000hsh.googlegroups.com> <1175884427.779950.267220@y80g2000hsf.googlegroups.com> <1176210960.3430.20.camel@dot.uniqsys.com> <740c3aec0704100810g5f962e8eu614fbaedecf3608e@mail.gmail.com> Message-ID: <1176221660.353713.132430@d57g2000hsg.googlegroups.com> On 10 Apr, 17:44, Carsten Haese wrote: > > You have a point. Here is my revised solution: > > assert current_player in p > opponents = tuple(x for x in p if x is not current_player) > > The added advantage is that AssertionError is better than IndexError for > conveying that a severe program bug has occurred. Unless you're running python with the -O flag. So, instead of the "unpythonic"... i = p.index(current_player) opponents = p[:i] + p[i+1:] ...we now have... if current_player not in p: raise ValueError, current_player opponents = tuple(x for x in p if x is not current_player) Sure, p would probably be a list for a lot of games, and as I've noted previously, since you have to specify all of the elements at once to initialise the tuple, you should know where the player is. But this only applies to situations where you have control over the code needing to know the index *and* the code making the tuple in the first place. Paul From bearophileHUGS at lycos.com Wed Apr 11 01:36:07 2007 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 10 Apr 2007 22:36:07 -0700 Subject: Does python have the static function member like C++ In-Reply-To: <1176262482.839148.276940@d57g2000hsg.googlegroups.com> References: <1176260903.362329.59370@o5g2000hsb.googlegroups.com> <1176261542.704649.240350@n76g2000hsh.googlegroups.com> <1176262482.839148.276940@d57g2000hsg.googlegroups.com> Message-ID: <1176269767.244724.66190@o5g2000hsb.googlegroups.com> > Many thanks for you! > I've never heard of the "staticmethod" , that's great! Note that you don't need an empty __init__ : class AAA: counter = 0 @staticmethod def counter_increase(): AAA.counter += 1 print "couter now:", AAA.counter AAA.counter_increase() Bye, bearophile From nogradi at gmail.com Sun Apr 1 17:09:36 2007 From: nogradi at gmail.com (Daniel Nogradi) Date: Sun, 1 Apr 2007 23:09:36 +0200 Subject: ISO programming projects In-Reply-To: References: Message-ID: <5f56302b0704011409u2aacf718mcabd0b096990686d@mail.gmail.com> > I'm looking for a collection of useful programming projects, at > the "hobbyist" level. > > My online search did turn up a few collections (isolated projects > are less useful to me at the moment), but these projects are either > more difficult than what I'm looking for (e.g. code a C compiler) > or not terribly useful to the average person (e.g. a function that > efficiently computes the n-th Fibonacci number). > > Any pointers would be much appreciated. > > kj http://wiki.python.org/moin/CodingProjectIdeas From jstroud at mbi.ucla.edu Sun Apr 15 23:35:58 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Mon, 16 Apr 2007 03:35:58 GMT Subject: Getting started with python In-Reply-To: <7x4pnh6rqi.fsf@ruckus.brouhaha.com> References: <1176598011.463543.96990@q75g2000hsh.googlegroups.com> <1176608302.928513.274400@y5g2000hsa.googlegroups.com> <%LyUh.10121$YL5.5753@newssvr29.news.prodigy.net> <7x4pnh6rqi.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > Steve Holden writes: >> You'd be worth more if you'd used elif and omitted the continue >> statements, but for a first solution it's acceptable. >> >> For better readability I'd have used >> if i % 5 == 0 > > I think I'd be more concerned about getting rid of the i%15 test. > What if a few more words get added? > > def fizzbuzz(n): > words = ((3, 'Fizz'), (5, 'Buzz'), (7, 'Jazz'), (11, 'Pizzazz')) > r = ''.join(b for a,b in words if n%a == 0) > return r or str(n) > > for i in xrange(1,101): > print fizzbuzz(i) I think that this is somewhat of an over-interpretation of the specification. 1. This doesn't act according to the specification if you add, for example, (2, 'Zonk'). Now 30 gives 'ZonkFizzBuzz' and not 'FizzBuzz' according to the specification. 2. What if additional words don't necessarily follow the pattern you infer? Nothing in the specification disallows adding (30, 'Whammo'). So, I would keep my original explicit testing: def fizzbuzz(n): words = ((30, 'Whammo'), (15, 'FizzBuzz'), (5, 'Fizz'), (3, 'Buzz'), (2, 'Zonk')) for k,v in words: if not k % n: return v return n for i in xrange(1,101): print fizzbuzz(i) James From sjmachin at lexicon.net Fri Apr 6 20:46:35 2007 From: sjmachin at lexicon.net (John Machin) Date: 6 Apr 2007 17:46:35 -0700 Subject: Indentifying the LAST occurrence of an item in a list In-Reply-To: <1175901942.342121.304730@l77g2000hsb.googlegroups.com> References: <1175702329.330032.250750@w1g2000hsg.googlegroups.com> <1175723121.298681.56600@n76g2000hsh.googlegroups.com> <1175799330.683339.93400@e65g2000hsc.googlegroups.com> <1175819867.740913.96430@y80g2000hsf.googlegroups.com> <1175901942.342121.304730@l77g2000hsb.googlegroups.com> Message-ID: <1175906795.281545.160970@p77g2000hsh.googlegroups.com> On Apr 7, 9:25 am, "mkPyVS" wrote: > On Apr 5, 6:37 pm, "John Machin" wrote: > > >>> help(list.index) > > Help on method_descriptor: > > > index(...) > > L.index(value, [start, [stop]]) -> integer -- return first index > > of value > > > I look forward to your next version. > > Great point! I was assuming the temp variable space was static but the > pointer to the start of the list was moving-> shame on me (what > language is this now ;)! Indeed. IMHO every function/method that searches a sequence should have start/stop arguments so that the caller can search a slice without actually copying the slice. > > Couldn't resist the temptation to just collect all of the locations as > I traversed > > m = [2,9,1,5,6,3,1,1,9,2] > f = 1 #What we're looking for > location = 0 #Start at beginning of list > fIndexs = [] > while 1: > try: > location = m.index(f,location) + 1 > fIndexs.append(location-1) > except ValueError: > break > > print("Last location = %d" % fIndexs[-1]) 1. print is a statement, not a function. 2. fIndexs[-1] will crash and burn if there are no occurrences of f in m. > print("All Items = %s" % fIndexs) FWIW, here's my take on a function that emulates the "missing" rindex method: 8<--- start rindex.py --- def rindex(seq, value, lo=0, hi=None): """If there is an x such that seq[x] == value and lo <= x < hi return the largest such x, else raise ValueError""" seqlen = len(seq) if lo < 0: lo += seqlen if lo < 0: lo = 0 if hi is None: hi = seqlen elif hi < 0: hi += seqlen if hi < 0: hi = 0 lo = seq.index(value, lo, hi) while True: try: lo = seq.index(value, lo + 1, hi) except ValueError: return lo if __name__ == "__main__": import sys av = sys.argv print rindex(av[4:], av[1], int(av[2]), int(av[3])) 8<--- end rindex.py --- Cheers, John From steve at holdenweb.com Fri Apr 27 13:50:21 2007 From: steve at holdenweb.com (Steve Holden) Date: Fri, 27 Apr 2007 13:50:21 -0400 Subject: http pipelining In-Reply-To: References: Message-ID: swq22 at yahoo.com wrote: > Which python module is capable of pipelining http requests? > > (I know httplib can send mulitple requests per tcp connection, but in > a strictly serial way. ) > > There's nothing in the standard library, I believe, that includes both client and server functionality in the same module. So you would need to glue them together. If you want a simple net proxy server I seem to remember the chameleon system allows you to write one in about twelve lines. If it has to be HTTP-specific, with header parsing and the like, you might want to think about Twisted, which supports both client and server functionality and tries to make it easy to plumb things together in pipelines. regards Steve -- Steve Holden +1 571 484 6266 +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 kamil.kisiel at gmail.com Mon Apr 23 00:10:41 2007 From: kamil.kisiel at gmail.com (Kamil Kisiel) Date: 22 Apr 2007 21:10:41 -0700 Subject: Initial Release: latexmath2png Message-ID: <1177301440.943838.5200@p77g2000hsh.googlegroups.com> This past week I cleaned up and released some of my code for converting LaTeX math equations in to PNG images. The current concept is to have a useful unix-style command line utility as well as a module that can be embedded in to other applications such as wikis, CMSs, etc. I've released it under an MIT license. The concept is based on an article by Kjell Fauske: http://www.fauskes.net/nb/htmleqII/ and some old code I wrote as a result several years ago. Currently there is only support for rendering individual equations as in the $...$ math environment in LaTeX, but I will be adding support for the equation and equation array environments in the future. Project page on Google Code: http://code.google.com/p/latexmath2png/ Some more details in my blog post: http://kamilkisiel.blogspot.com/2007/04/presenting-latexmath2png.html Please give it a try as I'd like to hear how it works for others. I welcome any comments, patches, and requests. From Florian.Lindner at xgm.de Mon Apr 2 15:20:21 2007 From: Florian.Lindner at xgm.de (Florian Lindner) Date: Mon, 02 Apr 2007 21:20:21 +0200 Subject: RSS feed parser References: <1175531874.535702.212510@n76g2000hsh.googlegroups.com> Message-ID: irstas at gmail.com wrote: > On Apr 2, 7:22 pm, Florian Lindner wrote: >> Hello, >> I'm looking for python RSS feed parser library. >> Feedparserhttp://feedparser.org/does not seem to maintained anymore. >> >> What alternatives are recommendable? >> >> Thanks, >> >> Florian > > Well, even if it's not maintained anymore (where does it say that?), > it works fine and the API is great. Although of course I do realize > that when a new version of RSS appears, feedparser won't be able to > support it unless someone updates it. But RSS 2.0 appeared already in > 2002 and no new versions have come since. So I wouldn't worry too much > about new RSSs popping up every month. Maybe the feedparser code > hasn't been updated in a while because it's already perfect and > there's nothing to add to it?-) No postings neither on the mailinglists nor in the forums are being answered. Somewhere he stated that he had turned to another hobby. Some of the question I have but found answered nowhere: I have a feedparser object that was created from a string. How can I trigger a update (from a new string) but the feedparser should treat the new string like the same feed (thus setting feed.updated etc.). - How can I trigger a update from a new file? - Does feedparser has the desired behavior? Regards, Florian From maskdaemon at yahoo.com Wed Apr 4 16:56:26 2007 From: maskdaemon at yahoo.com (Sily Ady) Date: Wed, 4 Apr 2007 13:56:26 -0700 (PDT) Subject: Shutting down windows using win32api Message-ID: <637903.8497.qm@web90304.mail.mud.yahoo.com> --------------------------------- 8:00? 8:25? 8:40? Find a flick in no time with theYahoo! Search movie showtime shortcut. -------------- next part -------------- An HTML attachment was scrubbed... URL: From socyl at 987jk.com.invalid Sun Apr 1 11:34:17 2007 From: socyl at 987jk.com.invalid (kj) Date: Sun, 1 Apr 2007 15:34:17 +0000 (UTC) Subject: ISO programming projects Message-ID: I'm looking for a collection of useful programming projects, at the "hobbyist" level. My online search did turn up a few collections (isolated projects are less useful to me at the moment), but these projects are either more difficult than what I'm looking for (e.g. code a C compiler) or not terribly useful to the average person (e.g. a function that efficiently computes the n-th Fibonacci number). Any pointers would be much appreciated. kj -- NOTE: In my address everything before the first period is backwards; and the last period, and everything after it, should be discarded. From onemoverx at gmail.com Sat Apr 7 02:06:48 2007 From: onemoverx at gmail.com (=?ISO-8859-1?Q?Yusnel_Rojas_Garc=EDa?=) Date: Sat, 7 Apr 2007 02:06:48 -0400 Subject: text extractor Message-ID: <9f45496e0704062306s3047472fl8e656e6a3bad4e07@mail.gmail.com> Some one knows some python module for working with pdf files (extract text)? or any kind of document such as PostScript, doc, etc? thanks in advance -------------- next part -------------- An HTML attachment was scrubbed... URL: From jstroud at mbi.ucla.edu Thu Apr 12 20:31:28 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Thu, 12 Apr 2007 17:31:28 -0700 Subject: Question About Creating Lists In-Reply-To: References: <1176414392.977660.16610@o5g2000hsb.googlegroups.com> Message-ID: Scott wrote: >>Please forgo the psychological self analysis from your future posts. > > > Unfortunately I can't, that's how I am, love it or leave it. But if your > going to be condescending about it, please leave your future replies in your > outbox. Now don't take that as I don't appreciate your reply. I just don't > appreciate the tone of that statement. I wouldn't say something about your > pseudonym possibly making up for some personal deficiency only because it > wouldn't be right. Email etiquette is a beautiful thing. > > And I'm sorry if you didn't mean it that way, but that's the way it read. > > >>I don't think your question has anything to do with lists. Maybe this >>will help: there is a distinction between what are called "literals" >>and "variables". > > > My question was in fact about lists and their proper "syntax" (I'm guessing > that's the right word). Basically all I was asking was if I had the idea > down or not, which was meant to be implied when I wrote: Am I safe in > assuming.... > > Maybe I didn't write it the exact way to get the response I needed, and if > it read differently I'm sorry. But that's all I was asking. > > 7stud probably meant that you don't need to apologize for asking questions. The only stupid question is the one that goes unasked. Also, I'm guessing that his (or her?) name is a reference to a card game he (or she?) likes particularly. James From mik3l3374 at gmail.com Thu Apr 5 00:22:46 2007 From: mik3l3374 at gmail.com (mik3l3374 at gmail.com) Date: 4 Apr 2007 21:22:46 -0700 Subject: shelve error In-Reply-To: <1175746456.995618.186190@e65g2000hsc.googlegroups.com> References: <1175746456.995618.186190@e65g2000hsc.googlegroups.com> Message-ID: <1175746966.023613.178830@n76g2000hsh.googlegroups.com> On Apr 5, 12:14 pm, "7stud" wrote: > test1.py: > -------------------- > import shelve > > s = shelve.open("/Users/me/2testing/dir1/aaa.txt") > s['x'] = "red" > s.close() > --------output:------ > > $ python test1.py > Traceback (most recent call last): > File "test1.py", line 3, in ? > s = shelve.open("/Users/me/2testing/dir1/aaa.txt") > File "/System/Library/Frameworks/Python.framework/Versions/2.3/lib/ > python2.3/shelve.py", line 231, in open > return DbfilenameShelf(filename, flag, protocol, writeback, > binary) > File "/System/Library/Frameworks/Python.framework/Versions/2.3/lib/ > python2.3/shelve.py", line 212, in __init__ > Shelf.__init__(self, anydbm.open(filename, flag), protocol, > writeback, binary) > File "/System/Library/Frameworks/Python.framework/Versions/2.3/lib/ > python2.3/anydbm.py", line 80, in open > raise error, "db type could not be determined" > anydbm.error: db type could not be determined > Exception exceptions.AttributeError: "DbfilenameShelf instance has no > attribute 'writeback'" in ignored > --------------------- > > What should I do to correct that error? how did you generate aaa.txt? From hlubenow2 at gmx.net Sun Apr 1 19:30:38 2007 From: hlubenow2 at gmx.net (hlubenow) Date: Mon, 02 Apr 2007 01:30:38 +0200 Subject: How can i compare a string which is non null and empty References: <1175469766.979636.65020@e65g2000hsc.googlegroups.com> Message-ID: Plissken.s at gmail.com wrote: > > Hi, > > how can i compare a string which is non null and empty? > > > i look thru the string methods here, but cant find one which does it? > > http://docs.python.org/lib/string-methods.html#string-methods > > In java,I do this: > if (str != null) && (!str.equals("")) .... > > how can i do that in python? What about if str != "": pass ? From mail at microcorp.co.za Sat Apr 14 01:58:10 2007 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Sat, 14 Apr 2007 07:58:10 +0200 Subject: tuples, index method, Python's design References: <1175953520.316208.241490@o5g2000hsb.googlegroups.com><7xzm5igbrb.fsf@ruckus.brouhaha.com><1176200361.260546.280510@n76g2000hsh.googlegroups.com><740c3aec0704100824m132c45fbi5c4c3ec0c0fa3a67@mail.gmail.com> <1176388675.4220.46.camel@dot.uniqsys.com> Message-ID: <007601c77e59$e2510c60$03000080@hendrik> "Carsten Haese" wrote: 8<------------ > sense in its context. Nobody seems to be complaining about "+" behaving > "inconsistently" depending on whether you're adding numbers or > sequences. I would If I thought it would do some good - the plus sign as a joiner was, I think, a bad decision. Just write a routine to calculate the checksum of an Intel Hex file record to see what I mean. - Hendrik From mbm at mediamonger.ch Wed Apr 4 06:48:38 2007 From: mbm at mediamonger.ch (=?ISO-8859-1?Q?Ma=EBl_Benjamin_Mettler?=) Date: Wed, 04 Apr 2007 12:48:38 +0200 Subject: how to remove multiple occurrences of a string within a list? In-Reply-To: <1175678400.712810.145330@y66g2000hsf.googlegroups.com> References: <1175624433.206953.214290@n59g2000hsh.googlegroups.com> <1175678400.712810.145330@y66g2000hsf.googlegroups.com> Message-ID: <46138286.10905@mediamonger.ch> How about: list(frozenset(['0024', 'haha', '0024'])) mik3l3374 at gmail.com schrieb: > On Apr 4, 2:20 am, "bahoo" wrote: >> Hi, >> >> I have a list like ['0024', 'haha', '0024'] >> and as output I want ['haha'] >> >> If I >> myList.remove('0024') >> >> then only the first instance of '0024' is removed. >> >> It seems like regular expressions is the rescue, but I couldn't find >> the right tool. >> >> Thanks! >> bahoo > > how about this: >>>> target = "0024" >>>> l = ["0024", "haha", "0024", "0024", "sfs"] >>>> result = [ item for item in l if item != target] >>>> result > ['haha', 'sfs'] > From robert.kern at gmail.com Fri Apr 6 15:23:54 2007 From: robert.kern at gmail.com (Robert Kern) Date: Fri, 06 Apr 2007 14:23:54 -0500 Subject: Basic Serialization - a design decision question In-Reply-To: <5d2e4d280704060940s3fa1defdl874c8c4e7fa92266@mail.gmail.com> References: <5d2e4d280704060940s3fa1defdl874c8c4e7fa92266@mail.gmail.com> Message-ID: Gizmo wrote: > Hello > I am a relative newcomer to Python, and I am studying it to understand > its design. It intrigues me. > I recently studied Serialization of classes via the pickle/cPickle > library, and I have a question. > > Why is Serialization handled by a separate library (ie, pickle). Is it > possible, by design, to have serialization "internally" implemented via > an implicit ___serialize___ method? Ofcourse, you have to make this > method not overrideable (sp?). For example, the __repr__ method gives us > the string representation of a class... similarly, the __serialize__ > method would give us the "serial norm" representation of the class. > > This would allow me to do something like this, > conn.send(serial(myClass)); // or something like that? Serialization is a complicated task. It needs at least a full module devoted to it just in terms of being able to implement it. Trying to stuff all of it into a builtin is asking for trouble. Of course, you can always do this: from cPickle import dumps ... conn.send(dumps(myClass)) -- 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 steve at holdenweb.com Wed Apr 25 09:58:23 2007 From: steve at holdenweb.com (Steve Holden) Date: Wed, 25 Apr 2007 09:58:23 -0400 Subject: Socket exceptions aren't in the standard exception hierarchy In-Reply-To: References: Message-ID: John Nagle wrote: > Steve Holden wrote: >> John Nagle wrote: >> >>> Steve Holden wrote: >>> >>>> John Nagle wrote: >>>> [socket.error bug report] > >> All these notes should be included in the bug report, as I suspect the >> module would benefit from additional clarity. > > Done. See > > [ 1706815 ] socket.error exceptions not subclass of StandardError > > Also see > > [ 805194 ] Inappropriate error received using socket timeout > [ 1019808 ] wrong socket error returned > [ 1571878 ] Improvements to socket module exceptions > [ 708927 ] socket timeouts produce wrong errors in win32 > > for related but not identical problems in that area. > Thanks. At least this is less likely to be overlooked now. regards Steve -- Steve Holden +1 571 484 6266 +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 cginboston at hotmail.com Sun Apr 15 14:40:57 2007 From: cginboston at hotmail.com (Chaz Ginger) Date: Sun, 15 Apr 2007 18:40:57 GMT Subject: Authenticating clients and servers In-Reply-To: References: Message-ID: <462271B9.9090901@hotmail.com> Thomas Kr?ger wrote: > Chaz Ginger schrieb: >> I am writing a distributed server system using Python. I need to support >> authentication and was wondering what approaches are available under >> Python and what are the best practices. > > Well, there are many ways of client authentication. To narrow it down it > would be nice if your tell us something about the protocol you are > planning to use. > > Many protocols support an additional SSL/TLS-Layers (e.g. HTTP -> > HTTPS). There you can use SSL certificate authentication. It may > berequired to set up a small CA, but done right it is pretty secure. > > Thomas > I am leaning toward using Kerberos via GSS, but I am willing to listen to other ideas. I've played around with TLS but the problem is that updating the .PEM files can be a pain. I was also thinking about X509, and was wondering if anyone has experience with it. Chaz From bdesth.quelquechose at free.quelquepart.fr Wed Apr 11 15:00:57 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Wed, 11 Apr 2007 21:00:57 +0200 Subject: how to pickle objects for database storage? In-Reply-To: References: Message-ID: <461d2747$0$3630$426a74cc@news.free.fr> krishnakant Mane a ?crit : > hello, > I have a strange but very interesting requirement? > provided that a database can provide for an object data type like > binary large object (blob), can I store a pickeled python object in > it? Certainly, but that's one of the dumbest things to do IMHO. If you use a relational DBMS, you'd better use it properly (FWIW, there's a pretty good Python abstraction layer/ORM named SQLAlchemy). And if you don't want a RDBMS, then there are good Python OODBMS (Zope and Durus to name the most famous ones). My 2 cents... From C.delete_this.Sanders at BoM.GOv.AU Wed Apr 18 22:42:47 2007 From: C.delete_this.Sanders at BoM.GOv.AU (Charles Sanders) Date: Thu, 19 Apr 2007 12:42:47 +1000 Subject: Strange terminal behavior after quitting Tkinter application In-Reply-To: <1176887530.377648.115510@n59g2000hsh.googlegroups.com> References: <1176881604.574369.77230@b58g2000hsg.googlegroups.com> <1176887530.377648.115510@n59g2000hsh.googlegroups.com> Message-ID: <4626d728$0$75704$c30e37c6@lon-reader.news.telstra.net> Chris wrote: > > But does anyone know why the Tkinter program is doing this to the > terminal in the first place? I don't want to have to tell users of my > program that they must recover their terminal's sanity each time after > running my program. > I don't know about Tkinter, but my guess would be that it has to change the terminal settings to do what it does, and you are quitting without restoring the settings. Is there some Tkinter clean up that you have omitted ? Have you ensured that the clean up runs on both normal exit and abnormal exit (eg ^C) ? For example, the curses library (in C) requires an endwin() call before exit to restore settings. If this is omitted, a "stty sane" is needed to set the terminal to a semi-sensible default. On Unix and similar systems, signal handlers are normally installed to ensure (as far as possible) that the cleanup occurs if the process is killed. This also applies to vi and similar programs that take total control of the terminal. Charles From steve at holdenweb.com Sat Apr 7 06:59:57 2007 From: steve at holdenweb.com (Steve Holden) Date: Sat, 07 Apr 2007 06:59:57 -0400 Subject: Understanding Python's interpreter In-Reply-To: <20070407052239.38f9b21e.rafaelc@dcc.ufmg.br> References: <20070407032024.bb27f5ee.rafaelc@dcc.ufmg.br> <20070407052239.38f9b21e.rafaelc@dcc.ufmg.br> Message-ID: Rafael Almeida wrote: > On Sat, 07 Apr 2007 04:35:49 +0200 > Gabriel Genellina wrote: > >> Speed? Eficiency? File size? Ease of use? >> A .pyc *could* be written in ASCII, but what do you gain? Replacing a >> few trivial functions in the Python core with a printf/scanf equivalent? >> At the same time you lose a lot of speed, so I don't see the point. > > Hm, I didn't realise that it would be that much slower. You may mistakenly believe that casts are an expensive operation, when in fact they take no time at all - they merely instruct the compiler to treat specific pieces of data in specific ways. > >> Why harder? Once you read the file, they're just numbers. Anyway, being >> harder to program the *interpreter* is not a problem, if you gain >> something like speed or eficiency for the interpreted language. > > Well, it's harder to get 4 bytes and create an int out of it in a > portable way than just call strtol or scanf, that's what I thought > while I was coding my interpreter. It's not the hardest thing to do, > of course, but it made me wonder why not just do the simplest thing. > Because they aer smarter than you, without wishing to be too rude. > Since I've never seen a .pyc bigger than a few kilobytes, I thought an > ascii file would take more space, but it wouldn't be anything really > prohibitive. > > I didn't think using strtol would make that much difference in speed. > But now you talked about it, and after thinking a little bit more about > it, I'm convinced that the speed difference may be relevant. > Which is a good reason to think about things *before* you post. >>> And when I tried to code an assembler my problems got greater, as I >>> wanted to code it in python (the interpreter was in C++) and I had a >>> hard time trying to figure out how I would print something that's not a >>> ascii or unicode string. As for the benefits, I couldn't figure out any. >> Sorry, I could not understand what you said here. > > It's not anything important, I was just saying that I had to write a > little more code to make an integer such as 0xff into '\0\0\0\377' than > it would need to just print the integer. Well, unless there's already a > python function that does just that and I didn't know about. It's was > just an example on how writting in ascii is easier. Speed, baby, speed. 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 Thu Apr 5 02:44:10 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: 4 Apr 2007 23:44:10 -0700 Subject: shelve error In-Reply-To: <1175746966.023613.178830@n76g2000hsh.googlegroups.com> References: <1175746456.995618.186190@e65g2000hsc.googlegroups.com> <1175746966.023613.178830@n76g2000hsh.googlegroups.com> Message-ID: <1175755450.172949.13510@d57g2000hsg.googlegroups.com> mik3l3374 at gmail.com wrote: > On Apr 5, 12:14 pm, "7stud" wrote: > > test1.py: > > -------------------- > > import shelve > > > > s = shelve.open("/Users/me/2testing/dir1/aaa.txt") > > s['x'] = "red" > > s.close() > > --------output:------ > > > > $ python test1.py > > Traceback (most recent call last): > > File "test1.py", line 3, in ? > > s = shelve.open("/Users/me/2testing/dir1/aaa.txt") > > File "/System/Library/Frameworks/Python.framework/Versions/2.3/lib/ > > python2.3/shelve.py", line 231, in open > > return DbfilenameShelf(filename, flag, protocol, writeback, > > binary) > > File "/System/Library/Frameworks/Python.framework/Versions/2.3/lib/ > > python2.3/shelve.py", line 212, in __init__ > > Shelf.__init__(self, anydbm.open(filename, flag), protocol, > > writeback, binary) > > File "/System/Library/Frameworks/Python.framework/Versions/2.3/lib/ > > python2.3/anydbm.py", line 80, in open > > raise error, "db type could not be determined" > > anydbm.error: db type could not be determined > > Exception exceptions.AttributeError: "DbfilenameShelf instance has no > > attribute 'writeback'" in ignored > > --------------------- > > > > What should I do to correct that error? > > how did you generate aaa.txt? In a text editor, which I then saved to that directory. From robert.rawlins at thinkbluemedia.co.uk Fri Apr 13 09:14:06 2007 From: robert.rawlins at thinkbluemedia.co.uk (Robert Rawlins - Think Blue) Date: Fri, 13 Apr 2007 14:14:06 +0100 Subject: Arrays, Got Me Confused In-Reply-To: <461F7F7C.6080906@timgolden.me.uk> References: <000101c77dc3$d4152a00$7c3f7e00$@rawlins@thinkbluemedia.co.uk> <461F7712.2040201@timgolden.me.uk> <001c01c77dca$67232210$35696630$@rawlins@thinkbluemedia.co.uk> <461F7F7C.6080906@timgolden.me.uk> Message-ID: <001e01c77dcd$9e003590$da00a0b0$@rawlins@thinkbluemedia.co.uk> Thanks for that Tim and Steve, greatly appreciated. I know that the class method is just a wrapper and it seems a little silly, but it is partly for the exercise. I'm pretty well savvy with the OOP stuff but its something my business partner is yet to venture into, so by working like this it helps him understand the concepts. I also feel more at home if i can wrap this stuff up in nice user friendly methods that I can access universally throughout the application. I will have plenty of other class's and methods throughout the application that will call upon this firewall stuff, and being able to universally reference it as Firewall.addDevice() makes things more logical in my mind, I find trying to go back to a more procedural method pretty tricky now. Thanks again guys, Rob -----Original Message----- From: python-list-bounces+robert.rawlins=thinkbluemedia.co.uk at python.org [mailto:python-list-bounces+robert.rawlins=thinkbluemedia.co.uk at python.org] On Behalf Of Tim Golden Sent: 13 April 2007 14:03 Cc: python-list at python.org Subject: Re: Arrays, Got Me Confused Robert Rawlins - Think Blue wrote: > Hello Guys, > > Wider fragments of code don't really exists at this moment in time :-D this > is just a bit of a 'tester' class for me to get used to the methods. > Basically I'm trying to create a class that contains an array of MAC > address, these look something like this 'FD:E4:55:00:FG:A9. I want the class > to have the following methods for easy manipulation of the array. > > addDevice(Address) - Pass in the MAC address and have it add it to the > array. > > removeDevice(Address) - Finds a device with that address in the array and > removes it. > > isFirewalled(Address) - looks for that address in the array and returns > true/false dependant on whether it finds it. > > Clear() - empty the array of all its contents. OK, it's easy enough to do this, but you might find that you don't actually need to do too much of it yourself. Python has two central datastructures built in: lists and dictionaries. There are loads of tutorials around (and if you join the python-tutor list, the welcome message points you towards several) so I won't go into the details, but it looks like you want a dict here. You could wrap it in a class if you wanted, but the great thing about Python is that you don't have to. *Very* rough example code: macs = {} # create an empty dict incoming_mac = 'FD:E4:55:00:FG:A9' macs[incoming_mac] = True example_mac = 'a:b:c:d' if example_mac in macs: mac_is_firewalled = macs[example_mac] If you really wanted to go with a class (for the exercise or because of wider requirements) you could do something like this: class Firewalled: def __init__ (self): self.macs = {} def addDevice (address): self.macs[address] = True def removeDevice (address): del self.macs[address] def isFirewalled (address): return address in self.macs # or return self.macs.get (address, False) but as you can see, in this form you're just wrapping Python with Python. > Sorry for the sloppy code so far, I'm really new to Python so it's a steep > learning curve for me, I'm by no means a programming numpty and allot of the > principles are the same, but the languages I'm used to are more robust and > vague so I don't have to define what type of data i'm storing the array and > things. Ummm... in Python you don't have to define what type of data you're storing. Welcome to the language in any case: you'll find that people around here are generally quite friendly but if you want, you might try the tutor list where people are very used to dealing with newcomers: http://mail.python.org/mailman/listinfo/tutor TJG -- http://mail.python.org/mailman/listinfo/python-list From mangabasi at gmail.com Wed Apr 4 08:14:08 2007 From: mangabasi at gmail.com (Mangabasi) Date: 4 Apr 2007 05:14:08 -0700 Subject: Calling Fortran from Python In-Reply-To: References: <1175640339.648190.207530@y66g2000hsf.googlegroups.com> Message-ID: <1175688848.036423.142210@d57g2000hsg.googlegroups.com> There may be a way to finish this without having to deal with distutils. F2py created three files so far samplemodule.c fortranobject.h fortranobject.c Is there a way to create the sample.pyd from these files? From bdesth.quelquechose at free.quelquepart.fr Fri Apr 13 18:39:48 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sat, 14 Apr 2007 00:39:48 +0200 Subject: Python editor/IDE on Linux? In-Reply-To: References: <1176488840.672572.101830@y80g2000hsf.googlegroups.com> <461fe88c$0$6420$426a74cc@news.free.fr> Message-ID: <461ffd80$0$27924$426a74cc@news.free.fr> Greg Donald a ?crit : > On 4/13/07, Bruno Desthuilliers > wrote: > >> Except for real programmers... > > That's correct. We use: > > # dd if=/dev/tty of=/dev/hda1 > > and such. > Hear hear !-) From castironpi at gmail.com Sun Apr 29 16:24:44 2007 From: castironpi at gmail.com (castironpi at gmail.com) Date: 29 Apr 2007 13:24:44 -0700 Subject: Counting In-Reply-To: <1177873864.502180.283390@u30g2000hsc.googlegroups.com> References: <1177873864.502180.283390@u30g2000hsc.googlegroups.com> Message-ID: <1177878284.581953.77290@n59g2000hsh.googlegroups.com> On Apr 29, 2:11 pm, Andy wrote: > Hi, the file below will print all the keywords in a file and also the > line # of the keyword. What I couldn't figure out is to count those > keywords per line. For example - "Line #1 has 3 keywords" > > Can I do like - > > total[j] = total[j] + numwords(k) > "Line number %d has %d keywords" % (j, total[j]) > > Seems sort of "illegal" in Python? > > ------------------------------------------------- > import keyword, sys, string, fileinput > def numwords(s): > list = string.split(s) > return len(list) > > # Get the file name either from the command-line or the user > if len(sys.argv) != 2: > name = raw_input("Enter the file name: ") > else: > name = sys.argv[1] > > inp = open(name,"r") > linelist = inp.readlines() > total, words,lines = 0, 0, 0 > > for i in range(len(linelist)): > line = linelist[i] > tempwords = line.split() > for k in tempwords: > if keyword.iskeyword(k): > total = total + numwords(k) > j = i + 1 > print" The word * %s * belongs in line number: %d" % (k, > j) > > print "Total keywords in this file are: %d" %(total) > tempwords = line.split() > for k in tempwords: linec = 0 > if keyword.iskeyword(k): > total = total + numwords(k) > j = i + 1 linec += 1 > print" The word * %s * belongs in line number: %d" % (k, > j) print "%i characters in line" % linec And less readably, > tempwords = line.split() > for k in tempwords: linec = j > if keyword.iskeyword(k): > total = total + numwords(k) > j = i + 1 > print" The word * %s * belongs in line number: %d" % (k, > j) print "%i characters in line" % ( j - linec ) From __peter__ at web.de Sat Apr 7 12:41:16 2007 From: __peter__ at web.de (Peter Otten) Date: Sat, 07 Apr 2007 18:41:16 +0200 Subject: Saving output of Turtle Graphics? References: Message-ID: Dick Moores wrote: > OK, thanks, now I've got [an svg file] > What do I do to see this? You can convert it to a jpeg using ImageMagick's convert. Peter From gregpinero at gmail.com Mon Apr 9 01:31:40 2007 From: gregpinero at gmail.com (=?ISO-8859-1?Q?Gregory_Pi=F1ero?=) Date: Mon, 9 Apr 2007 01:31:40 -0400 Subject: Exec Statement Question Message-ID: <312cfe2b0704082231p53fe2605laf3cfef732eaff61@mail.gmail.com> I'm curious why this code isn't working how I expect it to: import sys d=3 def func1(a,b,c): print a,b,c,d print sys.path exec "func1(1,2,3)" in {'func1':func1} ---- returns: 1 2 3 3 [ sys.path stuff ....] Since I'm telling exec to operate only within the context of the dictionary I give it, why does it still see sys.path and d? I figured it would throw a NameError. Is there a way to call exec such that it won't have access to any more objects than I explicitly give it? Thanks, Greg From Ingo.Wolf at gmx.de Wed Apr 18 07:52:22 2007 From: Ingo.Wolf at gmx.de (iwl) Date: 18 Apr 2007 04:52:22 -0700 Subject: no trace of PyRun_SimpleString() ??? Message-ID: <1176897142.241720.221910@o5g2000hsb.googlegroups.com> Hi, it seems like I can't trace scripts run by PyRun_SimpleString(): a=0 def test(frame, event, arg): global a a+=1 import sys sys.settrace(test) print a print a print a -> 0 0 0 Does anybody know how I can get something similar with the C-Funcs for Tracing?? From __peter__ at web.de Thu Apr 19 03:11:28 2007 From: __peter__ at web.de (Peter Otten) Date: Thu, 19 Apr 2007 09:11:28 +0200 Subject: Text Suffix to Prefix Conversion References: <1176958038.116780.104660@n59g2000hsh.googlegroups.com> <1176964848.464918.89690@n59g2000hsh.googlegroups.com> Message-ID: 7stud wrote: > On Apr 18, 11:08 pm, Steven Bethard wrote: >> EMC ROY wrote: >> > Original Sentence: An apple for you. >> > Present: An apple for you .<.> >> > Desire: An apple for you <.>. >> >>> text = 'An apple for you .<.>' >> >>> import re >> >>> re.sub(r'(\S+)(<[^>]+>)(\s*)', r'\2\1\3', text) >> >> 'An apple for you <.>.' > > If you end up calling re.sub() repeatedly, e.g. for each line in your > file, then you should "compile" the regular expression so that python > doesn't have to recompile it for every call: > > import re > > text = 'An apple for you .<.>' > myR = re.compile(r'(\S+)(<[^>]+>)(\s*)', r'\2\1\3') re.compile() doesn't accept a replacement pattern: """ Help on function compile in module re: compile(pattern, flags=0) Compile a regular expression pattern, returning a pattern object. """ > re.sub(myR, r'\2\1\3', text) > > > Unfortunately, I must be doing something wrong because I can't get > that code to work. When I run it, I get the error: > > Traceback (most recent call last): > File "2pythontest.py", line 3, in ? > myR = re.compile(r'(\S+)(<[^>]+>)(\s*)', r'\2\1\3') > File "/Library/Frameworks/Python.framework/Versions/2.4/lib/ > python2.4/sre.py", line 180, in compile > return _compile(pattern, flags) > File "/Library/Frameworks/Python.framework/Versions/2.4/lib/ > python2.4/sre.py", line 225, in _compile > p = sre_compile.compile(pattern, flags) > File "/Library/Frameworks/Python.framework/Versions/2.4/lib/ > python2.4/sre_compile.py", line 496, in compile > p = sre_parse.parse(p, flags) > File "/Library/Frameworks/Python.framework/Versions/2.4/lib/ > python2.4/sre_parse.py", line 668, in parse > p = _parse_sub(source, pattern, 0) > File "/Library/Frameworks/Python.framework/Versions/2.4/lib/ > python2.4/sre_parse.py", line 308, in _parse_sub > itemsappend(_parse(source, state)) > File "/Library/Frameworks/Python.framework/Versions/2.4/lib/ > python2.4/sre_parse.py", line 396, in _parse > if state.flags & SRE_FLAG_VERBOSE: > TypeError: unsupported operand type(s) for &: 'str' and 'int' > > > Yet, these two examples work without error: > > ------ > import re > > text = 'An apple for you .<.>' > #myR = re.compile(r'(\S+)(<[^>]+>)(\s*)', r'\2\1\3') > print re.sub(r'(\S+)(<[^>]+>)(\s*)', r'\2\1\3', text) > > myR = re.compile(r'(hello)') > text = "hello world" > print re.sub(myR, r"\1XXX", text) > > ---------output: > An apple for you <.>. > helloXXX world > > > Can anyone help? You can precompile the regular expression like this: >>> text = 'An apple for you .<.>' >>> r = re.compile(r'(\S+)(<[^>]+>)(\s*)') >>> r.sub(r'\2\1\3', text) 'An apple for you <.>.' or even >>> sub = re.compile(r'(\S+)(<[^>]+>)(\s*)').sub >>> sub(r'\2\1\3', text) 'An apple for you <.>.' Note that this is not as much more efficient as you might think since re.sub() and the other re functions look up already compiled regexps in a cache. Peter From skip at pobox.com Mon Apr 16 10:12:21 2007 From: skip at pobox.com (skip at pobox.com) Date: Mon, 16 Apr 2007 09:12:21 -0500 Subject: Writing Log CSV (Efficiently) In-Reply-To: <6e42ec490704160700i20469453j6af39db62dd6b427@mail.gmail.com> References: <7554276584215132819@unknownmsgid> <6e42ec490704160700i20469453j6af39db62dd6b427@mail.gmail.com> Message-ID: <17955.33861.211843.361355@montanaro.dyndns.org> Dave> Python has built in logging support. It's pretty flexible as far Dave> as formatting output. I can get a bit complicated to set up, but Dave> it will handle traffic well. Really? I've found it to be a dog in heavy logging situations. Skip From R.Brodie at rl.ac.uk Wed Apr 25 12:59:32 2007 From: R.Brodie at rl.ac.uk (Richard Brodie) Date: Wed, 25 Apr 2007 17:59:32 +0100 Subject: q: how to output a unicode string? References: <596qd4F2k129kU1@mid.uni-berlin.de> <598prcF2ihs92U1@mid.uni-berlin.de> Message-ID: "Frank Stajano" wrote in message news:f0o0qs$918$1 at gemini.csx.cam.ac.uk... > I find the encode/decode terminology somewhat confusing, because arguably both sides are > "encoded". For example, a unicode-encoded string (I mean a sequence of unicode code > points) should count as "decoded" in the terminology of this framework, right? Yes. Unicode is the one true Universal Character Set, and everything else (including ASCII and UTF-8) is a mere encoding. Once you've got your head round that, things may make more sense. From mail at timgolden.me.uk Wed Apr 25 03:59:37 2007 From: mail at timgolden.me.uk (Tim Golden) Date: Wed, 25 Apr 2007 08:59:37 +0100 Subject: Tutorial creates confusion about slices In-Reply-To: References: Message-ID: <462F0A69.8000906@timgolden.me.uk> Antoon Pardon wrote: > On 2007-04-24, Michael Hoffman wrote: > >> Really only one person has argued that the docs do not need to be >> changed. The other two people seemed to think you were asking for help >> rather than discussing how to revise the docs. Understandable, since >> that's why most people come to this group in my estimation. >> >> Your time is your own and it is good to spend your efforts on what you >> think will be most fruitful. But if you are going to let the opposition >> of one person stop you from doing anything, you will not accomplish very >> much. > > sjdevnull at yahoo.com has brought a point that is worth considering. > So I retreat now a bit to see if I can come with a proposal that > bears in mind his point. Now that this thread has slowed a little I would also point out -- while agreeing with sjdevnull's thoughtful post -- that reaction to an idea on a mailing list is possibly not the best means of gauging its validity. That's not to say you shouldn't listen to other posters; rather that, if you still feel after due consideration of other people's points of view that what you're proposing is right, then go ahead and create a patch. The people who are going to accept or reject your doc patch are (probably) not the people who are putting forward their ideas here on this list. Ultimately, patches aren't voted in by the denizens of python-list / c.l.py. Also, there may be 1000 people nodding thoughtfully (and silently) in agreement with your point of view, but who are unlikely to post a "me, too" comment. It seems likely that any posters are more likely to be those in disagreement with a point of view. Frankly, if you think after consideration that a change to the docs is advisable, post up a patch to the relevant place. If there are people on this list who disagree, they're at liberty to comment on the patch. But at that point, you've made the effort and said your piece. It's up to the naysayers to make the effort to comment on the patch. And, ultimately, up to the Python development community to accept or reject it as they see fit. (And as they have the time and inclination :) TJG From tinaweb at bestemselv.com Thu Apr 26 03:09:44 2007 From: tinaweb at bestemselv.com (Tina I) Date: Thu, 26 Apr 2007 09:09:44 +0200 Subject: lowercase class names, eg., qtgui ? (PyQt4) In-Reply-To: References: Message-ID: <6smdnRrvLvilza3bRVnzvQA@telenor.com> Glen wrote: > Hello, > > In the file generated by pyuic4 from Designer's .ui file I noticed the use > of lower case class names (I'm assuming these are the names of classes, > not modules). For example: > > It imports thusly: > > from PyQt4 import QtGui > > then uses things like: > self.gridlayout = qtgui.qgridlayout(dldialog) > > What exactly is going on here? Are these instances that are defined > somewhere else (their not in the local scope.)? Can I do the same in my > code when I import something? > > Thanks, > > Glen > > Glen > Hi, Are you sure? That's strange. I have never seen that. Here is a snippet of one of my typical .py files generated by 'pyuic4': self.gridlayout = QtGui.QGridLayout(self.centralwidget) self.gridlayout.setMargin(9) self.gridlayout.setSpacing(6) self.gridlayout.setObjectName("gridlayout") self.hboxlayout = QtGui.QHBoxLayout() self.hboxlayout.setMargin(0) self.hboxlayout.setSpacing(6) self.hboxlayout.setObjectName("hboxlayout") self.hboxlayout1 = QtGui.QHBoxLayout() self.hboxlayout1.setMargin(0) self.hboxlayout1.setSpacing(6) self.hboxlayout1.setObjectName("hboxlayout1") Upper case all the way... Tina From samjnaa at gmail.com Sat Apr 14 09:28:13 2007 From: samjnaa at gmail.com (jamadagni) Date: 14 Apr 2007 06:28:13 -0700 Subject: Python Feature Request: Add the "using" keyword which works like "with" in Visual Basic In-Reply-To: References: <1176547372.584539.89170@q75g2000hsh.googlegroups.com> Message-ID: <1176557293.861585.290070@b75g2000hsg.googlegroups.com> On Apr 14, 5:06 pm, Duncan Booth wrote: > I can't see how it is going to save you any typing over what you can > already do. > > The suggested example: The suggested example is only a small case. I realize that the main usage would be when there are a lot of repetitive usages when the five characters "using", the space and the colon at the end would be worth the full typing. > (259 characters including newlines but not leading indents). > would become: > (251 characters including newlines but not leading indents). So there *is* gain even in this small case. It's a matter of avoiding the bore and potential scope for typos in repetitive typing. > If you are going to reference self.quit a lot of times then it makes > sense to also assign it to a local variable and then you already get > even fewer characters (239): But you realize readability decreases considerably. From gagsl-py2 at yahoo.com.ar Mon Apr 30 19:56:16 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 30 Apr 2007 20:56:16 -0300 Subject: regular expression problem References: <61fdaffc0704301516m4eb3c92fp8a73c1c155dc014e@mail.gmail.com> Message-ID: En Mon, 30 Apr 2007 19:16:58 -0300, John Davis escribi?: > Hi all, > I have a large logged string "str". I would like to strip down "str" so > that > it contains only the lines that have "ERROR" in them. Could somebody > give me > and indication of how to do this? Forget about regular expressions! This famous quote [1] is entirely applicable here. Also, str is not a good name, it hides the builtin type str. Using text as the variable name instead: error_lines = [line for line in text.split("\n") if "ERROR" in line] [1] http://regex.info/blog/2006-09-15/247 -- Gabriel Genellina From steve at holdenweb.com Fri Apr 20 05:02:52 2007 From: steve at holdenweb.com (Steve Holden) Date: Fri, 20 Apr 2007 05:02:52 -0400 Subject: Python un-plugging the Interpreter In-Reply-To: References: <005f01c782a3$ae84d710$fa936540@cisco.com> Message-ID: Marc 'BlackJack' Rintsch wrote: > In , John Nagle wrote: > >> Many cases are easy. If a smart compiler sees >> >> for i in range(n) : >> ... # something >> >> and there are no other assignments to "i", then it's clear that >> "i" can be represented as an integer, without "boxing" into a >> general object. > > How is it clear that `i` is restricted to integers? That works only if > you assume `range` refers to the built-in `range()` function. So the > smart compiler has to check all possible control flows up to this point > and be sure `range` was not bound to something different. > That is, of course, exactly what a smart compiler would do. Only nowadays it would quite possibly do it just-in-time (so I suppose you might call it the run-time, though the boundary is continually getting more blurred) rather than as the result of static analysis, so it would *know* that the built-in generator had been called. 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 carsten at uniqsys.com Tue Apr 10 13:38:02 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Tue, 10 Apr 2007 13:38:02 -0400 Subject: tuples, index method, Python's design In-Reply-To: <740c3aec0704101021i1fd79ef2l99eac4ced1e252d9@mail.gmail.com> References: <1175867771.114540.61810@n76g2000hsh.googlegroups.com> <1175884427.779950.267220@y80g2000hsf.googlegroups.com> <1176210960.3430.20.camel@dot.uniqsys.com> <740c3aec0704100810g5f962e8eu614fbaedecf3608e@mail.gmail.com> <1176219856.3430.76.camel@dot.uniqsys.com> <740c3aec0704101021i1fd79ef2l99eac4ced1e252d9@mail.gmail.com> Message-ID: <1176226682.3430.86.camel@dot.uniqsys.com> On Tue, 2007-04-10 at 19:21 +0200, BJ?rn Lindqvist wrote: > On 4/10/07, Carsten Haese wrote: > > > > opponents = tuple(x for x in p if x is not current_player) > > > > > > > Your alternative is wrong because it wont raise ValueError if > > > current_player is not present in the tuple. Please revise your > > > "solution." > > > > You have a point. Here is my revised solution: > > > > assert current_player in p > > opponents = tuple(x for x in p if x is not current_player) > > > > The added advantage is that AssertionError is better than IndexError for > > conveying that a severe program bug has occurred. > > Assertions are not checked when you run scripts with -O. Right. Which is why you use assert to guard against situations that should never happen, and you determine in unit tests that they, in fact, don't happen. Realistically, in a game loop such as while not game_has_ended: for current_player in p: player_does_something(current_player) it's obvious that the assertion "current_player in p" will never fail. > Furthermore, > changing the exception type and the message it produces, is quite a > big deviation from list.index. What's your point? I wasn't talking about coding a drop-in replacement for list.index. I was suggesting one possible solution to a problem that may or may not be solved by using tuple.index. -Carsten From rokkamraja at gmail.com Wed Apr 25 01:05:57 2007 From: rokkamraja at gmail.com (Raja) Date: 24 Apr 2007 22:05:57 -0700 Subject: override settrace Message-ID: <1177477557.493519.124620@u32g2000prd.googlegroups.com> Hi, I want to override the sys.settrace() call, create a way to trace the execution of a python program. Keep track of all objects created and destroyed. Keep track of the call pattern throughout the execution of the program and output a simplified "call graph" to standard out. Please help me in this regard. Thank You, From Martin.Drautzburg at web.de Mon Apr 23 02:35:42 2007 From: Martin.Drautzburg at web.de (Martin Drautzburg) Date: Mon, 23 Apr 2007 08:35:42 +0200 Subject: serializable object references References: <1242622.P0zHLAfcMH@beaureve.gmx.net> <25065059.0D4t2YsirZ@beaureve.gmx.net> Message-ID: <2082235.4RuV3RCOoU@beaureve.gmx.net> Gabriel Genellina wrote: > En Sun, 22 Apr 2007 12:47:10 -0300, Martin Drautzburg > escribi?: > >> I was thinking that it would be nice if a web application could talk >> to real objects. The client side does not need to know the internals >> of an object, it acts as a "view" for server-side models. All it has >> to be able to do is invoke methods on "its" model. So a view could >> just store "its" object-reference in an instance variable and pass it >> to the server, where my problem of looking it up comes in. > > This is more or less what several web frameworks do. You publish > objects; URLs are mapped to method objects; URL parameters become > method parameters. See http://wiki.python.org/moin/WebFrameworks > Okay will look. I have checked out cherrypy, but it does not seem to support direct object references, i.e. the server-side objects are really stateless and all calls to an object method will see the same state unless you do something about it youself. I have also looked at the wonderful qooxdoo javascript framework and in the examples they have, the data I receive on a published object method on my cherrypy server is: dict: { '_ScriptTransport_id': '11', '_ScriptTransport_data': '{ "service":"qooxdoo.test", "method":"sleep", "id":13, "params":["10"], "server_data":null }', 'nocache': '1177256001914' } I am not sure what all of them mean, but my impression is that none of them denote an object in the sense of an INSTANCE, at least "service" and "method" definitely do not. The "id" is simply incremented with every call, so it is again not an instance. Now I could of course add an object reference do the "params" field and have qooxdoo.text dispatch the call to an INSTANCE of an object and invoke sleep() there. But first it is a shame, that I have to provide this magic myself, and second it raises again my original question: how to I pass an object reference and look up the object in qooxdoo.test. I know I can do this with a dictionary, I just thought that the __repr__() of an object could be used, as it seems the most obvious way to do it. From apardon at forel.vub.ac.be Fri Apr 27 03:10:08 2007 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 27 Apr 2007 07:10:08 GMT Subject: Feedback on Until recipe References: <1177430903.027128.86480@o40g2000prh.googlegroups.com> <1177626620.704830.223220@t39g2000prd.googlegroups.com> Message-ID: On 2007-04-26, MRAB wrote: > At http://mail.python.org/pipermail/python-dev/2006-February/060718.html > Raymond Hettinger suggested removing the final colon after the 'while' > if there's no statement after it, which I agree with, although I would > prefer 'repeat' instead of 'do' (IMHO that doesn't suggest repetition > clearly enough): > > repeat: > statements > while condition: > statements > > and: > > repeat: > statements > while condition I wouldn't object to this. But more important than how it will look like IMO is that it gets implemented. Acoording to your URL there is little chance that this will be implemented before Py3k. A pity. -- Antoon Pardon From mail at microcorp.co.za Tue Apr 10 02:31:47 2007 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Tue, 10 Apr 2007 08:31:47 +0200 Subject: Database in memory References: <1176124752.172926.129850@w1g2000hsg.googlegroups.com> Message-ID: <012d01c77b3c$0936f7c0$03000080@hendrik> "Jeremy Sanders" ...emy+comp...python at jer...rs.net > wrote: > Dictionaries are one of the most useful things in Python. Make sure you know > how to take adavantage of them... +1 for QOTW - Hendrik From ecir.hana at gmail.com Sun Apr 15 13:24:08 2007 From: ecir.hana at gmail.com (ecir.hana at gmail.com) Date: 15 Apr 2007 10:24:08 -0700 Subject: yield, curry, mix-in, new.function, global, closure, .... what will work? Message-ID: <1176657848.944538.169780@p77g2000hsh.googlegroups.com> Dear list, maybe I'm overlooking something obvious or this is not possible at all or I don't know. Please, consider the following code: ## insert here anything you like def changer(): change_i('changed_i') change_j('changed_j') def run(i='', j=''): ## insert here anything you like return i, j run() == 'changed_i', 'changed_j' Let me explain: First, changer() is kind of templating language so it should be written down in this form - however, it can change during run-time as you like. Basically, it is just ordinary python code which changes (should change) the local variables of another function, run(). Oh, and it has to be *thread-safe*. Here's what I tried and didn't work (maybe I just haven't tried hard enough): - pass i, j around: changer(i, j) and change_i(i, arg) - easiest, most obvious solution - can't do it, certainly not during writing of the code - have to preserve changer()'s form - global variable - not thread-safe - in run(), create dummy closure for changer() and call it - new.function(blah, blah, blah, dummy.func_closure) - not thread safe, i guess, and besides change_i() and change_j() would also need a such a trick - I am not sure how to alter the codeobject of changer() - new.function(new.code(... - oh my, this won't work - in run(), modify change_i() and change_j() so it actually yield-s the changes, collect them here - something like: change_i.__call__ = return yield ('changed_i', 'comes_from_changer_i()') - doesn't work, of course - update locals() - yes!! - no!! - doen't work, it's just a copy - curry, mix-in, ... - hmm.... - eval(blah, blah, locals()) - not safe, ugly - maybe? what do you think? - find out which file changer() is written in, which line it starts and ends, read that file's section, parse, edit, append the needed local variable's declarations, compile to changer_new() and changer = changer_new - there has to be something better! :) So, to wrap up, the question is: how can I pass a variable from one function to another, without writing down function's argument during coding, and still be thread-safe? I can only hope you are still with me and not very confused.... Thanks for any feedback!! From g.brandl at gmx.net Mon Apr 9 03:41:48 2007 From: g.brandl at gmx.net (Georg Brandl) Date: Mon, 09 Apr 2007 09:41:48 +0200 Subject: tuples, index method, Python's design In-Reply-To: <7xd52e8kgo.fsf@ruckus.brouhaha.com> References: <1175867771.114540.61810@n76g2000hsh.googlegroups.com> <1175884427.779950.267220@y80g2000hsf.googlegroups.com> <1175953520.316208.241490@o5g2000hsb.googlegroups.com> <7xzm5igbrb.fsf@ruckus.brouhaha.com> <7x8xd2iq53.fsf@ruckus.brouhaha.com> <7xd52e8kgo.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin schrieb: > Carsten Haese writes: >> Will tuples also get a sort method? What about append and extend? pop? >> __iadd__? __delslice__? > > They are immutable so they won't get .sort() etc. sorted(...) already > works on them. > >> How many brain cells are actually freed up by not having to remember >> that *one* method that you'd never use doesn't exist? > > I dunno but I do know that Ruby is attracting a lot of potential Python > users because it apparently has fewer of these inconsistencies. It remains to be proven that it is an inconsistency, rather than a design decision. > A big > web site I hang out on decided to do a software rewrite (currently using > a huge perl script) and evaluated a bunch of possible approaches. In > the final decision, Ruby/Rails won out over Python/Django. Given that so many web sites still decide to (re)write in PHP, I don't think that is much of an argument. Georg From linusno at gmail.com Thu Apr 12 12:53:51 2007 From: linusno at gmail.com (=?ISO-8859-1?Q?Linus_Nordstr=F6m?=) Date: Thu, 12 Apr 2007 18:53:51 +0200 Subject: bittorent In-Reply-To: <461D16B7.9090407@ncee.net> References: <1eb3a0e10704110922v17f83f79se5972dce07415a5@mail.gmail.com> <461D110F.8080908@rpath.com> <461D16B7.9090407@ncee.net> Message-ID: <1eb3a0e10704120953r12adc873vfcb10a563de394e7@mail.gmail.com> On 4/11/07, Shane Geiger wrote: > > > Jonathan Smith wrote: > > Linus Nordstr?m wrote: > > > >> Hello > >> Im planing playing a bit whit bittorrent, but I'm having some trouble > >> about where to start. So if anyone could point me in the right > >> direction it would be much appreciated. > >> The best would be if there are some already written modules that > >> handle downloading and seeding torrents, but if that cant be found a > >> good source on how one dose to build some sort of bitorrent client > >> would be nice. > >> > >> thanks in advance > >> > > > > you might start with bittorrent itself [1] - it is written in python. > > > > [1]: http://www.bittorrent.com/download > > > > -smithj > > > > Snakebite is written entirely in Python. This sounds like exactly what > you need. > I might have been a bit unclear on what i was looking for, im not looking for a finished bitorrent client, but rather module that can parse a .torrent file, or info on how i would goabout to write something that can do that. From jeba.ride at gmail.com Wed Apr 18 09:11:41 2007 From: jeba.ride at gmail.com (Clement) Date: 18 Apr 2007 06:11:41 -0700 Subject: Help on Shelve.... In-Reply-To: References: <1176810739.765433.47470@n59g2000hsh.googlegroups.com> Message-ID: <1176901901.908541.105870@e65g2000hsc.googlegroups.com> On Apr 17, 5:52 pm, Michael Bentley wrote: > On Apr 17, 2007, at 6:52 AM, Clement wrote: > > > Can i useShelvefor storing large amount of data around 6GB.. Is it > > stable...? if any problems come, can i retrive the document.. > > Do you know for sure your filesystem handles files that big? I am using NTFS that can hold more that 500GB of data From martin at v.loewis.de Thu Apr 12 14:38:19 2007 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Thu, 12 Apr 2007 20:38:19 +0200 Subject: odd unicode error In-Reply-To: References: Message-ID: <461E7C9B.20505@v.loewis.de> > path += '/' + b > UnicodeDecodeError: 'ascii' codec can't decode byte 0xd0 in position 1: > ordinal not in range(128) > > Any ideas? path is a Unicode string, b is a byte string and contains the byte \xd0. The problem is that you have a directory with file names in it that cannot be converted to Unicode strings, using the file system encoding. If you can't fix the file system, you have to make search_path a byte string. Regards, Martin From claird at lairds.us Thu Apr 26 10:53:05 2007 From: claird at lairds.us (Cameron Laird) Date: Thu, 26 Apr 2007 14:53:05 +0000 Subject: Store variable name in another variable References: <1177592072.498517.139260@b40g2000prd.googlegroups.com> Message-ID: In article , Laurent Pointal wrote: >loial a ?crit : >> I need to store a list of variable names in a dictionary or list. I >> then later need to retrieve the names of the variables and get the >> values from the named variables. The named variables will already have >> been created and given a value. > >"Named variables will already have been created"... in what namespace ? > >Store a list of names -> dict/list (see tutorial) > >Then, >use namespace.name >or getattr(namespace,"name") >or locals()["name"] >or globals()["name"] > > admin, I want to be sure you understand the advice you've been given. Yes, it is possible to "double dereference" through named variables; HOWEVER, it is essentially *never* advantageous to do so in application programming with Python (nor is it in Perl and PHP, despite what many senior people there teach). Use a dictionary, perhaps one with multi-dimensional keys. From basilisk96 at gmail.com Sat Apr 7 01:04:30 2007 From: basilisk96 at gmail.com (Basilisk96) Date: 6 Apr 2007 22:04:30 -0700 Subject: Extract zip file from email attachment In-Reply-To: <1175869873.747758.278050@b75g2000hsg.googlegroups.com> References: <1175815907.434721.274190@w1g2000hsg.googlegroups.com> <65fge4-j15.ln1@athlon.my> <1175821421.265541.120440@w1g2000hsg.googlegroups.com> <1175835107.288163.139050@b75g2000hsg.googlegroups.com> <1175869873.747758.278050@b75g2000hsg.googlegroups.com> Message-ID: <1175922270.358349.64630@b75g2000hsg.googlegroups.com> > > Could the file like object still be encoded in MIME or something? > Yes it is. You don't need to seek(0). Try this: decoded = email.base64mime.decode(part.get_payload()) fileObj.write(decoded) -Basilisk96 From oliver at obeattie.com Tue Apr 3 09:27:24 2007 From: oliver at obeattie.com (oliver at obeattie.com) Date: 3 Apr 2007 06:27:24 -0700 Subject: raw_input just continues anyway? Message-ID: <1175606844.249364.290060@o5g2000hsb.googlegroups.com> Hey Everyone, This is probably going to sound like a bit of a stupid question - but why does (in the following code) the script just continue to run past the raw_input, when the user hasn't entered anything? if __name__ == "__main__": bucket_name = raw_input('Name of the bucket you wish the files to be placed into? ') update_s3() Basically, it just asks the question and continues anyway? Many Thanks, Oliver From sjmachin at lexicon.net Sun Apr 22 03:44:55 2007 From: sjmachin at lexicon.net (John Machin) Date: 22 Apr 2007 00:44:55 -0700 Subject: Give me the google group address in Chinese. In-Reply-To: <1177208197.176088.121800@q75g2000hsh.googlegroups.com> References: <1177208197.176088.121800@q75g2000hsh.googlegroups.com> Message-ID: <1177227895.062577.321490@n59g2000hsh.googlegroups.com> On Apr 22, 12:16 pm, ?? wrote: > It's really annoying to find there are all English language posts here > because I wanna talk about something about the Chinese related > programs. > > Could you give me some ? http://python.cn/ -- (CPUG) Chinese Python Users' Group There is a mailing list; see http://python.cn/mailman/listinfo/python-chinese HTH, John From g.brandl at gmx.net Sat Apr 14 16:46:33 2007 From: g.brandl at gmx.net (Georg Brandl) Date: Sat, 14 Apr 2007 22:46:33 +0200 Subject: Python Feature Request: Add the "using" keyword which works like "with" in Visual Basic In-Reply-To: <740c3aec0704141049n7ad0b988m69f739c91a573493@mail.gmail.com> References: <1176547372.584539.89170@q75g2000hsh.googlegroups.com> <1176560672.108264.44890@p77g2000hsh.googlegroups.com> <740c3aec0704141046x7bcb2ac0qb924a04440633124@mail.gmail.com> <740c3aec0704141049n7ad0b988m69f739c91a573493@mail.gmail.com> Message-ID: BJ?rn Lindqvist schrieb: > On 4/14/07, BJ?rn Lindqvist wrote: >> On 14 Apr 2007 07:24:32 -0700, jamadagni wrote: >> > > You already can emulate the using statement like this: >> > >> > You can emulate only assignments like this. How would you emulate >> > function calls, like the ones in my example? >> >> You can't, of course. But using the with statement: >> >> using self.q: >> .doit() >> >> becomes: >> >> with self.quit as q: >> q.doit() > > Er.. I guess there are some details you need to work out for that. But > in principle, it works fine. No, it does not. The "q" here is *not* assigned to self.quit, but to the result of self.quit.__enter__(). Georg -- Thus spake the Lord: Thou shalt indent with four spaces. No more, no less. Four shall be the number of spaces thou shalt indent, and the number of thy indenting shall be four. Eight shalt thou not indent, nor either indent thou two, excepting that thou then proceed to four. Tabs are right out. From fdemmer at gmail.com Wed Apr 18 08:20:57 2007 From: fdemmer at gmail.com (Florian Demmer) Date: 18 Apr 2007 05:20:57 -0700 Subject: 2.5 from source install problem with extensions In-Reply-To: <1176892612.378898.34580@e65g2000hsc.googlegroups.com> References: <1176892612.378898.34580@e65g2000hsc.googlegroups.com> Message-ID: <1176898857.656696.221690@p77g2000hsh.googlegroups.com> On Apr 18, 12:36 pm, Florian Demmer wrote: > Hi! > > I am doing a from source installation of Python 2.5 on some old Debian > machine. As the target directoy I want /opt/somename so i added it to > the configure like so: > > ./configure --prefix=/opt/somedir > > The following make works fine as far as I can see. Then the make > install also actually works and installs python in /opt/somedir with > all its subdirectoris (bin, lib, man, include). > The extensions (*.so) however get put in /usr/local/lib/... and there > also in the wrong python directoy: 2.4 ...and the current /usr/bin/python symlink points to the 2.4 installation (from .deb) > This is a c/p of the make install output: > [...] > running build_scripts > running install_lib > changing mode of /usr/local/lib/python2.4/site-packages/_struct.so to > 755 > changing mode of /usr/local/lib/python2.4/site-packages/_ctypes.so to > 755 > [...] > > (How) can I change the install_dir for the extensions? > Why does it use python2.4 anyway?! What env var or else is set here > that I cannot find? > > thanks! From grante at visi.com Mon Apr 23 14:57:29 2007 From: grante at visi.com (Grant Edwards) Date: Mon, 23 Apr 2007 18:57:29 -0000 Subject: Generate report containing pdf or ps figures? References: <132pnp6r4qg0lc2@corp.supernews.com> <1177350202.388337.131110@d57g2000hsg.googlegroups.com> Message-ID: <132q0cpkpgt0ud1@corp.supernews.com> On 2007-04-23, Kjell Magne Fauske wrote: >> Is there a PDF generation library that can place EPS or PDF >> figures on a page? > > If you are familiar with LaTeX, an easy solution would be to > automatically generate a LaTeX document that includes your > images. Yea, I've been using TeX and LaTeX for 20+ years. :) I worked on a DoD project back in the 80's where we generated a 1000+ page requirements spec using LaTeX. It had to be broken up into a few dozen separate documents because LaTeX under VAX/VMS kept overflowing various internal counters. Doing a build of the document kept a VAX 780 busy most of the night. However, bundling a working copy of LaTeX with my Python app doesn't fall into the "easy" category. This app needs to be moderately cross-platform and "distributable". Using either LaTeX or Ghostscript (my current solution) makes it rather painful to bundle up the app and distrubute it. -- Grant Edwards grante Yow! The Korean War must at have been fun. visi.com From half.italian at gmail.com Mon Apr 23 15:14:07 2007 From: half.italian at gmail.com (half.italian at gmail.com) Date: 23 Apr 2007 12:14:07 -0700 Subject: Generate report containing pdf or ps figures? In-Reply-To: <132pnp6r4qg0lc2@corp.supernews.com> References: <132pnp6r4qg0lc2@corp.supernews.com> Message-ID: <1177355647.569658.69580@b58g2000hsg.googlegroups.com> On Apr 23, 9:30 am, Grant Edwards wrote: > I need to be able to generate a PDF report which consists > mostly of vector images (which I can generate as encapsulated > Postscript, PDF, or SVG). What I need is a way to combine > these figures into a single PDF document. Right now the > reports consist entire of these figures, so I just write the > figures out to temp files and then use os.system() to run > ghostscript with appropriate options to combine them into a > single PDF file. > > I'd like to be able to add some text and/or place the figures > in a manner other than one per page in the output document. > > I've looked at ReportLab's documentation, but although it > appears to be able to use bitmap images (e.g jpeg) it doesn't > appear to be able to use vector images (EPS/PDF/SVG). > > Is there a PDF generation library that can place EPS or > PDF figures on a page? > > -- > Grant Edwards grante Yow! Is a tattoo real, like > at a curb or a battleship? > visi.com Or are we suffering in > Safeway? On a Mac... http://developer.apple.com/graphicsimaging/pythonandquartz.html ~Sean From spe.stani.be at gmail.com Sat Apr 28 02:05:43 2007 From: spe.stani.be at gmail.com (SPE - Stani's Python Editor) Date: 27 Apr 2007 23:05:43 -0700 Subject: SPE In-Reply-To: <1177614402.334319.72830@n35g2000prd.googlegroups.com> References: <1177602331.523239.54930@b40g2000prd.googlegroups.com> <1177614402.334319.72830@n35g2000prd.googlegroups.com> Message-ID: <1177740343.546435.229370@o5g2000hsb.googlegroups.com> On Apr 26, 9:06 pm, Glich wrote: > After posting this message I realized the stupid mistake I had made! > But it was too late to change! I think patching it with py2exe would > be a good idea. > > Greetings also, > Glich Yes, it would. Please subscribe to the spe-dev list and I'll guide you there. There is done some work already which might be useful. Probably a new version of SPE will come out in May but is now already available in subversion. http://pythonide.blogspot.com/2007/02/how-to-download-latest-spe-from_26.html Stani -- http://pythonide.stani.be From mark.dufour at gmail.com Mon Apr 2 02:52:01 2007 From: mark.dufour at gmail.com (mark.dufour at gmail.com) Date: 1 Apr 2007 23:52:01 -0700 Subject: Shed Skin Python-to-C++ Compiler 0.0.21, Help needed In-Reply-To: <1175455529.936887.249170@e65g2000hsc.googlegroups.com> References: <576vhbF2ca1guU1@mid.individual.net> <1175376373.241744.6220@y80g2000hsf.googlegroups.com> <1175413310.295953.230840@e65g2000hsc.googlegroups.com> <1175455529.936887.249170@e65g2000hsc.googlegroups.com> Message-ID: <1175496721.899984.193690@n76g2000hsh.googlegroups.com> > You still dream of this, isn't it? Type inference in dynamic languages > doesn't scale. It didn't scale in twenty years of research on > SmallTalk and it doesn't in Python. However there is no no-go theorem type inference sure is difficult business, and I won't deny there are scalability issues, but the situation has improved a lot since back in the smalltalk days. since then, type inference theory has not stood still: agesen' cartesian product algorithm and plevyak's iterative flow analysis (both published around '96) have greatly improved the situation; a 1000-fold or more increase in computer speeds have additionally made actual type inference (experimentation) much more practical. (for anyone interested in the techniques powering shed skin, see agesen and plevyak's phd theses for a relatively recent update on the field.) but in any case, I believe there are several reasons why type inference scalability is actually not _that_ important (as long as it works and doesn't take infinite time): -I don't think we want to do type inference on large Python programs. this is indeed asking for problems, and it is not such a bad approach to only compile critical parts of programs (why would we want to compile PyQt code, for example.) I do think type inference scales well enough to analyze arbitrary programs of up to, say, 5,000 lines. I'm not there yet with Shed Skin, but I don't think it's that far away (of course I'll need to prove this now :-)) -type inference can be assisted by profiling (so dramatically less iterations are necessary to come to a full proof). profiling doesn't have to fully cover code, because type inference fills in the gaps; type inference can also be assisted by storing and reusing analysis results, so profiling only has to be done once, or the analysis can be made easier by running it multiple times during development. because Shed Skin doesn't use profiling or memorization, and I know many things to improve the type analysis scalability, I'm confident it can scale much further than the programs it works for now (see ss- progs.tgz from the homepage for a collection of 27 programs, such as ray tracers, chess engines, sat solvers, sudoku solvers, pystone and richards..). besides, (as john points out I think), there is a difference between analyzing an actual dynamic language and a essentially static language (such as the Python subset that Shed Skin accepts). it allows one to make certain assumptions that make type inference easier. > that prevents ambitious newbies to type theory wasting their time and > efforts. yes, it's probably a waste of time to try and analyze large, actually dynamic, Python programs, but I don't think we should want this at all. computer speeds make Python fast enough for many purposes, and global type inference scalability would demand us to throw out many nice Python features. a JIT compiler seems better here.. where I think Shed Skin and similar tools can shine is in compiling pure Python extensions modules and relatively small programs. having worked on type inference for some time now, with modern techniques :), I see no reason why we can't compile statically typed Python programs, up to several thousands of lines. my analysis works pretty well already (see ss-progs.tgz), and there are many things I can still improve, besides adding profiling and memorization.. > Read the related PEP, John. You will see that Guidos genius is that of > a good project manager in that case who knows that the community works > for him. The trade is that he supplies the syntax/interface and the > hackers around him fantasize about semantics and start > implementations. Not only annotations are optional but also their > meaning. This has nothing to do with VB and it has not even much to do > with what existed before in language design. I think it's more Pythonic to just profile a program to learn about actual types.. mark dufour (Shed Skin author). From steve at holdenweb.com Thu Apr 19 07:48:12 2007 From: steve at holdenweb.com (Steve Holden) Date: Thu, 19 Apr 2007 07:48:12 -0400 Subject: Do other Python GUI toolkits require this? In-Reply-To: <465B30B4-5BA0-459A-BE6F-1038874FA74B@jedimindworks.com> References: <462697A6.6010007@codebykevin.com> <465B30B4-5BA0-459A-BE6F-1038874FA74B@jedimindworks.com> Message-ID: Michael Bentley wrote: > On Apr 19, 2007, at 4:11 AM, Antoon Pardon wrote: > >> On 2007-04-19, Michael Bentley wrote: [...] The >>> learning curve is rather steep IMO, but worth it. >> Just a throw in remark, that you may ignore if you wish, but a steep >> learning curve means that the subject is easily familiarized and that >> the learning period is short. >> >> You seem to use it as if it is the opposite. > > Mathematical absurdities aside, it's the common usage -- but perhaps > you knew that. > > Perhaps in Belgium they prefer climbing mountains over walking up and down gentle hills? Or possibly they will simply pick any nit that is carelessly left within range? http://home.earthlink.net/~macrakis/Snail_Stew_Recipe.html Don't forget the salt, Antoon! 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 psdasilvaX at esotericaX.ptX Thu Apr 12 12:20:52 2007 From: psdasilvaX at esotericaX.ptX (Paulo da Silva) Date: Thu, 12 Apr 2007 17:20:52 +0100 Subject: "Cloning" file attributes and permissions Message-ID: <1176394818.428367@jubilee.claranet.pt> Hi! I need to process a file to produce another file that *must* have *exactly* the same attributes and permissions of the former. What is the best way to do this? The file must not exist with contents (it may exist empty) unless it has the same attributes and permissions. I know how to do this using, let me call it, "C type code" (stat, chmod, chown, etc). I would like to hear some opinions on if and how it would be possible in a more elegant/python way. Thanks. Paulo From bearophileHUGS at lycos.com Mon Apr 2 10:21:48 2007 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 2 Apr 2007 07:21:48 -0700 Subject: Sorting a multidimensional array by multiple keys In-Reply-To: <4vydnSCXtPBrkIzbnZ2dnUVZ_szinZ2d@comcast.com> References: <1hvww1d.1k8ozo312a7yazN%aleax@mac.com> <4vydnSCXtPBrkIzbnZ2dnUVZ_szinZ2d@comcast.com> Message-ID: <1175523708.287686.16690@q75g2000hsh.googlegroups.com> Steven Bethard: > there's almost never a reason to use the cmp= argument to > sort() anymore. It's almost always better to use the key= argument. I always use key now, but maybe cmp uses less memory. There can be few situations where cmp is better still. Bye, bearophile From kyosohma at gmail.com Tue Apr 3 11:43:57 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: 3 Apr 2007 08:43:57 -0700 Subject: low level networking in python In-Reply-To: References: Message-ID: <1175615037.137052.70980@w1g2000hsg.googlegroups.com> On Apr 3, 10:29 am, "Maxim Veksler" wrote: > Hello, > > I wish to do some low level network stuff using python. > > I've googled somewhat and came up with pylibpcap[1], trouble is I > can't compile it on my Ubuntu 6.10 workstation. Can someone please > suggest a way to read some bits from random ports? I'm looking to > write a simple pen-testing tool that would try from one side > connecting to ports and from the other side sniff traffic to see on > what ports traffic is coming. > > For pylibpcap I'm getting: > > """ > hq4ever at lucky:~/development/personal/pylibpcap/pylibpcap-0.5.1$ python > setup.py build > running build > running build_ext > building '_pcapmodule' extension > swig -python -shadow -ISWIG -o pcap.c pcap.i > pcap.i:72: Warning(124): Specifying the language name in %typemap is > deprecated - use #ifdef SWIG instead. > pcap.i:77: Warning(124): Specifying the language name in %typemap is > deprecated - use #ifdef SWIG instead. > pcap.i:82: Warning(124): Specifying the language name in %typemap is > deprecated - use #ifdef SWIG instead. > /usr/bin/python ./build-tools/docify.py pcap.c > /usr/bin/python ./build-tools/docify-shadow.py pcap.py > Traceback (most recent call last): > File "./build-tools/docify-shadow.py", line 30, in ? > raise 'source file doesn\'t look like swigged shadow class code' > source file doesn't look like swigged shadow class code > error: command '/usr/bin/python' failed with exit status 1 > """ > > [1]http://pylibpcap.sourceforge.net/ > [2]http://py.vaults.ca/apyllo.py/126307487 > > -- > Cheers, > Maxim Veksler > > "Free as in Freedom" - Do u GNU ? I would assume you could use the socket module. This post details someone else who opened ports with Python: http://www.thescripts.com/forum/thread44280.html Here's another resource using some python servers: http://docs.python.org/lib/socket-example.html Finally, a Socket programming howto: http://www.amk.ca/python/howto/sockets/ I'm also told that the Twisted framework is excellent for this sort of thing. Mike From steve at holdenweb.com Tue Apr 10 09:09:12 2007 From: steve at holdenweb.com (Steve Holden) Date: Tue, 10 Apr 2007 09:09:12 -0400 Subject: [offtopic?] problem with UDP broadcast on Windows XP In-Reply-To: <012e01c77b3c$09bd3ec0$03000080@hendrik> References: <461a271c$0$323$e4fe514c@news.xs4all.nl> <461a6523$0$327$e4fe514c@news.xs4all.nl> <012e01c77b3c$09bd3ec0$03000080@hendrik> Message-ID: Hendrik van Rooyen wrote: > "Irmen de Jong" wrote: > > >> Gabriel Genellina wrote: >> >>> Try running the service impersonating another user (not LOCAL_SERVICE, >>> the default). >>> You can change that from the service control panel. >> Alas, that didn't change anything. >> I made it run as a user account that has admin privileges even, >> and it still doesn't respond to the broadcasts. :-( >> > > I am not sure if this is at all relevant - but I seem to recall seeing > something once that had a list of socket numbers, splitting them > between UDP & TCP - can the socket actually rx UDP? > That's probably a red herring, Hendrik. Both UDP and TCP define ports from 1 through 65535, and so a port number doesn't "belong" to one protocol or the other. It's most likely, I suspect without knowing to much about it, that the service is stalling because of a failure to "pump" Windows messages. Irmen, are you taking any action in your service to ignore Windows messages that your service process receives? 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 kyosohma at gmail.com Tue Apr 3 17:16:26 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: 3 Apr 2007 14:16:26 -0700 Subject: Newbie - needs help In-Reply-To: <1175632937.838422.236850@y66g2000hsf.googlegroups.com> References: <1175632937.838422.236850@y66g2000hsf.googlegroups.com> Message-ID: <1175634986.745370.286200@o5g2000hsb.googlegroups.com> On Apr 3, 3:42 pm, "Anbeyon" wrote: > Hi > > I have not yet programmed in Python but am experienced in a number o > other languages. > > I'd like to start to use Python to develop cross platform applications > but havin kust started to investigate tols, libraries etc I feel a > little overwhelmed. > > I'm hoping someone might be able to point me in the right direction. > > What I'd like to achieve is the abilty to develop applications for > both Windows and Linux (Desktop and embedded). I'd also like to be > able to develop applications that make use of TCP/IP and things like > 'Widget' libraries. > > In an ideal would like to be able to pull together Python apps with > GUI front ends in a nice IDE with a debugger. > > Does such a toolset exisit ? > > Perhaps some people can sully me some links ? > > Thanks in advance. > > Anbeyon There's lot of Python tools available for you. ActiveState has ActivePython (free) - http://www.activestate.com/products/activepython/ Eclipse has a plugin to use for Python - http://www.easyeclipse.org/site/home/ If you use wxPython you can use: Boa Constructor - http://boa-constructor.sourceforge.net/ Stani's Python Editor - http://pythonide.blogspot.com/ Dabo - http://dabodev.com/ For others, check this: http://wiki.python.org/moin/IntegratedDevelopmentEnvironments Most are free, but some have different licenses. Read up on them. I still use IDLE for most of my work. Currently I am playing with XRCed. I did find PythonWin, ActiveState's and Eclipse's to be handy too though. Mike From gagsl-py2 at yahoo.com.ar Mon Apr 9 17:58:31 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 09 Apr 2007 18:58:31 -0300 Subject: How can I import functions from another python file References: <1176152771.761958.310740@w1g2000hsg.googlegroups.com> Message-ID: En Mon, 09 Apr 2007 18:06:11 -0300, yinglcs at gmail.com escribi?: > i have 2 python files in *different directory* , how can I import > python functions from 1 python file to another? See the tutorial about modules, packages, and the module search path: http://docs.python.org/tut/node8.html You can extend the search path using .pth files: http://docs.python.org/lib/module-site.html (but consider using packages instead of cluttering your search path with infinite entries) -- Gabriel Genellina From nogradi at gmail.com Sun Apr 22 12:02:00 2007 From: nogradi at gmail.com (Daniel Nogradi) Date: Sun, 22 Apr 2007 18:02:00 +0200 Subject: Dictionaries and dot notation In-Reply-To: <462b842e$0$28548$426a74cc@news.free.fr> References: <23087554.X5dcTmlj7P@beaureve.gmx.net> <462b842e$0$28548$426a74cc@news.free.fr> Message-ID: <5f56302b0704220902p5b612723p31a8d738e5ac27d@mail.gmail.com> > > This may be pretty obvious for most of you: > > > > When I have an object (an instance of a class "Foo") I can access > > attributes via dot notation: > > > > aFoo.bar > > > > however when I have a dictionary > > > > aDict = {"bar":"something"} > > > > I have to write > > > > aDict["bar"] > > > > What if I want to create a datastructure that can be used in dot > > notation without having to create a class, i.e. because those objects > > have no behavior at all? > > A class inheriting from dict and implementing __getattr__ and > __setattr__ should do the trick... It can do the trick but one has to be careful with attributes that are used by dict such as update, keys, pop, etc. Actually it's noted in a comment at http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/361668 why the whole idea (attribute access of dictionaries) is a bad idea and I tend to agree. Daniel From joshua at eeinternet.com Mon Apr 30 16:55:22 2007 From: joshua at eeinternet.com (Joshua J. Kugler) Date: Mon, 30 Apr 2007 12:55:22 -0800 Subject: Interop between C# and Python References: <1177722543.098518.192840@h2g2000hsg.googlegroups.com> Message-ID: <46364b5b$0$16331$88260bb3@free.teranews.com> On Friday 27 April 2007 17:09, urielka wrote: > i need a easy way to write a Python Service(be it SOAP or JSONRPC or > whatever) but i need to easily access it from C#,i created a web > service in ZSI(which is really easy) like this: You might want to take a look at Thrift too: http://developers.facebook.com/thrift/ 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 larry.bates at websafe.com Thu Apr 5 18:03:17 2007 From: larry.bates at websafe.com (Larry Bates) Date: Thu, 05 Apr 2007 17:03:17 -0500 Subject: ipython env In-Reply-To: References: Message-ID: <0Kadndcfb9O_74jbnZ2dnUVZ_hSdnZ2d@comcast.com> Greg Donald wrote: > Anyone know what's up with environment variables when using ipython? > > When I type 'env' and hit return I get a dictionary full of useful > information (trimmed for brevity): > > In [1]: env > Out[1]: > {'EDITOR': '/usr/bin/vim', > [...] > '_': '/Library/Frameworks/Python.framework/Versions/Current/bin/ipython', > '__CF_USER_TEXT_ENCODING': '0x1F5:0:0'} > > > But then when try to access the information in the dictionary it > doesn't seem to exist: > > In [2]: env['EDITOR'] > --------------------------------------------------------------------------- > exceptions.NameError Traceback (most > recent call last) > > /Users/destiney/ > > NameError: name 'env' is not defined > > > Thanks, > > In Cpython you get this with: import os os.environ['EDITOR'] -Larry From edfialk at gmail.com Mon Apr 23 16:44:11 2007 From: edfialk at gmail.com (edfialk) Date: 23 Apr 2007 13:44:11 -0700 Subject: script for seconds in given month? In-Reply-To: <1176796031.889407.323950@b75g2000hsg.googlegroups.com> References: <1176740556.859125.221980@l77g2000hsb.googlegroups.com> <1hwokmz.1ropcwj17pg55dN%aleax@mac.com> <1176796031.889407.323950@b75g2000hsg.googlegroups.com> Message-ID: <1177361051.070798.290350@d57g2000hsg.googlegroups.com> Alex, very nice. Thank you. Unfortunately, I just found out the platform for using the script will be IronPython, not Python. So, importing calendar in IronPython gives me: SyntaxError: future feature is not defined: with_statement (c: \Python25\Lib\calendar.py, line 8) so, compatibility issue. I'm extremely grateful for everyone's help so far and I have moved my question over to an IronPython group, but does anyone happen to know of a way to make this work with IronPython? Thanks! -Ed From http Sun Apr 15 03:55:09 2007 From: http (Paul Rubin) Date: 15 Apr 2007 00:55:09 -0700 Subject: tuples, index method, Python's design References: <1176200361.260546.280510@n76g2000hsh.googlegroups.com> <740c3aec0704100824m132c45fbi5c4c3ec0c0fa3a67@mail.gmail.com> <1176489534.568939.249910@q75g2000hsh.googlegroups.com> <7x3b33k0l9.fsf@ruckus.brouhaha.com> <1176572775.382873.282850@q75g2000hsh.googlegroups.com> <7xr6qmrg4x.fsf@ruckus.brouhaha.com> <1176618596.238855.122000@d57g2000hsg.googlegroups.com> Message-ID: <7xvefym5r6.fsf@ruckus.brouhaha.com> "Rhamphoryncus" writes: > Indexing cost, memory efficiency, and canonical representation: pick > two. You can't use a canonical representation (scalar values) without > some sort of costly search when indexing (O(log n) probably) or by > expanding to the worst-case size (UTF-32). Python has taken the > approach of always providing efficient indexing (O(1)), but you can > compile it with either UTF-16 (better memory efficiency) or UTF-32 > (canonical representation). I still don't get it. UTF-16 is just a data compression scheme, right? I mean, s[17] isn't the 17th character of the (unicode) string regardless of which memory byte it happens to live at? It could be that that accessing it takes more than constant time, but that's hidden by the implementation. So where does the invariant c==s[s.index(c)] fail, assuming s contains c? From rweth at cisco.com Sun Apr 8 02:56:02 2007 From: rweth at cisco.com (rweth) Date: Sat, 07 Apr 2007 23:56:02 -0700 Subject: Cant access http://cheeseshop.python.org/ or wiki In-Reply-To: References: Message-ID: <1176015363.235606@sj-nntpcache-2.cisco.com> cyb wrote: > For some reason I can ping these two sites fine, but when I try to go to > them I cannot get to them. Normal python.org homepage works just fine. > This is preventing me from getting setuptools and using pyOpenGL =( > > I'm using COmcast in savannah, GA "It's the finest cheese shop in these parts sir" "And what leads you to that conclusion" "well it's so clean sir" "well it's certainly uncontaminated by cheese!" http://www.youtube.com/watch?v=pDat9zdw7Gs Prey out of curiosity .. any idea where the spiders came from? I too noticed an issue downloading mechanize last night. From cam.ac.uk at mh391.invalid Thu Apr 12 15:07:12 2007 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Thu, 12 Apr 2007 20:07:12 +0100 Subject: Portably generating infinity and NaN Message-ID: What's the best way to portably generate binary floating point infinity and NaNs? I only know two solutions: 1. Using the fpconst module proposed in IEEE 754, which I believe shifts bits around. 2. Using an extension module (for example, numarray.ieeespecial will do it). I thought of using float(Decimal("nan")), but apparently Decimal.__float__(self) is float(str(self)), which isn't portable. -- Michael Hoffman From paul at boddie.org.uk Mon Apr 2 06:31:01 2007 From: paul at boddie.org.uk (Paul Boddie) Date: 2 Apr 2007 03:31:01 -0700 Subject: Shed Skin Python-to-C++ Compiler 0.0.21, Help needed In-Reply-To: References: <576vhbF2ca1guU1@mid.individual.net> <1175376373.241744.6220@y80g2000hsf.googlegroups.com> <1175413310.295953.230840@e65g2000hsc.googlegroups.com> <1175455529.936887.249170@e65g2000hsc.googlegroups.com> <1175496721.899984.193690@n76g2000hsh.googlegroups.com> Message-ID: <1175509861.292455.226280@b75g2000hsg.googlegroups.com> On 2 Apr, 09:17, John Nagle wrote: > > Something else worth trying: type inference for separately > compiled modules using the test cases for the modules. I mentioned such possibilities once upon a time: http://blog.amber.org/2004/12/23/static-typing-and-python/ Note the subject of the original article, by the way. And as a postscript, I'd advise anyone wondering what happened to Starkiller to take a look at Shed Skin instead, since it more or less does what Starkiller was supposed to do. > One big problem with compile-time type inference is what to do > about separate compilation, where you have to make decisions > without seeing the whole program. An answer to this is to > optimize for the module's test cases. If the test cases > always use an integer value for a parameter, generate hard > code for the case where that variable is a integer. As long > as there's some way to back down, at link time, to a more general > but slower version, programs will still run. If the test > cases reflect normal use cases for the module, this should > lead to generation of reasonable library module code cases. People are always going to argue that a just-in-time compiler saves everyone from thinking too hard about these issues, but I still think that there's a lot of mileage in deducing types at compile time for a number of reasons. Firstly, there are some applications where it might be desirable to avoid the overhead of a just-in-time compilation framework - I can imagine that this is highly desirable when developing software for embedded systems. Then, there are applications where one wants to know more about the behaviour of the code, perhaps for documentation purposes or to help with system refactoring, perhaps to minimise the risk of foreseeable errors. Certainly, if this latter area were not of interest, there wouldn't be tools like pylint. Paul P.S. Another aspect of the referenced article that is worth noting is the author's frustration with the state of the standard library: something which almost always gets mentioned in people's pet Python hates, but something mostly ignored in the wider enthusiasm for tidying up the language. From mmoum at woh.rr.com Sat Apr 14 21:49:11 2007 From: mmoum at woh.rr.com (Mike) Date: Sat, 14 Apr 2007 21:49:11 -0400 Subject: function with list argument defaulting to [] - what's going on here??? In-Reply-To: References: <46217e8f$0$19437$4c368faf@roadrunner.com> Message-ID: <46218497.1060706@woh.rr.com> Thanks, Troy. I never cease to be amazed at what can be discovered by reading the manual! Mike Troy Melhase wrote: > On 4/14/07, Mike wrote: >> While trying to write a recursive function involving lists, I came >> across some (to me) odd behavior which I don't quite understand. Here's >> a trivial function showing the problem. > > from http://docs.python.org/ref/function.html : > > Default parameter values are evaluated when the function definition is > executed. This means that the expression is evaluated once, when the > function is defined, and that that same ``pre-computed'' value is used > for each call. This is especially important to understand when a > default parameter is a mutable object, such as a list or a dictionary: > if the function modifies the object (e.g. by appending an item to a > list), the default value is in effect modified. From ark at acm.org Thu Apr 12 16:49:39 2007 From: ark at acm.org (Andrew Koenig) Date: Thu, 12 Apr 2007 20:49:39 GMT Subject: How to copy a file on Windows while preserving permissions Message-ID: The answer to this question probably involves pywin32 or a similar library. I would like to copy a file from one place to another on a Windows machine while preserving as much of the file permissions as it is possible to preserve with whatever my program's privileges happen to be. If the file is a directory (i.e. folder), this might require temporarily granting myself write permission for the directory so I can (recursively) create files in it--again, assuming that it is possible to do so. Obviously it would be necessary to determine whether my program's privileges are sufficient to solve this problem for the particular files in question. Can someone who is more familiar than I with the vagaries of Windows file protection and the Python interfaces available to it point me in a useful direction? From lhf at xtra.co.nz Sun Apr 15 00:54:32 2007 From: lhf at xtra.co.nz (LesF) Date: 14 Apr 2007 21:54:32 -0700 Subject: Emergence of Grok In-Reply-To: References: <1176424693.546746.238660@d57g2000hsg.googlegroups.com> Message-ID: <1176612872.924621.299580@n76g2000hsh.googlegroups.com> On Apr 14, 10:05 pm, Anton Vredegoor wrote: ... > That doesn't mean that I haven't met a lot of enthusiastic and helpful > zope developers and programmers, it's just that they don't understand or > don't want to understand that money can be a show stopper for people > wanting to learn about zope. Thank you for that post. I was starting to think it was just me. Despite having worked as a software developer for 20 years, and thoroughly enjoying programming, and loving Python... something about the Zope community just seems to be lacking, when it comes to grabbing the thing and working out how to be productive. I am not against people trying to earn a living, my career is based on that principle. I just find the atmosphere clouded and uncertain. I mean, are there secret street fight meetings where zope-2 and zope-3 gangs maim each other while chanting the names of their favorite API's... From thn at mail.utexas.edu Fri Apr 27 12:52:21 2007 From: thn at mail.utexas.edu (Thomas Nelson) Date: 27 Apr 2007 09:52:21 -0700 Subject: editing scripts on a mac In-Reply-To: References: Message-ID: <1177692741.619598.191540@r3g2000prh.googlegroups.com> On Apr 27, 11:37 am, Tommy Grav wrote: > > him> I do not have a text editor, but here are the answers to > > him> questions 1-5. > > > Now, frankly, I don't think this answer is correct, since I know OS > > X is > > a UNIX derivative, but I am loathe to involve a programming noob > > with vi > > or something similar. So I wondered if one of the c.l.py mac users > > could > > give brief instructions for firing up a visual text editor of some > > sort > > and saving a file somewhere it can easily be accessed from a terminal > > window (which I presume starts up in his home directory). > 1) Open Finder, click "Applications", and open "TextEdit". 2) hit shift-apple-T, or select Format -> Make Plain Text, to put you in plaintext mode (It's .rtf by default) 3) Make sure you save in the home directory (usually a picture of a house). HTH, Tom From gregcorradini at gmail.com Wed Apr 18 15:44:01 2007 From: gregcorradini at gmail.com (Greg Corradini) Date: Wed, 18 Apr 2007 12:44:01 -0700 (PDT) Subject: Help Understanding mx.ODBC Error In-Reply-To: References: <10063746.post@talk.nabble.com> Message-ID: <10065545.post@talk.nabble.com> Steve, As always, thanks for your consistent help on matters big and small. I've managed to solve the problem, although I'm scared b/c the bug is still elusive. I dumped and deleted my seperate Access DBs, created new ones and tried running the scripts on old data (that these scripts were able to digest successfully before) and new data (that they errored on to begin with). Everything works without me changing any code around. Hmm? I don't know much about Access or the JetEngine. Is it possible that .mdbs can go corrupt if overused? This seems unlikely, but I'm dumbfounded. Thanks again Greg Corradini Steve Holden wrote: > > Greg Corradini wrote: >> Hello All, >> A few weeks ago, I wrote two scripts using mx.ODBC on an Access DB. Among >> other things, both scripts create new tables, perform a query and then >> populate the tables with data in a dictionary that I've uploaded from >> elsewhere. These scripts have run hundreds of times in the last few weeks >> with no problems. >> >> But recently they continue to bail on the mycursor.execute('An SQL >> Statement') after the table has been created. I get the following error >> message: >> Traceback (most recent call last): >> File "C:\Documents and Settings\marv1shi\Desktop\Workspace\Existence >> Script\DBF Checker\Access_SQL.py", line 35, in ? >> curse.execute(sql) >> ProgrammingError: ('07001', -3010, '[Microsoft][ODBC Microsoft Access >> Driver] Too few parameters. Expected 4.', 4612) >> >> The real stinker, however, is that after it bails I can manually call >> mycursor.execute('An SQL Statement'), then call my insert statement in >> the >> Python Shell and it works fine. >> >> I just can't figure out how to reconcile this problem. Has anybody run >> into >> this before? >> >> Thanks >> Greg Corradini > > I suspect what's happening here is that you are presenting statements > you have made up programmatically, and the values you are trying to > insert include apostrophes that break the syntax of your SQL. However > there isn't really enough evidence to decide unless you are prepared to > show us the error traceback, possibly with a dump of the SQL statement > you are actually trying to execute. > > I apologize in advance if you are using parameterized queries (as you > should to avoid SQL injection vulnerabilities among other major > problems) but this message is typical of Access when it sees words it > can't parse. > > 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 > > -- > http://mail.python.org/mailman/listinfo/python-list > > -- View this message in context: http://www.nabble.com/Help-Understanding-mx.ODBC-Error-tf3602497.html#a10065545 Sent from the Python - python-list mailing list archive at Nabble.com. From bbxx789_05ss at yahoo.com Mon Apr 16 03:03:16 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: 16 Apr 2007 00:03:16 -0700 Subject: Getting started with python In-Reply-To: References: <1176598011.463543.96990@q75g2000hsh.googlegroups.com> <1176608302.928513.274400@y5g2000hsa.googlegroups.com> <%LyUh.10121$YL5.5753@newssvr29.news.prodigy.net> Message-ID: <1176706996.848574.196660@y5g2000hsa.googlegroups.com> On Apr 15, 9:49 pm, James Stroud wrote: > py> t = timeit.Timer(stmt=s) > py> print "%.2f usec/pass" % (1000000 * t.timeit(number=100000)/100000) > 40.88 usec/pass > What does this accomplish: 1000000 * t.timeit(number=100000)/100000 that the following doesn't accomplish: 10 * t.timeit(number=100000) From aleax at mac.com Sun Apr 15 01:58:05 2007 From: aleax at mac.com (Alex Martelli) Date: Sat, 14 Apr 2007 22:58:05 -0700 Subject: combination function in python References: <1176615838.830315.160210@b75g2000hsg.googlegroups.com> Message-ID: <1hwl0z1.1skx1jnvvvk39N%aleax@mac.com> DanielJohnson wrote: > how to use the combination function in python ? > > For example 9 choose 2 (written as 9C2) = 9!/7!*2!=36 > > Please help, I couldnt find the function through help. If you download and install gmpy, it's easy: >>> import gmpy >>> gmpy.comb(9,2) mpz(36) However, there's no equivalent function built into Python, if that's what you're asking (gmpy's a third-party extension). It's of course easy to write one for yourself, if you want the functionality but don't want to download gmpy and don't care for gmpy's superb speed. Alex From jstroud at mbi.ucla.edu Sat Apr 14 18:45:50 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Sat, 14 Apr 2007 15:45:50 -0700 Subject: Lists and Tuples and Much More In-Reply-To: References: <1176419437.278359.52800@q75g2000hsh.googlegroups.com> Message-ID: Hendrik van Rooyen wrote: > > "7stud" wrote: > > >>.......... But using a tuple as a >>key in a dictionary is probably something you will never do. > > > Yikes! I do this all the time... > > Think of an address in any one town. > It has a Street, and a number > (could be more complex, like a sub number for an apartment > in a block, but lets ignore that for now) > > so: > addy = ("First Avenue", 10) > Residents = {addy:"Frank Everyman",......} > > To make a thing where you can look up who lives at a place... > (this is simplistic of course, for illustrative purposes - few people > live completely alone. - it should be at least a list, or possibly a dict > by surname...) > > I find that when I do this, I almost invariably also create the > inverse dict: > > Addresses = {"Frank Everyman":addy,.....} > > So that you can get at stuff from all directions. If you keep it > up you have a home made relational database if you are not careful... > > But if you limit it to one thing and its inverse, its quite useful, and it > would be nice to have one "doubledict" that can be accessed as speedily > from either end... > > Sort of an internally linked list of mixed hashed immutables, where: > > doubledict["Frank Everyman"] yields addy, and > doubledict[addy] yields "Frank Everyman" > > It would have direct applicability in things like the label table in > an assembler, for debugging and so on. > > - Hendrik > I'm thinking that, to avoid big a lot of ambiguity, such a double dict would need to be implemented as two distinctly referenced data structures: class DD(object): def __init__(self, adict): self._fwd = {} self._fwd.update(adict) self._bkwk = dict(v,k for k,v in adict.items()) def fwd(self, k) return self._fwd[k] def bkwd(self, k) return self._bkwd[k] def __setitem__(self, k, v): self._fwd[k] = v self._bkwd[v] = k def __getitem__(self, k): if (k in self._fwd) and (k in self._bkwd): raise KeyError, 'Which do I look in first?' else: raise KeyError, 'Too much guesswork. Use fwd() or bkwd().' James From grahn+nntp at snipabacken.dyndns.org Thu Apr 19 17:07:09 2007 From: grahn+nntp at snipabacken.dyndns.org (Jorgen Grahn) Date: 19 Apr 2007 21:07:09 GMT Subject: Python un-plugging the Interpreter References: Message-ID: On Thu, 19 Apr 2007 10:56:25 -0600, S.Mohideen wrote: > Hi All, > I was thinking about the feasbility of adjusting Python as a > compiled language. Being said that I feel these are the following advantages > of doing so -- > 1) Using the powerful easy-to -use feature of Python programming language > constructs. We already do. > 2) Making the program to run at par with the compiled version of C/C++ > program- this is the main benefit which can be derived out of this. Depends on what you mean by 'at par'. In the general case, that code would have to basically work like the Python interpreter. Too much is happening at runtime and it cannot be determined at compile time. > 3) Highly re-use existing Python code for High performance application. A reformulation of (2). > 4) Acheive true parallelism and performance by getting rid of the > middle-man Interpreter and GIL. Is the GIL really an artifact of the interpreter? /Jorgen -- // Jorgen Grahn R'lyeh wgah'nagl fhtagn! From tjreedy at udel.edu Wed Apr 25 12:28:16 2007 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 25 Apr 2007 12:28:16 -0400 Subject: Advocacy: "Python up, Ruby down". References: <1177482210.379942.201930@n35g2000prd.googlegroups.com> Message-ID: "Paddy" wrote in message news:1177482210.379942.201930 at n35g2000prd.googlegroups.com... |I found this blog post on one users migration to Python. It states one | users frustrations but the comments section is quite good too. | | http://blog.cbcg.net/articles/2007/04/22/python-up-ruby-down-if-that-runtime-dont-work-then-its-bound-to-drizzown | | The time and effort the developers spend on the balance between fixing | what we have over adding new features is hard, but it did pay off for | this programmer who was lured over by a more robust implementation and | good documentation. I think the author should be invited to contribute a Python Success Story for the site! Definitely worth reading. tjr From Roka100 at gmail.com Wed Apr 18 11:03:16 2007 From: Roka100 at gmail.com (Jia Lu) Date: 18 Apr 2007 08:03:16 -0700 Subject: Combinate 2 lists to a dict ? Message-ID: <1176908596.222474.33440@n76g2000hsh.googlegroups.com> Hi all. I have 2 lists, a = [1,2,3] b = ["ooo","aaa","ppp"] What is the fastest way to make a dict like {1:"ooo",2:"aaa", 3:"ppp"} ? Thanx From bruno.42.desthuilliers at wtf.websiteburo.oops.com Thu Apr 12 03:05:35 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Thu, 12 Apr 2007 09:05:35 +0200 Subject: pop() clarification In-Reply-To: References: Message-ID: <461dd9d4$0$3195$426a74cc@news.free.fr> Hamilton, William a ?crit : >> -----Original Message----- >> From: python-list-bounces+whamil1=entergy.com at python.org > [mailto:python- >> list-bounces+whamil1=entergy.com at python.org] On Behalf Of Scott >> >> I understand all that. What I don't understand is why all the >> documentation >> I see says, "When removing a specific element from a list using pop() > it >> must be in this format: list.pop([i]). >> At first I took that to mean that list.pop(i) would return some type > of >> error, but it doesn't. >> I can't find any documentation saying that this rule that I keep > reading >> about (again list.pop([i]) ) is the only format to use when removing a >> specific element because......with the explaination to follow. > > I believe that the [i] notation is to indicate that it has to be a valid > index to your list. And you're wrong. Well, it has to be a valid index, but this has nothing to do with the notation used. Google for "Backus-Naur Form"... From nospam at invalid.com Fri Apr 13 16:18:26 2007 From: nospam at invalid.com (Jack) Date: Fri, 13 Apr 2007 13:18:26 -0700 Subject: Python editor/IDE on Linux? References: <1176494048.627760.323630@p77g2000hsh.googlegroups.com> Message-ID: Thanks but...I'm looking for something free :) > try wing ide. i tried it and i love it. it's available for windows as > well for linux From steve at holdenweb.com Fri Apr 6 15:50:17 2007 From: steve at holdenweb.com (Steve Holden) Date: Fri, 06 Apr 2007 15:50:17 -0400 Subject: Basic Serialization - a design decision question In-Reply-To: <5d2e4d280704060940s3fa1defdl874c8c4e7fa92266@mail.gmail.com> References: <5d2e4d280704060940s3fa1defdl874c8c4e7fa92266@mail.gmail.com> Message-ID: Gizmo wrote: > Hello > I am a relative newcomer to Python, and I am studying it to understand > its design. It intrigues me. > I recently studied Serialization of classes via the pickle/cPickle > library, and I have a question. > > Why is Serialization handled by a separate library (ie, pickle). Is it > possible, by design, to have serialization "internally" implemented via > an implicit ___serialize___ method? Ofcourse, you have to make this > method not overrideable (sp?). For example, the __repr__ method gives us > the string representation of a class... similarly, the __serialize__ > method would give us the "serial norm" representation of the class. > > This would allow me to do something like this, > conn.send(serial(myClass)); // or something like that? > > Thoughts? > > > It would be quite possible to do this - it just hasn't been done, is all. I'm not quite sure what advantage you see for serial(myClass) over pickle.dumps(myClass) though. 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 python at hope.cz Wed Apr 25 02:24:00 2007 From: python at hope.cz (Johny) Date: 24 Apr 2007 23:24:00 -0700 Subject: How to set font colour in PIL Message-ID: <1177482240.488474.108270@b40g2000prd.googlegroups.com> I use PIL to write some text to a picture.The text must be seen wery clearly. I write the text to different pictures but to the same position. As pictures maybe different, colour, in the position where I write the text, is also different. Is there a way how to set the font colour so that it will be seen very clearly in the picture? For example, if the picture is bright ( for example yellow), the font colour should be dark( e.g. black) and vice versa. Can anyone help? Thanks L. From bearophileHUGS at lycos.com Mon Apr 16 20:14:14 2007 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 16 Apr 2007 17:14:14 -0700 Subject: multirember&co Message-ID: <1176768854.720234.23320@w1g2000hsg.googlegroups.com> Once in while I too have something to ask. This is a little problem that comes from a Scheme Book (I have left this thread because this post contains too much Python code for a Scheme newsgroup): http://groups.google.com/group/comp.lang.scheme/browse_thread/thread/a059f78eb4457d08/ The function multiremberandco is hard (for me still) if done in that little Scheme subset, but it's very easy with Python. It collects two lists from a given one, at the end it applies the generic given fun function to the two collected lists and returns its result: def multiremberandco1(el, seq, fun): l1, l2 = [], [] for x in seq: if x == el: l2.append(el) else: l1.append(el) return fun(l1, l2) data = [1, 'a', 3, 'a', 4, 5, 6, 'a'] print multiremberandco1('a', data, lambda l1,l2: (len(l1), len(l2))) More compact: def multiremberandco2(el, seq, fun): l1, l2 = [], [] for x in seq: [l1, l2][x == el].append(el) return fun(l1, l2) A bit cleaner (but I don't like it much): def multiremberandco3(el, seq, fun): l1, l2 = [], [] for x in seq: (l2 if x == el else l1).append(el) return fun(l1, l2) For fun I have tried to make it lazy, if may be useful if seq is a very long iterable. So I've used tee: from itertools import ifilter, tee def multiremberandco4(el, iseq, fun): iseq1, iseq2 = tee(iseq) iterable1 = ifilter(lambda x: x == el, iseq1) iterable2 = ifilter(lambda x: x != el, iseq2) return fun(iterable1, iterable2) def leniter(seq): count = 0 for el in seq: count += 1 return count idata = iter(data) print multiremberandco4('a', idata, lambda l1,l2: (leniter(l1), leniter(l2))) But from the docs: >in general, if one iterator is going to use most or all of the data before the other iterator, it is faster to use list() instead of tee().< So I have tried to create two iterables for the fun function scanning seq once only, but I haven't succed so far (to do it I have tried to use two coroutines with the enhanced generators, sending el to one or to the other according to the value of x == el, this time I don't show my failed versions), do you have suggestions? (Note: in some situations it may be useful to create a "splitting" function that given an iterable and a fitering predicate, returns two lazy generators, of the items that satisfy the predicate and of the items that don't satisfy it, so this exercise isn't totally useless). Bye, bearophile From rzantow at gmail.com Mon Apr 2 19:19:02 2007 From: rzantow at gmail.com (rzed) Date: Mon, 02 Apr 2007 23:19:02 +0000 Subject: Clean "Durty" strings References: <1175463083.135907.128480@y80g2000hsf.googlegroups.com> <57bt02F2c9fpuU2@mid.uni-berlin.de> <57cddlF2bsqdbU2@mid.uni-berlin.de> Message-ID: "Diez B. Roggisch" wrote in news:57cddlF2bsqdbU2 at mid.uni-berlin.de: >> >> If the OP is constrained to standard libraries, then it may be >> a question of defining what should be done more clearly. The >> extraneous spaces can be removed by tokenizing the string and >> rejoining the tokens. Replacing portions of a string with >> equivalents is standard stuff. It might be preferable to create >> a function that will accept lists of from and to strings and >> translate the entire string by successively applying the >> replacements. From what I've seen so far, that would be all the >> OP needs for this task. It might take a half- dozen lines of >> code, plus the from/to table definition. > > The OP had
-tags in his text. Which is _more_ than a half > dozen lines of code to clean up. Because your simple > replacement-approach won't help here: > >
foo
bar
> > Which is perfectly legal HTML, but nasty to parse. Well, as I said, given the input the OP supplied, it's not even necessary to parse it. It isn't clear what the true desired operation is, but this seems to meet the criteria given: s ="""\ bonne mentalité mec!:) \n
bon pour info moi je suis un serial posteur arceleur dictateur ^^* \n
mais pour avoir des resultats probant il faut pas faire les mariolles, comme le "fondateur" de bvs krew \n mais pour avoir des resultats probant il faut pas faire les mariolles, comme le "fondateur" de bvs krew \n""" fromlist = ['
', 'é', '"'] tolist = ['', '?', '"' ] def withReplacements( s, flist,tlist ): for ix, f in enumerate(flist): t = tlist[ix] s = s.replace( f,t ) return s print withReplacements(' '.join(s.split()),fromlist,tolist)
If the question is about efficiency or robustness or generality, then that's another set of issues, but that's for the 1.1 version to handle. -- rzed From hayes.tyler at gmail.com Thu Apr 19 19:02:05 2007 From: hayes.tyler at gmail.com (Tyler) Date: 19 Apr 2007 16:02:05 -0700 Subject: wxPython and how to return text entry to main program? In-Reply-To: <1177018820.445401.131420@n59g2000hsh.googlegroups.com> References: <1177011490.435609.155870@o5g2000hsb.googlegroups.com> <1177018820.445401.131420@n59g2000hsh.googlegroups.com> Message-ID: <1177023725.234825.258630@q75g2000hsh.googlegroups.com> Hi Mike: I actually just picked up the wxPython in Action book the other day and my main class is a hack of his "realworld_print.py" program, with some added bells and whistles. I will try to post on the wxPython mailing list and let them have a go at it. Cheers, tyler From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Thu Apr 26 16:50:20 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Thu, 26 Apr 2007 22:50:20 +0200 Subject: My python annoyances so far References: <1177541453.471959.120830@c18g2000prb.googlegroups.com> <59bf34F2k27v5U1@mid.individual.net> <1177603623.774892.230390@t38g2000prd.googlegroups.com> Message-ID: <59chkcF2e6106U1@mid.individual.net> flifus at gmail.com wrote: > Hi. You wrote c++, didn't you? Yes :) But I mostly don't anymore and ported my main project from C++ to Python. > Well, why do some things in the library have to be functions, and > other things have to be class methods? Easy. Some things abstractly operate on all kind of stuff (called "overloaded" in other languages), while others are, regarding their function, tied to a specific class. > Why aren't they all just either functions or class methods? Easy. Not all code in Python operates on a class. But that's what Python's class methods are for. Only. > like perhaps ruby. If I were rude, I would ask now why you don't use ruby. But I bet ruby has some annoyances ready for you too. Regards, Bj?rn -- BOFH excuse #290: The CPU has shifted, and become decentralized. From aaronwmail-usenet at yahoo.com Wed Apr 18 15:33:47 2007 From: aaronwmail-usenet at yahoo.com (aaronwmail-usenet at yahoo.com) Date: 18 Apr 2007 12:33:47 -0700 Subject: ANN: PNG image CAPTCHA with PNG canvas available (SkimpyGimpy) Message-ID: <1176924827.409707.243450@y5g2000hsa.googlegroups.com> Announcing SkimpyGimpy Support for PNG image CAPTCHA generation and PNG canvases. You can now use SkimpyGimpy to generate CAPTCHA text representations as PNG image files in addition to preformatted text ASCII art, and WAVE format audio streams, either from command lines or within Python programs. Also general support for drawing text and graphics as PNG image files is available via a "PNG canvas" drawing interface. Enjoy! Skimpy Main Page: http://skimpygimpy.sourceforge.net/ PNG Canvas documentation: http://skimpygimpy.sourceforge.net/canvas.html Background Information: Skimpy is a tool for generating HTML visual, PNG visual, and WAVE audio representations for strings which people can understand but which web robots and other computer programs will have difficulty understanding. Skimpy is an example of a Captcha: an acronym for "Completely Automated Public Turing test to tell Computers and Humans Apart". I hope you like! -- Aaron Watters === "Do you expect me to talk?" "No, Mr. Bond, I expect you to die." From chris.lasher at gmail.com Wed Apr 4 17:23:19 2007 From: chris.lasher at gmail.com (Chris Lasher) Date: 4 Apr 2007 14:23:19 -0700 Subject: Why NOT only one class per file? Message-ID: <1175721799.714907.52770@o5g2000hsb.googlegroups.com> A friend of mine with a programming background in Java and Perl places each class in its own separate file in . I informed him that keeping all related classes together in a single file is more in the Python idiom than one file per class. He asked why, and frankly, his valid question has me flummoxed. I tried to rationalize this Python idiom by claiming a file--a single module--makes for a great container of code which is logically tied together, such as a class and its subclasses. He posited that directories (packages) can tie the files together just as well, and by having the classes as separate files, he can "diff" them to see how they differ, something he wouldn't be able to do with the code all in one file. I also offered that having related classes under one file gives more direct access to those classes, e.g.: ---------------------------------- file: foo.py === class Bar(object): pass === file demo1.py === import foo barinstance = foo.Bar() === ---------------------------------- versus ---------------------------------- file: foopkg/bar.py === class Bar(object): pass === file: demo2.py === import foopkg.bar barinstance = foopkg.bar.Bar() === ---------------------------------- He doesn't find my arguments convincing, so I thought I'd ask here to see why the Python idiom is the way it is: why should we NOT be placing classes in their own separate files? Thoughts, comments, and insight much appreciated, Chris From rwood at therandymon.com Sat Apr 21 19:28:27 2007 From: rwood at therandymon.com (R Wood) Date: Sun, 22 Apr 2007 00:28:27 +0100 Subject: Python for Vcard Parsing in UTF16 Message-ID: <132l7inssigkted@corp.supernews.com> Greetings - A recent Perl experiment hasn't turned out so well, which has piqued my interest in Python. The project is this: take a Vcard file exported from Apple's Addressbook and use a language that is good at parsing text to convert it into a mutt alias file. There are better ways to use Mutt with Mac's addressbook, but I want to be able to periodically convert my working addressbook file into an alias file I can then transfer across all my different machines - two Macs, two Linux, and one FreeBSD. It's basically a couple of regexes that look for FN: followed by a name and convert all the words of the name into a single structure separated by underscores, followed by the email addresses. You would wind up with alias Linus_Torvalds Linus Torvalds To me this was a natural task for Perl. Turns out however, there's a catch. Apple exports the file in UTF-16 to ensure anyone with Chinese characters in their addressbook gets a legitimate Vcard file. And of course Perl somewhat chokes on UTF. I've found several ways to do it that involve complicated downloads and installations of Perl modules, but that defeats the purpose of making it simple. In an ideal world you should be able to say "try this cool script" and be done with it. Once you have to say "go to CPAN, download and compile this module, then ..." it gets less exciting. I know nothing about Python except that it interests me and has interested me since I first learned the Rekall database frontend (Linux) runs on it. I just ordered Learning Python and if that works out satisfactorily I'm going to go back for Programming Python. In the meantime, I thought I would pose the question to this newsgroup: would Python be useful for a parsing exercise like this one? From arnodel at googlemail.com Mon Apr 30 05:25:23 2007 From: arnodel at googlemail.com (Arnaud Delobelle) Date: 30 Apr 2007 02:25:23 -0700 Subject: While we're talking about annoyances In-Reply-To: <1hxchgp.7sw7efb72rh2N%aleax@mac.com> References: <1177837565.317999.244420@c35g2000hsg.googlegroups.com> <1177857049.938363.166170@p77g2000hsh.googlegroups.com> <1hxchgp.7sw7efb72rh2N%aleax@mac.com> Message-ID: <1177925123.832888.228520@u30g2000hsc.googlegroups.com> On Apr 30, 2:50 am, a... at mac.com (Alex Martelli) wrote: > Arnaud Delobelle wrote: > > ... > > > > >> decorated.sort() > ... > > > def index(sequence): > > > return sorted(range(len(sequence)), key=sequence.__getitem__) > ... > > But really these two versions of rank are slower than the original one > > (as sorting a list is O(nlogn) whereas filling a table with > > precomputed values is O(n) ). > > Wrong, because the original one also had a sort step, of course, so it > was also, inevitably, O(N log N) -- I've quoted the .sort step above. I am fully aware of the meaning of O(...). Nevertheless (speed != asymptotic speed) and one sort is still better than two sorts IMHO. Moreover the second sort is redundant and less clear than a simple loop. > > Anyway I would like to contribute my own index function: > > > def index(seq): > > return sum(sorted(map(list,enumerate(seq)), key=list.pop), []) > > > It's short and has the advantage of being self-documenting, which will > > save Steven a lot of annoying typing I hope ;) Who said Python > > couldn't rival with perl? > > sum is for summing NUMBERS -- using it on lists is O(N squared). > > So, this solution is asymptotically VERY slow, as well as obfuscated. And it was also a JOKE. There were some clues: * I claimed that the function was self-documenting, even though it was obviously obfuscated (as you rightly pointed out). * It relies on a side effect of the 'key' function list.pop, which is very bad form. * It is indeed very slow (yes, sum() is not the best for lists) * I mentioned that Python could rival perl. I was meant to be a clumsy but 'concise' amalgam that would perform the task (although not efficiently) while being difficult to make sense of. -- Arnaud From gandalf at designaproduct.biz Tue Apr 10 11:24:11 2007 From: gandalf at designaproduct.biz (Laszlo Nagy) Date: Tue, 10 Apr 2007 17:24:11 +0200 Subject: convert html entities into real chars In-Reply-To: <461BA680.7050805@designaproduct.biz> References: <461BA680.7050805@designaproduct.biz> Message-ID: <461BAC1B.8040007@designaproduct.biz> > I would like to have a function that can convert '>' into '>', > '&' into '&' etc. I could not find how to do it easily (I have a > code snippet for the opposite). Found it, sorry def convertentity(m): """Convert a HTML entity into normal string (ISO-8859-1)""" if m.group(1)=='#': try: return chr(int(m.group(2))) except ValueError: return '&#%s;' % m.group(2) try: return htmlentitydefs.entitydefs[m.group(2)] except KeyError: return '&%s;' % m.group(2) def unquotehtml(s): """Convert a HTML quoted string into normal string (ISO-8859-1). Works with &#XX; and with   > etc.""" return re.sub(r'&(#?)(.+?);',convertentity,s) From bdesth.quelquechose at free.quelquepart.fr Wed Apr 11 18:10:56 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Thu, 12 Apr 2007 00:10:56 +0200 Subject: text file vs. cPickle vs sqlite a design question In-Reply-To: <1176325868.370542.21160@o5g2000hsb.googlegroups.com> References: <461d4561$0$6091$426a34cc@news.free.fr> <1176325868.370542.21160@o5g2000hsb.googlegroups.com> Message-ID: <461d53cc$0$31002$426a34cc@news.free.fr> John Machin a ?crit : (snip) > ... and a few more cents: > > There are *two* relations/tables involved (at least): a "tuple" table > and a "list" table. Mmm... From a purely technical POV, not necessarily. If there's no need for anything else than distinguishing between different lists, a single table with a compound key (list_id, tuple_id) could be enough... From carsten at uniqsys.com Fri Apr 6 15:24:17 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Fri, 06 Apr 2007 15:24:17 -0400 Subject: tuples, index method, Python's design In-Reply-To: <1175884427.779950.267220@y80g2000hsf.googlegroups.com> References: <1175867771.114540.61810@n76g2000hsh.googlegroups.com> <1175884427.779950.267220@y80g2000hsf.googlegroups.com> Message-ID: <1175887457.3454.80.camel@dot.uniqsys.com> On Fri, 2007-04-06 at 11:33 -0700, 7stud wrote: > On Apr 6, 7:56 am, "Paul Boddie" wrote: > > The problem with 7stud's quote from GvR is that it's out of date: > > I would argue that it shows the very guy who invented the language > stated publicly there was no good reason for tuples not to have an > index method---except for consistency; tuples had no other methods. > Now that tuples have other methods, the only justification he stated > no longer exists. Except that that wasn't the only justification. GvR also said: """ For tuples, I suspect such a function would rarely be used; I think that is most cases where x.index() would be useful, x is generally a list, whose contents varies in time, rather than a tuple (which cannot change easily). """ The lack of convincing use cases is still a pertinent reason today. Note that the original poster on this thread did not present a use case for tuple.index, they were only asking out of curiosity. If you have a use case for tuple.index, please show it to me, and I'll show you what you should be using instead of a tuple. -Carsten From aleax at mac.com Tue Apr 24 21:51:35 2007 From: aleax at mac.com (Alex Martelli) Date: Tue, 24 Apr 2007 18:51:35 -0700 Subject: Python un-plugging the Interpreter References: <1hwu415.1yyvbo61efn1uqN%aleax@mac.com> <1hx2dgy.zizz7ir95hlgN%aleax@mac.com> Message-ID: <1hx37hh.11tie3ibt2omhN%aleax@mac.com> John Nagle wrote: ... > >>>Perhaps the current wave of dual-core and quad-core CPUs in cheap > >>>consumer products would change people's perceptions -- I wonder... > > > IronPython would appear to be coming along nicely and getting acceptance > > in the Windows community, and I believe the underlying dotNet CLR does > > do threads nicely; we'll see what develops on that front, I guess. > > Thus we now have a demonstration that Python implementations need > not be as slow as CPython. And that Microsoft is beating open source > on Python. Not yet -- overall, CPython is still faster than IronPython in a vast majority of cases. Also, according to : """ You may use the Software for any commercial or noncommercial purpose, including distributing derivative works ... This license has not been submitted to OSI, but it allows developers to take full advantage of a dynamic language on the CLR and to have the freedom to distribute their works for the benefit of the community at large. The license is half of a page long and very straight forward. We believe it stands up to what developers demand of an "open" license. """ I.e., they're claiming that, while not OSI-approved, theirs _IS_ in essence an open-source license. > Python as a language is in good shape. But the CPython > implementation is holding back progress. What we need are better > and faster implementations of the language we've got. That's not what Guido thinks -- he thinks we first need a better version of the language (Python 3000), simplified by removing much of the stuff that's been hanging around forever for backwards compatibility (and with a few other enhancements, check the Py3k PEPs). As long as the volunteers who work on Python prefer to follow Guido's leadership rather than yours, it's going to be difficult to force them to do what _you_ think is most important, rather than what _he_ thinks is. > PyPy, ShedSkin, and Jython all were steps in the right > direction, but none had enough momentum to make it. > Jython hasn't had a release since 2002, ShedSkin is basically > one guy, and the EU pulled the plug on PyPy. > > Now what? If you can get enough people to agree with you, and those people have either technical nous and spare time, or some money and the willingness to invest it in funding a new Python implementation (presumably building on top of PyPy's excellent final deliverables), you can get a team together for the purpose. Or, if you're really enthusiastic about IronPython, you could look into supporting Mono () to make it ever better, and a faster platform for running IronPython-compiled applications than Microsoft's own proprietary CLR (and also modify IronPython as you require, given the above-mentioned license). Other possible alternative starting points include pirate (the Python compiler for the Parrot virtual machine) -- I don't believe it's currently under active development (no more than, say, Jython), but I might well be wrong on this issue; and "Python dialects" ranging from Pyrex to Boo. Alex From kyosohma at gmail.com Tue Apr 3 09:35:16 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: 3 Apr 2007 06:35:16 -0700 Subject: raw_input just continues anyway? In-Reply-To: <1175606844.249364.290060@o5g2000hsb.googlegroups.com> References: <1175606844.249364.290060@o5g2000hsb.googlegroups.com> Message-ID: <1175607316.666477.99270@y80g2000hsf.googlegroups.com> On Apr 3, 8:27 am, "oli... at obeattie.com" wrote: > Hey Everyone, > > This is probably going to sound like a bit of a stupid question - but > why does (in the following code) the script just continue to run past > the raw_input, when the user hasn't entered anything? > > if __name__ == "__main__": > bucket_name = raw_input('Name of the bucket you wish the files to be > placed into? ') > update_s3() > > Basically, it just asks the question and continues anyway? > > Many Thanks, > Oliver This code works on my machine: Python 2.4, Windows XP Pro SP2 From ptmcg at austin.rr.com Mon Apr 30 11:00:29 2007 From: ptmcg at austin.rr.com (Paul McGuire) Date: 30 Apr 2007 08:00:29 -0700 Subject: import structures In-Reply-To: <1177945012.753497.117630@o5g2000hsb.googlegroups.com> References: <1177945012.753497.117630@o5g2000hsb.googlegroups.com> Message-ID: <1177945229.856966.309080@y80g2000hsf.googlegroups.com> On Apr 30, 9:56 am, spohle wrote: > hi, > > i have written a small project for myself all in seperate classes and > each of the classes lives in a seperate file. now i am looking for an > import structure something like import wx, and then have access to all > my classes just like wx.Button or wx.BoxSizer etc. > > as of now i have a __init__.py file in the directory with: > from pkgutil import extend_path > __path__ = extend_path(__path__, __name__) > > but i still have to import each class by it's own. im really looking > for something like import wx > and then get all my access right away under this new namespace. > > thank you in advance If it really is a small project, consider just putting all the classes into a single module, say spohlePkg.py. Then your users would import this module using "import spohlePkg", and would access the classes as "spohlePkg.ClassA", "spohlePkg.ClassB", etc. -- Paul From gagsl-py2 at yahoo.com.ar Mon Apr 23 08:49:31 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 23 Apr 2007 09:49:31 -0300 Subject: redirect ouput References: <1177331380.838772.240200@b58g2000hsg.googlegroups.com> Message-ID: En Mon, 23 Apr 2007 09:29:40 -0300, escribi?: > I am working on parsing an xml file using python.How can i > redirect the output to 2 files,say,for some portion of code the output > has to go to one file and for some part the o/p be directed to another > file. Using two separate files? out1 = open("output1.txt", "w") out2 = open("output2.txt", "w") ... if some_condition: out1.write(...) else: out2.write(...) ... out1.close() out2.close() (If that's not what you want, I may have misundertstood your question, please reformulate it) -- Gabriel Genellina From irstas at gmail.com Mon Apr 2 15:15:33 2007 From: irstas at gmail.com (irstas at gmail.com) Date: 2 Apr 2007 12:15:33 -0700 Subject: Math with unicode strings? In-Reply-To: <1175540961.679578.199370@o5g2000hsb.googlegroups.com> References: <1175540961.679578.199370@o5g2000hsb.googlegroups.com> Message-ID: <1175541333.582265.10790@y80g2000hsf.googlegroups.com> On Apr 2, 10:09 pm, "erikcw" wrote: > Hi, > > I'm parsing xml data with xml.sax and I need to perform some > arithmetic on some of the xml attributes. The problem is they are all > being "extracted" as unicode strings, so whenever I try to perform > math operations on the variables, I get this error: > > cr[0] = data['cls1']/data['ims1']; > TypeError: unsupported operand type(s) for /: 'unicode' and 'unicode' > > What do I need to do to extract the intergers from these unicode > strings (or better yet, parse them as intergers in the first place.). > I'm using the SAX method attrs.get('cls1',"") to parse the xml. Can I > "cast" the string into an interger? > > Thanks! > Erik int(u'123') == 123 float(u'123') == 123.0 From claird at lairds.us Tue Apr 17 23:55:38 2007 From: claird at lairds.us (Cameron Laird) Date: Wed, 18 Apr 2007 03:55:38 +0000 Subject: python - dll access (ctypes or swig) References: Message-ID: In article , Larry Bates wrote: >Daniel Watrous wrote: >> Hello, >> >> I am interested in using python to script access to some hardware for >> which there are existing drivers in the form of DLLs. The DLLs each >> have four exported functions and a host of COM Properties and COM >> Methods. The four exported functions are as follows: >> DllCanUnloadNow >> DllGetClassObject >> DllRegisterServer >> DllUnregisterServer >> >> The COM methods and properties all begin with I, followed by a unique name. >> >> I am able to load the DLL using ctypes and it can access the exported >> functions, but I'm not sure how to access the COM methods and >> properties. I have read that ctypes once had support for COM but that >> it has since been separated into its own project. I couldn't find any >> information about how these work together. >> >> All help is appreciated. THANKS in advance... >> >> Daniel > >I recently learned that you can ship COM as either an .EXE or a .DLL (nobody >has yet let me know why). You don't have a traditional .DLL that you would >use ctypes to call methods in, you have a COM .DLL. COM methods need to be >access with Win32com > >obj=win32com.client.Dispatch("typelib name"). > >You need to find out the COM dispatch typelib name and make sure the DLL is >registered (regsvr32 your.dll). > >-Larry Is this--adroit use of Win32com with special-purpose DLLs--written up anywhere? Doing this with unusual hardware that turns up in the real world is ENTIRELY more satisfying than trying to wrangle the Visual C bindings that vendors usually push, but, apart from Mark and Andy's book, now over seven years old, I know of no appropri- ately ambitious tutorial in the subject. Daniel, do you have what you need to make progress? Have you seen ? From apardon at forel.vub.ac.be Tue Apr 10 09:29:59 2007 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 10 Apr 2007 13:29:59 GMT Subject: tuples, index method, Python's design References: <1175867771.114540.61810@n76g2000hsh.googlegroups.com> <1175884427.779950.267220@y80g2000hsf.googlegroups.com> Message-ID: On 2007-04-10, Carsten Haese wrote: > >> Adding the index method to tuples is not adding a feature. It is >> removing a limitation. > > The non-existence of tuple.index is only a limitation if there is a need > for the method to exist. Please prove that this need exists. It doesn't because "need" is such a strong word, that just the fact that you can write your own index function means the method isn't needed. -- Antoon Pardon From hlubenow2 at gmx.net Thu Apr 26 14:17:47 2007 From: hlubenow2 at gmx.net (hlubenow) Date: Thu, 26 Apr 2007 20:17:47 +0200 Subject: key detect References: Message-ID: Alex Taslab wrote: > Hi everybody, does anyone know how to detect a key press from a > keyboard. Well I do know how to do that, but i need to detect just one > press and ignore the others. I mean, my program checks an input from the > outside (a sensor) and i emulate that signal as a keypress, but the > sensor doesn`t send the signal as a unique pulse y just keeps sending > signal during some seconds, so that is like to be pressing one key for a > period of time. How can i take that first press of a key and ignore the > others? I am using pygtk. thanks everybody! Perhaps you could emulate the sensor-signal as something else than a keypress, perhaps pipe the event-data into some temporary file or so. H. From http Mon Apr 9 00:03:19 2007 From: http (Paul Rubin) Date: 08 Apr 2007 21:03:19 -0700 Subject: Crypto Suggestion/Help References: Message-ID: <7xveg68a9k.fsf@ruckus.brouhaha.com> Jimmy E Touma writes: > I need some advise on doing the following. I have a Linux application > that allows users to access it via a code (password). At the end of the > day, I gather a log of activities of the users and zip the file and > would like to encrypt it so that the users can not access it or tamper > with it. Only manager should. If I use a private/public key for doing so > I have to store the private key on my computer. What is a good way to > encrypt a file and have the key well hidden on the same computer? If you > have any other way to do, like MD5 or similar, please let me know. Are you saying you have a desktop app that's running on the user's own machine and you're trying to prevent the user from getting at the log data? That is impossible if the user has control over the machine and is willing and able to hack the software. If you just want to make an encrypted file that the user can't decrypt, use a public key on the user's machine, and only have the secret key on the manager's machine. From C.delete_this.Sanders at BoM.GOv.AU Thu Apr 19 23:31:36 2007 From: C.delete_this.Sanders at BoM.GOv.AU (Charles Sanders) Date: Fri, 20 Apr 2007 13:31:36 +1000 Subject: Compare regular expressions In-Reply-To: References: Message-ID: <46283419$0$75706$c30e37c6@lon-reader.news.telstra.net> Thomas Dybdahl Ahle wrote: > Hi, I'm writing a program with a large data stream to which modules can > connect using regular expressions. > > Now I'd like to not have to test all expressions every time I get a line, > as most of the time, one of them having a match means none of the others > can have so. Not what you want, and would be a LOT of work, but if I remember correctly (from university more than 20 years ago) there is an algorithm that could be adapted to return a list of all the regular expressions that match a string. I thing the base algorithms were documented in Aho and Ullman ("The Dragon book" if I remember correctly). There was one for converting a regular expression into a Non-deterministic Finite-state Automaton, and another for converting the NFA to a Deterministic Finite-state Automaton. The book mentioned that this also handles multiple regular expressions which can be treated as the sub-expressions combined using the or operator. Other, newer books on compiler design would probably contain similar information in their sections on lexical analysis. The algorithm given (if my memory is correct) only handled the case where a true/false match/no-match result was required, but mentioned how to generalise it to return which of several expressions separated by or operators was matched. I think an additional generalisation to return a set of matches rather than one would be relatively straight-forward. I believe these algorithms are the basis of lex/flex and similar utilities, as well as the regular expression handling of many languages. Of course, I would like to emphasise that all this is based on memory of university courses more than 20 years ago, so the details could be wrong. Charles From bernhard.voigt at gmail.com Tue Apr 3 07:11:45 2007 From: bernhard.voigt at gmail.com (bernhard.voigt at gmail.com) Date: 3 Apr 2007 04:11:45 -0700 Subject: Numeric compiling problem under QNX 4.25 In-Reply-To: <1175578324.426293.21970@y80g2000hsf.googlegroups.com> References: <1175578324.426293.21970@y80g2000hsf.googlegroups.com> Message-ID: <1175598705.298670.39960@b75g2000hsg.googlegroups.com> Hi, unfortunately I don't have a solution. However, if you're not forced to use Python2.2 and Numeric you should use Numpy (the successor for both, Numeric and Numarray). Numpy requires Python2.3, though. Bernhard On Apr 3, 7:32 am, "ZMY" wrote: > Dear all, > > I am a real newbie for both python and QNX, but I am still trying to > compile Numeric-24.2 under QNX4.25 with python 2.2. I got following > error message: > > $ sudo python setup.py install > Password: > running install > ... > building '_numpy' extension > skipping Src/_numpymodule.c (build/temp.qnx-O-PCI-2.2/_numpymodule.o > up-to-date) > skipping Src/arrayobject.c (build/temp.qnx-O-PCI-2.2/arrayobject.o up- > to-date) > skipping Src/ufuncobject.c (build/temp.qnx-O-PCI-2.2/ufuncobject.o up- > to-date) > ld build/temp.qnx-O-PCI-2.2/_numpymodule.o build/temp.qnx-O-PCI-2.2/ > arrayobject.o build/temp.qnx-O-PCI-2.2/ufuncobject.o -o build/lib.qnx- > O-PCI-2.2/_numpy.so > unable to execute ld: No such file or directory > error: command 'ld' failed with exit status 1 > > I looked at directory /build/temp.qnx-O-PCI-2.2/ and found following > object files: > > _numpymodule.o, arrayobject.o, ufuncobject.o > > So it looks that ld got all files before linking them - or is it?? > > Thanks a lot for any suggestions, > > - ZMY From steve at holdenweb.com Tue Apr 3 12:43:17 2007 From: steve at holdenweb.com (Steve Holden) Date: Tue, 03 Apr 2007 12:43:17 -0400 Subject: getattr/setattr q. In-Reply-To: <4NSdnWz849OSHo_bnZ2dnUVZ_s_inZ2d@comcast.com> References: <1175573213.682671@jubilee.claranet.pt> <1175614741.823795@jubilee.claranet.pt> <4NSdnWz849OSHo_bnZ2dnUVZ_s_inZ2d@comcast.com> Message-ID: Steven Bethard wrote: > Steve Holden wrote: >> You don't need setattr/getattr if you know in advance the name of the >> attribute you need to access and you can get a reference to the object >> whose attribute it is. So: >> >> >>> x = "Hello, Paulo" >> >>> import sys >> >>> sys.modules['__main__'].x >> 'Hello, Paulo' > > a.k.a > > >>> import __main__ > >>> __main__.x > 'Hello, Paulo' > Indeed. Any handle on the right object will do. 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 Thu Apr 12 15:03:44 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: 12 Apr 2007 12:03:44 -0700 Subject: wxPython, mac, wx.HSCROLL not working In-Reply-To: <1176392605.298630.8210@y5g2000hsa.googlegroups.com> References: <1176364597.741079.25840@n59g2000hsh.googlegroups.com> <586qvsF2fbq3rU1@mid.individual.net> <1176392605.298630.8210@y5g2000hsa.googlegroups.com> Message-ID: <1176404623.968720.118370@e65g2000hsc.googlegroups.com> On Apr 12, 9:43 am, kyoso... at gmail.com wrote: > On Apr 12, 8:37 am, Bjoern Schliessmann > > > mail-0306.20.chr0n... at spamgourmet.com> wrote: > > 7stud wrote: > > > I'm trying to allow for a horizontal scrollbar on a textarea, but > > > the scrollbar won't appear when I enter a long string of text(by > > > leaning on one character on my keyboard): > > > Works for me (Linux, self-built Python 2.5 and wxPython 2.8.3.0). > > > Regards, > > > Bj?rn > > > -- > > BOFH excuse #285: > > > Telecommunications is upgrading. > > This works for me too. I'm using Python 2.4, Windows XP Pro, wxPython > 2.6. > > You may want to post this to the wxpython users group list. It could > be a Mac-specific bug. > > Mike For the record, I'm using an intel mac, python 2.4.4, and wxPython2.8-osx-unicode-2.8.3.0-universal10.4-py2.4.dmg From wangday at gmail.com Wed Apr 4 09:15:18 2007 From: wangday at gmail.com (lancered) Date: 4 Apr 2007 06:15:18 -0700 Subject: An error of matrix inversion using NumPy Message-ID: <1175692518.282887.3040@y66g2000hsf.googlegroups.com> Hi dear all, I am using Python2.4.2+NumPy1.0.1 to deal with a parameter estimation problem with the least square methods. During the calculations, I use NumPy package to deal with matrix operations, mostly matrix inversion and trasposition. The dimentions of the matrices used are about 29x19,19x19 and 29x29. During the calculation, I noticed an apparent error of inverion of a 19x19 matrix. Denote this matrix as KK, U=KK^ -1, I found the product of U and KK is not equivalent to unit matrix! This apparently violate the definition of inversion. The inversion is through the function linalg.inv(). I have checked that det(KK)=-1.2E+40. At first, I thought the error may be caused by such a large determinant, so I scaled it as LL=KK/100, then invert LL. Since det(LL)=11.5 and all its elements are within -180.0 to 850.0, this seems easier. But the result is still not correct, the product of LL^-1 thus obtained and LL still not unit matrix ... At the same time, the inversion results of some 29x19 matrices are correct. So, can you tell me what goes wrong? Is this a bug in Numpy.linalg? How to deal with this situation? If you need, I can post the matrix I used below, but it is so long,so not at the moment. Thanks in advance! From hlubenow2 at gmx.net Wed Apr 18 14:59:40 2007 From: hlubenow2 at gmx.net (hlubenow) Date: Wed, 18 Apr 2007 20:59:40 +0200 Subject: Compiling python from soruce vs RPM ? References: <1176911689.026633.230390@l77g2000hsb.googlegroups.com> Message-ID: howa wrote: > I have compiled python 2.5 from source > > i.e. > > ./configure > make > make install > > > but when i try to install another package require python, seems it > can't regonize python... > > e.g.. > > > /usr/bin/python is needed by xyz Does "/usr/bin/python" exist ? Why haven't you installed via rpm ? H. From robert.rawlins at thinkbluemedia.co.uk Tue Apr 24 12:40:33 2007 From: robert.rawlins at thinkbluemedia.co.uk (Robert Rawlins - Think Blue) Date: Tue, 24 Apr 2007 17:40:33 +0100 Subject: If Dict Contains... Message-ID: <001201c7868f$47620540$d6260fc0$@rawlins@thinkbluemedia.co.uk> Hello Guys, Looking to build a quick if/else statement that checks a dictionary for a key like follows. If myDict contains ThisKey: Do this... Else Do that... Thats the best way of doing this? Thanks, Rob -------------- next part -------------- An HTML attachment was scrubbed... URL: From gherron at islandtraining.com Sat Apr 7 12:16:48 2007 From: gherron at islandtraining.com (Gary Herron) Date: Sat, 07 Apr 2007 09:16:48 -0700 Subject: Checking whether list element exists In-Reply-To: References: Message-ID: <4617C3F0.7020101@islandtraining.com> Rehceb Rotkiv wrote: > I want to check whether, for example, the element myList[-3] exists. So > far I did it like this: > > index = -3 > if len(myList) >= abs(index): > print myList[index] > > Another idea I had was to (ab-?)use the try...except structure: > > index = -3 > try: > print myList[index] > except: > print "Does not exist!" > A try...except is a perfectly valid way to make the test. However, the printing of the result is not necessary, and a "naked" except, as you have, is very dangerous programming practice. That form of the except will catch ANY error and end up printing "Does not exist!", even errors that have nothing to do with what you're intending to test. For instance, if you mistype the myList[index] as myList[indx] or mylist[indx] an exception would be raised and caught by your except clause. Or if you hit a keyboard control-c at exactly the right time, the resulting SystemExit exception would also be caught by your except clause. A good programming practice would be to ALWAYS catch only the specific exception you want, and let any other's be reported as the errors they are: try: myList[index] except IndexError: ...whatever... Gary Herron > Is it ok to use try...except for the test or is it bad coding style? Or > is there another, more elegant method than these two? > > Regards, > Rehceb > From goodTweetieBird at hotmail.com Tue Apr 3 09:21:37 2007 From: goodTweetieBird at hotmail.com (gtb) Date: 3 Apr 2007 06:21:37 -0700 Subject: Finding and copying files with python. Message-ID: <1175606497.896681.119490@l77g2000hsb.googlegroups.com> I wish to copy the highest version number of a file from directory \ \ \fileserver\D:\scripts to C:\scripts where the file names are of the form filename_MM.NN.SS.zip, where MM, NN, and SS can be one to three digits. Example directory: other.zip dx_ver_1.1.63.zip dx_ver_1.2.01.zip dx_ver_1.12.7.zip temp.txt Does python have string matching routines that would find the bottom listed zip file and/or file copying routines? A little pointer or two would be much appreciated. Thanks, jh From michael at jedimindworks.com Sun Apr 15 23:48:33 2007 From: michael at jedimindworks.com (Michael Bentley) Date: Sun, 15 Apr 2007 22:48:33 -0500 Subject: how to strip the domain name in python? In-Reply-To: <19C3B41E-B67E-4A9B-8FC2-1222EF25F1AD@jedimindworks.com> References: <1176526155.679721.159870@l77g2000hsb.googlegroups.com> <1176564977.498635.171600@n59g2000hsh.googlegroups.com> <1176654669.737355.78300@y5g2000hsa.googlegroups.com> <1176672270.932679.283230@d57g2000hsg.googlegroups.com> <19C3B41E-B67E-4A9B-8FC2-1222EF25F1AD@jedimindworks.com> Message-ID: <53095E38-E8F4-4C4F-9318-AD7B3659F240@jedimindworks.com> On Apr 15, 2007, at 7:57 PM, Michael Bentley wrote: > if net_location[0].lower() == 'www': > net_location = net_location[1:] It is not guaranteed that the host name will be 'www' though, is it? If you *really* want to strip the host portion of a domain name, I suppose you could make calls to whois until you get a match. For instance, a whois lookup on www.cnn.com will not find a match while a lookup on cnn.com will. hth, Michael From jjl at pobox.com Wed Apr 11 16:51:47 2007 From: jjl at pobox.com (John J. Lee) Date: Wed, 11 Apr 2007 20:51:47 GMT Subject: Getting Stack Trace on segfault References: Message-ID: <87fy767hxz.fsf@pobox.com> James Stroud writes: > Hello All, > > The built-in mac osx vecLib is segfaulting in some cases--A very fun > fact to find out the hard way over two nights of work. I also spent an > embarrassing amount of time figuring out just where. Although I'm in > quite a self-congratulatory mood right now, in the future, I feel like > I could save a lot of time by coercing the interpreter to spew forth > method calls to stderr. Is this possible? > > > I would hope to produce something hauntingly reminiscent of > > [] my_function > [my_function] another_function > [my_function -> another_function] yet_a_deeper_function [...] I remember David Beazley (of SWIG fame) wrote something called WAD that claimed to turn segfaults into Python exceptions (hence tracebacks). IIRC it was Linux-specific, and I have no idea how it worked. I guess it could be ported to Windows with SEH, but no idea about OS X. John From pavlovevidence at gmail.com Wed Apr 11 20:35:13 2007 From: pavlovevidence at gmail.com (Carl Banks) Date: 11 Apr 2007 17:35:13 -0700 Subject: pop() clarification In-Reply-To: <1176318615.056436.47430@y5g2000hsa.googlegroups.com> References: <1176318615.056436.47430@y5g2000hsa.googlegroups.com> Message-ID: <1176338113.035908.52880@b75g2000hsg.googlegroups.com> On Apr 11, 3:10 pm, "7stud" wrote: > On Apr 11, 10:44 am, "Scott" wrote: > > > > > As said before I'm new to programming, and I need in depth explaination to > > understand everything the way I want to know it, call it a personality quirk > > ;p. > > > With pop() you remove the last element of a list and return its value: > > > Now I know list is a bad name, but for the sake of arguement lets assume its > > not a built in sequence> > > > >>>list = ['this', 'is', 'an', 'example'] > > >>>list.pop() > > 'example' > > >>>list > > > ['this', 'is', 'an'] > > > I understand all that. What I don't understand is why all the documentation > > I see says, "When removing a specific element from a list using pop() it > > must be in this format: list.pop([i]). > > At first I took that to mean that list.pop(i) would return some type of > > error, but it doesn't. > > It's understandable that the definition of pop() is confusing in that > way. It looks like the argument should be a list. As others have > said, that is not what the brackets mean when the documents show the > formal definition of a function. I wonder if the documentation could take advantage of Python 3000 annotation syntax. So pop([x]) would be replaced in the docs by pop(x: OPTIONAL) Just a thought, probably not a good one. The brackets are so pervasive that it's probably better to just let newbies be confused for a little bit. Carl Banks From boyee118 at gmail.com Fri Apr 6 05:05:17 2007 From: boyee118 at gmail.com (boyeestudio) Date: Fri, 6 Apr 2007 17:05:17 +0800 Subject: How to fix this? Sybase module and character set!!!! Message-ID: C:\>python msMdbPro2.py Traceback (most recent call last): File "msMdbPro2.py", line 152, in ? main() File "msMdbPro2.py", line 132, in main testSyb = SybaseProc(199477,'10.130.58.154','sa','','zxdb_ecity',173624) File "msMdbPro2.py", line 44, in __init__ self.sybdata = Sybase.connect(hostip,user,pwd,databasename) File "C:\Python24\lib\site-packages\Sybase.py", line 1087, in connect strip, auto_commit, delay_connect, locking, datetime) File "C:\Python24\lib\site-packages\Sybase.py", line 866, in __init__ self.connect() File "C:\Python24\lib\site-packages\Sybase.py", line 960, in connect status = conn.ct_connect(self.dsn) File "C:\Python24\lib\site-packages\Sybase.py", line 200, in _servermsg_cb raise DatabaseError(_fmt_server(msg)) Sybase.DatabaseError: Msg 2401, Level 11, State 2 Character set conversion is not available between client character set 'iso_1' and server character set 'eucgb'. Msg 2411, Level 10, State 1 No conversions will be done. Msg 2415, Level 10, State 1 Due to previous errors, the language for this session is being forced to 'us_english'. How to change the client(My python program)'s character set from iso_1 to eucgb(Chinese gb2312)? Thanks! -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at holdenweb.com Tue Apr 24 07:18:53 2007 From: steve at holdenweb.com (Steve Holden) Date: Tue, 24 Apr 2007 07:18:53 -0400 Subject: Does socket.setdefaulttimeout affect the timeouts in MySQLdb? In-Reply-To: References: Message-ID: John Nagle wrote: > Does setting "socket.setdefaulttimeout" affect the timeout in MySQLdb > for connections to the database? I'm getting database connection timeouts on > a local (same machine) connnection, and I've been setting > "socket.setdefaulttimeout" to 15 seconds so web page opens don't hang. > But MySQLdb uses the MySQL C library, which doesn't use Python opens. > So that would be a "no", then. regards Steve -- Steve Holden +1 571 484 6266 +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 irstas at gmail.com Mon Apr 2 12:37:54 2007 From: irstas at gmail.com (irstas at gmail.com) Date: 2 Apr 2007 09:37:54 -0700 Subject: RSS feed parser In-Reply-To: References: Message-ID: <1175531874.535702.212510@n76g2000hsh.googlegroups.com> On Apr 2, 7:22 pm, Florian Lindner wrote: > Hello, > I'm looking for python RSS feed parser library. Feedparserhttp://feedparser.org/does not seem to maintained anymore. > > What alternatives are recommendable? > > Thanks, > > Florian Well, even if it's not maintained anymore (where does it say that?), it works fine and the API is great. Although of course I do realize that when a new version of RSS appears, feedparser won't be able to support it unless someone updates it. But RSS 2.0 appeared already in 2002 and no new versions have come since. So I wouldn't worry too much about new RSSs popping up every month. Maybe the feedparser code hasn't been updated in a while because it's already perfect and there's nothing to add to it?-) From steve at REMOVE.THIS.cybersource.com.au Sat Apr 14 21:30:21 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Sun, 15 Apr 2007 11:30:21 +1000 Subject: That might be the case for more complex objects... References: <1176546078.934340.253810@y5g2000hsa.googlegroups.com> <1176557734.456820.275780@p77g2000hsh.googlegroups.com> <7saUh.37$4S1.2@newsfe12.lga> Message-ID: On Sat, 14 Apr 2007 16:03:03 -0400, Bart Willems wrote: > I can try this in interactive mode: > >>> a = 5 > >>> b = a > >>> a += 1 > >>> print b > 5 > > So, if /a/ and /b/ where pointing to the *same* "5" in memory, then I > would expect b to be increased, just as a. This is what you are implicitly _thinking_: "a" points to a memory location, holding a few bytes with the bit pattern 0x05. When I add 1 to it, the bytes change to 0x06. But integers in Python aren't bit patterns, they are objects. You can't make the 5 object have value 6, that would be terrible: py> 5 + 5 # remember that 5 has been changed to have value six! 12 So a += 1 rebinds the name "a" to the object 6. The name "b" still points to the object 5, because you didn't do anything to "b". Now, for extra credit: can you explain why this happens? >>> alist = [0] >>> blist = alist >>> alist += [1] >>> blist [0, 1] -- Steven. From bj_666 at gmx.net Mon Apr 16 02:05:29 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Mon, 16 Apr 2007 08:05:29 +0200 Subject: How to initialize a table of months. References: Message-ID: In , Steven W. Orr wrote: > I want to call datetime.datetim() whose arg2 is a number between 1-12 so I > have to convert the month to an integer. > I wrote this, but I have a sneaky suspicion there's a better way to do it. > > mons = {'Jan':1, 'Feb':2, 'Mar':3, 'Apr':4, 'May':5, 'Jun':6, > 'Jul':7, 'Aug':8, 'Sep':9, 'Oct':10, 'Nov':11, 'Dec':12 } > > def mon2int( mon ): > global mons > return mons[mon] You've already got some answers, I just want to point out that the ``global`` is unnecessary here and that `mons` as a constant should be spelled in capital letters by convention. And maybe it's better to write `MONTHS` instead the abbreviation. Ciao, Marc 'BlackJack' Rintsch From vizcaynot at gmail.com Sat Apr 7 10:44:35 2007 From: vizcaynot at gmail.com (asker) Date: 7 Apr 2007 07:44:35 -0700 Subject: What happened to http://www.pythonware.com/daily and http://mechanicalcat.net/pyblagg.html? Message-ID: <1175957075.056246.15120@l77g2000hsb.googlegroups.com> These sites are not updated since almost one month. Does anybody knows why? From marcpp at gmail.com Thu Apr 12 06:34:44 2007 From: marcpp at gmail.com (Marcpp) Date: 12 Apr 2007 03:34:44 -0700 Subject: Pyqt programming question In-Reply-To: <1176372437.336751.75840@d57g2000hsg.googlegroups.com> References: <1176369822.364743.243700@n76g2000hsh.googlegroups.com> <1176372437.336751.75840@d57g2000hsg.googlegroups.com> Message-ID: <1176374084.884158.27800@w1g2000hsg.googlegroups.com> On 12 abr, 12:07, "Marcpp" wrote: > On 12 abr, 11:48, Phil Thompson wrote: > > > On Thursday 12 April 2007 10:23 am, Marcpp wrote: > > > > I have a program (python + pyqt), with a button I'll would to open a > > > new dialog window to input text, when press save or ok, this text is > > > returned to the principal program. > > > I've seek in internet but i don't find anything. > > > Use QInputDialog.getText() > > > Phil > > I can't do it, have you any example? > Thank you. I've created a personal dialog. From arnodel at googlemail.com Sun Apr 29 12:48:46 2007 From: arnodel at googlemail.com (Arnaud Delobelle) Date: 29 Apr 2007 09:48:46 -0700 Subject: While we're talking about annoyances In-Reply-To: <7x1wi3dtsq.fsf@ruckus.brouhaha.com> References: <7x1wi3dtsq.fsf@ruckus.brouhaha.com> Message-ID: <1177865326.575336.116910@n76g2000hsh.googlegroups.com> On Apr 29, 5:33 pm, Paul Rubin wrote: > Steven D'Aprano writes: > > I recently needed to write a function to generate a rank table from a > > list. That is, a list of ranks, where the rank of an item is the position > > it would be in if the list were sorted: > > > alist = list('defabc') > > ranks = [3, 4, 5, 0, 1, 2] > > fst = operator.itemgetter(0) # these should be builtins... > snd = operator.itemgetter(1) > > ranks=map(fst, sorted(enumerate(alist), key=snd)) This is what the OP calls the index table, not the ranks table (both are the same for the example above, but that's an unfortunate coincidence...) -- Arnaud From malkarouri at gmail.com Wed Apr 11 17:22:43 2007 From: malkarouri at gmail.com (malkarouri at gmail.com) Date: 11 Apr 2007 14:22:43 -0700 Subject: run function in separate process In-Reply-To: <1hweao8.1t99a5vdqygvbN%aleax@mac.com> References: <1176301427.183706.321920@n76g2000hsh.googlegroups.com> <1hweao8.1t99a5vdqygvbN%aleax@mac.com> Message-ID: <1176326563.927966.299320@l77g2000hsb.googlegroups.com> After playing a little with Alex's function, I got to: import os, cPickle def run_in_separate_process_2(f, *args, **kwds): pread, pwrite = os.pipe() pid = os.fork() if pid > 0: os.close(pwrite) with os.fdopen(pread, 'rb') as f: status, result = cPickle.load(f) os.waitpid(pid, 0) if status == 0: return result else: raise result else: os.close(pread) try: result = f(*args, **kwds) status = 0 except Exception, exc: result = exc status = 1 with os.fdopen(pwrite, 'wb') as f: try: cPickle.dump((status,result), f, cPickle.HIGHEST_PROTOCOL) except cPickle.PicklingError, exc: cPickle.dump((2,exc), f, cPickle.HIGHEST_PROTOCOL) f.close() os._exit(0) It handles exceptions as well, partially. Basically the child process returns a status code as well as a result. If the status is 0, then the function returned successfully and its result is returned. If the status is 1, then the function raised an exception, which will be raised in the parent. If the status is 2, then the function has returned successfully but the result is not picklable, an exception is raised. Exceptions such as SystemExit and KeyboardInterrupt in the child are not checked and will result in an EOFError in the parent. Any comments? Regards, Muhammad From brzrkr0 at gmail.com Wed Apr 4 15:47:49 2007 From: brzrkr0 at gmail.com (brzrkr0 at gmail.com) Date: 4 Apr 2007 12:47:49 -0700 Subject: Newbie - needs help In-Reply-To: <1175635684.420398.101540@n59g2000hsh.googlegroups.com> References: <1175632937.838422.236850@y66g2000hsf.googlegroups.com> <1175635684.420398.101540@n59g2000hsh.googlegroups.com> Message-ID: <1175716069.820892.18170@d57g2000hsg.googlegroups.com> On Apr 3, 4:28 pm, "7stud" wrote: > "Learning Python" can be purchased at amazon.com. Or, not as good: > "Beginning Python: From Novice to Professional". If you get the > second one, you'll need "Python in a Nutshell: A Desktop Quick > Reference" to fill in all the gaps. If you already have experience with other programming languages, I think you might find that "Learning Python" is a bit too beginner- oriented. "Dive into Python" is probably a better choice for a first reading, IMO. From howe.steven at gmail.com Wed Apr 25 12:41:28 2007 From: howe.steven at gmail.com (Steven Howe) Date: Wed, 25 Apr 2007 09:41:28 -0700 Subject: Python not giving free memory back to the os get's me in real problems ... In-Reply-To: <132uv54ncsspm91@corp.supernews.com> References: <1177510121.882503.145560@n15g2000prd.googlegroups.com> <_LidnenBcrz7-rLbnZ2dnUVZ_tCtnZ2d@comcast.com> <59990rF2ja6c7U3@mid.dfncis.de> <132uv54ncsspm91@corp.supernews.com> Message-ID: <462F84B8.9040001@gmail.com> Grant Edwards wrote: > On 2007-04-25, Chris Mellon wrote: > > >> "Returning memory to the OS" doesn't affect exhaustion of your virtual >> address space. More likely, your nested loops are just creating more >> objects than is possible to hold within a single process. >> > > I'm a bit fuzzy on this, but I don't think there _is_ a > practical way to "return memory to the OS" in many OSes. For > example in Unix the C library uses the sbrk() call to increase > the size of the data segment when additional memory is needed > to handle soemthing like malloc() calls. > > In theory, one can use brk() to reduce the size of the data > segment, but I think making the segment smaller will produce > undefined behavior if any of the standard C library's dynamic > memory routines (e.g. malloc/free) have ever been used by the > program prior to the call to brk(). > > Interesting questions. What happens when an object is 'cleaned' up by using the 'del' command. Does the memory space stay in the python process, get handed back to the OS, or some combination of both? I remember 'C' on VMS at least, could be coerced into return memory on block boundaries. 'C++' was suppose to have garbage collect, but I was always doubtful it worked well. sph From whamil1 at entergy.com Wed Apr 11 09:01:55 2007 From: whamil1 at entergy.com (Hamilton, William ) Date: Wed, 11 Apr 2007 08:01:55 -0500 Subject: tuples, index method, Python's design In-Reply-To: Message-ID: <588D53831C701746A2DF46E365C018CE01D2CA6B@LITEXETSP001.etrsouth.corp.entergy.com> > -----Original Message----- > From: python-list-bounces+whamil1=entergy.com at python.org [mailto:python- > list-bounces+whamil1=entergy.com at python.org] On Behalf Of Steven D'Aprano > Sent: Wednesday, April 11, 2007 7:49 AM > To: python-list at python.org > Subject: Re: tuples, index method, Python's design > > (There is one other option: you care that 32 is somewhere in the tuple, > but you don't care where. That's when you use the "in" operator.) > > Anyway, that was the original design. When you see tuple, think struct. If > you have a struct, it doesn't make a whole lot of sense to ask "which > field contains 32?", and so according to this intended usage, giving > tuples index and count methods would be a Bad Idea: it just makes extra > work for the Python Dev team, for no benefit. > > Personally, I think that tuples do double-duty as *both* immutable lists > and structs/records. So even though index and count methods don't make > sense for a struct, it does make sense for an immutable list, and I for > one would not object to seeing tuples grow those two methods. >From another function, you receive a tuple of data that it extracted from a stream. Within that tuple is a marker that indicates where the head of the incoming stream's data structure is. You need to find the marker and scan from that location on to sync your local data structure to the incoming stream's data. Should the external function provide the stream data in a list rather than a tuple? Probably, but someone else wrote the function so that's out of your control. Can you cast the tuple to a list? Sure, but for a large tuple that's potentially a large speed and memory hit. That probably the biggest general use case for tuple.index(). A third-party module returns a tuple in which you need to find a piece of data. --- -Bill Hamilton whamil1 at entergy.com From anthonydevine69 at hotmail.com Sat Apr 7 08:24:31 2007 From: anthonydevine69 at hotmail.com (tonydevlin) Date: Sat, 7 Apr 2007 05:24:31 -0700 (PDT) Subject: Automated email response Message-ID: <9883575.post@talk.nabble.com> I currently have the python code obj=sti.object creator = obj.Creator() history = sti.getHistory() wf_tool = context.portal_workflow mMsg = """ Content has been submitted for your review. The url was %s. The reason was %s. """ member = context.portal_membership.getMemberById(creator) creator = {'member':member, 'id':member.getId(), 'fullname':member.getProperty('fullname', 'Fullname missing'), 'email':member.getProperty('email', None)} actorid = wf_tool.getInfoFor(obj, 'actor') actor = context.portal_membership.getMemberById(actorid) reviewer = {'member':actor, 'id':actor.getId(), 'fullname':actor.getProperty('fullname', 'Fullname missing'), 'email':actor.getProperty('email', None)} mTo = reviewer['email'] mFrom = creator['email'] mSubj = 'Your item has transitioned' obj_url = obj.absolute_url() #use portal_url + relative_url comments = wf_tool.getInfoFor(obj, 'comments') message = mMsg % (obj_url, comments) context.MailHost.send(message, mTo, mFrom, mSubj) This is attached to a transitions in a workflow and when a user selects the transition they are emailed. I want it to email all of the users or selected members like managers. How would I go about changing the above code to do that? I have tried the following code from the definitve guide to plone book, but it does not have any effect on my workflow and does not email anyone. Is there something that I need to change on my setting possibly in Plone to get the email response working, I have set up my mailhost and this works because when I add a new user it emails them. # the objects we need object = state_change.object mship = context.portal_membership mhost = context.MailHost administratorEmailAddress = context.email_from_address # the message format, %s will be filled in from data message = """ From: %s To: %s Subject: New item submitted for approval - %s %s URL: %s """ for user in mship.listMembers(): if "Reviewer" in mship.getMemberById(user.id).getRoles(): if user.email: msg = message % ( administratorEmailAddress, user.email, object.TitleOrId(), object.Description(), object.absolute_url() ) mhost.send(msg) -- View this message in context: http://www.nabble.com/Automated-email-response-tf3540615.html#a9883575 Sent from the Python - python-list mailing list archive at Nabble.com. From bbxx789_05ss at yahoo.com Thu Apr 19 23:13:01 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: 19 Apr 2007 20:13:01 -0700 Subject: List of Objects In-Reply-To: <1177037915.042476.153190@n76g2000hsh.googlegroups.com> References: <1177037915.042476.153190@n76g2000hsh.googlegroups.com> Message-ID: <1177038781.794424.43980@p77g2000hsh.googlegroups.com> datamonkey.r... at gmail.com wrote: > > However, Python doesn't support pointers As I understand it, every name in Python is a pointer. class Gazelle(object): def __init__(self): self.x = 0 g_list =[] for x in range(10): g_list.append(Gazelle()) for g in g_list: g.x = 10 print g_list[2].x From arnodel at googlemail.com Sun Apr 29 10:30:50 2007 From: arnodel at googlemail.com (Arnaud Delobelle) Date: 29 Apr 2007 07:30:50 -0700 Subject: While we're talking about annoyances In-Reply-To: References: <1177837565.317999.244420@c35g2000hsg.googlegroups.com> Message-ID: <1177857049.938363.166170@p77g2000hsh.googlegroups.com> On Apr 29, 11:46 am, Michael Hoffman wrote: > GHUM wrote: > > Steven, > > >> def index(sequence): > >> decorated = zip(sequence, xrange(len(sequence))) > >> decorated.sort() > >> return [idx for (value, idx) in decorated] > > > would'nt that be equivalent code? > > > def index(sequence): > > return [c for _,c in sorted((b,a) for a, b in > > enumerate(sequence))] > > Or even these: > > def index(sequence): > return sorted(range(len(sequence)), key=sequence.__getitem__) > > def rank(sequence): > return sorted(range(len(sequence)), > key=index(sequence).__getitem__) Better still: def rank(sequence): return index(index(sequence)) :) But really these two versions of rank are slower than the original one (as sorting a list is O(nlogn) whereas filling a table with precomputed values is O(n) ). Anyway I would like to contribute my own index function: def index(seq): return sum(sorted(map(list,enumerate(seq)), key=list.pop), []) It's short and has the advantage of being self-documenting, which will save Steven a lot of annoying typing I hope ;) Who said Python couldn't rival with perl? -- Arnaud From wyldwolf at gmail.com Fri Apr 13 09:15:56 2007 From: wyldwolf at gmail.com (Kevin Kelley) Date: Fri, 13 Apr 2007 08:15:56 -0500 Subject: "Cloning" file attributes and permissions In-Reply-To: <77895c1d0704130539o5e516e1ds67da360d6527bd5b@mail.gmail.com> References: <1176394818.428367@jubilee.claranet.pt> <1176406707.711609.211110@q75g2000hsh.googlegroups.com> <1176419326.395692@jubilee.claranet.pt> <1176423552.199317.129400@n59g2000hsh.googlegroups.com> <1176423910.777066.45850@y80g2000hsf.googlegroups.com> <1176434728.43319@jubilee.claranet.pt> <77895c1d0704130539o5e516e1ds67da360d6527bd5b@mail.gmail.com> Message-ID: <77895c1d0704130615m61516f41j899172f57404af4c@mail.gmail.com> This is what I (just now) put together as an example: from os import stat,mknod,chown def match_perms(org_fname,new_fname): # Get information on old file st = stat(org_fname) st_mode = st.st_mode st_uid = st.st_uid st_gid = st.st_gid # Create the new file mknod(new_fname,st_mode) # Matching permissions chown(new_fname,st_uid,st_gid) if __name__ == "__main__": match_perms('old_filename','new_filename') On 4/13/07, Kevin Kelley wrote: > > If you know what the permissions are going to be then you can use umask to > set the default file creation permissions to match. Then any files created > in that directory will have the correct permissions. > > I think the "pythonic" way to solve this problem would be to code up your > own module which handles all the dirty parts in the background. It would > create the new file, stat the original, and chmod/chown the new file as > needed to match the original. All you would have to do after creating the > module is pass the new function the original and new file information. > > -- > Kevin Kelley > > On 4/12/07, Paulo da Silva wrote: > > > > attn.steven.kuo at gmail.com escreveu: > > > On Apr 12, 5:19 pm, attn.steven.... at gmail.com wrote: > > >> On Apr 12, 4:09 pm, Paulo da Silva > > wrote: > > >> > > ... > > > > > > After poking around a bit I also discovered the > > > shutil module. It looks like you can use > > > shutil.copy2. More Pythonic, yes? > > > > > > > > > I have seen that in the index but I thought it was a different thing > > because it was referenced as "high-level operations". > > Anyway that helps but I still need to copy the whole file or to use stat > > and chown for the user/group ids. > > > > -- > > http://mail.python.org/mailman/listinfo/python-list > > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From malkarouri at gmail.com Wed Apr 11 10:23:47 2007 From: malkarouri at gmail.com (malkarouri at gmail.com) Date: 11 Apr 2007 07:23:47 -0700 Subject: run function in separate process Message-ID: <1176301427.183706.321920@n76g2000hsh.googlegroups.com> Hi everyone, I have written a function that runs functions in separate processes. I hope you can help me improving it, and I would like to submit it to the Python cookbook if its quality is good enough. I was writing a numerical program (using numpy) which uses huge amounts of memory, the memory increasing with time. The program structure was essentially: for radius in radii: result = do_work(params) where do_work actually uses a large number of temporary arrays. The variable params is large as well and is the result of computations before the loop. After playing with gc for some time, trying to convince it to to release the memory, I gave up. I will be happy, by the way, if somebody points me to a web page/reference that says how to call a function then reclaim the whole memory back in python. Meanwhile, the best that I could do is fork a process, compute the results, and return them back to the parent process. This I implemented in the following function, which is kinda working for me now, but I am sure it can be much improved. There should be a better way to return the result that a temporary file, for example. I actually thought of posting this after noticing that the pypy project had what I thought was a similar thing in their testing, but they probably dealt with it differently in the autotest driver [1]; I am not sure. Here is the function: def run_in_separate_process(f, *args, **kwds): from os import tmpnam, fork, waitpid, remove from sys import exit from pickle import load, dump from contextlib import closing fname = tmpnam() pid = fork() if pid > 0: #parent waitpid(pid, 0) # should have checked for correct finishing with closing(file(fname)) as f: result = load(f) remove(fname) return result else: #child result = f(*args, **kwds) with closing(file(fname,'w')) as f: dump(result, f) exit(0) To be used as: for radius in radii: result = run_in_separate_process (do_work, params) [1] http://codespeak.net/pipermail/pypy-dev/2006q3/003273.html Regards, Muhammad Alkarouri From bbxx789_05ss at yahoo.com Wed Apr 4 13:01:11 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: 4 Apr 2007 10:01:11 -0700 Subject: heap doesn't appear to work as described In-Reply-To: References: <1175641694.226975.258820@n76g2000hsh.googlegroups.com> <17938.58082.317522.331513@montanaro.dyndns.org> <1175676343.513378.205790@y80g2000hsf.googlegroups.com> Message-ID: <1175706069.736313.237090@d57g2000hsg.googlegroups.com> On Apr 4, 7:05 am, s... at pobox.com wrote: > >>>> My book says that in a heap, a value at position i will be than the > >>>> values at positions 2*i and 2*i + 1. > > >> I am sure your book either uses 1-based arrays or a 0-based arrays > >> with the first not used. The need to keep these alternatives in mind > >> is an unfortunate fact of programming life. > > > My book uses lists. > > Yes, but is the first element of the list addressed as element 1 or element > 0? Here is the example: --------- from heapq import * from random import shuffle data = range(10) shuffle(data) heap = [] for n in data: heappush(heap, n) print heap heappush(heap, 0.5) print heap #my test: print heap[0] #output: 0 ------- It's from Beginning Python: Novice to Professional, which I think is a really poorly written book chock full of mistakes and ambiguous example code. From google at mrabarnett.plus.com Sat Apr 7 20:54:42 2007 From: google at mrabarnett.plus.com (MRAB) Date: 7 Apr 2007 17:54:42 -0700 Subject: block scope? In-Reply-To: References: <7xr6qwal50.fsf@ruckus.brouhaha.com> <7xtzvseqzo.fsf@ruckus.brouhaha.com> Message-ID: <1175993682.947032.42220@d57g2000hsg.googlegroups.com> On Apr 7, 8:50 am, James Stroud wrote: > Paul Rubin wrote: > > John Nagle writes: > >> In a language with few declarations, it's probably best not to > >> have too many different nested scopes. Python has a reasonable > >> compromise in this area. Functions and classes have a scope, but > >> "if" and "for" do not. That works adequately. > > > I think Perl did this pretty good. If you say "my $i" that declares > > $i to have block scope, and it's considered good practice to do this, > > but it's not required. You can say "for (my $i=0; $i < 5; $i++) { ... }" > > and that gives $i the same scope as the for loop. Come to think of it > > you can do something similar in C++. > > How then might one define a block? All lines at the same indent level > and the lines nested within those lines? > > i = 5 > for my i in xrange(4): > if i: # skips first when i is 0 > my i = 100 > if i: > print i # of course 100 > break > print i # i is between 0 & 3 here > print i # i is 5 here > > Doesn't leave a particularly bad taste in one's mouth, I guess (except > for the intended abuse). > How about something like this instead: i = 5 block: for i in xrange(4): if i: # skips first when i is 0 block: i = 100 if i: print i # of course 100 break print i # i is between 0 & 3 here print i # i is 5 here Any variable that's assigned to within a block would be local to that block, as it is in functions. From propertirumah at yahoo.com Mon Apr 9 19:40:19 2007 From: propertirumah at yahoo.com (Cindy) Date: 9 Apr 2007 16:40:19 -0700 Subject: Find Programming Job? Message-ID: <1176162019.291963.294330@n76g2000hsh.googlegroups.com> Find Your Programming Job Vacancy and resources here --> http://www.jobbankdata.com/job-programming.htm From donn at u.washington.edu Thu Apr 26 12:45:35 2007 From: donn at u.washington.edu (Donn Cave) Date: Thu, 26 Apr 2007 09:45:35 -0700 Subject: Access to raw command line? References: <1177571070.229968.155710@t39g2000prd.googlegroups.com> Message-ID: In article <1177571070.229968.155710 at t39g2000prd.googlegroups.com>, Pieter Edelman wrote: > One possible way to work around this is to get the raw command line > and do the shell expansions ourselves from within Python. Ignoring the > question of whether it is worth the trouble, does anybody know if it > is possible to obtain the raw (unexpanded) command line? If you're on VMS (well, you didn't say), you're in luck. The UNIX shell has already expanded the file globbing by the time your program starts up, but VMS leaves it to the application, with the help of a handy RMS$ function or two so it gets done in a consistent way. This allows the command line interface to interact with the user in a little more transparent way, since the input seen by the program is congruent with what the user typed in. E.g., "rename *.jpeg *.jpg" is trivial on VMS, impossible on UNIX. Donn Cave, donn at u.washington.edu From jstroud at mbi.ucla.edu Sun Apr 15 19:42:51 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Sun, 15 Apr 2007 23:42:51 GMT Subject: Getting started with python In-Reply-To: References: <1176598011.463543.96990@q75g2000hsh.googlegroups.com> <1176608302.928513.274400@y5g2000hsa.googlegroups.com> Message-ID: <%LyUh.10121$YL5.5753@newssvr29.news.prodigy.net> Gabriel Genellina wrote: > En Sun, 15 Apr 2007 10:46:54 -0300, Army1987 escribi?: > >> "Paddy" ha scritto nel messaggio >> news:1176608302.928513.274400 at y5g2000hsa.googlegroups.com... >> >>> On a different tack, from: >>> http://tickletux.wordpress.com/2007/01/24/using-fizzbuzz-to-find-developers-who-grok-coding/ >>> >>> It seems you need to learn how to write a Fizz-Buzz >>> program to get a job now-a-days :-) >> >> Something less idiotic? I took longer to type a program to do that >> than to >> figure out how to do that. > > We've used it as part of a test a few weeks ago. You'd be surprised on > how many guys couldn't write anything remotely sensible. > > --Gabriel Genellina py> for i in xrange(1,101): ... if not i % 15: ... print 'fizzbuzz' ... continue ... if not i % 5: ... print 'buzz' ... continue ... if not i % 3: ... print 'fizz' ... else: ... print i ... I typed this without so much as hitting delete. Didn't time it but I'm guessing less than 2 minutes. How much am I worth a year? (Hopefully capitalization is not important for this exercise.) James From bbxx789_05ss at yahoo.com Sat Apr 28 13:35:50 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: 28 Apr 2007 10:35:50 -0700 Subject: python function in pipe In-Reply-To: References: Message-ID: <1177781750.667445.305900@l77g2000hsb.googlegroups.com> On Apr 28, 7:37 am, Bart wrote: > Hi everyone! > > Im using module that gives errors to stderr/stdout (generated by SWIG) > Problem is that I need to parse this errors/information from module. > > os.popen3 looks nice but this executes command not function. > > Is there any solution? > > Best regards > Bart. Maybe something like this: moduleA.py: ----------- def someFunc(): print "hello" raise ValueError someFunc() ---------- import subprocess print "Main executing" try: p = subprocess.Popen(["python", "6test.py"], stdout=subprocess.PIPE, stderr=subprocess.PIPE) result = p.wait() if result == 0: print "output:", p.stdout.read() else: print "output before error:", p.stdout.read() print "error:", p.stderr.read() except (OSError, TypeError, ValueError), e: print "subprocess was never started" print e From bjourne at gmail.com Tue Apr 10 11:24:15 2007 From: bjourne at gmail.com (=?ISO-8859-1?Q?BJ=F6rn_Lindqvist?=) Date: Tue, 10 Apr 2007 17:24:15 +0200 Subject: tuples, index method, Python's design In-Reply-To: References: <1175953520.316208.241490@o5g2000hsb.googlegroups.com> <7xzm5igbrb.fsf@ruckus.brouhaha.com> <1176200361.260546.280510@n76g2000hsh.googlegroups.com> Message-ID: <740c3aec0704100824m132c45fbi5c4c3ec0c0fa3a67@mail.gmail.com> On 4/10/07, Steve Holden wrote: > Paul Boddie wrote: > > On 10 Apr, 11:48, Antoon Pardon wrote: > >> On 2007-04-10, Duncan Booth wrote: > >> > >>> There is a cost to every new language feature: it has to be implemented, > >>> documented, maintained, and above all learned by the users. Good design > >>> involves, in part, not adding to these burdens except where there is a > >>> benefit at least equal to the cost. > >> So what is the easiest to learn: "All sequences have an index method" or > >> "Such and so sequences have an index method and others don't" > > > > I think this observation leads to insights both at the end-user level > > and at the implementer level. Tuples and lists are sequences; the > > index method can be defined generically for all sequences; adding such > > a method to the tuple type can be done with barely any changes to the > > implementation taken from the list type. This leads to the observation > > that a generic index method (defined as a function in the > > implementation) could be made to work with both lists and tuples, and > > that various other methods might also be defined similarly, although > > things like append, extend and other mutating methods wouldn't be > > appropriate for a tuple. > > > A generic definition of index would be tricky, though, if you wanted to > include strings as sequences. In that case you aren't testing for the > presence of a single element but a sub-sequence - I think this change > was introduced in 2.4 to allow checks like > > "men" in "three good men" > > to succeed where formerly only single characters could be checked for. > One might perversely allow extension to lists and tuples to allow > > [3, 4] in [1, 2, 3, 4, 5, 6] > > to succeed, but that's forcing the use case beyond normal limits. The > point I am trying to make is that circumstances alter cases, and that we > can't always rely on our intuition to determine how specific methods > work, let alone whether they are available. I'd love to have that! There are at least one million use cases for finding a sequence in a sequence and implementing it yourself is non-trivial. Plus then both list and tuple's index methods would work *exactly* like string's. It would be easier to document and more useful. A big win. > Indeed the syntax is deliberately "crippled" - Guido's reasoning being, > I believe, that if it were too easy and natural to use then people would > use it inappropriately and too frequently. There are no appropriate use cases for that feature. Maybe not for tuple.index either, but increasing consistency and being able to say "ALL sequences have an index method that works like THIS" would be a big win. Unfortunately, it really is the string type that screws up the symmetry. -- mvh Bj?rn From nagle at animats.com Thu Apr 26 16:53:51 2007 From: nagle at animats.com (John Nagle) Date: Thu, 26 Apr 2007 20:53:51 GMT Subject: Dedicated CPU core for Python? In-Reply-To: References: <1177607759.916727.180950@t39g2000prd.googlegroups.com> Message-ID: Michael Hoffman wrote: > Louise Hoffman wrote: > >> I was wondering, if Python in the foerseeable future will allocate one >> CPU core just for the interpreter, so heavy Python operations does >> slow down the OS? > > > When running scripts, or loading modules, Python does not really behave > as an interpreter. Instead it compiles the human-readable code to a > bytecode which it then runs on a virtual machine. That's how interpreters have worked since UCSD Pascal, circa 1977. Very few direct source interpreters, where the source is reprocessed each time a line is executed, are still used. The original IBM PC had one of those in ROM. Everbody grinds the code down to some kind of tree representation, and usually represents the tree as a string of operations for a stack machine. Then a little intepreter runs the stack machine. This is typically 10-100x slower than executing code compiled to the real machine. I saw a true source interpreter in a Galil industrial motor controller as recently as 2004, but that's one of the few remaining uses for that obsolete technology. When the documentation says that comments take time to execute, you've found one of those antiques. John Nagle From andre.roberge at gmail.com Sun Apr 29 19:39:45 2007 From: andre.roberge at gmail.com (=?iso-8859-1?B?QW5kcuk=?=) Date: 29 Apr 2007 16:39:45 -0700 Subject: Launching an independent Python program in a cross-platform way (including mac) In-Reply-To: <1177889540.489960.176380@u30g2000hsc.googlegroups.com> References: <1177889540.489960.176380@u30g2000hsc.googlegroups.com> Message-ID: <1177889985.709948.128370@n59g2000hsh.googlegroups.com> On Apr 29, 8:32 pm, Andr? wrote: > I would like to find out how I can launch an independent Python > program from existing one in a cross-platform way. The result I am > after is that a new terminal window should open (for io independent of > the original script). > > The following seems to work correctly under Ubuntu and Windows ... but > I haven't been able to find a way to make it work under Mac OS. > Forgot to add that there was an import as follows: import os # should have been obvious from subprocess import Popen # slightly less so > def exec_external(code, path): > """execute code in an external process > currently works under: > * Windows NT (tested) > * GNOME (tested) [January 2nd and 15th change untested] > This also needs to be implemented for OS X, KDE > and some form of linux fallback (xterm?) > """ > if os.name == 'nt': > current_dir = os.getcwd() > target_dir, fname = os.path.split(path) > > filename = open(path, 'w') > filename.write(code) > filename.close() > > if os.name == 'nt': > os.chdir(target_dir) # change dir so as to deal with paths > that > # include spaces > Popen(["cmd.exe", ('/c start python %s'%fname)]) > os.chdir(current_dir) > elif os.name == 'posix': > try: > os.spawnlp(os.P_NOWAIT, 'gnome-terminal', 'gnome- terminal', > '-x', 'python', '%s'%path) > except: > raise NotImplementedError > else: > raise NotImplementedError > ========================== > Any help would be greatly appreciated. > > Andr? From apardon at forel.vub.ac.be Tue Apr 10 12:53:19 2007 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 10 Apr 2007 16:53:19 GMT Subject: tuples, index method, Python's design References: Message-ID: On 2007-04-10, Carsten Haese wrote: > On Tue, 2007-04-10 at 13:21 +0000, Antoon Pardon wrote: >> > But if you are so eager to rewrite, how about the following: >> > >> > I am using the struct module to get binary data from a file. >> > Sometimes I want to skip until I find a particular binary >> > number. Somewhat simplified it looks like this: >> > >> > >> > class Itemfile: >> > def __init__(self, fn): >> > self.fl = open(fn) >> > self.ix = 80 >> > >> > def nextitem(self): >> > if self.ix == 80: >> > self.buf = struct.unpack("80i", self.fl.read(320)) >> > self.ix = 0 >> > result = self.buf[self.ix] >> > self.ix += 1 >> > return result >> > >> > def skipuntil(self, val): >> > done = False >> > while not done: >> > try: >> > self.ix = self.buf.index(val, self.ix) >> > done = True >> > except ValueError: >> > self.ix = 0 >> > self.buf = struct.unpack("80i", self.fl.read(320)) >> > >> > >> > Now I'm sure you can rewrite this without the need of tuple.index. >> > It just seems odd that I have to go through extra hoops here to >> > get the effect of tuple.index because struct.unpack returns its result >> > in a tuple and a tuple doesn't provide index. > > Your data is an array. Choosing a data structure that doesn't fit your > data is always going to cause pain. Instead of using struct.unpack, you > should use array.array, and voila!, you get an index method. No it is not. This is exactly what I thought was going to happen. One simplifies a problem so that the code is not too big to discuss here and people will use characteristics of the simplified code to suggest how one should have solved the problem differently. I'm not interrested in going through such a merry around again. As I said, writing an index function that works with any kind of sequence is easy enough and once written can be used as often as one whishes. So although I prefer more consistency from a language that python currently provides the language has enough going for it to stick with it dispite these kind of warts. So having that function is a practical enough solution for me. And curiously, having that function makes using tuples no longer painfull in situations where other would argue that tuples don't fit my data. If tuples don't fit my data, I sure find it strange that one little function causes you to no longer experience it as such. -- Antoon Pardon From daraburke78 at gmail.com Wed Apr 18 22:02:38 2007 From: daraburke78 at gmail.com (dbee) Date: 18 Apr 2007 19:02:38 -0700 Subject: Third party script debugging on remote server ... In-Reply-To: <1176943924.267007.182270@q75g2000hsh.googlegroups.com> References: <1176938153.119084.214700@d57g2000hsg.googlegroups.com> <1176939110.773939.83160@p77g2000hsh.googlegroups.com> <1176943924.267007.182270@q75g2000hsh.googlegroups.com> Message-ID: <1176948158.559571.100730@n76g2000hsh.googlegroups.com> On Apr 19, 1:52 am, dbee wrote: > On Apr 19, 12:31 am, Graham Dumpleton > wrote: > > > > > After calling whatever it is that is writing to standard output/error, > > do: > > > import sys > > sys.stdout.flush() > > sys.stderr.flush() > > > This should cause any buffered data to be immediately flushed to the > > main Apache error log, ie., don't look in any virtual host logs, check > > the main one. > > > Graham > > > On Apr 19, 9:15 am, dbee wrote: > > > > Right. I've got a really, really annoying/difficult/time consuming > > > problem with my development environment. I'm using django to build a > > > web app with paypal integration. My server is hosted remotely, and it > > > is receiving IPN (payment notifications) POST requests from Paypal. > > > I've checked on google and irc and this is my last shot at solving > > > this before I go mad ... :-( > > > > The problem is that I can't debug those POST requests. Browser > > > debugging is out of the question obviously cause I'm not at the > > > computer, ( and it doesn't have X ). > > > > I've tried cgitb but that doesn't seem to work at all ... > > > > import cgitb; cgitb.enable(display=0,logdir='/tmp/',format='plain') > > > import cgitb; cgitb.enable() > > > > ... neither of those commands have any effect. Although I do log other > > > parts of the script to /tmp, so I know that it's reachable... > > > > mod_pythonabsolutely refuses to error_log to the apache error_log. I > > > have restarted it and it still won't flush whatever error buffer it > > > may ( or may not ) have stored. > > > > I can re-constitute the requests in my browser using a GET request. > > > But frankly, that's kinda messy - there are lots of paypal IPN > > > combinations and I may have to integrate other applications with > > > paypal. So ideally speaking I'm looking for a proper debugging > > > environment for this kind of thing ... > > > > Basically, I either wantmod_pythonto start error_logging properly, > > > or I want some type of working traceback environment to be available. > > > Help ! > > > > Server version: Apache/2.0.52 > > > Server built: Aug 13 2006 03:29:43 > > > CentOS4.x: (RedHat Clone)mod_python.i386 3.1.3-5.1 > > > installed > > > > # httpd.conf > > > > > > > > ServerName mydomain.biz > > > ServerAliaswww.mydomain.biz > > > SetHandlermod_python > > > PythonPath "['/home/babo/django'] + sys.path" > > > PythonHandler django.core.handlers.modpython > > > SetEnv DJANGO_SETTINGS_MODULE mydomain.settings > > > > > > > SetHandler None > > > Options None > > > > > > > > > > > My python.conf: ( seems pretty normal ) > > > > # > > > #Mod_pythonis a module that embeds the Python language interpreter > > > # within the server, allowing Apache handlers to be written in Python. > > > # > > > > LoadModule python_module modules/mod_python.so > > > > # Override type-map handler for /var/www/manual > > > > > > > > > SetHandler default-handler > > > > > > > > > > # This will cause files beneath /var/www/html with the extension .spam > > > # to be handled by the Python script /var/www/html/eggs.py > > > # > > > # > > > # AddHandler python-program .spam > > > # PythonHandler eggs > > > # > > > > # This will cause all requests to the /python heirachy of your > > > # webserver to be handled by the python script /path/to/myhandler.py > > > # > > > # > > > # SetHandler python-program > > > # PythonPath "sys.path + ['/path/to']" > > > # PythonHandler myhandler > > > # > > > > # This will cause all requests to the /python heirachy of your > > > # webserver to be handled bymod_python'sPublisher handler > > > # (seehttp://localhost/manual/mod/mod_python/hand-pub.html) > > > # > > > # This will cause the output of all requests to files beneath > > > # /var/www/html with the extension .flt to be filtered through > > > # the Python script /var/www/html/filter.py > > > # > > > # > > > # PythonOutputFilter filter MYFILTER > > > # AddOutputFilter MYFILTER .flt > > > # > > Hi Graeme, > > Thanks for the suggestion. Unluckily for me, it doesn't seem to be > working though ... > > I've tried it a number of different ways. I guess if I put the code > after an exception, then the code won't be called. > So I ran an error in the python script and then I called the > sys.stderr.flush() from the python shell. No luck though. > > I called on it's own, still no luck, > > Then I tried ... > > try: > > raise Exception('Please log this error') > > except: > > import sys > > sys.stderr.flush() > sys.stdout.flush() > > The error log still has no error info in it :-( .... > > Is this problem unique to me ? > > This is startup message that gets posted to error_log on apache > restart ... (The IIS string is a mod_sec Security Signature) > [Wed Apr 18 19:58:25 2007] [notice] mod_python: (Re)importing module > 'django.core.handlers.modpython' > [Wed Apr 18 19:58:32 2007] [notice] mod_python: (Re)importing module > 'django.core.handlers.modpython' > DEBUG: InitPostgres > DEBUG: InitPostgres > [Wed Apr 18 19:59:56 2007] [notice] caught SIGTERM, shutting down > [Wed Apr 18 19:59:57 2007] [notice] suEXEC mechanism enabled > (wrapper: /usr/sbin/suexec) > [Wed Apr 18 19:59:57 2007] [notice] mod_security/1.9.4 configured - > Apache/2.0.52 (CentOS) > [Wed Apr 18 19:59:58 2007] [notice] Digest: generating secret for > digest authentication ... > [Wed Apr 18 19:59:58 2007] [notice] Digest: done > [Wed Apr 18 19:59:58 2007] [notice] LDAP: Built with OpenLDAP LDAP SDK > [Wed Apr 18 19:59:58 2007] [notice] LDAP: SSL support unavailable > [Wed Apr 18 19:59:58 2007] [notice] mod_python: Creating 4 session > mutexes based on 256 max processes and 0 max threads. > [Wed Apr 18 19:59:58 2007] [notice] Microsoft-IIS/5.0 configured -- > resuming normal operations > > There are no python debug messages ... > > Also, I've reinstalled mod_python, but it makes no difference. And put > this into my VirtualHost, just in case ... > > PythonDebug On > > Is there any answer for my problem ? I came across this logging class on the web. I've written it into the app, but it doesn't seem to work as I'd hoped ... It seems to log errors, but not actual system errors .... /home/babo/django/flowerhour/flowerhour1/views.py:40: SyntaxWarning: import * only allowed at module level def index(request): DEBUG: InitPostgres Is this class supposed to override the mod_python standard error functions ? And log to /tmp instead ? I couldn't find the __debug__ builtin in the docs, and I'm relatively new to python ... class Log: def __init__(self, file, mode): if __debug__: delf.__descriptor = open(file, mode) def __del__(self): self.close() def append(self, string): self.__descriptor.write(string + "\n\n") # add some more information if you please def close(self): self.__descriptor.close() # Variables __descriptor = [] # global log log = Log("log.txt") From jstroud at mbi.ucla.edu Wed Apr 18 05:24:07 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Wed, 18 Apr 2007 09:24:07 GMT Subject: exception just to avoid output error (newbie) In-Reply-To: <1176887598.528960.240820@d57g2000hsg.googlegroups.com> References: <1176887598.528960.240820@d57g2000hsg.googlegroups.com> Message-ID: Flyzone wrote: > Hi > I'm trying to delete some files, but i get an exception error if the > file don't exist. > I can use an {if fileexist(file) then delete}, but it will get cpu > time. > So i catch the exception with: > try: os.remove(filename) > except EnvironmentError: error=1 > If i just want to avoid the output error, is this the right way to > write the code? > I don't care of get if is in error, but an "except EvironmetError" > without the ":" will give me a sytax error. > Am I too much complicated? :-) > > Thanks in advance > You got it! Not to complicated--just right. I would make the tiniest of changes for style and speed: try: os.remove(filename) except EnvironmentError: pass But what you have already is fine. James From rNOSPAMon at flownet.com Mon Apr 23 03:33:22 2007 From: rNOSPAMon at flownet.com (Ron Garret) Date: Mon, 23 Apr 2007 00:33:22 -0700 Subject: Select weirdness References: <462b3e47$0$326$e4fe514c@news.xs4all.nl> <462c54cb$0$336$e4fe514c@news.xs4all.nl> Message-ID: In article <462c54cb$0$336$e4fe514c at news.xs4all.nl>, Irmen de Jong wrote: > Ron Garret wrote: > > I don't understand why socketserver calling select should matter. (And > > BTW, there are no calls to select in SocketServer.py. I'm using > > Python2.5.) > > You don't *need* a select at all. Yes I do, because what I'm really writing is a dispatching proxy that has to serve many simultaneous connections. Here's the full story in case you're interested: We have an application that is currently fielded as a cgi. We have a development server that needs to run multiple copies of the application at the same time. This is so that developers can push changes into their private "sandboxes" for evaluation before going into the main development branch. Each sandbox has its own source tree, its own database, and its own URL namespace. There are a small number of URLs in the application that are performance bottlenecks (they are used to serve AJAX updates). In order to alleviate that bottleneck without having to rewrite the whole application to run under mod_python or some such thing we've written a special dedicated server that handles only the AJAX requests. The tricky part is that each developer needs to have their own copy of this server running because each developer can have different code that needs to run to serve those requests. Assigning each developer a dedicated IP port would be a configuration nightmare, so these servers serve run on unix sockets rather than TCP sockets. I have not been able to find a proxy server that can proxy to unix sockets, so I need to write my own. Conceptually its a very simple thing: read the first line of an HTTP request, parse it with a regexp to extract the sandbox name, connect to the appropriate unix server socket, and then bidirectionally pipe bytes back and forth. But it has to do this for multiple connections simultaneously, which is why I need select. > >> Anyway, try the following instead: > >> > > > > That won't work for POST requests. > > > > Why not? Because POST requests can be very complicated. > Just add some more code to deal with the POST request body. I was really hoping to avoid having to write a fully HTTP-aware proxy. > There should be a content-length header to tell you how many > bytes to read after the header section has finished. Not if the content-transfer-encoding is chunked. Or if there are multiple file attachments. Also, even GET requests can become very complicated (from a protocol point of view) in HTTP 1.1. rg From richardjones at optushome.com.au Sat Apr 21 21:49:13 2007 From: richardjones at optushome.com.au (Richard Jones) Date: Sun, 22 Apr 2007 11:49:13 +1000 Subject: Another Python Game Programming Challenge concludes Message-ID: <200704221149.13512.richardjones@optushome.com.au> The fourth Python Game Programming Challenge (PyWeek) has now concluded with judges (PyWeek being peer-judged) declaring the winners: Individual: Which way is up? by Hectigo http://www.pyweek.org/e/Hectic/ Team: Bubble Kong by The Olde Battleaxe http://www.pyweek.org/e/toba4/ Congratulations to them and to the other entrants. You may view the complete listing of entries here: http://www.pyweek.org/4/entries/ and the scores here: http://media.pyweek.org/static/pyweek4_ratings.html and everything else about PyWeek is here: http://www.pyweek.org/ Before anyone asks, the next challenge will be in 6 months. There is no a date set. Richard Jones (the PyWeek guy ;) From bearophileHUGS at lycos.com Tue Apr 17 18:52:33 2007 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 17 Apr 2007 15:52:33 -0700 Subject: multirember&co In-Reply-To: <1176790588.024371.119360@n76g2000hsh.googlegroups.com> References: <1176768854.720234.23320@w1g2000hsg.googlegroups.com> <1176790588.024371.119360@n76g2000hsh.googlegroups.com> Message-ID: <1176850352.999231.79260@n59g2000hsh.googlegroups.com> Paddy: > def multiremberandco1(el, seq, fun): > l1, l2 = [], [] > c = seq.count(e1) > l1 = [el] * c > l2 = [el] * (len(seq) - c) > return fun(l1, l2) Thank you Paddy, but unfortunately there is a bug in my first function, this is more correct: def multiremberandco1b(el, seq, fun): l1, l2 = [], [] for x in seq: if x == el: l2.append(x) else: l1.append(x) return fun(l1, l2) So your version may become: def multiremberandco1c(el, seq, fun): l2 = [el] * seq.count(el) l1 = filter(lambda x: x != el, seq) return fun(l1, l2) ------------------- I am grateful to everyone that has answered me, but Steven has invented what I was looking for. It's code quite twisted on itself :-) I have modified, simplified and (hopefully) improved Steven's code like this (but it may be a bit slower, because the class It is inside the function?): import collections def xsplitter(iseq, pred): class It(object): def __init__(self, fun, parity): self.divert = fun self.parity = parity self.queue = collections.deque() def append(self, item): self.queue.append(item) def __iter__(self): while True: if self.queue: yield self.queue.popleft() else: try: item = iseq.next() if pred(item) == self.parity: yield item else: self.divert(item) except StopIteration: raise it1 = It(lambda y: it2.append(y), True) it2 = It(lambda y: it1.append(y), False) return it1, it2 idata = iter([1, 'a', 3, 'a', 4, 5, 6, 'a']) it1, it2 = xsplitter(idata, lambda x: x == 'a') from itertools import izip for el1, el2 in izip(it1, it2): print el1, el2 (The izip stops when the first iterable ends, with while-True loop and more code that they can be printed fully). Now this code is the lazy splitter I was talking about. I don't know if it can be useful, but I like it enough. Probably it's useless if one iterable is used whole before the other one (because a deque becomes filled up more and more), so I think in most situations a much simpler eager list splitter is enough. So I don't know if an improved version of it is fit for the itertools module. So far I haven't succed using the coroutine Python 2.5 allows using the generators, and I think still that xsplitter can be done with two coroutines instead of two It objects. Despite Steven's code I am unable still to write a working code with coroutines (probably because I haven't understood how they work yet). This time I take a breath and I show my wrong code: import collections def xsplitter(iseq, pred): def it(parity): queue = collections.deque() while True: received = (yield) if received is not None: queue.append(received) if queue: yield queue.popleft() else: try: el = iseq.next() if pred(el) == parity: yield el else: its[not parity].send(el) except StopIteration: raise its = [it(False), it(True)] return its[True], its[False] idata = iter([1, 'a', 3, 'a', 4, 5, 6, 'a']) it1, it2 = xsplitter(idata, lambda x: x == 'a') from itertools import izip for el1, el2 in izip(it1, it2): print el1, el2 It prints: None None None None a 3 None None a 4 None None None None None None Can it be fixed? Are you able to fix it for me? (If you want you can think of it as an exercise to understand Python coroutines :-) ). Bye and thank you, bearophile From lorenzo at excitement.com Sun Apr 8 13:29:56 2007 From: lorenzo at excitement.com (Lorenzo) Date: Sun, 08 Apr 2007 12:29:56 -0500 Subject: How do I get a slice of a string held in a tuple? References: <25ine4-rvt.ln1@Hedley.internal.thethurmans.com> <1176050876.835238.68560@d57g2000hsg.googlegroups.com> Message-ID: In article <1176050876.835238.68560 at d57g2000hsg.googlegroups.com>, "mensanator at aol.com" wrote: > On Apr 8, 11:34?am, Lorenzo Thurman > wrote: > > I have tuple which hold a string in tup[0]. I want to get a slice of > > that string. I thought I would do something like: > > tup[0][start:end] > > But this fails. > > No, it doesn't. > > >>> a = ('abcdefg','hijkl') > >>> a[0] > 'abcdefg' > >>> a[0][1:2] > 'b' > > > > How do I go about it? > > Do it correctly. Post your actual example that fails > and the related error message. Possibnly your indexes > were out of range. > > > I googled this and found a couple > > of references, but no solution. > > Well, there wouldn't be a solution to a non-existent > problem, would there? > > > TIA How would you get a slice of a[0] from your example? 'cde' for example? -- "My Break-Dancing days are over, but there's always the Funky Chicken" --The Full Monty From steve at REMOVE.THIS.cybersource.com.au Sun Apr 15 00:11:02 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Sun, 15 Apr 2007 14:11:02 +1000 Subject: function with list argument defaulting to [] - what's going on here??? References: <46217e8f$0$19437$4c368faf@roadrunner.com> Message-ID: On Sun, 15 Apr 2007 05:29:01 +0200, BJ?rn Lindqvist wrote: >> This comes up so often that I wonder whether Python should issue a warning >> when it sees [] or {} as a default argument. >> >> >> What do people think? A misuse or good use of warnings? > > I think Python should reevaluate the default values. That would break code that relies on the current behaviour. That makes it a "maybe" for Python 3.0, and an absolute "NO!!!" for Python 2.x. -- Steven. From exarkun at divmod.com Tue Apr 10 11:59:23 2007 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Tue, 10 Apr 2007 11:59:23 -0400 Subject: Why is __getslice__ still implemented? In-Reply-To: Message-ID: <20070410155923.18920.2006069208.divmod.quotient.10076@ohm> On Tue, 10 Apr 2007 09:51:45 -0600, Steven Bethard wrote: >Jean-Paul Calderone wrote: >> On Tue, 10 Apr 2007 08:35:56 -0600, Steven Bethard >> wrote: >>> Yes, you do still need to implement __getslice__ if you're subclassing >>> a class (like unicode or list) which provides it. The __getslice__ >>> method can't be removed entirely for backwards compatibility reasons >>> (though it is being removed in Python 3000). >> >> Why does this mean that the unicode type has to implement __getslice__? > >Because code could exist like:: > > >>> class C(list): > ... def __getslice__(self, start, stop): > ... return C(list.__getslice__(self, start, stop)) > ... > >>> type(C([1, 2, 3, 4])[:2]) > > Ah, excellent point. Jean-Paul From tejovathi.p at gmail.com Thu Apr 19 06:58:12 2007 From: tejovathi.p at gmail.com (Teja) Date: 19 Apr 2007 03:58:12 -0700 Subject: Helpbook and CHM In-Reply-To: References: <1176979477.204864.72900@n59g2000hsh.googlegroups.com> Message-ID: <1176980292.290091.10420@y5g2000hsa.googlegroups.com> On Apr 19, 3:48 pm, Tim Golden wrote: > Teja wrote: > > how to generate CHM files in Boa(Python)??? > > http://www.rutherfurd.net/software/rst2chm/index.html > > TJG Can't I do it in Boa constructor ??? I have seen an option in Boa to create a new helpbook and compile it to CHm and help files, But no clue how to do it....... From mahs at telcopartners.com Tue Apr 3 17:32:08 2007 From: mahs at telcopartners.com (Michael Spencer) Date: Tue, 03 Apr 2007 14:32:08 -0700 Subject: Problem with filter() In-Reply-To: <09042D621CD4AA479C678463F3A646D0F73D1A@sottemail1.ent.ad.cognos.com> References: <09042D621CD4AA479C678463F3A646D0F73D1A@sottemail1.ent.ad.cognos.com> Message-ID: Boudreau, Emile wrote: > Hey all, > So I'm trying to filter a list with the built-in function > filter(). My list looks something like this: > ['logs', 'rqp-8.2.104.0.dep', 'rqp-8.2.93.0.dep', > 'rqp-win32-app-8.2.96.0-inst.tar.gz', 'rqp-win32-app-8.2.96.0-inst.tar.gz'] > > Calling filter like this: compFiles = filter(is_Dev, compFiles) > compFiles is my list and is_dev is the following > > def is_Dev(stringy): > print stringy > stringx = stringy.split('-') > if stringx[1] == r'win32': > if stringx[2] == r'app': > if stringx[4] == r'dev.tar.gz': > return 1 > Use fnmatch.filter instead? >>> source = ['logs', 'rqp-8.2.104.0.dep', 'rqp-8.2.93.0.dep', 'rqp-win32-app-8.2.96.0-inst.tar.gz', 'rqp-win32-app-8.2.96.0-inst.tar.gz'] >>> >>> import fnmatch >>> fnmatch.filter(source, '*-win32-app-*-inst.tar.gz') ['rqp-win32-app-8.2.96.0-inst.tar.gz', 'rqp-win32-app-8.2.96.0-inst.tar.gz'] >>> Michael From mcPas.De.Spam at mclaveauPas.De.Spam.com Mon Apr 16 02:18:44 2007 From: mcPas.De.Spam at mclaveauPas.De.Spam.com (Michel Claveau) Date: Mon, 16 Apr 2007 08:18:44 +0200 Subject: How to initialize a table of months. References: Message-ID: Hi! Not best, but another lisibility : mons=dict(Jan=1, Feb=2, Fev=2, Mar=3, Apr=4, Avr=4, May=5, Mai=5, Jun=6, Jui=6, Jul=7, Aug=8, Aou=8, Sep=9, Oct=10, Nov=11, Dec=12) def mon2int(m): return mons[m] def mond2int(**m): return mons[m.keys()[0]] print mons['Mar'] print mon2int('May') print mond2int(Jul=0) > 3 > 5 > 7 (The dict is mixed : French/English) -- @-salutations Michel Claveau From jhefferon at smcvt.edu Mon Apr 16 12:45:29 2007 From: jhefferon at smcvt.edu (Jim) Date: 16 Apr 2007 09:45:29 -0700 Subject: script for seconds in given month? In-Reply-To: <1176740556.859125.221980@l77g2000hsb.googlegroups.com> References: <1176740556.859125.221980@l77g2000hsb.googlegroups.com> Message-ID: <1176741929.753396.297050@b75g2000hsg.googlegroups.com> On Apr 16, 12:22 pm, "edfialk" wrote: > Hi, does anyone happen to know of a script that would return the > number of seconds in a month if I give it a month and a year? > > My python is a little weak, but if anyone could offer some suggestions > I think I could handle it myself, or if anyone happens to know of a > script already written that performs this I would be extremely > grateful. Probably there are sophisticated answers, but have you tried something like: monthDays={'Jan':31,'Feb':28, ..} secs=60*60*24*monthDays[thisMonth] if (thisMonth=='Feb' and isLeap(thisYear)): secs+=60*60*24 return secs ? From qilong_ren at yahoo.com Wed Apr 11 21:10:07 2007 From: qilong_ren at yahoo.com (Qilong Ren) Date: Wed, 11 Apr 2007 18:10:07 -0700 (PDT) Subject: python regular expression help Message-ID: <402459.62579.qm@web58905.mail.re1.yahoo.com> Hi, everyone, I am extracting some information from a given string using python RE. The string is ,for example, s = 'a = 4 b =3.4 5.4 c = 4.5' What I want is : a = 4 b = 3.4 5.4 c = 4.5 Right now I use : pattern = re.compile(r'\w+\s*=\s*.*?\s+') lists = pattern.findall(s) It works for the string like 'a = 4 b = 3.4 c = 4.5', but does not work with strings like 'a=4 b=3.4 5.4 c = 4.5' Any suggestion? Thanks,Qilong ____________________________________________________________________________________ It's here! Your new message! Get new email alerts with the free Yahoo! Toolbar. http://tools.search.yahoo.com/toolbar/features/mail/ -------------- next part -------------- An HTML attachment was scrubbed... URL: From bbxx789_05ss at yahoo.com Thu Apr 12 03:36:29 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: 12 Apr 2007 00:36:29 -0700 Subject: python regular expression help In-Reply-To: <1176354923.264709.291150@b75g2000hsg.googlegroups.com> References: <138221.90891.qm@web58906.mail.re1.yahoo.com> <1176354923.264709.291150@b75g2000hsg.googlegroups.com> Message-ID: <1176363389.005798.312440@n59g2000hsh.googlegroups.com> On Apr 11, 11:15 pm, attn.steven.... at gmail.com wrote: > On Apr 11, 9:50 pm, "Gabriel Genellina" > lhs = re.compile(r'\s*(\b\w+\s*=)') > for s in [ "a = 4 b =3.4 5.4 c = 4.5", > "a = 4.5 b = 'h' 'd' c = 4.5 3.5"]: > tokens = lhs.split(s) > results = [tokens[_] + tokens[_+1] for _ in range(1,len(tokens), The only thing I can think when I look at that is: what a syntactic abomination. From steve at holdenweb.com Fri Apr 20 01:06:21 2007 From: steve at holdenweb.com (Steve Holden) Date: Fri, 20 Apr 2007 01:06:21 -0400 Subject: HTTP getreply() never returns In-Reply-To: <1177022299.791968.154520@b75g2000hsg.googlegroups.com> References: <1177009226.847229.34210@n76g2000hsh.googlegroups.com> <1177022299.791968.154520@b75g2000hsg.googlegroups.com> Message-ID: Marko.Cain.23 at gmail.com wrote: > On Apr 19, 2:39 pm, Steve Holden wrote: >> Marko.Cain... at gmail.com wrote: >>> Hi, >>> I have the following code which send/receive HTTP request/response: >>> # where sampleUrl is '127.0.0.1' and >>> # url is 'www.cnn.com' >>> h = httplib.HTTP(self.sampleUrl, 8080) >>> h.putrequest('GET', '/sample?url=' + self.url) >>> h.endheaders() >>> errcode, errmsg, headers = h.getreply() >>> But it never returns from h.getreply(). >>> I am using python 2.3.4. Can you please tell me what am I missing? >>> I am sure the url is correctly. I try putting this 'http:// >>> 127.0.0.1:8080/sample?url=www.cnn.com'and it works. >>> Thank you for any help. >[...] >> >> For what it's worth you *do* appear to have formed the calls correctly, >> so something a little more complex is going on here. >> >> You might consider using WireShark (nee Ethereal) to look at the data >> passing across the wire when you use the browser and when you use >> httplib then comparing the data. That won't work on Windows because it >> disobligingly refuses to let you tap into the loopback (127) network. >> >> regards >> Steve > > > Thanks. I run the same script hits the same server (a tomcat server): > One is on Fedora 5 with python 2.4, this works. > But one is on Red Hat 4 with python 2.3, this one does not work. > > Can you please tell me how can I make the script works on RHEL 4 > without upgrading it to python 2.3? > I can't see anything in http://svn.python.org/view/python/trunk/Lib/httplib.py?rev=54581&view=log that screams it might have fixed a problem. But I'd be tempted to try and "borrow" a copy of 2.4's httplib, run your program with that in a directory where it will be found before the standard library 2.3 module and see if it fixes the problem. If so, would it be a usable workaround just to use the 2.4 httplib for that one program? 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 Marko.Cain.23 at gmail.com Thu Apr 19 18:38:19 2007 From: Marko.Cain.23 at gmail.com (Marko.Cain.23 at gmail.com) Date: 19 Apr 2007 15:38:19 -0700 Subject: HTTP getreply() never returns In-Reply-To: References: <1177009226.847229.34210@n76g2000hsh.googlegroups.com> Message-ID: <1177022299.791968.154520@b75g2000hsg.googlegroups.com> On Apr 19, 2:39 pm, Steve Holden wrote: > Marko.Cain... at gmail.com wrote: > > Hi, > > > I have the following code which send/receive HTTP request/response: > > > # where sampleUrl is '127.0.0.1' and > > # url is 'www.cnn.com' > > > h = httplib.HTTP(self.sampleUrl, 8080) > > h.putrequest('GET', '/sample?url=' + self.url) > > h.endheaders() > > > errcode, errmsg, headers = h.getreply() > > > But it never returns from h.getreply(). > > > I am using python 2.3.4. Can you please tell me what am I missing? > > I am sure the url is correctly. I try putting this 'http:// > > 127.0.0.1:8080/sample?url=www.cnn.com'and it works. > > > Thank you for any help. > > >>> h = httplib.HTTP("www.cnn.com", 80) > >>> h.putrequest('GET', "/") > >>> h.endheaders() > >>> c, m, h = h.getreply() > >>> c > 200 > >>> m > 'OK' > >>> h > > >>> h.getheaders("content-type") > ['text/html'] > > The above shows you the basics of using httplib - if your own server > isn't responding that's probably not the library's fault. What is the > server? Perhaps its implementation of the HTTP protocol is slightly off, > but not so far off that browsers can't work with it. > > For what it's worth you *do* appear to have formed the calls correctly, > so something a little more complex is going on here. > > You might consider using WireShark (nee Ethereal) to look at the data > passing across the wire when you use the browser and when you use > httplib then comparing the data. That won't work on Windows because it > disobligingly refuses to let you tap into the loopback (127) network. > > regards > Steve Thanks. I run the same script hits the same server (a tomcat server): One is on Fedora 5 with python 2.4, this works. But one is on Red Hat 4 with python 2.3, this one does not work. Can you please tell me how can I make the script works on RHEL 4 without upgrading it to python 2.3? > -- > 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 steven.bethard at gmail.com Sun Apr 15 21:41:25 2007 From: steven.bethard at gmail.com (Steven Bethard) Date: Sun, 15 Apr 2007 19:41:25 -0600 Subject: pyparsing Catch-22 In-Reply-To: <1176686782.270354.164630@l77g2000hsb.googlegroups.com> References: <1176686782.270354.164630@l77g2000hsb.googlegroups.com> Message-ID: 7stud wrote: > For as hard as you push pyparsing on this forum, I would think you > would make it easier to download and install your module. In my > opinion, the wiki should provide detailed installation instructions > for all supported os's, and the sourceforge downloading process is too > complicated. FWIW, here's what works for me:: * Go to http://pyparsing.wikispaces.com/ * Click the link at the top that says "Download from SourceForge" * Click the big green "Download Python parsing module" button * Click the big green "Download" button next to "pyparsing-1.4.6" * Click pyparsing-1.4.6.tar.gz * Extract the dowloaded .tar.gz * Use the standard python installation idiom "python setup.py install" If you're not familiar with the standard Python installation idiom, take a few minutes to read: "Installing Python Modules" http://docs.python.org/inst/inst.html In particular it starts with "The new standard: Distutils", which tells you to try:: python setup.py install HTH, STeVe From robert.rawlins at thinkbluemedia.co.uk Tue Apr 24 13:28:08 2007 From: robert.rawlins at thinkbluemedia.co.uk (Robert Rawlins - Think Blue) Date: Tue, 24 Apr 2007 18:28:08 +0100 Subject: If Dict Contains a particular key Message-ID: <000001c78695$ed321540$c7963fc0$@rawlins@thinkbluemedia.co.uk> Hello Guys, I'm Looking to build a quick if/else statement that checks a dictionary for a key like follows. If myDict contains ThisKey: Do this... Else Do that... Thats the best way of doing this? Thanks, Rob -------------- next part -------------- An HTML attachment was scrubbed... URL: From jorge.vargas at gmail.com Mon Apr 9 11:05:02 2007 From: jorge.vargas at gmail.com (Jorge Vargas) Date: Mon, 9 Apr 2007 11:05:02 -0400 Subject: ctypes failing when a library needs another library Message-ID: <32822fe60704090805j33898e1dx2ae2ac5a77215e6d@mail.gmail.com> Hi I'm having an issue with ctypes loading libraries. I got the following setup. I have a library (coded by me) that calls a external library (installed with the package manager), and my ctypes program calls my lib. at first python couldn't find my lib but setting LD_LIBRARY_PATH=. fix that, but now it's failing inside my lib because it can't find the "system" library. the library itself is not an issue since I have a C program that test it and it's working fine. I'm running python 2.4 with the external ctypes module. under ubuntu linux 6.10 From mccredie at gmail.com Thu Apr 12 10:25:08 2007 From: mccredie at gmail.com (Matimus) Date: 12 Apr 2007 07:25:08 -0700 Subject: reading from sys.stdin In-Reply-To: <1176366058.261031.111870@p77g2000hsh.googlegroups.com> References: <1176366058.261031.111870@p77g2000hsh.googlegroups.com> Message-ID: <1176387908.406115.270630@w1g2000hsg.googlegroups.com> On Apr 12, 1:20 am, "7stud" wrote: > I can't break out of the for loop in this example: > > ------ > import sys > > lst = [] > for line in sys.stdin: > lst.append(line) > break > > print lst > ----------- > > But, I can break out of the for loop when I do this: > > --------- > import sys > > lst = [] > for line in open("aaa.txt"): > lst.append(line) > break > > print lst > ---------- > > Why doesn't break work in the first example? 1. Why are you breaking in the for loop? That will only give you the first line. 2. Your issue is caused by buffered IO. Because of the buffered IO, your code is equivalent to doing this: lst = [] s = sys.stdin.read() #All* of the reading up to EOF is done upfront. for line in s: lst.append(line) break # I'm sure you don't really want the break here though :) One way to get around the buffering is to do this: [code] # Open a file or the input stream if filename: f = open(filename,"r") else: f = sys.stdin # Then you check to see if your file is interactive if f.isatty(): # This is unbuffered, and will iterate the same as f f = iter(raw_input(),"") # Now do your stuff lst = [] for line in f: lst.append(line) print lst [/code] * well, not ALL, it will read in chunks. But, I think they are 4096 Byte chunks by default. From john.thingstad at chello.no Sun Apr 15 16:43:09 2007 From: john.thingstad at chello.no (John Thingstad) Date: Sun, 15 Apr 2007 22:43:09 +0200 Subject: is laziness a programer's virtue? References: <1176654319.273907.167280@q75g2000hsh.googlegroups.com> Message-ID: On Sun, 15 Apr 2007 18:25:19 +0200, Xah Lee wrote: > Laziness, Perl, and Larry Wall > > Xah Lee, 20021124 > > In the unix community there's quite a large confusion and wishful > thinking about the word laziness. In this post, i'd like to make some > clarifications. > > American Heritage Dictionary third edition defines laziness as: > ?Resistant to work or exertion; disposed to idleness.? > In this context I think you can safely take it to mean: Don't work hard, work smart. Avoid repetitious work. If somthing seems to elaborate find a more efficient way. In a course I took on verifiable programming I found working with Hoare logic extremely tedious. So I started using rewriting loops as recursive procedures and using induction instead. It took about a quarter of the time as the invariant of a loop fell out rather naturally this way. I failed the course, but when I took the course over again a year later I noticed that the book had been rewritten and now half the book was dedicated to Generator Induction. (Seems the professor noticed I failed in a interesting way and figured out it was not so stupid after all.) Naturally I had no problems the second time ;) This is just one example but it should convey the idea. -- Using Opera's revolutionary e-mail client: http://www.opera.com/mail/ From tgrav at mac.com Fri Apr 20 15:46:36 2007 From: tgrav at mac.com (Tommy Grav) Date: Fri, 20 Apr 2007 15:46:36 -0400 Subject: matplotlib basic question In-Reply-To: References: <1177016327.543985.34500@o5g2000hsb.googlegroups.com> <1177092157.763869.77600@o5g2000hsb.googlegroups.com> Message-ID: <76C22CF3-C355-4670-90AC-02054B0B9F8F@mac.com> On Apr 20, 2007, at 2:44 PM, Robert Kern wrote: > Colin J. Williams wrote: > >> I'm not sure that scipy has been updated to Python 2.5 > > ? scipy certainly works with 2.5. Are you referring to something > else perhaps? A side question: Is there any plans of updating the scipy.org Superpack bundle for Mac OS X to work with 2.5? Cheers Tommy From thn at mail.utexas.edu Tue Apr 3 14:56:48 2007 From: thn at mail.utexas.edu (Thomas Nelson) Date: 3 Apr 2007 11:56:48 -0700 Subject: how to remove multiple occurrences of a string within a list? In-Reply-To: <1175626164.428718.267670@w1g2000hsg.googlegroups.com> References: <1175624433.206953.214290@n59g2000hsh.googlegroups.com> <1175625098.269660.184790@o5g2000hsb.googlegroups.com> <1175626164.428718.267670@w1g2000hsg.googlegroups.com> Message-ID: <1175626608.884303.78060@l77g2000hsb.googlegroups.com> On Apr 3, 1:49 pm, kyoso... at gmail.com wrote: > On Apr 3, 1:31 pm, "Matimus" wrote: > > > It depends on your application, but a 'set' might really be what you > > want, as opposed to a list. > > > >>> s = set(["0024","haha","0024"]) > > >>> s > > > set(["0024","haha"])>>> s.remove("0024") > > >>> s > > > set(["haha"]) > > If you want, you can also loop over the list, like so: > > counter = 0 > your_list = ["0024","haha","0024"] > for i in your_list: > if i == '0024': > your_list.pop(counter) > counter += 1 > > Mike This method doesn't work. >>> li = list('hello larry') >>> count = 0 >>> for i in li: ... if i=='l': ... li.pop(count) ... coun += 1 ... 'l' 'l' >>> l ['h', 'e', 'l', 'o', ' ', 'a', 'r', 'r', 'y'] because the indexes change as you pop, it gets some of them but not all. From rehceb at no.spam.plz Sun Apr 1 09:54:35 2007 From: rehceb at no.spam.plz (Rehceb Rotkiv) Date: Sun, 01 Apr 2007 08:54:35 -0500 Subject: Unicode list References: <460F4CA3.8090904@v.loewis.de> Message-ID: > When printing a list, the individual elements are converted with repr(), > not with str(). For a string object, repr() adds escape codes for all > bytes that are not printable ASCII characters. Thanks Martin, you're right, it were the repr() calls that messed up the output. Iterating the array like you proposed is even 1/100s faster ;) Regards, Rehceb From rupole at hotmail.com Tue Apr 17 11:36:52 2007 From: rupole at hotmail.com (Roger Upole) Date: Tue, 17 Apr 2007 11:36:52 -0400 Subject: Printing Using Python References: <1176750825.770991.141640@y80g2000hsf.googlegroups.com> Message-ID: <1176824385_5321@sp12lax.superfeed.net> "Raja" wrote: > Hi, > Attached is the code . I want my program to save the current printer > job properties and , when I reconnect the printer at a latter date , i > need to print the saved job . Can you please help with my code ? How > to print a document at a later stage and any errors in my code ? > > import win32ui > import win32con > > myprinter_name = "" > # get the name from your Printers folder > > printer_properties=[] > > def save(): > pHandle = win32print.OpenPrinter(myprinter_name) > properties = win32print.GetPrinter(pHandle, 2) > pDevModeObj = properties["pDevMode"] > printer_properties.append(pDevModeObj.FormName) > printer_properties.append(pDevModeObj.PaperSize) > printer_properties.append(pDevModeObj.Orientation) > printer_properties.append(pDevModeObj.Color) > printer_properties.append(pDevModeObj.Copies) > printer_properties.append(pDevModeObj.DefaultSource) > win32print.ClosePrinter(pHandle) > > def apply(): > hprinter = win32print.OpenPrinter(myprinter_name) > > devmode = win32print.GetPrinter(hprinter, 2)["pDevMode"] > devmode.FormName=printer_properties[0] > devmode.PaperSize=printer_properties[1] > devmode.Orientation=printer_properties[2] > devmode.Color=printer_properties[3] > devmode.Copies=printer_properties[4] > devmode.DefaultSource=printer_properties[5] > > hdc = win32gui.CreateDC("WinPrint",myprinter_name,devmode) > dc = win32ui.CreateDCFromHandle(hdc) > > dc.StartDoc('My Python Document') > dc.StartPage() > dc.EndPage() > dc.EndDoc() > del dc > > > You help is greatly appreciated. > > Thank You, > Raja. > You should be able to pause the job using win32print.SetJob with JOB_CONTROL_PAUSE and resume it later using JOB_CONTROL_RESUME. That way you won't even have to store the print parameters yourself. hth Roger ----== 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 cjw at sympatico.ca Fri Apr 13 08:36:32 2007 From: cjw at sympatico.ca (Colin J. Williams) Date: Fri, 13 Apr 2007 08:36:32 -0400 Subject: HELP PARAMETERS IN SQL QUERY In-Reply-To: References: Message-ID: pierre-yves guido wrote: > hello, > > I'm doing a training course and I'm a newbie in Python. My problem : > I have a form, and when I click, I make an update. But all the parameters > are all required to make the update. So I'd like to put in my code something > like [optional]... > > My code (simplyfied) : > > prg.ev_ind_update(wf_pk_ev_ind=wf_pk_ev_ind,wf_fonction=wf_fonction,wf_nom=wf_nom) > > and so, when I put nothing in wf_nom, it put me that error :"the parameter > wf_nom...was omitted from the request...". But sometimes, wf_nom is not > required ! > > Thanks for your help user None? Colin W. From carsten at uniqsys.com Tue Apr 24 16:30:04 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Tue, 24 Apr 2007 16:30:04 -0400 Subject: how to serialize a COM object ? In-Reply-To: <1177445437.543694.49070@r3g2000prh.googlegroups.com> References: <1177445437.543694.49070@r3g2000prh.googlegroups.com> Message-ID: <1177446604.3441.32.camel@dot.uniqsys.com> On Tue, 2007-04-24 at 13:10 -0700, vml wrote: > I have a problem : > > I have a COM object. > > I would like to pass this com object from a server to a client through > a socket. That is just as feasible as passing a cruise ship through a phone line. A COM object represents a connection to a service or executable that is running on one computer. Transferring that connection to another computer is impossible. -Carsten From Dean.Brotzel at gmail.com Sun Apr 1 11:37:51 2007 From: Dean.Brotzel at gmail.com (Dean.Brotzel at gmail.com) Date: 1 Apr 2007 08:37:51 -0700 Subject: Python Based API Message-ID: <1175441871.933442.152630@p77g2000hsh.googlegroups.com> Hi, I work on a project that is built entirely using python and Tkinter. We are at the point where we would like to give access to our functionality to others via some sort of API. People who would use our API develop in all kinds of languages from C/C++ to Pascal. Ideas that come to mind that allow us to build such an API are: 1) Require others to imbed the python interpreter via the c API to be able to utilize our functionality. 2) Build an XML RPC interface around our code. 3) Rewrite our code base in C/C++, which should make it accessible to all modern languages. I'm looking for more and potentially better ideas that will allow us to offer an API to our customers without having to throw away or redo a lot of the python code that we have already written. Thanks in advance, Dean From nagle at animats.com Sun Apr 1 16:34:49 2007 From: nagle at animats.com (John Nagle) Date: Sun, 01 Apr 2007 20:34:49 GMT Subject: Shed Skin Python-to-C++ Compiler 0.0.21, Help needed In-Reply-To: <1175455529.936887.249170@e65g2000hsc.googlegroups.com> References: <576vhbF2ca1guU1@mid.individual.net> <1175376373.241744.6220@y80g2000hsf.googlegroups.com> <1175413310.295953.230840@e65g2000hsc.googlegroups.com> <1175455529.936887.249170@e65g2000hsc.googlegroups.com> Message-ID: Kay Schluehr wrote: > On Apr 1, 6:07 pm, John Nagle wrote: > >>Kay Schluehr wrote: >> >>>Indeed. The only serious problem from an acceptance point of view is >>>that Mark tried to solve the more difficult problem first and hung on >>>it. Instead of integrating a translator/compiler early with CPython, >>>doing some factorization of Python module code into compilable and >>>interpretable functions ( which can be quite rudimentary at first ) >>>together with some automatically generated glue code and *always have >>>a running system* with monotone benefit for all Python code he seemed >>>to stem an impossible task, namely translating the whole Python to C++ >>>and created therefore a "lesser Python". >> >> Trying to incrementally convert an old interpreter into a compiler >>is probably not going to work. > > > I'm talking about something that is not very different from what Psyco > does but Psyco works at runtime and makes continous measurements for > deciding whether it can compile some bytecodes just-in-time or let the > interpreter perform their execution. That can work. That's how the Tamirin JIT compiler does Javascript inside Mozilla. The second time something is executed interpretively, it's compiled. That's a tiny JIT engine, too; it's inside the Flash player. Runs both JavaScript and ActionScript generated programs. Might be able to run Python, with some work. > A factorization always follows a certain pattern that preserves the > general form and creates a specialization: > > def func(x,y): > # algorithm > > ====> > > from native import func_int_int > > def func(x,y): > if isinstance(x, int) and isinstance(y, int): > return func_int_int(x,y) # wrapper of natively compiled > specialized function > else: > # perform original unmodified algorithm on bytecode interpreter You can probably offload that decision onto the linker by creating specializations with different type signatures and letting the C++ name resolution process throw out the ones that aren't needed at link time. >>>Otherwise it >>>wouldn't be a big deal to do what is necessary here and even extend >>>the system with perspective on Py3K annotations or other means to ship >>>typed Python code into the compiler. >> >> Shed Skin may be demonstrating that "annotations" are unnecessary >>cruft and need not be added to Python. Automatic type inference >>may be sufficient to get good performance. > > > You still dream of this, isn't it? Type inference in dynamic languages > doesn't scale. It didn't scale in twenty years of research on > SmallTalk and it doesn't in Python. I'll have to ask some of the Smalltalk people from the PARC era about that one. > However there is no no-go theorem > that prevents ambitious newbies to type theory wasting their time and > efforts. Type inference analysis of Python indicates that types really don't change all that much. See http://www.python.org/workshops/2000-01/proceedings/papers/aycock/aycock.html Only a small percentage of Python variables ever experience a type change. So type inference can work well on real Python code. The PyPy developers don't see type annotations as a win. See Karl Botlz' comments in http://www.velocityreviews.com/forums/t494368-p3-pypy-10-jit-compilers-for-free-and-more.html where he writes: "Also, I fail to see how type annotations can have a huge speed-advantage versus what our JIT and Psyco are doing." >>The Py3K annotation model is to some extent a repeat of the old >>Visual Basic model. Visual Basic started as an interpreter with one >>default type, which is now called Variant, and later added the usual types, >>Integer, String, Boolean, etc., which were then manually declared. >>That's where Py3K is going. > > This has nothing to do with VB and it has not even much to do > with what existed before in language design. Type annotations, advisory or otherwise, aren't novel. They were tried in some LISP variants. Take a look at this experimental work on Self, too. http://www.cs.ucla.edu/~palsberg/paper/spe95.pdf Visual Basic started out more or less declaration-free, and gradually backed into having declarations. VB kept a "Variant" type, which can hold anything and was the implicit type. Stripped of the Python jargon, that's what's proposed for Py3K. Just because it has a new name doesn't mean it's new. It's common for languages to start out untyped and "simple", then slowly become more typed as the limits of the untyped model are reached. Another thing that can go wrong with a language: if you get too hung up on providing ultimate flexibility in the type and object system, too much of the language design and machinery is devoted to features that are very seldom used. C++ took that wrong turn a few years ago, when the language designers became carried away with their template mechanism, to the exclusion of fixing the real problems that drive their user base to Java or C#. Python, the language, is in good shape. It's the limitations of the CPython implementation that are holding it back. It looks like at least two projects are on track to go beyond the limitations of that implementation. This is good. John Nagle From nospam at nospam.net Thu Apr 5 16:49:29 2007 From: nospam at nospam.net (Andrew) Date: Thu, 05 Apr 2007 13:49:29 -0700 Subject: Pil Raw Image Viewer-- How to get image mode Message-ID: <131aoadsg7cf417@corp.supernews.com> Hello Ive been messing around with a simple raw image viewer using Pil and Tkinter However I am running into problems displaying the images they appear to be not correct I believe it is cause of the modes for the different files but I am unsure If someone could examine my code and assist in helping me solve my problem(s) It would be greatly appreciated from Tkinter import * import Image, ImageTk import os import tkFileDialog size = 1024, 768 def getfiles(): try: entry.delete(0, END) global fileopen fileopen = tkFileDialog.askdirectory() entry.insert(END, fileopen) finally: listb.delete(0, END) filenames = {'': []} getfileext = fileentry.get() path = entry.get() for root, dirs, files in os.walk(path): for name in files: lname = name.lower()# if on windows global names for ext, names in filenames.iteritems(): if lname.endswith(getfileext): names.append(os.path.join(root, name)) listb.insert(END, name) break def select(event): selection = listb.curselection() global selectit selectit = names[int(selection[0])] global im image_file = open(selectit, 'rb') data = image_file.read() im = Image.fromstring("RGB", (size), data, "raw") im.thumbnail((700, 700)) image = ImageTk.PhotoImage(im) label["image"]=image label.image = image root = Tk() root.title("Engrooved Image Viewer") root.wm_resizable(0, 0) root.wm_iconbitmap("shinobi.ico") frame = Frame(root) im = Image.open("startimage.jpg") image = ImageTk.PhotoImage(im) ##canvas = Canvas(frame, width=400, height=400) ##canvas.create_image(0, 0, image=image) ##canvas.grid(row=0, column=0, sticky=N+S+W+E) label = Label(frame, image=image) label.image = image label.grid(row=0, column=0, sticky=N+S+W+E) scrollbar2 = Scrollbar(frame) scrollbar2.grid(row=0, column=2, rowspan=1, columnspan=1, stick=N+S) listb = Listbox(frame, selectmode=SINGLE) listb.grid(row=0, column=1, columnspan=1, sticky=N+S+W+E) listb.bind('', select) scrollbar2.config(command=listb.yview) listb.config(yscrollcommand=scrollbar2.set) frame.grid(sticky=N+S+W+E) frame3 = Frame(root) entry = Entry(frame3) entry.grid(row=1, column=1, stick=W+E, columnspan=1) label2 = Label(frame3, text="EXT").grid(row=1, column=2) fileentry = Entry(frame3) fileentry.grid(row=1, column=3, columnspan=1, sticky=W+E) button = Button(frame3, text="Open and List Directory", command=getfiles) button.grid(row=1, column=4) frame3.grid(sticky=W+E) root.mainloop() Ty Cheers From half.italian at gmail.com Sun Apr 29 16:00:12 2007 From: half.italian at gmail.com (half.italian at gmail.com) Date: 29 Apr 2007 13:00:12 -0700 Subject: I can't inherit from "compiled" classes ? In-Reply-To: References: Message-ID: <1177876812.473265.29210@e65g2000hsc.googlegroups.com> On Apr 29, 12:48 pm, "Maxim Veksler" wrote: > Hello list, > > I'm trying to subclass socket and select, for both I get: > """ TypeError: Error when calling the metaclass bases > module.__init__() takes at most 2 arguments (3 given) """, I don't > understand this error. Why would python try to pass 3 arguments (what > are they) ? > > Googling for this error gave random results talking about try to > inherit a "Package" but socket is definitely a class, > (/usr/lib/python2.4/socket.py). Not sure about select thought. > > I've did the following to receive the error: > """ > In [1]: import socket > > In [2]: class PollingSocket(socket): > ...: pass > ...: > --------------------------------------------------------------------------- > exceptions.TypeError Traceback (most > recent call last) > > /home/hq4ever/ > > TypeError: Error when calling the metaclass bases > module.__init__() takes at most 2 arguments (3 given) > """ > > What am I breaking wrong? > > Thank you, > Maxim. > > -- > Cheers, > Maxim Veksler > > "Free as in Freedom" - Do u GNU ? Try: import socket class PollingSocket(socket.socket): pass ~Sean From Leo.Kislov at gmail.com Sun Apr 22 15:48:21 2007 From: Leo.Kislov at gmail.com (Leo Kislov) Date: 22 Apr 2007 12:48:21 -0700 Subject: Python's handling of unicode surrogates In-Reply-To: <1177122874.524447.85130@p77g2000hsh.googlegroups.com> References: <4628532B.5060104@v.loewis.de> <1177051493.468698.176740@b75g2000hsg.googlegroups.com> <4629591a$0$13629$9b622d9e@news.freenet.de> <1177122874.524447.85130@p77g2000hsh.googlegroups.com> Message-ID: <1177271301.924370.101450@q75g2000hsh.googlegroups.com> On Apr 20, 7:34 pm, Rhamphoryncus wrote: > On Apr 20, 6:21 pm, "Martin v. L?wis" wrote: > > If you absolutely think support for non-BMP characters is necessary > > in every program, suggesting that Python use UCS-4 by default on > > all systems has a higher chance of finding acceptance (in comparison). > > I wish to write software that supports Unicode. Like it or not, > Unicode goes beyond the BMP, so I'd be lying if I said I supported > Unicode if I only handled the BMP. Having ability to iterate over code points doesn't mean you support Unicode. For example if you want to determine if a string is one word and you iterate over code points and call isalpha you'll get incorrect result in some cases in some languages (just to backup this claim this isn't going to work at least in Russian. Russian language uses U+0301 combining acute accent which is not part of the alphabet but it's an element of the Russian writing system). IMHO what is really needed is a bunch of high level methods like .graphemes() - iterate over graphemes .codepoints() - iterate over codepoints .isword() - check if the string represents one word etc... Then you can actually support all unicode characters in utf-16 build of Python. Just make all existing unicode methods (except unicode.__iter__) iterate over code points. Changing __iter__ to iterate over code points will make indexing wierd. When the programmer is *ready* to support unicode he/she will explicitly call .codepoints() or .graphemes(). As they say: You can lead a horse to water, but you can't make it drink. -- Leo From development-2006-8ecbb5cc8aREMOVETHIS at ANDTHATm-e-leypold.de Tue Apr 17 06:33:23 2007 From: development-2006-8ecbb5cc8aREMOVETHIS at ANDTHATm-e-leypold.de (Markus E Leypold) Date: Tue, 17 Apr 2007 12:33:23 +0200 Subject: is laziness a programer's virtue? References: <1176757271.282365.319740@n76g2000hsh.googlegroups.com> <1176797558.403629.53140@b75g2000hsg.googlegroups.com> Message-ID: Ingo Menger writes: > On 16 Apr., 23:01, "Xah Lee" wrote: > >> If your article is relevant to X, Y, and Z, >> please cross post it. > > Yeah right, and if it is not, don't post it at all. Your articles are > nothing but a bunch of unfounded allegations, moralism and your > personal notion of what alledgedly "hurts society". As such, they have > no relevance at all in technical news groups. But we already had of topic discussions in some of those groups (meandering into the non technical) that weren't stomped upon by the group's subscribers. The difference in my eyes is, that Xah is a troll. What makes Xah a troll is neither off-topic posts nor being incoherent -- its the attitude. He's broadcasting his drivel to a number of groups not with the intention to discuss (he hardly ever answers to answers to his posts), but solely with the intention to inform the world at large about his own magnificient thoughts. As also evidenced by reposting some of his stuff (as if he had a fan community or as if it were a FAQ) or posting stuff dated from 2002. Trying to correct Xah's behaviour is probably impossible. People who publish pictures of themselves as he does on the WWW probably don't have any sense of embarrasment left -- and I consider that a necessary part in the feedback loop which makes people change: "Look what you did! Do you really want to look like a dolt in public?" "Umpf. No. God that was embarrasing" . But that won't happen to Xah. Regards -- Markus From steve at REMOVE.THIS.cybersource.com.au Fri Apr 20 21:48:33 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Sat, 21 Apr 2007 11:48:33 +1000 Subject: When to clear a dictionary... References: Message-ID: On Fri, 20 Apr 2007 09:48:07 -0700, Bill Jackson wrote: > What is the benefit of clearing a dictionary, when you can just reassign > it as empty? They are two different things. In the first place, you clear the dictionary. In the second place, you reassign the name to a new object (which may be an empty dictionary, or anything else) while leaving the dictionary as-is. Here's an example of clearing the dictionary. >>> adict = {1:"parrot"} >>> bdict = adict >>> adict.clear() >>> bdict {} Because both adict and bdict point to the same dictionary object, clearing it results in an empty dictionary no matter what name (if any!) you use to refer to it. Here's an example of re-assigning the name. >>> adict = {1:"parrot"} >>> bdict = adict >>> adict = {} # re-assign the name to an empty dict >>> bdict {1: 'parrot'} Although adict and bdict both start off pointing to the same dictionary, once you re-assign the name adict, they now point to different dictionaries, only one of which is empty. In this specific case, if bdict didn't exist, the original dictionary would then be garbage-collected and the memory re-claimed. In the C implementation of Python (CPython), that will happen immediately; in the Java and (I think) .Net implementations of Python (Jython and IronPython) it will happen "eventually", with no guarantee of how long it will take. > Similarly, suppose I generate a new dictionary b, and need > to have it accessible from a. What is the best method, under which > circumstances? That depends on what you are trying to do. >>> adict = {1: "parrot"} >>> bdict = {2: "spam") What is it that you want to do? (1) "I want the name 'adict' to point to the same dict as bdict." Solution: adict = bdict (2) "I want the data in bdict to update the data in adict, keeping items in adict that are not in bdict but replacing them if they are in bdict." Solution: adict.update(bdict) (3) "I want the data in bdict to be copied into adict, throwing away whatever was already there." Solution: adict.clear() adict.update(bdict) (4) "I want the data in bdict to be copied into adict, but keeping what was already there." Solution: for key in bdict: if adict.has_key(key): pass # ignore it else: adict[key] = bdict[key] # add it -- Steven. From mail at timgolden.me.uk Tue Apr 17 08:13:00 2007 From: mail at timgolden.me.uk (Tim Golden) Date: Tue, 17 Apr 2007 13:13:00 +0100 Subject: question of easyExcel (<>) In-Reply-To: <46243BD2.0D637F.28583@m5-85.163.com> References: <46243BD2.0D637F.28583@m5-85.163.com> Message-ID: <4624B9CC.4000502@timgolden.me.uk> Tommy Zong wrote: > class easyExcel: [... snip ...] > However, I found a problem today - it works fine in single thread version > but can not work properly in multi-thread version - If I move excel file > operations to sub-thread, it will complain 'CoInitialize has not been > called'. I noticed the exception is thrown in > "Lib\site-packages\win32com\client\dynamic.py", I tried to add > "pythoncom.CoInitialize()" in line 78 and "pythoncom.CoUninitialize()" in > line 330, it will be ok. > 1. After doing such modifications, the excel file will be opened as > "read only" mode, how to avoid this? No idea. Sounds improbable but I haven't tried it. > 2. Is it necessary to add these two lines? Is there any mistake I > made? Yes. If you want to use any kind of COM/DCOM routines in a multithreaded environment, you must tell the COM subsystem that you want threading, and possibly what kind of threading you want. If you stick "CoInitialize" into your favourite search engine you'll get far more information than you really need. Here's the authoritative page: http://msdn2.microsoft.com/en-us/library/ms678543.aspx TJG From mensanator at aol.com Sat Apr 7 12:04:49 2007 From: mensanator at aol.com (mensanator at aol.com) Date: 7 Apr 2007 09:04:49 -0700 Subject: Checking whether list element exists In-Reply-To: References: Message-ID: <1175961889.021736.5960@d57g2000hsg.googlegroups.com> On Apr 7, 10:52???am, Rehceb Rotkiv wrote: > > In general case it won't work, because lists accept negative indexes: > >http://docs.python.org/lib/typesseq.html, 3rd note. > > Yes, I know! I _want_ the "3rd last list element", i.e. list[-3]. But it > may be that the list does not have 3 elements. In this case, list[-3] > will throw an error, cf.: > > >>> arr = ['a','b','c'] > >>> print arr[-3] > a > >>> print arr[-4] > > Traceback (most recent call last): > ? File "", line 1, in ? > IndexError: list index out of range > > > > I thought maybe I could catch the error with try...except so that I do > not need the if-test, but I don't know whether this is proper usage of > the try...except structure. It's better than seeing if length>=abs(index). >>> b = [] >>> index = 0 >>> if len(b)>=abs(index): print b[index] Traceback (most recent call last): File "", line 2, in print b[index] IndexError: list index out of range >>> try: print b[index] except: print 'does not exist' does not exist The length test fails for an empty list but the try/except method works when the list is empty. From apardon at forel.vub.ac.be Fri Apr 20 10:49:57 2007 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 20 Apr 2007 14:49:57 GMT Subject: Do other Python GUI toolkits require this? References: <462697A6.6010007@codebykevin.com> <1177014799.004875.262060@y80g2000hsf.googlegroups.com> Message-ID: On 2007-04-20, Max Erickson wrote: > > If we are being pedantic about describing a curve that shows the > progress of a person in learning a topic, there is no arguing with > you, a steep curve describes fast uptake and is a good thing. > > If we are being pedantic about what a learning curve describes, it > seems possible that it describes the rate of knowledge uptake > required to master a given topic, and that such a learning curve > could exclude people that were unable to take in knowledge at that > rate(for whatever reason) from mastering that topic, making it > reasonable to describe such a topic as both 'hard' and 'having a > steep learning curve'. I must confess I don't follow you here. A rate is a single number. Now some second variable can be a function of this rate or vice versa but I can't make out what this second variable is supposed to be from your explanation. -- Antoon Pardon From alainpoint at yahoo.fr Wed Apr 4 05:53:07 2007 From: alainpoint at yahoo.fr (alain) Date: 4 Apr 2007 02:53:07 -0700 Subject: SNMP agent Message-ID: <1175680387.575097.4590@e65g2000hsc.googlegroups.com> Hi, I have a Python app and i would like to add some SNMP agent functionality to it. I know it's possible to write a sub-agent with netsnmp but it is in C and quite complicated. I know of YAPSNMP (a wrapper around NETSNMP) but it doesn't seem to support agent writing. Any suggestion ? Thanks to all in advance Alain From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Fri Apr 20 13:09:52 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Fri, 20 Apr 2007 19:09:52 +0200 Subject: When are immutable tuples *essential*? Why can't you just use lists *everywhere* instead? References: <1177088796.622928.224890@d57g2000hsg.googlegroups.com> Message-ID: <58sacjF2i0sviU1@mid.individual.net> seberino at spawar.navy.mil wrote: > Please help me think of an example where immutable tuples are > essential. When used as dictionary keys (also everywhere else where they must be in a constant order). Yes, this *is* used in practice. Regards, Bj?rn -- BOFH excuse #14: sounds like a Windows problem, try calling Microsoft support From sjmachin at lexicon.net Wed Apr 11 16:14:38 2007 From: sjmachin at lexicon.net (John Machin) Date: 11 Apr 2007 13:14:38 -0700 Subject: ValueError: too many values to unpack In-Reply-To: <1176319688.666986.183980@o5g2000hsb.googlegroups.com> References: <1176311618.617765.120560@p77g2000hsh.googlegroups.com> <1176319688.666986.183980@o5g2000hsb.googlegroups.com> Message-ID: <1176322478.868786.214270@o5g2000hsb.googlegroups.com> On Apr 12, 5:28 am, "fscked" wrote: > On Apr 11, 10:26 am, Laszlo Nagy wrote: > > > > > fscked ?rta:> Trying to use CSV to read in a line with 11 fields and I keep getting > > > this error. I have googled a bit and have been unable to figure it out. > > > Probably you have more than 11 values in some (or all) of the rows in > > the CSV file. Try this code: > > > L = (1,2,3,4,5) > > a1,a2,a3 = L > > > If you are sure that you only need a certain number of values, "the > > first N columns": > > > a1,a2,a3 = L[:3] > > > Then you still can have a "not enough values to unpack" error, guess > > what that means. ;-) > > > Laszlo > > Hmm, well I have counted the fields in the CSV and verified there are > only 11. Counted how? Checked each line in the file? Let Python do it; see below. > Here is the offending code: > > myfile = open('ClientsXMLUpdate.csv') Put in a second arg of 'rb'; if not the case now, someone might run your code on Windows some day. What platform, what version of Python? > csvreader = csv.reader(myfile) > > for boxid, mac, activated, hw_ver, sw_ver, heartbeat, name, address, > phone, country, city in csvreader: Not exactly bullet-proof code. > I just don't get it... :/ Possibly (in one or more rows) the address field has a comma in it and it's not quoted properly. Try writing your code in a more defensive fashion: ENCOLS = 11 rownum = 0 for row in csvreader: rownum += 1 ancols = len(row) if ancols != ENCOLS: print "Row %d has %d columns (expected %d)" \ % (rownum, ancols, ENCOLS) print row # pass/return/continue/break/raise/call error logger ..... (boxid, mac, activated, hw_ver, sw_ver, heartbeat, name, address, phone, country, city) = row HTH, John From tjreedy at udel.edu Tue Apr 3 12:30:54 2007 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 3 Apr 2007 12:30:54 -0400 Subject: Stack experiment References: <5QuQh.152$9L1.108@read3.inet.fi> Message-ID: wrote in message news:5QuQh.152$9L1.108 at read3.inet.fi... | Hi! Im new to Python and doing exercise found from internet. It is | supposed to evaluate expression given with postfix operator using | Stack() class. | | class Stack: | def __init__(self): | self.items = [] | | def push(self, item): | self.items.append(item) | | def pop(self): | return self.items.pop() | | def isEmpty(self): | return (self.items == []) | | def evaluatePostfix(expr): | import re | tokenList = re.split(" ([^0-9])", expr) To see what is wrong, print tokenList. tokenList = expr.split() is probably what you want | stack = Stack() | for token in tokenList: | if token == '' or token == ' ': | continue | if token == '+': | sum = stack.pop() + stack.pop() | stack.push(sum) | elif token == '*': | product = stack.pop() * stack.pop() | stack.push(product) | else: | stack.push(int(token)) | return stack.pop() | | print evaluatePostfix("56 47 + 2 *") | | Errormsg: | Traceback (most recent call last): | File "C:\*\postfix1.py", line 31, in | print evaluatePostfix("56 47 + 2 *") | File "C:\*\postfix1.py", line 28, in evaluatePostfix | stack.push(int(token)) | ValueError: invalid literal for int() with base 10: '56 47' | | How can I avoid the error and get desired result? | -- | http://mail.python.org/mailman/listinfo/python-list | From tdelaney at avaya.com Tue Apr 10 19:38:13 2007 From: tdelaney at avaya.com (Delaney, Timothy (Tim)) Date: Wed, 11 Apr 2007 09:38:13 +1000 Subject: Why NOT only one class per file? Message-ID: <2773CAC687FD5F4689F526998C7E4E5FF1ED58@au3010avexu1.global.avaya.com> Bruno Desthuilliers wrote: > I came to this conclusion from my own experience, and it seems that > quite a few other programmers (most of them either better and/or more > experimented than me) came to the same conclusion. But feel free to Been more experimented on, or have experimented more on others? Tim Delaney From gregcorradini at gmail.com Wed Apr 18 15:17:25 2007 From: gregcorradini at gmail.com (Greg Corradini) Date: Wed, 18 Apr 2007 12:17:25 -0700 (PDT) Subject: Help Understanding mx.ODBC Error In-Reply-To: <1176923312.859650.6430@q75g2000hsh.googlegroups.com> References: <10063746.post@talk.nabble.com> <1176923312.859650.6430@q75g2000hsh.googlegroups.com> Message-ID: <10065312.post@talk.nabble.com> Thanks for you help kyosohma, Unfortunately, the data I'm using isn't chaning either. I've reused data that these scripts have successfully used before, but that won't work with them now. kyosohma wrote: > > On Apr 18, 1:36 pm, Greg Corradini wrote: >> Hello All, >> A few weeks ago, I wrote two scripts using mx.ODBC on an Access DB. Among >> other things, both scripts create new tables, perform a query and then >> populate the tables with data in a dictionary that I've uploaded from >> elsewhere. These scripts have run hundreds of times in the last few weeks >> with no problems. >> >> But recently they continue to bail on the mycursor.execute('An SQL >> Statement') after the table has been created. I get the following error >> message: >> Traceback (most recent call last): >> File "C:\Documents and Settings\marv1shi\Desktop\Workspace\Existence >> Script\DBF Checker\Access_SQL.py", line 35, in ? >> curse.execute(sql) >> ProgrammingError: ('07001', -3010, '[Microsoft][ODBC Microsoft Access >> Driver] Too few parameters. Expected 4.', 4612) >> >> The real stinker, however, is that after it bails I can manually call >> mycursor.execute('An SQL Statement'), then call my insert statement in >> the >> Python Shell and it works fine. >> >> I just can't figure out how to reconcile this problem. Has anybody run >> into >> this before? >> >> Thanks >> Greg Corradini >> -- >> View this message in >> context:http://www.nabble.com/Help-Understanding-mx.ODBC-Error-tf3602497.html... >> Sent from the Python - python-list mailing list archive at Nabble.com. > > Normally too few parameters refers to the SQL statement not inserting > the proper number of items. An example would be to list 4 values and > only insert 3. See below for a pseudo-SQL statement: > > INSERT into someDB (id, name, address, state) VALUES (value1, value2, > value3) > > That should give the same error, I would think. You may need to check > if your SQL statement or the way your db is created has changed in > some way. > > Mike > > -- > http://mail.python.org/mailman/listinfo/python-list > > -- View this message in context: http://www.nabble.com/Help-Understanding-mx.ODBC-Error-tf3602497.html#a10065312 Sent from the Python - python-list mailing list archive at Nabble.com. From gregcorradini at gmail.com Thu Apr 19 08:13:05 2007 From: gregcorradini at gmail.com (Greg Corradini) Date: Thu, 19 Apr 2007 05:13:05 -0700 (PDT) Subject: Help Understanding mx.ODBC Error In-Reply-To: References: <10063746.post@talk.nabble.com> <10065545.post@talk.nabble.com> Message-ID: <10077031.post@talk.nabble.com> Steve Holden wrote: > > Greg Corradini wrote: > [actually, her wrote it here but I moved it to the bottom] >> Steve Holden wrote: >>> Greg Corradini wrote: >>>> Hello All, >>>> A few weeks ago, I wrote two scripts using mx.ODBC on an Access DB. >>>> Among >>>> other things, both scripts create new tables, perform a query and then >>>> populate the tables with data in a dictionary that I've uploaded from >>>> elsewhere. These scripts have run hundreds of times in the last few >>>> weeks >>>> with no problems. >>>> >>>> But recently they continue to bail on the mycursor.execute('An SQL >>>> Statement') after the table has been created. I get the following error >>>> message: >>>> Traceback (most recent call last): >>>> File "C:\Documents and Settings\marv1shi\Desktop\Workspace\Existence >>>> Script\DBF Checker\Access_SQL.py", line 35, in ? >>>> curse.execute(sql) >>>> ProgrammingError: ('07001', -3010, '[Microsoft][ODBC Microsoft Access >>>> Driver] Too few parameters. Expected 4.', 4612) >>>> >>>> The real stinker, however, is that after it bails I can manually call >>>> mycursor.execute('An SQL Statement'), then call my insert statement in >>>> the >>>> Python Shell and it works fine. >>>> >>>> I just can't figure out how to reconcile this problem. Has anybody run >>>> into >>>> this before? >>>> >>>> Thanks >>>> Greg Corradini >>> I suspect what's happening here is that you are presenting statements >>> you have made up programmatically, and the values you are trying to >>> insert include apostrophes that break the syntax of your SQL. However >>> there isn't really enough evidence to decide unless you are prepared to >>> show us the error traceback, possibly with a dump of the SQL statement >>> you are actually trying to execute. >>> >>> I apologize in advance if you are using parameterized queries (as you >>> should to avoid SQL injection vulnerabilities among other major >>> problems) but this message is typical of Access when it sees words it >>> can't parse. >>> > > Steve, > > As always, thanks for your consistent help on matters big and small. > > I've managed to solve the problem, although I'm scared b/c the bug is > still > > elusive. > > I dumped and deleted my separate Access DBs, created new ones and tried > > running the scripts on old data (that these scripts were able to digest > > successfully before) and new data (that they errored on to begin with). > > Everything works without me changing any code around. Hmm? > > > > I don't know much about Access or the JetEngine. Is it possible that > .mdbs > > can go corrupt if overused? This seems unlikely, but I'm dumbfounded. > > Greg: > > No, there are no known cases of a database getting "tired" :-) > > It sounds like a data dependency of some sort, but if the error has > "gone away" then I guess we no longer have anything to work with. This > is somewhat annoying, as I hate to see an error go untraced. > > Take it from me, it does look like a SQL error - *are* you building your > statements in the program, or are you using proper parameterization with > "?" in your statements where a parameter would go? > > 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 > > -- > http://mail.python.org/mailman/listinfo/python-list > > Steve, Thanks for your reply. I used the proper parameterization with "?" in my SQL statements and still the problem persisted (although now it's gone). I do agree, an untraced error is definately annoying. Next time, I'll be more patient despite the workflow pileing up in front of me. Marc-Andre Lemburg did offer a couple pieces of advice that I'll follow up on and read about. He mentioneded the connection pooling and Access driver version I'm working with. Thanks again Greg Corradini -- View this message in context: http://www.nabble.com/Help-Understanding-mx.ODBC-Error-tf3602497.html#a10077031 Sent from the Python - python-list mailing list archive at Nabble.com. From SWEETLADYFRMBAMA at tmomail.net Thu Apr 26 11:25:03 2007 From: SWEETLADYFRMBAMA at tmomail.net (SWEETLADYFRMBAMA at tmomail.net) Date: Thu, 26 Apr 2007 08:25:03 -0700 (PDT) Subject: http://www.t-mobileapps.com/vs/istream_int2/LinkLibrary/Go.cfm?ID=1809 Message-ID: <11297869.1177601103390.JavaMail.root@prowig04> Go From steve at holdenweb.com Tue Apr 3 13:50:18 2007 From: steve at holdenweb.com (Steve Holden) Date: Tue, 03 Apr 2007 13:50:18 -0400 Subject: How can I kill a running thread when exiting from __main__ In-Reply-To: <17938.37496.3294.776762@montanaro.dyndns.org> References: <1175620919.478708.292150@p77g2000hsh.googlegroups.com> <17938.37496.3294.776762@montanaro.dyndns.org> Message-ID: skip at pobox.com wrote: > Steve> The only way to do this is to have the thread regularly examine a > Steve> "please quit" flag that is set from the main thread when > Steve> termination is required. > > I thought the process would terminate when only daemon threads were left. > > Skip So it does - according to the documentation. In which case why is the OP asking the question, since his code sets the queuethread daemonic before starting it? Maybe, then, the real answer is "just exit from the main thread"? 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 Apr 27 10:50:15 2007 From: ptmcg at austin.rr.com (Paul McGuire) Date: 27 Apr 2007 07:50:15 -0700 Subject: regex question In-Reply-To: <1177683018.566343.105620@c18g2000prb.googlegroups.com> References: <1177655637.717863.93920@o40g2000prh.googlegroups.com> <1177659238.159411.40640@c18g2000prb.googlegroups.com> <1177683018.566343.105620@c18g2000prb.googlegroups.com> Message-ID: <1177685415.648222.281100@o40g2000prh.googlegroups.com> On Apr 27, 9:10 am, proctor <12cc... at gmail.com> wrote: > On Apr 27, 1:33 am, Paul McGuire wrote: > > > > > > > On Apr 27, 1:33 am, proctor <12cc... at gmail.com> wrote: > > > > hello, > > > > i have a regex: rx_test = re.compile('/x([^x])*x/') > > > > which is part of this test program: > > > > ============ > > > > import re > > > > rx_test = re.compile('/x([^x])*x/') > > > > s = '/xabcx/' > > > > if rx_test.findall(s): > > > print rx_test.findall(s) > > > > ============ > > > > i expect the output to be ['abc'] however it gives me only the last > > > single character in the group: ['c'] > > > > C:\test>python retest.py > > > ['c'] > > > > can anyone point out why this is occurring? i can capture the entire > > > group by doing this: > > > > rx_test = re.compile('/x([^x]+)*x/') > > > but why isn't the 'star' grabbing the whole group? and why isn't each > > > letter 'a', 'b', and 'c' present, either individually, or as a group > > > (group is expected)? > > > > any clarification is appreciated! > > > > sincerely, > > > proctor > > > As Josiah already pointed out, the * needs to be inside the grouping > > parens. > > > Since re's do lookahead/backtracking, you can also write: > > > rx_test = re.compile('/x(.*?)x/') > > > The '?' is there to make sure the .* repetition stops at the first > > occurrence of x/. > > > -- Paul > > i am working through an example from the oreilly book mastering > regular expressions (2nd edition) by jeffrey friedl. my post was a > snippet from a regex to match C comments. every 'x' in the regex > represents a 'star' in actual usage, so that backslash escaping is not > needed in the example (on page 275). it looks like this: > > =========== > > /x([^x]|x+[^/x])*x+/ > > it is supposed to match '/x', the opening delimiter, then > > ( > either anything that is 'not x', > > or, > > 'x' one or more times, 'not followed by a slash or an x' > ) any number of times (the 'star') > > followed finally by the closing delimiter. > > =========== > > this does not seem to work in python the way i understand it should > from the book, and i simplified the example in my first post to > concentrate on just one part of the alternation that i felt was not > acting as expected. > > so my question remains, why doesn't the star quantifier seem to grab > all the data. isn't findall() intended to return all matches? i > would expect either 'abc' or 'a', 'b', 'c' or at least just > 'a' (because that would be the first match). why does it give only > one letter, and at that, the /last/ letter in the sequence?? > > thanks again for replying! > > sincerely, > proctor- Hide quoted text - > > - Show quoted text - Again, I'll repeat some earlier advice: you need to move the '*' inside the parens - you are still leaving it outside. Also, get in the habit of using raw literal notation (that is r"slkjdfljf" instead of "lsjdlfkjs") when defining re strings - you don't have backslash issues yet, but you will as soon as you start putting real '*' characters in your expression. However, when I test this, restr = r'/x(([^x]|x+[^/])*)x+/' re_ = re.compile(restr) print re_.findall("/xabxxcx/ /x123xxx/") findall now starts to give a tuple for each "comment", [('abxxc', 'xxc'), ('123xx', 'xx')] so you have gone beyond my limited re skill, and will need help from someone else. But I suggest you add some tests with multiple consecutive 'x' characters in the middle of your comment, and multiple consecutive 'x' characters before the trailing comment. In fact, from my recollections of trying to implement this type of comment recognizer by hand a long time ago in a job far, far away, test with both even and odd numbers of 'x' characters. -- Paul From victor.roig at gmail.com Sat Apr 14 17:41:48 2007 From: victor.roig at gmail.com (Victor Roig) Date: Sat, 14 Apr 2007 23:41:48 +0200 Subject: No can load a image with gnome-python and canvas Message-ID: Code --> http://pastebin.ca/439954 <-- resume: import gtk import gnomecanvas ... im = GdkImlib.Image("5b.png") w = self.acanvas.root().add('GnomeCanvasImage', image=im, width=70, height=105) ... at execurion time: NameError: global name 'GdkImlib' is not defined and if I probe: ... im = gnomecanvas.GdkImlib.Image("5b.png") w = self.acanvas.root().add('GnomeCanvasImage', image=im, width=70, height=105) ... at execution time: AttributeError: 'module' object has no attribute 'GdkImlib' Perhaps the problem is that I use the 'python-gdk-imlib-1.2' and GdkImlib is not defined at python2.4-gnome2 ???? thks -------------- next part -------------- An HTML attachment was scrubbed... URL: From soren.skou.nielsen at gmail.com Mon Apr 30 06:19:19 2007 From: soren.skou.nielsen at gmail.com (Soren) Date: 30 Apr 2007 03:19:19 -0700 Subject: How do I parse a string to a tuple?? In-Reply-To: References: <1177926452.830059.269230@n59g2000hsh.googlegroups.com> Message-ID: <1177928359.873007.327600@n59g2000hsh.googlegroups.com> Thanks alot everyone! Soren From aleax at mac.com Sat Apr 14 23:07:41 2007 From: aleax at mac.com (Alex Martelli) Date: Sat, 14 Apr 2007 20:07:41 -0700 Subject: function with list argument defaulting to [] - what's going on here??? References: <46217e8f$0$19437$4c368faf@roadrunner.com> Message-ID: <1hwkt6z.bo37tvvwmmesN%aleax@mac.com> Mike wrote: ... > Why is "r" not being reset to the empty list on subsequent calls? It > seems like it should be reinitialized when not explicitly provided. Alex From aleax at mac.com Fri Apr 20 22:48:02 2007 From: aleax at mac.com (Alex Martelli) Date: Fri, 20 Apr 2007 19:48:02 -0700 Subject: comparison with None References: <3IqdnfRnCNWPC7vbnZ2dnUVZ_jqdnZ2d@rcn.net> <2qzVh.7373$xL6.982@trnddc05> <_JAVh.1700$jR5.897@trnddc08> <1hwu26k.oyynyowsbxvcN%aleax@mac.com> <1hwuyed.1pfg5y31tp64kmN%aleax@mac.com> Message-ID: <1hwvw04.btbo2u17yso3sN%aleax@mac.com> Gabriel Genellina wrote: > En Fri, 20 Apr 2007 11:40:00 -0300, Alex Martelli escribi?: > > > I'm still interested to know where that erroneous quote from Alan Isaac > > comes from, because if it's in Python's docs, it can be fixed. > > It was a partial quote, that's why it appeared to be wrong: > > Library reference, 3.3 Comparisons > > "Objects of different types, except different numeric types and different > string types, never compare equal; such objects are ordered consistently > but arbitrarily." > > Reference Manual, 5.9 Comparisons > > "The objects need not have the same type. If both are numbers, they are > converted to a common type. Otherwise, objects of different types always > compare unequal, and are ordered consistently but arbitrarily." > > (Apart from the latter not menctioning string types too, looks good to me). Right. However, it might be worth underscoring that this applies to _built-in_ types, and user-defined types are free to implement different comparison semantics, although that should be done with care and good taste; for example, one might have a collection type defining __eq__ to mean "the same set of items as the other [iterable] operand in any order", though that might cause weird behavior such as a==b but b!=a (unfortunately there's no __req__, and __coerce__ is not involved in comparisons either). Still, not a major concern -- numbers and strings _do_ exhaust a vast majority of the use cases for object of different types comparing equal. Alex From ZeeGeek at gmail.com Sun Apr 15 14:02:20 2007 From: ZeeGeek at gmail.com (ZeeGeek) Date: 15 Apr 2007 11:02:20 -0700 Subject: Standardizing XML In-Reply-To: <462215bc$1@griseus.its.uu.se> References: <1176625793.392269.24060@n59g2000hsh.googlegroups.com> <462215bc$1@griseus.its.uu.se> Message-ID: <1176660139.990518.239470@l77g2000hsb.googlegroups.com> On Apr 15, 7:08 am, Jan Danielsson wrote: > ZeeGeek wrote: > > Is there a module for python to standardize XML? Since MSN Live Space > > doesn't use standard XML in the posts, I want to standardize them so > > that I can use them elsewhere. > > Hmm... XML _is_ standardized. If it doesn't follow the specs, then > it's not XML. If you want to make XML out of something which isn't XML, > you'll probably have to be a little more specific about how this other > format works. Thanks for correcting me. I worded it inproperly. For example, in the code returned by Live Space, they use
instead of
so that Blogger will complain that this tag is not valid because it doesn't have a closing tag. Another example is that the contents of a lot of the tag attributes like "color" and "size" are not surrounded by quotes. > > -- > Kind regards, > Jan Danielsson From anton.vredegoor at gmail.com Sat Apr 14 06:05:05 2007 From: anton.vredegoor at gmail.com (Anton Vredegoor) Date: Sat, 14 Apr 2007 12:05:05 +0200 Subject: Emergence of Grok In-Reply-To: <1176424693.546746.238660@d57g2000hsg.googlegroups.com> References: <1176424693.546746.238660@d57g2000hsg.googlegroups.com> Message-ID: Paul McGuire wrote: > I just stumbled upon a great-looking project, to make Zope3 more > approachable to mere mortals such as myself. Echoing the ROR mantra > of "convention over configuration", the Grok project (http:// > grok.zope.org/) aims to stand on the shoulders of Zope3, while > providing the ease of development of ROR (for instance, no more ZCML). > > Philipp von Weitershausen has a set of slides at > http://philikon.de/files/grok-bbq-sprint.pdf, and the Grok project > page links to a number of tutorials. > > Am I the last person to hear about this? No, not anymore since I learned about it later than you :-) However I can assure you this won't work. I'll tell you why. I'm a reasonably experienced python programmer and eager and interested to explore new -to me- paradigms, especially when there seems to be a possibility for making some money. I was lucky to find some programming job where I could learn zope and plone and make some money at the same time. I noticed that somewhere between pure python and zope there is a division where one cannot cross except by *paying* someone some money in order to learn how things work. When I told my employer at the time about this -he was totally *not* a programmer- the response was like, hey, but his other guy learned about it in one month etc, etc, or he just pointed at some plone programming colleagues who 'kicked ass'. Upon inspection of the 'ass kicking' colleagues' code I noticed that they had only a very rudimentary knowledge of python, or even didn't know much about programming altogether. There is no way around paying money because however 'intuitive' the code seems to be to the developers it is just not possible to read their sourcecode and understand what they are doing. This is a result of rapidly changing conventions that make it impossible to reproduce or adapt working code to one's specific likings. So the code examples are just one offs, working only for this specific case. Any adaptation will break the code, forcing one to contact -and pay- the developers, who are probably already working on some more advanced version. As result we see the emergence of 'more easy' solutions -like plone- which try to hide the complexities of zope for the end user but end up becoming even harder to 'grok' because the zope developers are racing ahead and don't bother to explain things unless they get paid. And why shouldn't they because they have to make a living too, don't they? Well I've got to make a living too and being forced to continually follow them around unable to pay for education and as a consequence not able to reproduce their code is just not financially feasible. Sorry, but this stuff is only 'grokkable' for the early adopters, however good ones' general python skills are. The problem gets even worse because by now -in order to make any money programming zope at all- one has to learn the zillion different ways _plone_ makes things 'easier' (it's not like there is a clean slate when one starts to work at a zope/plone programming site). The plone community is generally despised by the zope community because they are even more programming for money and not for universal enlightenment. I even suspect some plone programmers of hiding essential information from colleagues because that make *them* the experts, it's either that or maybe they just don't know themselves why things work the way they do and can't answer questions. OK, lets give them the benefit of doubt. While such deviousness generally cannot be assumed for the zope developers - try and ask questions on zope versus plone forums and notice the difference in attitude to persons asking for information- there is still a large difference in the way the zope community and the general python community 'think' about documentation. One can get close to understanding but in order to make it work there is no way around paying someone. I just know because I am good with python, I can read code and I know when things are not explained adequately. Essentially all this stuff is a pyramid scheme, only profitable for the well connected and/or the early adopters. That doesn't mean that I haven't met a lot of enthusiastic and helpful zope developers and programmers, it's just that they don't understand or don't want to understand that money can be a show stopper for people wanting to learn about zope. A. From bj_666 at gmx.net Sun Apr 15 12:57:35 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Sun, 15 Apr 2007 18:57:35 +0200 Subject: how to strip the domain name in python? References: <1176526155.679721.159870@l77g2000hsb.googlegroups.com> <1176564977.498635.171600@n59g2000hsh.googlegroups.com> <1176654669.737355.78300@y5g2000hsa.googlegroups.com> Message-ID: In <1176654669.737355.78300 at y5g2000hsa.googlegroups.com>, Marko.Cain.23 wrote: > On Apr 14, 10:36 am, Marko.Cain... at gmail.com wrote: >> On Apr 14, 12:02 am, Michael Bentley >> wrote: >> >> >> >> > On Apr 13, 2007, at 11:49 PM, Marko.Cain... at gmail.com wrote: >> >> > > Hi, >> >> > > I have a list of url names like this, and I am trying to strip out the >> > > domain name using the following code: >> >> > >http://www.cnn.com >> > >www.yahoo.com >> > >http://www.ebay.co.uk >> >> > > pattern = re.compile("http:\\\\(.*)\.(.*)", re.S) >> > > match = re.findall(pattern, line) >> >> > > if (match): >> > > s1, s2 = match[0] >> >> > > print s2 >> >> > > but none of the site matched, can you please tell me what am i >> > > missing? >> >> > change re.compile("http:\\\\(.*)\.(.*)", re.S) to re.compile("http:\/ >> > \/(.*)\.(.*)", re.S) >> >> Thanks. I try this: >> >> but when the 'line' ishttp://www.cnn.com, I get 's2' com, >> but i want 'cnn.com' (everything after the first '.'), how can I do >> that? >> >> pattern = re.compile("http:\/\/(.*)\.(.*)", re.S) >> >> match = re.findall(pattern, line) >> >> if (match): >> >> s1, s2 = match[0] >> >> print s2 > > Can anyone please help me with my problem? I still can't solve it. > > Basically, I want to strip out the text after the first '.' in url > address: > > http://www.cnn.com -> cnn.com from urlparse import urlsplit def get_domain(url): net_location = urlsplit(url)[1] return '.'.join(net_location.rsplit('.', 2)[-2:]) def main(): print get_domain('http://www.cnn.com') Ciao, Marc 'BlackJack' Rintsch From exarkun at divmod.com Thu Apr 26 14:39:31 2007 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Thu, 26 Apr 2007 14:39:31 -0400 Subject: wtf In-Reply-To: <9d7816d30704261135ta3cf99n854519e843bdd6e7@mail.gmail.com> Message-ID: <20070426183931.19381.344615427.divmod.quotient.5565@ohm> On Thu, 26 Apr 2007 21:35:03 +0300, Sergiy wrote: >print 1 / 2 >print -1 / 2 > >0 >-1 > >correct? Quoting http://www.python.org/doc/lib/typesnumeric.html: (1) For (plain or long) integer division, the result is an integer. The result is always rounded towards minus infinity: 1/2 is 0, (-1)/2 is -1, 1/(-2) is -1, and (-1)/(-2) is 0. Note that the result is a long integer if either operand is a long integer, regardless of the numeric value. Jean-Paul From rockym.z at gmail.com Mon Apr 2 01:30:03 2007 From: rockym.z at gmail.com (Rocky Zhou) Date: 1 Apr 2007 22:30:03 -0700 Subject: vim python: substitute 'spaces' indent to 'tabs'? Message-ID: <1175491803.283208.198020@l77g2000hsb.googlegroups.com> I am accustomed to vi my pthon scripts with 'tab' indent. But when I copy some code to my script, the indent may be 'spaces'. So I wanna a way to substitute those 'spaces' to be 'tabs' conveniently. For example, I: expand -t4 test.py >/tmp/test2.py vi /tmp/test2.py Then in vim, the indents should be: /^\( \{4\}\)*/ but I don't know how to substitute this to that: /^\(\t\{\4\}\)*/ Is there any way? Thanks. From gtcopeland at gmail.com Mon Apr 2 15:30:05 2007 From: gtcopeland at gmail.com (Greg Copeland) Date: 2 Apr 2007 12:30:05 -0700 Subject: DBAPI Loss DB Connection Message-ID: <1175542205.886388.152770@q75g2000hsh.googlegroups.com> According to the SQLAlchemy list, the DBAPI specification does not define a standard error reporting mechanism which would allow for generic detection of loss of database connection without DB specific exception handling. For me, this is a requisite for robust error handling. Not to mention, this seeminly defeats the purpose of using DBAPI since one can not have a robust DB application without tethering it to a specific DBAPI DB implementation; which seemingly defeates the purpose of using a DBAPI implementation. Assuming what I've been told is correct, what is the proper method to request a revision to the DBAPI specification to specifically address loss of DB connection and error handling in this regard? Greg From psdasilvaX at esotericaX.ptX Fri Apr 13 20:51:54 2007 From: psdasilvaX at esotericaX.ptX (Paulo da Silva) Date: Sat, 14 Apr 2007 01:51:54 +0100 Subject: Python editor/IDE on Linux? In-Reply-To: References: Message-ID: <1176565513.534115@jubilee.claranet.pt> Jack escreveu: > I wonder what everybody uses for Python editor/IDE on Linux? > I use PyScripter on Windows, which is very good. Not sure if > there's something handy like that on Linux. I need to do some > development work on Linux and the distro I am using is Xubuntu. > > eric3 is nice and simple. From larry.bates at websafe.com Mon Apr 9 15:00:15 2007 From: larry.bates at websafe.com (Larry Bates) Date: Mon, 09 Apr 2007 14:00:15 -0500 Subject: Hosting Companies: Help for Python Users? In-Reply-To: References: Message-ID: <_PednXh2AN6gEIfbnZ2dnUVZ_r3inZ2d@comcast.com> Steve Holden wrote: > I know there are quite a few hosting companies now who represent > themselves as Python-friendly. Rather than trawl through the Wiki pages, > however, and email each one separately I am sending this request to the > comp.lang.python list (and putting it on my blog) in the hope of > attracting those companies who are more involved with the Python community. > > There is a particular problem, highlighted recently by this comment from > Dennis Lee Beiber: > >> Too many 3rd-party modules still aren't available in 2.5 >> versions for my tastes... > > This applies particularly (though not exclusively) to the Windows > platform, for various reasons -- the most common one is that Linux > developers frequently don't have a Windows machine available to help > them test their builds and ensure that distributions are available. > > I am trying to address this problem, initially by making hosted Windows > machines available for use as buildbots. I already have agreement from > Grig Gheorghiu (who maintains the PSF's buildbots) to try and support > these efforts, and from Microsoft to consider providing appropriate > software. > > What I *don't* have is hosting companies offering me space on machines > in their racks. If anyone reading this can help out I'd appreciate it if > they would get in touch with me (replying to the newsgroup post or > commenting on the blog entry should do it). These machines would need > remote desktop access so they could be managed without physical presence. > > The intention is to try and shorten the "version lag" so that new > versions of Python can be better supported more quickly. I don't > guarantee that this will happen overnight, but I'd like to make a start. > > regards > Steve Apollo Hosting has this available (www.apollohosting.com). -Larry From donn at u.washington.edu Mon Apr 23 13:13:55 2007 From: donn at u.washington.edu (Donn Cave) Date: Mon, 23 Apr 2007 10:13:55 -0700 Subject: Select weirdness References: Message-ID: In article , Ron Garret wrote: > The answer is obvious: select is looking only at the underlying socket, > and not at the rfile buffers. > > So... is this a bug in select? Or a bug in my code? Yes. I don't see any specific followup to this point, but it is or at least should be a well known limitation of C library I/O and select. select() is an operating system function that has no way to know the state of your process I/O buffers, nor do the C stdio buffers don't come with a standard way to inspect that state. Therefore, if you mix C I/O with select(), you're more or less out of luck. This applies directly to Python, because it calls the operating system select() function and it uses C stdio buffers for its file object (and entices you to make this mistake by supporting a file object as an input to select().) This conflict can be relieved after a fashion by eliminating the buffer. The now unbuffered C fgets / Python readline won't store extra lines that select can't see, but the semantics of the operation are still a poor fit with the usual application of select. The number of system-level I/O calls is significantly greater as you transfer data one byte at a time, which may add a lot of overhead if you transfer a lot of data, and your readline() function still can't return until it gets that '\n', so a half line can block your application. It isn't a lot of work to read data with operating system functions that are compatible with select - os.read(), socket.recv() - and break it up into lines on your own, and this completely and efficiently resolves the problem. I haven't looked at your code. Donn Cave, donn at u.washington.edu From steve at REMOVEME.cybersource.com.au Mon Apr 30 06:15:41 2007 From: steve at REMOVEME.cybersource.com.au (Steven D'Aprano) Date: Mon, 30 Apr 2007 20:15:41 +1000 Subject: Dict Copy & Compare References: <4635AB95.4010309@timgolden.me.uk> Message-ID: On Mon, 30 Apr 2007 10:05:40 +0100, Robert Rawlins - Think Blue wrote: > I have two dicts, one named 'this' and the other named 'that'. > > I want to get all the unique keys from 'this' and log them into a file, I > then want to take all the unique values from 'that' and log them into a > separate file. The most straight-forward way is doing a simple pair of loops: for key in this: if key not in that: logThis(key) for key in that: if key not in this: logThat(key) > So it's just a case of firstly returning a list of all keys that are in > 'this' but NOT in 'that' and then visa versa, then loop over them performing > the function. Well, if you really do need to collect the list up front (why???) you can do this: uniqueFromThis = [key for key in this if key not in that] uniqueFromThat = [key for key in that if key not in this] Membership testing in dicts is efficient, so that should run quite fast unless you have millions of keys common to both dictionaries. -- Steven D'Aprano From carsten at uniqsys.com Tue Apr 10 07:41:09 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Tue, 10 Apr 2007 07:41:09 -0400 Subject: tuples, index method, Python's design In-Reply-To: References: <1175867771.114540.61810@n76g2000hsh.googlegroups.com> <1175884427.779950.267220@y80g2000hsf.googlegroups.com> Message-ID: <20070410113133.M92824@uniqsys.com> On 10 Apr 2007 07:31:13 GMT, Antoon Pardon wrote > On 2007-04-06, Carsten Haese wrote: > > If you have a use case for tuple.index, please show it to me, and I'll > > show you what you should be using instead of a tuple. > > No wonder no convincing use cases for tuples have shown up. You just > defined use cases of tuples as unconvincing. It's not a definition, it's an observation. I'm simply saying that all use cases I've seen for tuple.index could be written in a clearer fashion by using something else. Please prove me wrong by supplying a use case of tuple.index that can not be improved by rewriting. Note that I have proved elsewhere on this thread that any real use case for tuple.index will involve an operation to explicitly use an index different from the one obtained by the call to tuple.index(). I'd like to hear your opinion on this. > My personal opinion is that lack of use cases are used too much as an > excuse. Limiting the development of your language to use cases makes > your language less consistent and so makes your language less easy to > learn. That is your opinion, and you are entitled to your opinion. My opinion is that adding features that don't have any uses just weigh the language down unnecessarily, and they distract programmers from finding the best solution to their problem. > Of course it also limits the language to what the developers can > think off. Initially, yes, but if enough use cases exist for a feature that the developers didn't think of, it will be implemented. -Carsten From nogradi at gmail.com Mon Apr 30 06:47:42 2007 From: nogradi at gmail.com (Daniel Nogradi) Date: Mon, 30 Apr 2007 12:47:42 +0200 Subject: I/O Operations ..... In-Reply-To: <1177924784.122690.233540@p77g2000hsh.googlegroups.com> References: <1177919063.650070.321560@y80g2000hsf.googlegroups.com> <1177924784.122690.233540@p77g2000hsh.googlegroups.com> Message-ID: <5f56302b0704300347k11d24df5j80f7a97f2ba5670f@mail.gmail.com> > > > I am parsing an XML file and sending the output to two files.The > > > code asks the user to enter the input file,something like: > > > > > file_input = raw_input("Enter The ODX File Path:") > > > input_xml = open(file_input,'r') > > > > > Now suppose the user enters the path as : > > > C:\Projects\ODX Import\Sample Files\Global _A_UHP_Low_0.7.odx.xml > > > > > I have 2 output files to which i have to redirect the output.The > > > output file name should be same as input file in the same path ( the > > > extension has to change to a format "ini" which is basically text file > > > opened using notepad).Eg.. > > > output files should be : > > > C:\Projects\ODX Import\Sample Files\Global _A_UHP_Low_0.7.ini, and, > > > C:\Projects\ODX Import\Sample Files\Global _A_UHP_Low_0.7.xls > > > > If you only would like to know how to write files, this might help: > > > > content1 = .............. > > content2 = ............... > > > > f = open( 'file1', 'w' ) > > f.write( content1 ) > > f.close( ) > > > > f = open( 'file2', 'w' ) > > f.write( content2 ) > > f.close( ) > > > > HTH, > > Daniel- Hide quoted text - > > > > - Show quoted text - > > Hi, > File writing can be done in that way,but my query is > something different.I have to rename the output file by default with > input file name(only changing the extension. Maybe something like this will help (on Linux, Windows is similar): >>> from os import path >>> f = '/tmp/hello.xls' >>> path.splitext( f ) ('/tmp/hello', '.xls') >>> path.dirname( f ) '/tmp' >>> path.basename( f ) 'hello.xls' Daniel From http Fri Apr 6 04:14:13 2007 From: http (Paul Rubin) Date: 06 Apr 2007 01:14:13 -0700 Subject: Why NOT only one class per file? References: <1175721799.714907.52770@o5g2000hsb.googlegroups.com> <46142acc$0$7532$426a34cc@news.free.fr> <4614b40e$0$26843$426a74cc@news.free.fr> <1175778276.603838.86500@l77g2000hsb.googlegroups.com> <2O9Rh.24647$uo3.24013@newssvr14.news.prodigy.net> Message-ID: <7xirc9kjhm.fsf@ruckus.brouhaha.com> John Nagle writes: > Interestingly, PHP breaks this model; PHP programs are web pages. > They may be on to something. See also "literate programming", including the version built into Haskell. From seberino at spawar.navy.mil Fri Apr 20 18:36:00 2007 From: seberino at spawar.navy.mil (seberino at spawar.navy.mil) Date: 20 Apr 2007 15:36:00 -0700 Subject: When are immutable tuples *essential*? Why can't you just use lists *everywhere* instead? In-Reply-To: <1177103370.022138.110320@n59g2000hsh.googlegroups.com> References: <1177088796.622928.224890@d57g2000hsg.googlegroups.com> <1177089206.550423.288670@q75g2000hsh.googlegroups.com> <58sf33F2b1q8tU1@mid.individual.net> <1177103370.022138.110320@n59g2000hsh.googlegroups.com> Message-ID: <1177108560.660288.171890@n76g2000hsh.googlegroups.com> > The article explains that, amongst other things, tuples are faster > than lists, so if you are working with constant values (inmutables) > they are more indicated than lists. Thanks. I thought Python's design wasn't so concerned with optimizations. Adding a new type "just" for optimization reasons seems perhaps unnecessary. I could be wrong. From robert.rawlins at thinkbluemedia.co.uk Wed Apr 11 13:05:50 2007 From: robert.rawlins at thinkbluemedia.co.uk (Robert Rawlins - Think Blue) Date: Wed, 11 Apr 2007 18:05:50 +0100 Subject: SOAPPY Install Issues Message-ID: <009501c77c5b$ad157040$074050c0$@rawlins@thinkbluemedia.co.uk> Hi Guys, I've been trying hopelessly -ALL- afternoon to get python-xml and python-soappy working nicely, but for the -LIFE- of me I keep running into the same brick wall over and over. I'm running Debian and I've installed the latest stable builds of Python, Python-XML and Python-SOAPPY along with all there depensancies but i get the following error when trying to run my code. Traceback (most recent call last): File "xml.py", line 1, in ? from SOAPpy import SOAPProxy File "/var/lib/python-support/python2.4/SOAPpy/__init__.py", line 5, in ? from Client import * File "/var/lib/python-support/python2.4/SOAPpy/Client.py", line 57, in ? from Parser import parseSOAPRPC File "/var/lib/python-support/python2.4/SOAPpy/Parser.py", line 9, in ? import xml.sax File "/pblue/xml.py", line 1, in ? from SOAPpy import SOAPProxy ImportError: cannot import name SOAPProxy This is my Code: from SOAPpy import SOAPProxy url = 'http://services.xmethods.net:80/soap/servlet/rpcrouter' namespace = 'urn:xmethods-Temperature' server = SOAPProxy(url, namespace) server.getTemp('27502') It's a very simple program, and its driving me bonkers not being able to get it working, I'd appreciate any help you can offer to help resolve it. Thanks guys, I'm sure this is just a typical NOOB mistake, but hopefully once the damn thing is up and running it'll be clear sailing. Rob -------------- next part -------------- An HTML attachment was scrubbed... URL: From apardon at forel.vub.ac.be Tue Apr 10 08:29:11 2007 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 10 Apr 2007 12:29:11 GMT Subject: tuples, index method, Python's design References: <1175867771.114540.61810@n76g2000hsh.googlegroups.com> <1175884427.779950.267220@y80g2000hsf.googlegroups.com> Message-ID: On 2007-04-10, Carsten Haese wrote: > On 10 Apr 2007 07:31:13 GMT, Antoon Pardon wrote >> On 2007-04-06, Carsten Haese wrote: >> > If you have a use case for tuple.index, please show it to me, and I'll >> > show you what you should be using instead of a tuple. >> >> No wonder no convincing use cases for tuples have shown up. You just >> defined use cases of tuples as unconvincing. > > It's not a definition, it's an observation. I'm simply saying that all use > cases I've seen for tuple.index could be written in a clearer fashion by using > something else. Please prove me wrong by supplying a use case of tuple.index > that can not be improved by rewriting. No it is a defintion because it states this can be done for every possible case, even cases you have no idea about. > Note that I have proved elsewhere on this thread that any real use case for > tuple.index will involve an operation to explicitly use an index different > from the one obtained by the call to tuple.index(). I'd like to hear your > opinion on this. And what relevance would such a proof have? >> My personal opinion is that lack of use cases are used too much as an >> excuse. Limiting the development of your language to use cases makes >> your language less consistent and so makes your language less easy to >> learn. > > That is your opinion, and you are entitled to your opinion. My opinion is that > adding features that don't have any uses just weigh the language down > unnecessarily, and they distract programmers from finding the best solution to > their problem. Adding the index method to tuples is not adding a feature. It is removing a limitation. Writing an index function in python that works with whatever sequence is dead easy. So if the python core implementation only works with a specific sequence that is putting on unnecessary limitations. >> Of course it also limits the language to what the developers can >> think off. > > Initially, yes, but if enough use cases exist for a feature that the > developers didn't think of, it will be implemented. Which means your language will not be that usefull for a number of things until you have frustrated enough people. -- Antoon Pardon From bbxx789_05ss at yahoo.com Tue Apr 10 02:02:22 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: 9 Apr 2007 23:02:22 -0700 Subject: setup() and C extensions Message-ID: <1176184942.119878.230850@p77g2000hsh.googlegroups.com> Hi, I can't find any documentation on the setup() function in the distutils.core module; specifically I want to know what the 'name' argument does. In some examples in the python docs, they use the name argument like this: ---- from distutils.core import setup, Extension module1 = Extension('demo', sources = ['demo.c']) setup (name = 'PackageName', version = '1.0', description = 'This is a demo package', ext_modules = [module1]) ---- http://python.org/doc/current/ext/building.html#building So it looks like the 'name' argument should be a package name. However, when I compile an extension module using that format, I can import the module using the syntax: import module1 I don't have to use PackageName.module1. On the other hand, in another example in the python docs, they do this: --- from distutils.core import setup, Extension setup(name='foo', version='1.0', ext_modules=[Extension('foo', ['foo.c'])], ) ---- http://python.org/doc/current/dist/describing-extensions.html In that example, the name argument matches the module name in the Extension constructor. A similar example by Alex Martelli can be found at: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66509 So what is the name argument in setup() used for? From kyosohma at gmail.com Tue Apr 10 16:36:29 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: 10 Apr 2007 13:36:29 -0700 Subject: About Eggs In-Reply-To: <131nspji8t6559b@corp.supernews.com> References: <131nspji8t6559b@corp.supernews.com> Message-ID: <1176237389.246845.89850@v33g2000cwv.googlegroups.com> On Apr 10, 3:30 pm, Mark Elston wrote: > This is probably a *really* stupid question but... > I have looked at all the documentation I have for 2.4.3 > and all the docs I can download for 2.5 and I simply cannot > find anything, anywhere that documents what egg files are. > > I have read posts referring to them and have been able to > deduce that they are some form of zip file for the distribution > of modules but beyond that I cannot find *any* docs for them > anywhere. > > Where are they documented and how do I take advantage of them? > > Mark You need to go here: http://peak.telecommunity.com/DevCenter/PythonEggs http://peak.telecommunity.com/DevCenter/EggFormats Enjoy! Mike From http Mon Apr 16 22:54:51 2007 From: http (Paul Rubin) Date: 16 Apr 2007 19:54:51 -0700 Subject: Queue enhancement suggestion References: Message-ID: <7x3b2zd81w.fsf@ruckus.brouhaha.com> Jean-Paul Calderone writes: > Instead of putting multiple sentinels, just pre-construct the iterator > object. > work = iter(q.get, sentinel) > Re-use the same iterator in each thread, and you'll get the behavior > you're after. Whaaat???!!!! Can I dooooo that? It looks like it depends on the insides of iter being thread-safe, which I wouldn't have been willing to assume. Am I missing something? Thanks. From dmbkiwi at gmail.com Fri Apr 6 18:39:01 2007 From: dmbkiwi at gmail.com (dumbkiwi) Date: 6 Apr 2007 15:39:01 -0700 Subject: Convert xml symbol notation Message-ID: <1175899141.354348.207530@q75g2000hsh.googlegroups.com> Hi, I'm working on a script to download and parse a web page, and it includes xml symbol notation, such as ' for the ' character. Does anyone know of a pre-existing python script/lib to convert the xml notation back to the actual symbol it represents? From kyosohma at gmail.com Mon Apr 9 10:42:33 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: 9 Apr 2007 07:42:33 -0700 Subject: Database Timestamp conversion error In-Reply-To: <1175915704.435784.213830@b75g2000hsg.googlegroups.com> References: <1175892527.110813.26570@n76g2000hsh.googlegroups.com> <1175901654.390331.150420@e65g2000hsc.googlegroups.com> <1175915704.435784.213830@b75g2000hsg.googlegroups.com> Message-ID: <1176129753.861995.132950@n59g2000hsh.googlegroups.com> On Apr 6, 10:15 pm, kyoso... at gmail.com wrote: > On Apr 6, 6:20 pm, "John Machin" wrote: > > > > > On Apr 7, 6:48 am, kyoso... at gmail.com wrote: > > > > Hi, > > > > I am populating a mySQL database with data from the MS Access > > > database. I have successfully figured out how to extract the data from > > > Access, and I can insert the data successfully into mySQL with Python. > > > My problem is that I keep hitting screwy records with what appears to > > > be a malformed dbiDate object when I insert certain records. I get the > > > following traceback: > > > Ummm ... I didn't start using Python on databases till after DB API > > 2.0 came out (1999) so please pardon my ignorance, but isn't dbiDate > > something that was in API 1.0 but vanished in API 2.0 [e.g. its > > mentioned only briefly in the history section of the current mxODBC > > docs]? > > > If that's what you are still using: > > (a) I can't imagine how printing a dbiDate object would give such a > > garbled result -- try: > > > print type(obj) > > print repr(obj) > > for both a "bad" obj and a "good" obj. > > > (b) The API 1.0 docs give a clue: > > """ > > dbiDate(value) > > > This function constructs a 'dbiDate' instance that holds a > > date value. The value should be specified as an integer > > number of seconds since the "epoch" (e.g. time.time()). > > """ > > and googling brought up a few hits mentioning that not handling dates > > earlier that the "epoch" (1970-01-01T00:00:00) was a limitation. > > > So: if you are calling dbiDate yourself, you can inspect its input > > argument; presumably a date in the year 112 will show up as negative. > > > > Traceback (most recent call last): > > > File "\\someServer\Development\collectiveFleet.py", line 68, in - > > > toplevel- > > > mycursor.execute(sql) > > > TypeError: argument 1 must be string without null bytes, not str > > > > When I print the timestamp variable, I get this output: > > > > (I31 > > > (S'OK' > > > p1 > > > Nttp2 > > > . > > > > If I look in the MS Access database, I see the timestamp as "5/6/112". > > > Obviously some user didn't enter the correct date and the programmer > > > before me didn't give Access strict enough rules to block bad dates. > > > How do I test for a malformed date object so I can avoid this? > > > There > > > are thousands of records to transfer. > > > > I am using the odbc module for connection purposes with Python 2.4 on > > > Windows XP SP2. > > > If this is the odbc module that comes in the win32all package: > > 1. There are much better options available on Windows e.g. mxODBC. > > 2. Doesn't document dbiDate objects AFAICT. > > > If your SELECT from the Access db is returning you "seconds since the > > epoch" values, proceed as I suggested earlier. > > > If it is returning you dbiDate objects directly, find out if the > > dbiDate obj has any useful attributes or methods e.g. > > > obj.date_as_tuple() -> (2007, 4, 7, ...) > > or > > obj.year -> 2007 > > obj.month -> 4 > > etc > > > How to find out: insert code like > > print dir(obj) > > in your script and inspect the output for likely attribute/method > > names. > > > And if that doesn't help, abandon the odbc module and use e.g. mxODBC > > or Python adodb. > > > Hope some of this helps, > > John > > I did find a workaround that I implemented right before it was > quitting time, but I want to look into both of your guy's answers. I > have used the adodb module and I can't recall why I switched to the > odbc one. I think one of my co-workers said that the adodb wouldn't > work with mySQL on Linux or something. > > The quick-fix I used included using the datetime module and the time > module with the strftime() method. The type that was returned said it > was a dbiDate object (which is what I think I get in one of my other > programs that does use the adodb module!) > > John - when I tried printing a dir() on the returned object, I got and > empty list. > > Thanks for the suggestions. I won't get to try them until Monday. > > Mike I tried your suggestion: print type(timestamp) print repr(timestamp) Here's my results: # bad # good datetime.datetime(2007, 4, 9, 0, 0) When trying to use the "date_as_tuple" method on the object, I get the following: AttributeError: date_as_tuple Currently, I am using a "try" block to catch the error and just set it to the current date. This does work, but I've discovered that there are duplicates in the database somehow so I will need to find a way around that as well. Thanks for the feedback. Mike From n.pontikos at laconic.com Sat Apr 14 09:28:32 2007 From: n.pontikos at laconic.com (nikolas pontikos) Date: Sat, 14 Apr 2007 14:28:32 +0100 Subject: Python Feature Request: Explicit variable declarations In-Reply-To: <1176546078.934340.253810@y5g2000hsa.googlegroups.com> References: <1176546078.934340.253810@y5g2000hsa.googlegroups.com> Message-ID: samjnaa at gmail.com wrote: > Hello. Please tell me whether this feature request is sane (and not > done before) for python so it can be posted to the python-dev mailing > list. I should say first that I am not a professional programmer with > too much technical knowledge. > > I would like to have something like the "option explicit" statement in > Visual Basic which turns on C-like checking for declaration of > variables. This is highly helpful for people who are coming from C/C+ > +, for people who are learning programming using Python, and even > professionals, since this helps prevent typo errors like: > > sunlognitude = sunlongitude + 180.0 > > where the user has inadvertantly typed "g" before "n" and will later > wonder why his application is not working as expected. > Just as a side-note, if you used a+=1 instead of a=a+1 then you wouldn't have this problem. Languages like Perl and VB need a strict mode because they will auto-vivify variable for you. I.e. they will bring variables to life with defined or undefined values if you use them in a l-value (left hand side of an assignment) without having declared them prior. If you do that in Python you get an exception. From bcwhite at pobox.com Mon Apr 23 13:05:24 2007 From: bcwhite at pobox.com (bcwhite at pobox.com) Date: 23 Apr 2007 10:05:24 -0700 Subject: wx.TextCtrl.SetDefaultStyle not working? In-Reply-To: <1177159392.124932.218960@n76g2000hsh.googlegroups.com> References: <1177123135.263882.238100@y5g2000hsa.googlegroups.com> <1177159392.124932.218960@n76g2000hsh.googlegroups.com> Message-ID: <1177347923.815387.205690@q75g2000hsh.googlegroups.com> > On my platform, styling the text doesn't work for single line > TextCtrl's(which seems kind of stupid), and on Windows I think you are > required to specify wx.TE_RICH2 to style the text. This following > code colors the entered text red for me: That's it! I didn't have the TE_RICH2 option set. It works now. The docs say it's Windows only. Does the GTK version work without this flag? -- Brian From me2 at privacy.net Sun Apr 29 10:36:55 2007 From: me2 at privacy.net (Spin Dryer) Date: Sun, 29 Apr 2007 15:36:55 +0100 Subject: SEO - Search Engine Optimization - Seo Consulting References: <1177808356.681710.42980@n76g2000hsh.googlegroups.com> Message-ID: On Sat, 28 Apr 2007 21:21:39 -0400, ["Alvin Bruney [MVP]" ] said :- >Please don't spam this group Top posting and without removing the spamvertised site, you are as bad as the spammer. Call yourself an MVP, that's a joke Slick. Indeed the spam was not even seen by probably many servers until you decided to reply. From mehmetsyildirim at gmail.com Thu Apr 5 11:47:32 2007 From: mehmetsyildirim at gmail.com (msy) Date: 5 Apr 2007 08:47:32 -0700 Subject: embedded python project Message-ID: <1175788052.692903.28990@o5g2000hsb.googlegroups.com> selamlar; T?rkiyeden selamlar. Grubunuza yeni kat?ld?m. Pythonu ?ok merak ediyorum.Y?ksek lisans projemi python ile yapmak istiyorum. G?m?l? sistemler ?zerine bir konu tasarlamay? d???n?yorum. Basit olursa sevinirim. ?nerilerinizi bekliyorum. ?imdiden te?ekk?rler. Hi from Turkey. I am new in your grub. I wonder The Python. I want to do master project with python.I am thinking about to design an embedded system. ii will be happy if it be a simple. I wait your recommends. thanks for now. Mehmet S. YILDIRIM Bucak/Burdur Teacher of Computer || Bilgisayar ??retmeni Isparta S?leyman Demirel University || S?leyman Demirel ?niversitesi Institute of Sciences || Fen Bilimleri Enstit?s? Departman of Electronic and Computer || Elektronik ve Bilgisayar B?l?m? Master Student || Y?ksek Lisans ??rencisi T?rkiye From qilong_ren at yahoo.com Thu Apr 12 01:09:15 2007 From: qilong_ren at yahoo.com (Qilong Ren) Date: Wed, 11 Apr 2007 22:09:15 -0700 (PDT) Subject: python regular expression help Message-ID: <153830.63576.qm@web58915.mail.re1.yahoo.com> Hi, I don't quite understand the regular expression: re.compile("[a-z]+.*?(?=[a-z]|$)" ) and I tried. In some cases it works. But if the string looks like: s = 'a = 3.4 b = 4.5 5.6 c = "h","d"' it failed. What I came up with is : names = re.compile(r'(\w+)\s*=').findall(s) the corresponding values values = re.split(r'\w+\s*=',s)[1:] It dose not look good but it works. What do you think? Thanks,Qilong ----- Original Message ---- From: 7stud To: python-list at python.org Sent: Wednesday, April 11, 2007 8:27:57 PM Subject: Re: python regular expression help On Apr 11, 7:41 pm, liupeng wrote: > pattern = re.compile(r'\w+\s*=\s*[0-9]*.[0-9]*\s*') > lists = pattern.findall(s) > print lists > ['a=4 ', 'b=3.4 ', 'c=4.5'] > > On Wed, Apr 11, 2007 at 06:10:07PM -0700, Qilong Ren wrote: > > Hi, everyone, > > > I am extracting some information from a given string using python RE. The > > string is ,for example, > > s = 'a = 4 b =3.4 5.4 c = 4.5' > > What I want is : > > a = 4 > > b = 3.4 5.4 > > c = 4.5 > > Right now I use : > > pattern = re.compile(r'\w+\s*=\s*.*?\s+') > > lists = pattern.findall(s) > > It works for the string like 'a = 4 b = 3.4 c = 4.5', but does not work with > > strings like 'a=4 b=3.4 5.4 c = 4.5' > > > Any suggestion? > > > Thanks,Qilong > > > ??????????????????????????????????????????????????????????????????????????? ???? > > Don't get soaked. Take a quick peak at the forecast > > with theYahoo! Search weather shortcut. > > -- > >http://mail.python.org/mailman/listinfo/python-list > > signature.asc > 1KDownload Try this: import re s = 'a = 4 b =3.4 5.4 c = 4.5' r = re.compile("[a-z]+.*?(?=[a-z]|$)" ) l = r.findall(s) print l -- http://mail.python.org/mailman/listinfo/python-list ____________________________________________________________________________________ Be a PS3 game guru. Get your game face on with the latest PS3 news and previews at Yahoo! Games. http://videogames.yahoo.com/platform?platform=120121 -------------- next part -------------- An HTML attachment was scrubbed... URL: From sjmachin at lexicon.net Wed Apr 4 17:45:22 2007 From: sjmachin at lexicon.net (John Machin) Date: 4 Apr 2007 14:45:22 -0700 Subject: Indentifying the LAST occurrence of an item in a list In-Reply-To: <1175702329.330032.250750@w1g2000hsg.googlegroups.com> References: <1175702329.330032.250750@w1g2000hsg.googlegroups.com> Message-ID: <1175723121.298681.56600@n76g2000hsh.googlegroups.com> On Apr 5, 1:58 am, tkp... at hotmail.com wrote: > For any list x, x.index(item) returns the index of the FIRST > occurrence of the item in x. Is there a simple way to identify the > LAST occurrence of an item in a list? My solution feels complex - > reverse the list, look for the first occurence of the item in the > reversed list, and then subtract its index from the length of the list > - 1, i.e. > > LastOcc = len(x) - 1 - x[::-1].index(item) > > Is there a simpler solution? > If you need to do this for several possible items in the same list, it may be worthwhile to build a dictionary containing all the answers: | >>> seq = ['foo', 'bar', 'foo', 'bar', 'zot', 'foo'] | >>> rindex = dict((elt, inx) for inx, elt in enumerate(seq)) | >>> rindex | {'zot': 4, 'foo': 5, 'bar': 3} If you tell us what is the higher-level problem, we may be able to help you further. In other words, if lists did have a rindex method, what would you be using it to do? Are you constrained to use a list, or would another data structure be better? HTH, John From peter.mosley at talk21.com Tue Apr 17 18:06:38 2007 From: peter.mosley at talk21.com (peter) Date: 17 Apr 2007 15:06:38 -0700 Subject: Screen Control in WinXP and Linux Message-ID: <1176847598.832345.220270@b75g2000hsg.googlegroups.com> I've been wrestling on and off with this problem for over a year now, without success. Basically, I am looking for a simple set of screen and keyboard manipulation commands that will run identically under Linux and Windows. Nothing fancy - just clear the screen, print a string at an arbitrary xy position and detect a keystroke. I've googled around this newsgroup and elsewhere, and come across various suggestions (and even posted my own partial solutions), but still haven't come up with an elegant solution. My latest attempt is a throw back to the 1980's, using ANSI control codes. Seems to work on Linux, but not under Windows XP. I've found references to an application called ansi.com (didn't work), and instructions to modify the config.nt file to include dosonly device=%SystemRoot%\system32\ansi.sys then run command.com. I thought I was there - I could echo control codes satisfactorily, then when I tried to run python got an error message 'This program cannot be run in DOS mode'. Why is something which is apparently so simple such a hurdle? Other cross platform languages (euphoria, yabasic) seem to manage it. I don't have the expertise to write the code myself, but surely for the gurus this is not difficult. Any ideas? How can I run ansi.sys in WindowsXP. Can anyone come up with module with locate(), cls() and getch() functions? Is there any point in searching further? I realise this may come across as a bit petulant - not intended, but I am genuinely perplexed as to why this is such a show stopper. Peter From ptmcg at austin.rr.com Wed Apr 25 22:11:37 2007 From: ptmcg at austin.rr.com (Paul McGuire) Date: 25 Apr 2007 19:11:37 -0700 Subject: Feedback on Until recipe In-Reply-To: <1177430903.027128.86480@o40g2000prh.googlegroups.com> References: <1177430903.027128.86480@o40g2000prh.googlegroups.com> Message-ID: <1177553497.739324.135970@r35g2000prh.googlegroups.com> I moved the state into the Until instance vs. the Until class, so that it now supports nesting. But the calling syntax is even uglier - but necessary to avoid creating a new Until instance each time around. That is "while Until(blah):" evaluates and constructs a new Until instance each time around the loop, so that is why the state had to be kept in a class-level variable in your original design (which is why nesting doesn't work). class Until: def __init__(self, mybool): self.lastTest = True self.mybool = mybool def __nonzero__(self): ret,self.lastTest = self.lastTest,self.mybool() return ret i = 0 u1 = Until(lambda : i < 0 ) while u1: print "hello" i += 1 j = 0 u2 = Until(lambda : j < 0 ) while u2: print "byebye" j += 1 From cam.ac.uk at mh391.invalid Tue Apr 24 07:10:44 2007 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Tue, 24 Apr 2007 12:10:44 +0100 Subject: adjust In-Reply-To: <1177412489.683970.45320@u32g2000prd.googlegroups.com> References: <1177412489.683970.45320@u32g2000prd.googlegroups.com> Message-ID: saif.shakeel at gmail.com wrote: > How do i right adjust my output using python. http://docs.python.org/lib/typesseq-strings.html > minlength= 3, 3, 4, 2, 10, 10, 40, 2, 150, 4, 1, > 2, 2, 1, 2, 1, 6, 3, 17, 1, Something like: >>> def write_sequence(label, sequence): ... expanded_text = ",".join("%4d" % item for item in sequence) ... print "%s=%s" % (label, expanded_text) ... >>> write_sequence("minlength", minlength) minlength= 3, 3, 4, 2, 10, 10, 40, 2, 150, 4, 1 Completing with a trailing ",", using the entire sequence instead of a subset, and dealing with your hex constants are left as an exercise to the reader. -- Michael Hoffman From gdonald at gmail.com Fri Apr 13 16:40:26 2007 From: gdonald at gmail.com (Greg Donald) Date: Fri, 13 Apr 2007 15:40:26 -0500 Subject: Python editor/IDE on Linux? In-Reply-To: <461fe88c$0$6420$426a74cc@news.free.fr> References: <1176488840.672572.101830@y80g2000hsf.googlegroups.com> <461fe88c$0$6420$426a74cc@news.free.fr> Message-ID: <15e66e4e0704131340n15848178r96b3ebf6d9757011@mail.gmail.com> On 4/13/07, Bruno Desthuilliers wrote: > Except for real programmers... That's correct. We use: # dd if=/dev/tty of=/dev/hda1 and such. -- Greg Donald http://destiney.com/ From fuzzyman at gmail.com Sat Apr 21 20:14:04 2007 From: fuzzyman at gmail.com (Fuzzyman) Date: 21 Apr 2007 17:14:04 -0700 Subject: No speedup on multi-processor machine? In-Reply-To: References: <1177189332.916296.205280@d57g2000hsg.googlegroups.com> <1177197495.821701.140390@b58g2000hsg.googlegroups.com> Message-ID: <1177200844.134908.192110@q75g2000hsh.googlegroups.com> On Apr 22, 1:03 am, Neil Hodgson wrote: > Fuzzyman: > > > IronPython is *definitely* not restricted by the GIL. > > IronPython is currently mostly slower than CPython although the > particular problem should be tested to see if IronPython helps. > > Some recent benchmarks between IronPython and CPython:http://sparcs.kaist.ac.kr/~tinuviel/pybench/ > Yep, I've seen that. :-) http://www.voidspace.org.uk/python/weblog/arch_d7_2007_04_21.shtml#e687 It's not entirely slower, but mainly slower. OTOH, if you split a job into two threads on a twin-core machine, IronPython performance will increase dramatically whilst CPython will go down... Additionally, extending IronPython from C# is orders of magnitude easier than extending CPython from C. Fuzzyman http://www.voidspace.org.uk/ironpython/index.shtml > Neil From Art at Arthurian.com Wed Apr 4 15:15:57 2007 From: Art at Arthurian.com (Frank Arthur) Date: Wed, 4 Apr 2007 15:15:57 -0400 Subject: Over a billion people believe Allah will provide 72 virgins to some Muslims. References: <1175713650.228538.165920@p77g2000hsh.googlegroups.com> Message-ID: wrote in message news:1175713650.228538.165920 at p77g2000hsh.googlegroups.com... > Please visit www.nkusa.org, www.911blogger.com, www.stj911.org: > > I am surprised at the number of un-informed, ill-informed sheeple on > earth as well as politically correct hypocrites. And you are one of them Over a billion people believe Allah will provide 72 virgins to some Muslims. That doesn't mean it is at all true! From erendisaldarion at gmail.com Thu Apr 12 20:33:48 2007 From: erendisaldarion at gmail.com (Aldarion) Date: Fri, 13 Apr 2007 08:33:48 +0800 Subject: [ANN] mlabwrap-1.0final In-Reply-To: References: Message-ID: <461ECFEC.3070905@gmail.com> Stef Mientki wrote: > What can do MatLab, that can't be done in Python (SciPy) ? > (Ok I accept there's no SimuLink/PowerSim). > What about SVD(Singular value decomposition) for Sparse Matrix. I can't find this in numpy/scipy, someone told me it's in matrix. though I don't know how to get it in mlabwrap. From sberub at gmail.com Fri Apr 27 15:56:43 2007 From: sberub at gmail.com (Simon Berube) Date: 27 Apr 2007 12:56:43 -0700 Subject: Memory addressing In-Reply-To: References: <1177702902.156596.52510@n35g2000prd.googlegroups.com> Message-ID: <1177703803.179501.95300@n35g2000prd.googlegroups.com> On Apr 27, 3:52 pm, Carsten Haese wrote: > On Fri, 2007-04-27 at 12:41 -0700, Simon Berube wrote: > > Hi, > > > I have a rather simple question for which I couldn't find an > > answer. I noticed how a significant number of objects in Python return > > a __repr__() string along the lines of : > > > < Object at 0xXXXXXX> > > > I find this notation quite convenient to avoid out of control > > strings when using large arrays but I was wondering how you can use > > the memory address for assigning a new object. > > You can't. > > > In c, one could simple have a pointer to that memory address and > > voila, you have a new object you can analyze however it seems like > > python is allergic to direct memory manipulation. > > For good reason. Python is not C. > > > Hence, I was wondering what is the correct way to go about obtaining > > objects returned in such a fashion? What am I going wrong or what am I > > not getting? > > What is the actual problem you're trying to solve? > > -Carsten First of all, thanks for your reply. I am not trying to solve a problem in particular, I know that my way of thinking of very wrong in a python sense and I am simply trying to find the equivalent accepted practice. When you call certain objects __repr__() strings in python you often get the : happen. I am simply trying to understand how that information can be used to recreate a certain object that failed as per the given purpose of the __repr__() functions. In short, how do I used strings to recreate a an object. I hope this is clearer. From michael at jedimindworks.com Mon Apr 9 15:07:22 2007 From: michael at jedimindworks.com (Michael Bentley) Date: Mon, 9 Apr 2007 14:07:22 -0500 Subject: Is there a simple function to generate a list like ['a', 'b', 'c', ... 'z']? In-Reply-To: References: <1176107364.000517.68580@q75g2000hsh.googlegroups.com> Message-ID: <04657C8B-4991-4B37-932A-1F6EDD6C466B@jedimindworks.com> On Apr 9, 2007, at 6:30 AM, Duncan Booth wrote: > Michael Bentley wrote: > >> >> On Apr 9, 2007, at 3:29 AM, ??????????????????????????????????????? >> ?????? wrote: >> >>> Is there a simple function to generate a list like ['a', 'b', >>> 'c', ... >>> 'z']? The range() just can generate the numeric list. >> >> >> import string >> list(string.lowercase) >> > Be careful here. If you change locale that will return all lowercase > letters not just 'a' to 'z'. For example: > >>>> import locale, string >>>> locale.setlocale(locale.LC_ALL, '') > 'English_United Kingdom.1252' >>>> print string.lowercase > abcdefghijklmnopqrstuvwxyz??????????????????????????????????????? > Thanks, Duncan -- that would have eventually bitten me. From cam.ac.uk at mh391.invalid Sun Apr 1 21:35:51 2007 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Mon, 02 Apr 2007 02:35:51 +0100 Subject: capturing system exit status In-Reply-To: <1175474718.989364.18900@l77g2000hsb.googlegroups.com> References: <1175474718.989364.18900@l77g2000hsb.googlegroups.com> Message-ID: oscartheduck wrote: > in a program I'm writing I have several commands I pass to the unix OS > underneath the code. > > I want to perform error checking to make sure that the OS commands' > exit gracefully, but I'm not seeing a simple python module to do this. If you're using Python 2.5, you can use subprocess.check_call() which will raise CalledProcessError for nonzero exit code. If you're using Python 2.4, you can use retcode = subprocess.call() and check it yourself. -- Michael Hoffman From steve at holdenweb.com Wed Apr 25 10:30:33 2007 From: steve at holdenweb.com (Steve Holden) Date: Wed, 25 Apr 2007 10:30:33 -0400 Subject: Would You Write Python Articles or Screencasts for Money? In-Reply-To: References: <462DCCE6.9060908@taupro.com> <1hx2dvj.10ek1v51noh1otN%aleax@mac.com> Message-ID: Anton Vredegoor wrote: > Antoon Pardon wrote: >> On 2007-04-25, Anton Vredegoor wrote: >>> Antoon Pardon wrote: >>> >>>>>> That's a good point, and also a valid reason for restricting the >>>>>> voting community to PSF members. Thanks, Alex. >>>>> So in order to avoid a suspicion of a conflict of interest you want to >>>>> turn the whole thing into private property of the PSF? >>>>> >>>>> That is the most ridiculous suggestion I have ever >>>> I kind of understand why they would want to do this. If you have >>>> no limitations on who may vote, such a contest can easily turn >>>> into a contest of who can mobilize the biggest clan of supporters. >>> Sure, any democratic process can be derailed by a coordinated effort of >>> people with a different mentality. To prevent such things by killing the >>> democratic process oneself right at the beginning of a project is a >>> peculiar way of avoiding this risk. >> As far as I understood the idea was to reward excellence. The process >> to achieve this can be democratic, but in that case it is just a means >> to an end. The democratic process was not an end itself. > > Yes, but this sub thread was about avoiding a suspicion of a conflict of > interests. If this suspicion is to be avoided by just openly promoting > the interests of the members of the PSF that is one hell of a way of > solving the problem. > Perhaps you misunderstood. The quote you were reacting to said """... for restricting the *voting* community to PSF members""" (emphasisi added here). In other words, the PSF members get to decide who wins awards, while themselves being ineligible. Does this make a difference? regards Steve -- Steve Holden +1 571 484 6266 +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 arnodel at googlemail.com Sun Apr 22 08:12:58 2007 From: arnodel at googlemail.com (Arnaud Delobelle) Date: 22 Apr 2007 05:12:58 -0700 Subject: Can __init__ not return an object? In-Reply-To: References: Message-ID: <1177243978.232076.35630@q75g2000hsh.googlegroups.com> On Apr 22, 3:36 am, "Steven W. Orr" wrote: > When I go to create an object I want to be able to decide whether the > object is valid or not in __init__, and if not, I want the constructor to > return something other than an object, (like maybe None). [...] __init__ doesn't create an instance, it initializes it, i.e. does things like settings some attributes, etc. The method that creates instances is called __new__ (see http://docs.python.org/ref/customization.html). -- Arnaud From kelvin.you at gmail.com Mon Apr 9 07:11:43 2007 From: kelvin.you at gmail.com (=?utf-8?B?5Lq66KiA6JC95pel5piv5aSp5rav77yM5pyb5p6B5aSp5rav5LiN6KeB5a62?=) Date: 9 Apr 2007 04:11:43 -0700 Subject: how to use the string '\\.\' Message-ID: <1176117103.670611.291740@n59g2000hsh.googlegroups.com> print r'\\.\' This line will cause error. I just want to print the \\.\ why the prefix character "r" isn't effective. Thanks! From henriklied at gmail.com Thu Apr 5 17:53:04 2007 From: henriklied at gmail.com (Henrik Lied) Date: 5 Apr 2007 14:53:04 -0700 Subject: Problems with os.spawnv In-Reply-To: References: <1175807996.524018.146070@n76g2000hsh.googlegroups.com> Message-ID: <1175809984.762401.11020@n59g2000hsh.googlegroups.com> On Apr 5, 11:39 pm, "Gabriel Genellina" wrote: > En Thu, 05 Apr 2007 18:19:56 -0300, Henrik Lied > escribi?: > > > So, I thought to myself that spawnv would be a good fit for this. The > > problem is that it doesn't fire of the command. > > > Here's my test script:http://dpaste.com/hold/7981/ > > > Why won't this work? The while-loop is printed, but the os command > > isn't executed. I've also tried to specify the whole path to mencoder > > (/opt/local/bin/mencoder), but to no use. > > You are using: > v = os.spawnv(os.P_NOWAIT, "mencoder", "/Users/henriklied/test.mov > -ofps 25 -o test.flv ...") > > Read the docs about the spawnv function: http://docs.python.org/lib/os-process.html#l2h-2749 > > In particular "...The "v" variants are good when the number of parameters > is variable, with the arguments being passed in a list or tuple as the > args parameter. In either case, the arguments to the child process must > start with the name of the command being run." > > So, for spawnv, you should build a list with each argument as an item, > being "mencoder" the first item. > But in your case it's a lot easier to use spawnl: > > v = os.spawnl(os.P_NOWAIT, "mencoder", "mencoder", > "/Users/henriklied/test.mov", "-ofps", "25", "-o", "...") > > -- > Gabriel Genellina Hi Gabriel, Thanks for your reply - but I'm afraid to tell you that spawnl didn't do the trick either. Here's the full command I used: http://dpaste.com/hold/7982/ I'd still love to get a working example of my problem using the Subprocess module. :-) From johnjsal at NOSPAMgmail.com Fri Apr 13 11:37:36 2007 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Fri, 13 Apr 2007 11:37:36 -0400 Subject: Databases with python In-Reply-To: References: Message-ID: <461fa3c1$0$21352$c3e8da3@news.astraweb.com> Anthony Irwin wrote: > Also is wxpython the best cross platform gui library it seems to be the > best I have seen so far. IMO, it's an extremely mature and well-supported library. I have no experience with others (except a brief stint with Tkinter) but the consensus I hear seems to be that wxPython is probably the most popular choice. From victor.lebrun at gmail.com Sat Apr 28 17:27:35 2007 From: victor.lebrun at gmail.com (vml) Date: 28 Apr 2007 14:27:35 -0700 Subject: python and activeX control In-Reply-To: <4633b838$0$27395$ba4acef3@news.orange.fr> References: <1177792357.047096.18480@q75g2000hsh.googlegroups.com> <4633b838$0$27395$ba4acef3@news.orange.fr> Message-ID: <1177795655.431410.216110@e65g2000hsc.googlegroups.com> On 28 avr, 23:09, "M?ta-MCI" wrote: > Bonsoir ! > > Flagrant d?lit de manque de confiance dans les newsgroups fran?ais en vue... > > Ha ! Ha ! Ha ! Bonne chance avec les US... c'est vrai j'avoue ;) From kushal.kumaran at gmail.com Mon Apr 2 00:31:59 2007 From: kushal.kumaran at gmail.com (Kushal Kumaran) Date: 1 Apr 2007 21:31:59 -0700 Subject: Question about using urllib2 to load a url In-Reply-To: <1175464332.246623.30090@b75g2000hsg.googlegroups.com> References: <1175464332.246623.30090@b75g2000hsg.googlegroups.com> Message-ID: <1175488319.637226.219090@n59g2000hsh.googlegroups.com> On Apr 2, 2:52 am, "ken" wrote: > Hi, > > i have the following code to load a url. > My question is what if I try to load an invalide url > ("http://www.heise.de/"), will I get an IOException? or it will wait > forever? > Depends on why the URL is invalid. If the URL refers to a non- existent domain, a DNS request will result in error and you will get an "urllib2.URLError: ". If the name resolves but the host is not reachable, the connect code will timeout (eventually) and result in an "urllib2.URLError: ". If the host exists but does not have a web server running, you will get an "urllib2.URLError: ". If a webserver is running but the requested page does not exist, you will get an "urllib2.HTTPError: HTTP Error 404: Not Found". The URL you gave above does not meet any of these conditions, so results in a valid handle to read from. If, at any time, an error response fails to reach your machine, the code will have to wait for a timeout. It should not have to wait forever. > Thanks for any help. > > opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj)) > urllib2.install_opener(opener) > > txheaders = {'User-agent': 'Mozilla/5.0 (X11; U; Linux i686; en- > US; rv:1.8.1.3) Gecko/20070309 Firefox/2.0.0.3'} > > try: > req = Request(url, txdata, txheaders) > handle = urlopen(req) > except IOError, e: > print e > print 'Failed to open %s' % url > return 0; -- Kushal From kw at codebykevin.com Thu Apr 5 11:39:04 2007 From: kw at codebykevin.com (Kevin Walzer) Date: Thu, 05 Apr 2007 11:39:04 -0400 Subject: Welch essential for learning Tkinter well? In-Reply-To: References: Message-ID: <46151818.6080302@codebykevin.com> James Stroud wrote: >This begs the > question, is anyone truly an expert in Tkinter? Frederick Lundh is, if anyone is. http://www.pythonware.com/library/tkinter/introduction/index.htm (outdated) http://effbot.org/tkinterbook/ (new but incomplete) Coming to Python from a Tcl/Tk background, I find Tkinter to be pretty compatible with what I know about Tk: usually it's just a matter of figuring out how to translate the code. Having a Tk background from Tcl is also helpful in using some of the more advanced Tcl/Tk stuff that has been wrapped in Python, but isn't much documented or widely used, such as BWidgets. From that standpoint, the Welch book is a useful resource, though probably not essential. -- Kevin Walzer Code by Kevin http://www.codebykevin.com From jura.grozni at gmail.com Thu Apr 19 15:31:36 2007 From: jura.grozni at gmail.com (azrael) Date: 19 Apr 2007 12:31:36 -0700 Subject: Creating search engine in Python Good or Bad [in performance] In-Reply-To: References: <1177007283.157437.271230@n76g2000hsh.googlegroups.com> Message-ID: <1177011096.243340.73610@q75g2000hsh.googlegroups.com> That's right. It all depends on your design. When you do a select you could brute force it to to return the data, but the speed comes from elegant designing and programing skills. Using C++ or even Better C would probably boost your database model. Try to sort the data in the database so you can efficient use Hash-es On Apr 19, 8:46 pm, Larry Bates wrote: > Clement wrote: > > I am now creating IR engine in python which has its own database > > implementation . For nearly 2GB files it works fast. Can i expect the > > same speed when my database goes large. Else i have to chose other > > language[c/c++] for the speed............. > > Please tell me the solution................................ > > Your speed will be good if your database design is good. We don't have > a crystal ball out here to see into your database design. It is also > not clear what the bottlenecks to "speed" would be for you. If it is > disk I/O or LAN bandwidth C won't help at all. > > -Larry From howe.steven at gmail.com Thu Apr 19 02:19:39 2007 From: howe.steven at gmail.com (Steven Howe) Date: Wed, 18 Apr 2007 23:19:39 -0700 Subject: comparison with None In-Reply-To: <_JAVh.1700$jR5.897@trnddc08> References: <_JAVh.1700$jR5.897@trnddc08> Message-ID: <462709FB.9020607@gmail.com> Alan Isaac wrote: > "Terry Reedy" wrote in message > news:mailman.6686.1176934558.32031.python-list at python.org... > >> Should be in the reference manual section on comparisons. >> > > Only to this extent: > http://www.python.org/doc/2.4/ref/comparisons.html > > objects of different types always compare unequal, and are ordered > consistently but arbitrarily. > > (This unusual definition of comparison was used to simplify the > definition of operations like sorting and the in and not in > operators. > In the future, the comparison rules for objects of different types > are > likely to change.) > > ... Most other types compare unequal unless they are the same > object; > the choice whether one object is considered smaller or larger than > another one is made arbitrarily but consistently within one > execution > of a program. > > This does not provide a direct answer to "why" None comparisons. > (As far as I can tell, None is less than any object.) > > However, Gary Herron's explanation makes sense: this provides a stable > sort when None is involved, and meets the criterion that objects of > different types must always compare unequal. However this would also > be true if None always compared greater than any object, and the current > behavior does not seem to be guaranteed. > > Is that about right? > > Cheers, > Alan Isaac > > > I love scripting languages ... but sometimes an explicit evaluation that one would find in a compiled language is better. Which is why I suggested using the explicit type(x) == types.NoneType as opposed to x is None -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at holdenweb.com Mon Apr 23 13:28:09 2007 From: steve at holdenweb.com (Steve Holden) Date: Mon, 23 Apr 2007 13:28:09 -0400 Subject: When are immutable tuples *essential*? Why can't you just use lists *everywhere* instead? In-Reply-To: References: <1177088796.622928.224890@d57g2000hsg.googlegroups.com> <1177089206.550423.288670@q75g2000hsh.googlegroups.com> <58sf33F2b1q8tU1@mid.individual.net> <1177103370.022138.110320@n59g2000hsh.googlegroups.com> <1177108560.660288.171890@n76g2000hsh.googlegroups.com> Message-ID: Neil Cerutti wrote: > On 2007-04-21, Steven D'Aprano wrote: >> On Fri, 20 Apr 2007 15:36:00 -0700, seberino at spawar.navy.mil wrote: >>>> The article explains that, amongst other things, tuples are >>>> faster than lists, so if you are working with constant values >>>> (inmutables) they are more indicated than lists. >>> Thanks. I thought Python's design wasn't so concerned with >>> optimizations. Adding a new type "just" for optimization >>> reasons seems perhaps unnecessary. I could be wrong. >> It's times like this I want to cry... >> >> >>>>> adict = {(1,2): "parrot"} >> Try replacing that tuple with a list. "Just optimization" my eye! > > So the question becomes: Why do Python dictionaries require keys > to be of an immutable type? > Because otherwise people would expect to be able to use a list to select a dictionary entry even after they'd modified elements of the list after creating the dictionary entry. Which they couldn't. So Python doesn't let them use lists. regards Steve -- Steve Holden +1 571 484 6266 +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 robert.kern at gmail.com Fri Apr 20 17:29:57 2007 From: robert.kern at gmail.com (Robert Kern) Date: Fri, 20 Apr 2007 16:29:57 -0500 Subject: how to get a wrap aound slice of numpy array In-Reply-To: <1177100936.803752.54890@y5g2000hsa.googlegroups.com> References: <1177100936.803752.54890@y5g2000hsa.googlegroups.com> Message-ID: danfan1981 at yahoo.com wrote: > Hi, I am learning Numpy and using it for a course project. Welcome! You might want to ask more numpy questions on the numpy mailing list. Answers to numpy questions here tend to be hit-or-miss. http://www.scipy.org/Mailing_Lists > Suppose x = [0, 1, 2, 3, 4], I know that x[0:2] would give [0,1], and > x[-1] give [4], is there a way that I can get [4,0,1]. I try x[-1:2], > but it returns an empty array. x[[-1, 0, 1]] -- 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 kelvin.you at gmail.com Sun Apr 29 07:51:19 2007 From: kelvin.you at gmail.com (=?utf-8?B?5Lq66KiA6JC95pel5piv5aSp5rav77yM5pyb5p6B5aSp5rav5LiN6KeB5a62?=) Date: 29 Apr 2007 04:51:19 -0700 Subject: Could zipfile module process the zip data in memory? In-Reply-To: References: <1177845313.798239.71580@o5g2000hsb.googlegroups.com> Message-ID: <1177847479.803195.12820@c35g2000hsg.googlegroups.com> On Apr 29, 7:37?pm, "Daniel Nogradi" wrote: > > I made a C/S network program, the client receive the zip file from the > > server, and read the data into a variable. how could I process the > > zipfile directly without saving it into file. > > In the document of the zipfile module, I note that it mentions the > > file-like object? what does it mean? > > > class ZipFile( file[, mode[, compression[, allowZip64]]]) > > ? ? ? ? ?Open a ZIP file, where file can be either a path to a file (a > > string) or a file-like object. > > Yes it is possible to process the content of the zipfile without > saving every file: > > [untested] > > ? ? ? ? from zipfile import ZipFile > ? ? ? ? from StringIO import StringIO > > ? ? ? ? zipp = ZipFile( this_is_the_zip_file_from_your_server, 'r' ) > ? ? ? ? for name in zipp.namelist( ): > ? ? ? ? ? ? ? ? content = zipp.read( name ) > ? ? ? ? ? ? ? ? s = StringIO( ) > ? ? ? ? ? ? ? ? s.write( content ) > ? ? ? ? ? ? ? ? # now the file 'name' is in 's' (in memory) > ? ? ? ? ? ? ? ? # you can process it further > ? ? ? ? ? ? ? ? # ............ > ? ? ? ? ? ? ? ? s.close( ) > ? ? ? ? zipp.close( ) > > HTH, > Daniel Thanks! Maybe my poor english makes you confusion:-). The client receive the zip file data from the server, and keep these data as a variable, not as a file in harddisk. such as "zipFileData", but the first argument of the "ZipFile" is filename. I would like to let the ZipFile() open the file from "zipFileData" directly but not file in harddisk zipp = ZipFile( this_is_the_zip_file_from_your_server, 'r' ) ^ I don't have this file, all its data is in a variable. From jstroud at mbi.ucla.edu Fri Apr 6 19:30:12 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Fri, 06 Apr 2007 16:30:12 -0700 Subject: Comments in ConfigParser module In-Reply-To: References: Message-ID: Joel Andres Granados wrote: > Hi list: > Any comment greatly appreciated.... Very clever. From nagle at animats.com Sun Apr 1 01:15:45 2007 From: nagle at animats.com (John Nagle) Date: Sun, 01 Apr 2007 05:15:45 GMT Subject: Shed Skin Python-to-C++ Compiler 0.0.21, Help needed In-Reply-To: References: Message-ID: <5eHPh.11067$JZ3.4396@newssvr13.news.prodigy.net> Mark Dufour wrote: > Hi all, > > I have recently released version 0.0.20 and 0.0.21 of Shed Skin, an > optimizing Python-to-C++ compiler. Shed Skin allows for translation of > pure (unmodified), implicitly statically typed Python programs into > optimized C++, and hence, highly optimized machine language. Besides > many bug fixes and optimizations, these releases add the following > changes: > > I'm also > hoping someone else would like to deal with integration with CPython > (so Shed Skin can generate extension modules, and it becomes easier to > use 'arbitrary' external CPython modules such as 're' and 'pygame'.) Reusing precompiled external modules will be tough. Even CPython has trouble with that. But that's just a conversion problem. Maybe SWIG (yuck, but it exists) could be persuaded to cooperate. For regular expressions, here's an implementation, in C++, of Python-like regular expressions. http://linuxgazette.net/issue27/mueller.html That might be a way to get a regular expression capability into Shed Skin quickly. > Finally, there may be some interesting Master's thesis subjects in > improving Shed Skin, such as transforming heap allocation into stack- > and static preallocation, where possible, to bring performance even > closer to manual C++. Please let me know if you are interested in > helping out, and/or join the Shed Skin mailing list. Find out where the time is going before spending it on that. A good test: BeautifulSoup. Many people use it for parsing web pages, and it's seriously compute-bound. John Nagle From nospam at invalid.com Mon Apr 9 23:17:33 2007 From: nospam at invalid.com (Jack) Date: Mon, 9 Apr 2007 20:17:33 -0700 Subject: Custom Python Runtime References: <2NudnVn5jsm2QIvbnZ2dnUVZ_vqpnZ2d@comcast.com> Message-ID: Thanks for all the replies. It would be great to have all customization related information on one doc page. A few more questions: 1. One Windows, it's possible to zip all files in a Python24.zip. I'm not very clear if it's used in the stardard distribution. What can, and what can not be put into this file? I suppose zip file will help reduce the distribution size. 2. I remember trying the compiler option to strip doc strings didn't help but maybe I didn't do it right. I had to write some code to compile selected py files. Is there a way to compile a stripped Python with compile time options? 3. Some files go to the Windows\system32 directory, including some win32all files. Can they be in the current directory as python.exe? 4. Are the registry entries necessary? Thanks "Jack" wrote in message news:2NudnVn5jsm2QIvbnZ2dnUVZ_vqpnZ2d at comcast.com... > Since the full installation of Python (from either the standard installer > or ActiveState installer) is too big for my intended use, I'd like to > build a custom distribution of Python for Windows platform, omitting some > lib files, such as audio, tk, printing, testing units, etc. > > Is there a way to customize the Windows build? In my case, there is no > need to build an installer. The best way is to have everything in a > directory, as long as I know where to find Python and Python knows where > to find the necessary libs. Any online docs describing this? Thanks! > From TimeHorse at gmail.com Thu Apr 5 17:08:46 2007 From: TimeHorse at gmail.com (darklord@timehorse.com) Date: 5 Apr 2007 14:08:46 -0700 Subject: RFC: Assignment as expression (pre-PEP) In-Reply-To: References: <1175802680.021987.39220@p77g2000hsh.googlegroups.com> Message-ID: <1175807326.466842.219820@p77g2000hsh.googlegroups.com> On Apr 5, 4:22 pm, Duncan Booth wrote: > Can you come up with a real example where this happens and which cannot be > easily rewritten to provide better, clearer code without the indentation? > > I'll admit to having occasionally had code not entirely dissimilar to this > when first written, but I don't believe it has ever survived more than a > few minutes before being refactored into a cleaner form. I would claim that > it is a good thing that Python makes it obvious that code like this should > be refactored. I am trying to write a parser for a text string. Specifically, I am trying to take a filename that contains meta-data about the content of the A/V file (mpg, mp3, etc.). I first split the filename into fields separated by spaces and dots. Then I have a series of regular expression matches. I like Cartesian's 'event-based' parser approach though the even table gets a bit unwieldy as it grows. Also, I would prefer to have the 'action' result in a variable assignment specific to the test. E.g. def parseName(name): fields = sd.split(name) fields, ext = fields[:-1], fields[-1] year = '' capper = '' series = None episodeNum = None programme = '' episodeName = '' past_title = false for f in fields: if year_re.match(f): year = f past_title = True else: my_match = capper_re.match(f): if my_match: capper = capper_re.match(f).group(1) if capper == 'JJ' or capper == 'JeffreyJacobs': capper = 'Jeffrey C. Jacobs' past_title = True else: my_match = epnum_re.match(f): if my_match: series, episodeNum = my_match.group('series', 'episode') past_title = True else: # If I think of other parse elements, they go here. # Otherwise, name is part of a title; check for capitalization if f[0] >= 'a' and f[0] <= 'z' and f not in do_not_capitalize: f = f.capitalize() if past_title: if episodeName: episodeName += ' ' episodeName += f else: if programme: programme += ' ' programme += f return programme, series, episodeName, episodeNum, year, capper, ext Now, the problem with this code is that it assumes only 2 pieces of free-form meta-data in the name (i.e. Programme Name and Episode Name). Also, although this is not directly adaptable to Cartesian's approach, you COULD rewrite it using a dictionary in the place of local variable names so that the event lookup could consist of 3 properties per event: compiled_re, action_method, dictionary_string. But even with that, in the case of the epnum match, two assignments are required so perhaps a convoluted scheme such that if dictionary_string is a list, for each of the values returned by action_method, bind the result to the corresponding ith dictionary element named in dictionary_string, which seems a bit convoluted. And the fall-through case is state-dependent since the 'unrecognized field' should be shuffled into a different variable dependent on state. Still, if there is a better approach I am certainly up for it. I love event-based parsers so I have no problem with that approach in general. From nogradi at gmail.com Sat Apr 21 05:44:35 2007 From: nogradi at gmail.com (Daniel Nogradi) Date: Sat, 21 Apr 2007 11:44:35 +0200 Subject: Styled Output In-Reply-To: <3512790415788360620@unknownmsgid> References: <3512790415788360620@unknownmsgid> Message-ID: <5f56302b0704210244m738f3cb7n84d2b0cbc7091b5e@mail.gmail.com> > I'm running a program of mine from Linux bash script and it currently > outputs status messages to the command prompt, but they all look a little > boring to say the least, it'll be like this. [snip] > And perhaps have the word 'success' in green, or red for 'failed' and things > like that, just to make it a little more presentable to the user. You might find that urwid, a console user interface library, meets your needs: http://excess.org/urwid/ Daniel From carsten at uniqsys.com Sun Apr 8 20:10:21 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Sun, 08 Apr 2007 20:10:21 -0400 Subject: tuples, index method, Python's design In-Reply-To: <7x8xd2iq53.fsf@ruckus.brouhaha.com> References: <1175867771.114540.61810@n76g2000hsh.googlegroups.com> <1175884427.779950.267220@y80g2000hsf.googlegroups.com> <1175953520.316208.241490@o5g2000hsb.googlegroups.com> <7xzm5igbrb.fsf@ruckus.brouhaha.com> <7x8xd2iq53.fsf@ruckus.brouhaha.com> Message-ID: <1176077421.3220.6.camel@localhost.localdomain> On Sun, 2007-04-08 at 13:10 -0700, Paul Rubin wrote: > Carsten Haese writes: > > > Do you not see the gratuituous inconsistency between tuples and lists > > > as a useless feature? What is the use case for keeping it? > > > > When a new feature is requested, the burden of proof is on the requester > > to show that it has uses. The use case for not having tuple.index is > > that there are no use cases for having it. If that answer sounds absurd, > > it is because your question is absurd. > > The use case has already been discussed. Removing the pointless > inconsistency between lists and tuples means you can stop having to > remember it, so you can free up brain cells for implementing useful > things. That increases your programming productivity. Will tuples also get a sort method? What about append and extend? pop? __iadd__? __delslice__? How many brain cells are actually freed up by not having to remember that *one* method that you'd never use doesn't exist? -Carsten From usenet at nicko.org Tue Apr 10 13:32:54 2007 From: usenet at nicko.org (Nicko) Date: 10 Apr 2007 10:32:54 -0700 Subject: Database in memory In-Reply-To: <1176207003.322736.114820@y5g2000hsa.googlegroups.com> References: <1176124752.172926.129850@w1g2000hsg.googlegroups.com> <1176207003.322736.114820@y5g2000hsa.googlegroups.com> Message-ID: <1176226373.505011.63100@e65g2000hsc.googlegroups.com> On Apr 10, 1:10 pm, "Nicko" wrote: > If you expect to do exact-match look-up where the keys are not unique > then build a dictionary containing 'set' objects which are the sets of > records which have the given key. This lets you neatly find the > intersection of selections on multiple criteria (e.g. matches = > zipcode_index["94101"] & hometype_index["condo"] ). Just FYI, if you're going to go this route then the items that you are indexing have to be hashable, which the built in 'list' type is not. Tuples are, or you can make some custom class (or your own subtype of list) which implements the __hash__ method based on some 'primary key' value from your data. Or you could just go for SQLite... From ptmcg at austin.rr.com Fri Apr 13 12:49:54 2007 From: ptmcg at austin.rr.com (Paul McGuire) Date: 13 Apr 2007 09:49:54 -0700 Subject: Problem with algorithm In-Reply-To: <1176478891.573874.16050@y80g2000hsf.googlegroups.com> References: <1176434160.047703.214600@q75g2000hsh.googlegroups.com> <1176434937.258002.162220@p77g2000hsh.googlegroups.com> <1176448576.047996.12930@d57g2000hsg.googlegroups.com> <1176473989.420067.190970@l77g2000hsb.googlegroups.com> <1176478891.573874.16050@y80g2000hsf.googlegroups.com> Message-ID: <1176482994.875545.196530@y80g2000hsf.googlegroups.com> On Apr 13, 10:41 am, "Paul McGuire" wrote: > On Apr 13, 10:22 am, Michael Bentley > wrote: > > > > > > > On Apr 13, 2007, at 9:19 AM, Paul McGuire wrote: > > > > If you just expand the length to five million* or so, one of those > > > strings will contain all the works of Shakespeare. > > > Not likely, even with a tiny sampling of the works of Shakespeare: > > > # :-) > > > import string > > import random > > > def main(bardText, maxTries=5000000): > > tries = 0 > > while tries < maxTries: > > tries += 1 > > attempt = [] > > for letter in bardText.lower(): > > if random.choice( > > string.lowercase[:26] > > + string.punctuation > > + ' ' > > ) == letter: > > attempt.append(letter) > > else: > > break > > if len(attempt) >= 4: > > print '%d: %s' % ( > > tries, > > ''.join(attempt) > > ) > > > if __name__ == "__main__": > > main("Alas, poor Yorick!") > > 5000000 << infinity > > Keep tryin'! > > Also, the OP's technique was not doing random string permutations, but > generating an exhaustive list of all possible sequences from aaa... to > zzz... . So I think the works of Shakespeare are *bound* to be in > there somewhere. > > For proof, here's an extract from my sample code from running this > exhaustive program with length=14: > > ... > ALASPOORYORICG > ALASPOORYORICH > ALASPOORYORICI > ALASPOORYORICJ > ALASPOORYORICK > ALASPOORYORICL > ALASPOORYORICM > ALASPOORYORICN > ALASPOORYORICO > ... > > -- Paul > :) (too late for April 1, unfortunately)- Hide quoted text - > > - Show quoted text - And apologies to the OP for beating a dead horse into the ground. -- Paul From DustanGroups at gmail.com Sat Apr 21 19:47:33 2007 From: DustanGroups at gmail.com (Dustan) Date: 21 Apr 2007 16:47:33 -0700 Subject: Suggestion: str.itersplit() In-Reply-To: <1177190327.236981.153770@o5g2000hsb.googlegroups.com> References: <1177160280.784224.53460@b58g2000hsg.googlegroups.com> <1177190327.236981.153770@o5g2000hsb.googlegroups.com> Message-ID: <1177199253.412551.62650@n76g2000hsh.googlegroups.com> On Apr 21, 4:18 pm, Dustan wrote: > On Apr 21, 7:58 am, Dustan wrote: > > > >From my searches here, there is no equivalent to java's > > > StringTokenizer in python, which seems like a real shame to me. > > > However, str.split() works just as well, except for the fact that it > > creates it all at one go. I suggest an itersplit be introduced for > > lazy evaluation, if you don't want to take up recourses, and it could > > be used just like java's StringTokenizer. > > > Comments? > > If anybody could inform me on how to get my hands on the python source > code, I might even be able to come up with an example of how it could > be implemented. I have no idea how to unzip that tgz or tar.bz2 file > on a windows machine, though (and that's not from lack of trying). Thanks to both Jorge Godoy and Alex Martelli for their responses; I went with winzip. After spending about 10 minutes looking at this stuff, I can easily conclude that having the code and understanding the code are 2 very different things (and yes, I do have some experience in C and C++). But that's a matter to tackle on another day. From leuchte at gmail.com Thu Apr 26 05:50:12 2007 From: leuchte at gmail.com (TimC) Date: 26 Apr 2007 09:50:12 GMT Subject: Python not giving free memory back to the os get's me in real problems ... References: <1177510121.882503.145560@n15g2000prd.googlegroups.com> <599nhgF2jlkssU1@mid.dfncis.de> <59a66qF2j472uU1@mid.uni-berlin.de> Message-ID: <59baukF2ke97aU1@mid.dfncis.de> "Diez B. Roggisch" wrote: > Maybe delegating the actual processing to an external python > process you feed through the macro might work. Thanks for the idea. I'll check it out soon and will report about possible improvements. From Eric_Dexter at msn.com Tue Apr 10 08:39:52 2007 From: Eric_Dexter at msn.com (Eric_Dexter at msn.com) Date: 10 Apr 2007 05:39:52 -0700 Subject: pluie documentation in english In-Reply-To: <461b479a$0$27407$ba4acef3@news.orange.fr> References: <1176109628.413745.285120@n76g2000hsh.googlegroups.com> <1176114900.964184.46880@y80g2000hsf.googlegroups.com> <461b479a$0$27407$ba4acef3@news.orange.fr> Message-ID: <1176208792.766963.304080@q75g2000hsh.googlegroups.com> On Apr 10, 3:14 am, "M?ta-MCI" wrote: > Bonjour ! > > Avec Internet-Explorer 6 : > > Dans Internet-explorer, par le menu, faire : Outils + Options_internet > Aller sur le dernier onglet (Avanc?), et cocher : autoriser le contenu actif > > (d?sol? pour le fran?ais, mais mon anglais est vraiment trop mauvais). > > Et, merci pour l'info, ?a m'a permis d'ajouter un item ? la F.A.Q. > > @-salutations > -- > Michel Claveau with windows the .py files are executable as a link so that it doesn't have to comunicate with the program it can just hang out and be a web page.. I like the grid I was looking at is there a way to add lines after the web page has been created??? avec des fen?tres les dossiers de py sont ex?cutables comme lien de sorte qu'il pas ait d? comunicate avec le programme que ce peut juste tra?ner et ?tre une page Web. J'aime la grille que je regardais est l? une mani?re d'ajouter des lignes apr?s que la page Web ait ?t? cr??e ? ? ? .. From godzillaismad at gmail.com Tue Apr 10 02:47:28 2007 From: godzillaismad at gmail.com (Godzilla) Date: 9 Apr 2007 23:47:28 -0700 Subject: Queue get timeout parameter question In-Reply-To: <7x1wisg8ru.fsf@ruckus.brouhaha.com> References: <1176178232.836311.19390@p77g2000hsh.googlegroups.com> <7x1wisg8ru.fsf@ruckus.brouhaha.com> Message-ID: <1176187648.664744.69430@y80g2000hsf.googlegroups.com> On Apr 10, 2:20 pm, Paul Rubin wrote: > "Godzilla" writes: > > After the time sync, say 15 seconds backward, the thread is sitting on > > that get() method for a total of 17 seconds. We can only sync the > > device once per day and the time can drift up to 15 seconds per day!! > > Try to avoid syncing lke that. System clocks drift but the drift > rates tend to be constant, so there are schemes for gradually slowing > down or speeding up the system clock in order to keep it synchronized > with an external reference. > > > Anyone knows a solution to this problem or an alternative method? > > http://www.ntp.org Hi Paul, Ok... But I'm afraid no syncing is not an option for the device... From wangday at gmail.com Wed Apr 4 10:52:24 2007 From: wangday at gmail.com (lancered) Date: 4 Apr 2007 07:52:24 -0700 Subject: An error of matrix inversion using NumPy In-Reply-To: References: <1175692530.364381.77110@n59g2000hsh.googlegroups.com> Message-ID: <1175698343.919351.9710@o5g2000hsb.googlegroups.com> Here is the eigenvalues of KK I obtained: >>> linalg.eigvals(KK) array([ 1.11748411e+05, 3.67154458e+04, 3.41580846e+04, 2.75272440e+04, 2.09790868e+04, 1.86242332e+04, 8.68628325e+03, 6.66127732e+03, 6.15547187e+03, 4.68626197e+03, 3.17838339e+03, 2.84888045e+03, 1.88279736e+03, 1.32427574e+03, 1.04946287e+03, 5.79303171e+02, 3.83111876e+02, 4.93826556e-12, 1.50263232e-12]) You are right. The ratio of max/min eigenvalues is 7.4368432669e+016 Maybe this exceed the of precision of my machine? Is there any tricks for me to be able to deal with this matrix correctly with NumPy? On Apr 4, 3:58 pm, Robin Becker wrote: > lancered wrote: > > Hi dear all, > .......... > > matrices are correct. > > > So, can you tell me what goes wrong? Is this a bug in > > Numpy.linalg? How to deal with this situation? If you need, I can > > post the matrix I used below, but it is so long,so not at the moment. > > ....... > > presumably the matrix KK is actually some kind of normal matrix obtained from > the data. So you have say n variables and m observations the data matrix is than > an n x m real valued thing say D then you want the inverse of something like D'D > ie an n by n thing. Typically the data D is de-meaned and normalized by the > column norms so that you end up with a fairly well scaled problem. > > A long time ago I used Numeric+python to do exactly this sort of calculation > with excellent results and the matrices were as large or larger eg 100 x 100 and > above. I don't think the underlying numeric routines have changed that much. If > your matrix is symmetric then you should certainly be using > > Even if you can't post the matrix, perhaps you should indicate how you proceed > from data to matrix. Another problem is that a large determinant is no guarantee > of stability for the inversion. If the largest eigenvalue is 10**100 and the > smallest 10**-200 I probably have an ill determined problem; surprisingly easy > to achieve :( > -- > Robin Becker From anton.vredegoor at gmail.com Fri Apr 20 12:02:10 2007 From: anton.vredegoor at gmail.com (Anton Vredegoor) Date: Fri, 20 Apr 2007 18:02:10 +0200 Subject: multirember&co In-Reply-To: References: <1176768854.720234.23320@w1g2000hsg.googlegroups.com> <1176790588.024371.119360@n76g2000hsh.googlegroups.com> <1176850352.999231.79260@n59g2000hsh.googlegroups.com> <1176921030.330467.76860@o5g2000hsb.googlegroups.com> <1176925857.535835.130010@b58g2000hsg.googlegroups.com> <1177010211.252779.83620@y5g2000hsa.googlegroups.com> <1177025176.943890.252910@b75g2000hsg.googlegroups.com> Message-ID: Anton Vredegoor wrote: > from collections import deque > > def xsplitter(seq, pred): > Q = deque(),deque() > it = iter(seq) > def gen(p): > for x in it: > if pred(x) == p: > Q[p].append(x) > while Q[p]: yield Q[p].popleft() > else: > Q[~p].append(x) > for x in gen(p): yield x > while Q[p]: yield Q[p].popleft() > return gen(1),gen(0) Do we even need the line > for x in gen(p): yield x ??!! It seems to work the same without it. from collections import deque def xsplitter(seq, pred): Q = deque(),deque() it = iter(seq) def gen(p): for x in it: if pred(x) == p: Q[p].append(x) while Q[p]: yield Q[p].popleft() else: Q[~p].append(x) while Q[p]: yield Q[p].popleft() return gen(1),gen(0) What's up here? Was it a fata morgana? Am I overlooking something? A. From steven.bethard at gmail.com Thu Apr 5 15:07:28 2007 From: steven.bethard at gmail.com (Steven Bethard) Date: Thu, 05 Apr 2007 13:07:28 -0600 Subject: Review/commit patch? In-Reply-To: References: Message-ID: Kevin Walzer wrote: > How long does it take for a patch at the Python SF tracker to be > reviewed and/or committed? I am unfamiliar with how the process works. Raymond's given you the details on your particular patch. It's also worth noting that some folks on python-dev offer the following deal: * review five other patches * make useful comments in their trackers * post a message to python-dev with - the five patches you reviewed - the patch you'd like to have reviewed * they'll review your patch (and commit it if possible) STeVe From gagsl-py2 at yahoo.com.ar Sun Apr 15 17:52:13 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sun, 15 Apr 2007 18:52:13 -0300 Subject: sqlite3 question References: Message-ID: En Thu, 12 Apr 2007 08:43:49 -0300, Marc 'BlackJack' Rintsch escribi?: > In , Jorgen Bodde > wrote: > >>>>> r = c.execute('select * from song where id = 1') >>>>> for s in r: >> ... print s >> ... >> (1, u'Spikedrivers Blues', u'Mississippi John Hurt') > This should not work because `r` should not be a `Cursor` object. The > `execute()`-Method returns an integer with the number of "affected rows". Actually DBAPI 2.0 says the return value is undefined. -- Gabriel Genellina From user at domain.invalid Sat Apr 21 04:38:47 2007 From: user at domain.invalid (user at domain.invalid) Date: Sat, 21 Apr 2007 01:38:47 -0700 Subject: newbie: HTTPS screen scraping Message-ID: Hi, Can anyone help me out here. I would like to authenticate myself to a website which uses HTTPS and then after authentication, I would like to get the contents of the webpage. How can this be done using python. I have tried urllib and urllib2 but it has not solved my problem. TIA /varun From jeba.ride at gmail.com Sat Apr 7 21:12:00 2007 From: jeba.ride at gmail.com (Clement) Date: 7 Apr 2007 18:12:00 -0700 Subject: Console UI Message-ID: <1175994720.819372.232380@o5g2000hsb.googlegroups.com> My project is based on console Application. Is there any console UI except urwid. If so, can i come to know. From bobbie at ua.fm Wed Apr 4 03:27:48 2007 From: bobbie at ua.fm (Vityok) Date: 4 Apr 2007 00:27:48 -0700 Subject: Requirements For A Visualization Software System For 2010 In-Reply-To: <1175628186.459945.290750@d57g2000hsg.googlegroups.com> References: <1175628186.459945.290750@d57g2000hsg.googlegroups.com> Message-ID: <1175671668.913917.266260@n59g2000hsh.googlegroups.com> Xah Lee ???????: > REQUIREMENTS FOR A VISUALIZATION SOFTWARE SYSTEM FOR 2010 > > Xah Lee, 2007-03-16 > > In this essay, i give a list of requirements that i think is necessary > for a software system for creating scientific visualization for the > next decade (2007-2017). > > (for a HTML version with images, please see > http://xahlee.org/3d/viz.html ) > An interesting essay, of course it is much better to read the HTML version (with illustrations). With best regards, Victor Anyakin http://vityok.org.ua From robert.rawlins at thinkbluemedia.co.uk Sat Apr 21 04:21:17 2007 From: robert.rawlins at thinkbluemedia.co.uk (Robert Rawlins - Think Blue) Date: Sat, 21 Apr 2007 09:21:17 +0100 Subject: Styled Output Message-ID: <001b01c783ee$090d2520$1b276f60$@rawlins@thinkbluemedia.co.uk> Chaps, Hope you're all having a good weekend, I'm sure it'll only be the more 'hard core' of you reading this, anyone with any sanity would be out in the sunshine right now. I'm running a program of mine from Linux bash script and it currently outputs status messages to the command prompt, but they all look a little boring to say the least, it'll be like this. Application Started Sucess Application Configured Failed Retry Application Configured Success What I'd ideally like to do it give it a little bit of format, so it perhaps looks something like this. Application Started [Success] Application Configured [Success] And perhaps have the word 'success' in green, or red for 'failed' and things like that, just to make it a little more presentable to the user. Any ideas on the best way to achieve this? Thanks, Rob -------------- next part -------------- An HTML attachment was scrubbed... URL: From grante at visi.com Thu Apr 5 10:38:06 2007 From: grante at visi.com (Grant Edwards) Date: Thu, 05 Apr 2007 14:38:06 -0000 Subject: AW: Write to a binary file References: Message-ID: <131a2eeq2feuefe@corp.supernews.com> On 2007-04-05, Thomi Aurel RUAG A wrote: > A simplified test programm to compare the function for opening > a file i used ("file()") and your suggested "os.open()" showed > different behaviour. > > My simple testprogramm: > > --- START --- > import os > > msg = chr(0x02) + chr(0x36) + chr(0x00) + chr(0x01) + chr(0x0a) + > chr(0xb0) + chr(0x77) > > f = os.open('/dev/pytest', os.O_RDWR) > os.write(f,msg) > os.close(f) > > f = file('/dev/pytest', 'wb') > f.write(msg) > f.close() > --- END --- > > The "pytest" device is a very simple device-driver which > prints out (using "printk()") the buffer delivered to the > write function in a hexadecimal format ("Pytest write> [buffer > in hex format]"). > > The output was: > --- Start --- > Pytest write> 02 36 00 01 0a b0 77 > Pytest write> 02 36 00 01 0a > Pytest write> b0 77 > --- END --- I'm surprised that the normal file object's write method does that -- especially for a "binary" file. IMO, it's a bug when a binary file object treats 0x0a differently than other byte values. But, using the file object to read/write a device is probably not a good idea because of undefined behavior like that. File objects also do their own buffering, which I suspect isn't what you want. > Using os.open will work for me, i wasn't aware of the > existence of several file interaces. The os.file/open ones are just very thin wrappers around the corresponding libc routines. The file object contains it's own buffering and other features that will just get in the way of what you probably want to do. -- Grant Edwards grante Yow! .. here I am in 53 at B.C. and all I want is a visi.com dill pickle!! From grante at visi.com Sun Apr 1 15:27:24 2007 From: grante at visi.com (Grant Edwards) Date: Sun, 01 Apr 2007 19:27:24 -0000 Subject: Character set woes with binary data References: <1175415685.21349.79.camel@pepper.trausch.us> <1175455271.758386.27060@l77g2000hsb.googlegroups.com> Message-ID: <13101ss4fds2jdd@corp.supernews.com> On 2007-04-01, Ene wrote: > On Apr 1, 11:44 am, John Nagle wrote: >> Michael B. Trausch wrote: >> > In short: How do I create a string that contains raw binary content >> > without Python caring? Is that possible? >> >> Given where we're now at with strings in Python, Python should >> really have a "byte" type and a way to deal with arrays of >> bytes, independent of the string operators. I agree. It would be very nice to have a built-in data-type that is an efficient implementation of a list/array of bytes. When manipulating binary data, it really makes it unreadable when it's full of chr() and ord() calls that are only there because when you index into a string you get a string of length 1 and not a byte. >> Efficient handling of lists of bytes would do it. >> >> John Nagle > > Python has a module base64 that allows you to handle binary > data as a string. Huh? How does the base64 module address the problem? It still relies on the "string" type as an immutable list of bytes. -- Grant Edwards grante Yow! I like your SNOOPY at POSTER!! visi.com From collinw at gmail.com Sun Apr 1 12:49:51 2007 From: collinw at gmail.com (Collin Winter) Date: Sun, 1 Apr 2007 11:49:51 -0500 Subject: [Python-Dev] Python 3000 PEP: Postfix type declarations In-Reply-To: References: Message-ID: <43aa6ff70704010949v5d38ccb2pa2c183594124267c@mail.gmail.com> On 4/1/07, Georg Brandl wrote: [snip several pages of excellent ideas] > > The mapping between types and declarators is not static. It can be completely > customized by the programmer, but for convenience there are some predefined > mappings for some built-in types: > > ========================= =================================================== > Type Declarator > ========================= =================================================== > ``object`` ? (REPLACEMENT CHARACTER) > ``int`` ? (DOUBLE-STRUCK CAPITAL N) > ``float`` ? (ESTIMATED SYMBOL) > ``bool`` ? (CHECK MARK) > ``complex`` ? (DOUBLE-STRUCK CAPITAL C) > ``str`` ? (LOWER RIGHT PENCIL) > ``unicode`` ? (BLACK NIB) > ``tuple`` ? (PARENTHESIZED LATIN SMALL LETTER T) > ``list`` ? (HOT SPRINGS) > ``dict`` ? (DOUBLE-ENDED MULTIMAP) > ``set`` ? (EMPTY SET) (*Note:* this is also for full sets) > ``frozenset`` ? (SNOWMAN) > ``datetime`` ? (WATCH) > ``function`` ? (LATIN SMALL LETTER LAMBDA WITH STROKE) > ``generator`` ? (ATOM SYMBOL) > ``Exception`` ? (ELECTRIC ARROW) > ========================= =================================================== > > The declarator for the ``None`` type is a zero-width space. > > These characters should be obvious and easy to remember and type for every > programmer. > [snip] > > Example > ======= > > This is the standard ``os.path.normpath`` function, converted to type declaration > syntax:: > > def normpath?(path?)?: > """Normalize path, eliminating double slashes, etc.""" > if path? == '': > return '.' > initial_slashes? = path?.startswith?('/')? > # POSIX allows one or two initial slashes, but treats three or more > # as single slash. > if (initial_slashes? and > path?.startswith?('//')? and not path?.startswith?('///')?)?: > initial_slashes? = 2 > comps? = path?.split?('/')? > new_comps? = []? > for comp? in comps?: > if comp? in ('', '.')?: > continue > if (comp? != '..' or (not initial_slashes? and not new_comps?)? or > (new_comps? and new_comps?[-1]? == '..')?)?: > new_comps?.append?(comp?) > elif new_comps?: > new_comps?.pop?()? > comps? = new_comps? > path? = '/'.join(comps?)? > if initial_slashes?: > path? = '/'*initial_slashes? + path? > return path? or '.' > > As you can clearly see, the type declarations add expressiveness, while at the > same time they make the code look much more professional. My only concern is that this doesn't go far enough. While knowing that some object is a ? is a good start, it would be so much more helpful to know that it's a ? of ?s. I think something like ???3? to indicate a 3-? of ?s would be nice. This would change the line in the above from "if comp? in ('', '.')?:" to "if comp? in ('', '.')??2?:", which I think is a nice win in terms of readability, EIBTI and all that. (Sidebar: I think the PEP should feature a section on how these new type declarations will cut down on mailing list volume and documentation size.) In light of this PEP, PEP 3107's function annotations should be rejected. All that hippie feel-good crap about "user-defined annotations" and "open-ended semantics" and "no rules, man" was just going to get us into trouble. This PEP's more modern conception of type annotations give the language a power and expressiveness that my PEP could never hope to match. This is clearly a move in the right direction. +4 billion. Collin Winter From mailmaverick666 at gmail.com Wed Apr 11 07:17:30 2007 From: mailmaverick666 at gmail.com (rishi pathak) Date: Wed, 11 Apr 2007 16:47:30 +0530 Subject: Pass A Var To a Python Script? In-Reply-To: References: Message-ID: <180b672e0704110417k1a5fcc8pf217a27273d3e5b6@mail.gmail.com> Hi, Use sys.argv to access the command line arguments eg: import sys print sys.argv[0] print sys.argv[1] Run the above script as /test.py hello world On 4/7/07, Eric Price wrote: > > Hi; > How do I pass a variable to a python script? Something like this (which > doesn't work): > > ./test.py?var=hello_world > > TIA, > Eric > > _________________________________________________________________ > Mortgage refinance is Hot. *Terms. Get a 5.375%* fix rate. Check savings > > https://www2.nextag.com/goto.jsp?product=100000035&url=%2fst.jsp&tm=y&search=mortgage_text_links_88_h2bbb&disc=y&vers=925&s=4056&p=5117 > > -- > 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 b83503104 at yahoo.com Tue Apr 3 18:09:43 2007 From: b83503104 at yahoo.com (bahoo) Date: 3 Apr 2007 15:09:43 -0700 Subject: how to remove multiple occurrences of a string within a list? In-Reply-To: References: <1175624433.206953.214290@n59g2000hsh.googlegroups.com> <1175625098.269660.184790@o5g2000hsb.googlegroups.com> <1175627593.307674.11280@w1g2000hsg.googlegroups.com> <1175637133.938883.224570@q75g2000hsh.googlegroups.com> Message-ID: <1175638183.743451.126360@w1g2000hsg.googlegroups.com> On Apr 3, 6:05 pm, Steven Bethard wrote: > bahoo wrote: > > The larger problem is, I have a list of strings that I want to remove > > from another list of strings. > > If you don't care about the resulting order:: > > >>> items = ['foo', 'bar', 'baz', 'bar', 'foo', 'frobble'] > >>> to_remove = ['foo', 'bar'] > >>> set(items) - set(to_remove) > set(['frobble', 'baz']) > > If you do care about the resulting order:: > > >>> to_remove = set(to_remove) > >>> [item for item in items if item not in to_remove] > ['baz', 'frobble'] > > STeVe This is amazing. I love python! From editor at musicwords.net Tue Apr 3 02:44:41 2007 From: editor at musicwords.net (Jim Aikin) Date: Mon, 2 Apr 2007 23:44:41 -0700 Subject: pyc file [Newbie Question] Message-ID: Just starting to learn Python and going through the Tutorial in the Help file. FWIW, I'm a hobbyist programmer -- not extremely knowledgeable, but not entirely clueless. In 6.1.2 of the Tutorial, I find this: "The modification time of the version of spam.py used to create spam.pyc is recorded in spam.pyc, and the .pyc file is ignored if these don't match." Either I don't understand this, or it isn't correct. Working through the tutorial, I created a file called fibo.py in my text editor, and imported it into Idle. It worked as expected. I then edited the file and resaved it. I used del fibo, followed by import fibo. My edits are not accessible in Idle. Python seems still to be importing the earlier version of fibo.pyc, even though the modification time of fibo.py is now different. (I'm in Windows XP, if that makes a difference.) I consistently get the error message "AttributeError: 'module' object has no attribute 'xyz'", even though I've just defined a new function xyz in fibo.py and saved the file, then deleted and reimported. One point of possible confusion here is in the line in the following paragraph of 6.1.2, "Whenever spam.py is successfully compiled...." My question is, is it compiled when being imported? I didn't spot any mention in the Tutorial of when or how a .py file might be (or would automatically be) compiled, so I'm assuming that it's automatically compiled while being imported. If this is a bad assumption, then maybe it's the root of my misunderstanding. Maybe I have to _do_ something to fibo.py in order to create a new version of fibo.pyc. Sorry to be so long-winded, but I want to be precise about this. Can anyone clarify for me what's happening here? Thanks! --Jim Aikin From phd at phd.pp.ru Wed Apr 11 12:26:42 2007 From: phd at phd.pp.ru (Oleg Broytmann) Date: Wed, 11 Apr 2007 20:26:42 +0400 Subject: SQLObject 0.9.0b1 Message-ID: <20070411162642.GC22672@phd.pp.ru> Hello! I'm pleased to announce the 0.9.0b1 release of SQLObject, the first beta of the upcoming 0.9 release. 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 Development: http://sqlobject.org/devel/ 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.9.0b1 News and changes: http://sqlobject.org/News.html What's New ========== News since 0.8 -------------- Features & Interface -------------------- * Support for Python 2.2 has been declared obsolete. * Removed actively deprecated attributes; lowered deprecation level for other attributes to be removed after 0.9. * SQLite connection got columnsFromSchema(). Now all connections fully support fromDatabase. There are two version of columnsFromSchema() for SQLite - one parses the result of "SELECT sql FROM sqlite_master" and the other uses "PRAGMA table_info"; the user can choose one over the other by using "use_table_info" parameter in DB URI; default is False as the pragma is available only in the later versions of SQLite. * Changed connection.delColumn(): the first argument is sqlmeta, not tableName (required for SQLite). * SQLite connection got delColumn(). Now all connections fully support delColumn(). As SQLite backend doesn't implement "ALTER TABLE DROP COLUMN" delColumn() is implemented by creating a new table without the column, copying all data, dropping the original table and renaming the new table. * Versioning_. .. _Versioning: Versioning.html * MySQLConnection got new keyword "conv" - a list of custom converters. * Use logging if it's available and is configured via DB URI. * New columns: TimestampCol to support MySQL TIMESTAMP type; SetCol to support MySQL SET type; TinyIntCol for TINYINT; SmallIntCol for SMALLINT; MediumIntCol for MEDIUMINT; BigIntCol for BIGINT. Small Features -------------- * Support for MySQL INT type attributes: UNSIGNED, ZEROFILL. * Support for DEFAULT SQL attribute via defaultSQL keyword argument. * Support for MySQL storage ENGINEs. * cls.tableExists() as a shortcut for conn.tableExists(cls.sqlmeta.table). * cls.deleteMany(), cls.deleteBy(). Bug Fixes --------- * idName can be inherited from the parent sqlmeta class. For a more complete list, please see the news: http://sqlobject.org/News.html Oleg. -- Oleg Broytmann http://phd.pp.ru/ phd at phd.pp.ru Programmers don't die, they just GOSUB without RETURN. From yujorodrigues at gmail.com Tue Apr 10 14:15:57 2007 From: yujorodrigues at gmail.com (Yujo) Date: 10 Apr 2007 11:15:57 -0700 Subject: Can I get the exit code "n" passed to sys.exit(n) ? Message-ID: <1176228956.865875.295980@p77g2000hsh.googlegroups.com> Hello everybody, In the following code of the finish() function, is there any way to get the exit code passed to sys.exit() ? def finish() : RETURN_CODE_FROM_SYS_EXIT = ???? # how can I get it ? if RETURN_CODE_FROM_SYS_EXIT = 0 : # process ended OK else : # process ended with some error # execute something atexit.register(finish) # this is my main program.... ERR_CODE=3 sys.exit(ERR_CODE) Regards, Yujo From filyph at gmail.com Tue Apr 17 04:41:31 2007 From: filyph at gmail.com (filyph) Date: 17 Apr 2007 01:41:31 -0700 Subject: Handling sorted dictionaries In-Reply-To: <1176796915.492317.203190@p77g2000hsh.googlegroups.com> References: <1176796915.492317.203190@p77g2000hsh.googlegroups.com> Message-ID: <1176799291.719403.38950@w1g2000hsg.googlegroups.com> Hello, Dictionary items are inordered and can not be sorted. Function sorted() returns list of tuples in each is 0. item key from dictionary and 1. is value from key-value pair from dict machines. List indices must be integers and machine keys are strings. See http://www.python.org/dev/peps/pep-0265/ about sorting dictionaries. You need to know what type is variable in each line of code. Dict is not same as list, even when you can get values from they very similar way. dict[key] and list[index], key can be everything what can be hashed, but index can be only integer. I am not english, so I hope you understand me. loial nap?sal(a): > The following code gives the error > d=sortedmachines[machine] > TypeError: list indices must be integers > What works for the unsorted dictionary does not work for the sorted > dictionary. > Can anyone help? > machinekey = "111111" > machines = {} > machines[machinekey]=[1,0,0,0,0,0,0,0,0,0,0,0,0] > machinekey = "222222" > machines[machinekey]=[0,1,0,0,0,0,0,0,0,0,0,0,0] > ddd=0 > for machine in machines.keys(): > d=machines[machine] > print machine > print d [ddd] > > sortedmachines=sorted(machines) > for machine in sortedmachines: > d=sortedmachines[machine] > print machine > print d [ddd] From cam.ac.uk at mh391.invalid Mon Apr 23 11:09:16 2007 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Mon, 23 Apr 2007 16:09:16 +0100 Subject: Two syntax questions (newbie) In-Reply-To: <593e3sF2iscqaU1@mid.uni-berlin.de> References: <1177316126.432039.232300@o5g2000hsb.googlegroups.com> <1177320268.228495.186590@y5g2000hsa.googlegroups.com> <593e3sF2iscqaU1@mid.uni-berlin.de> Message-ID: Diez B. Roggisch wrote: >> This is already better. Is it possible to define function composition >> as an operator and have something like (list at reversed@sorted)(items) >> or (list*reversed*sorted)(items) ? > > Not on functions, but on classes/instances. So something like this might > work for you (untested): > > class FunctionComposer(object): > def __init__(self, f=None): > if f is None: > f = lambda x: x > self._f = f > > def __call__(self, *args, **kwargs): > return self._f(*args, **kwargs) > > def __mul__(self, other): > def combined(*args, **kwargs): > return other(self._f(*args, **kwargs)) > return FunctionComposer(combined) > > fc = FunctionComposer > > Then you can write > > (fc() * list * reversed * sorted)(items) A clever little hack, but please don't do this. Anyone else who will read your code will thank you. -- Michael Hoffman From grante at visi.com Tue Apr 10 15:50:59 2007 From: grante at visi.com (Grant Edwards) Date: Tue, 10 Apr 2007 19:50:59 -0000 Subject: OT: Question about RGB color method References: <461be63b$0$31839$c3e8da3@news.astraweb.com> Message-ID: <131nql3kbil5hed@corp.supernews.com> On 2007-04-10, John Salerno wrote: > Sorry for this non-Python question, but since it's computer related It isn't. Computer-related, that is. > I'm wondering, why do computers use a RGB color scheme instead > of the primary colors? The same reason televisions and all other additive-mixing media use RGB: http://en.wikipedia.org/wiki/Primary_colors -- Grant Edwards grante Yow! I'm also against at BODY-SURFING!! visi.com From beliavsky at aol.com Fri Apr 27 18:58:23 2007 From: beliavsky at aol.com (Beliavsky) Date: 27 Apr 2007 15:58:23 -0700 Subject: Portable SciPy v0.1 released In-Reply-To: <2418d$463275ce$d443bb3a$25239@news.speedlinq.nl> References: <2418d$463275ce$d443bb3a$25239@news.speedlinq.nl> Message-ID: <1177714703.751242.61090@e65g2000hsc.googlegroups.com> On Apr 27, 6:17 pm, Stef Mientki wrote: > Portable SciPy, is an easy installer of SciPy for M$ windows users. If you have an announcement for Windows users, I suggest that you not needlessly turn them off by abbreviating Microsoft as M$ . You don't like Windows, but many of us Windows users don't like the anti-Windows snobs. There is nothing wrong with making money by selling software. From b83503104 at yahoo.com Tue Apr 3 12:12:30 2007 From: b83503104 at yahoo.com (bahoo) Date: 3 Apr 2007 09:12:30 -0700 Subject: How to have a list of lists (or array of lists) Message-ID: <1175616750.744309.156580@n76g2000hsh.googlegroups.com> Hi, I want to have many lists, such as list0, list1, list2, ..., each one holding different number of items. Is there something like list[0] list[1] list[2] so that I can iterate through this list of lists? Thanks! bahoo From http Mon Apr 16 22:56:51 2007 From: http (Paul Rubin) Date: 16 Apr 2007 19:56:51 -0700 Subject: Python and SSL References: <1176737058.203036.53170@n59g2000hsh.googlegroups.com> <4623ECE0.3010103@v.loewis.de> Message-ID: <7xy7krbte4.fsf@ruckus.brouhaha.com> "Martin v. L?wis" writes: > It means that these modules can do encrypted communication for their > respective protocol. They cannot validate that they are really talking > to the server they think they talk to (so they are prone to a > man-in-the-middle attack), however, as communication is encrypted, they > are protected against wire-tapping. Unless the wiretapper is running a man-in-the-middle attack... From chris.lasher at gmail.com Wed Apr 11 12:29:11 2007 From: chris.lasher at gmail.com (Chris Lasher) Date: 11 Apr 2007 09:29:11 -0700 Subject: Shebang or Hashbang for modules or not? Message-ID: <1176308951.932721.197630@y80g2000hsf.googlegroups.com> Should a Python module not intended to be executed have shebang/ hashbang (e.g., "#!/usr/bin/env python") or not? I'm used to having a shebang in every .py file but I recently heard someone argue that shebangs were only appropriate for Python code intended to be executable (i.e., run from the command line). From howe.steven at gmail.com Sun Apr 15 13:15:55 2007 From: howe.steven at gmail.com (Steven Howe) Date: Sun, 15 Apr 2007 10:15:55 -0700 Subject: how to strip the domain name in python? In-Reply-To: <1176654669.737355.78300@y5g2000hsa.googlegroups.com> References: <1176526155.679721.159870@l77g2000hsb.googlegroups.com> <1176564977.498635.171600@n59g2000hsh.googlegroups.com> <1176654669.737355.78300@y5g2000hsa.googlegroups.com> Message-ID: <46225DCB.5090902@gmail.com> An HTML attachment was scrubbed... URL: From deets at nospam.web.de Fri Apr 20 08:30:20 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Fri, 20 Apr 2007 14:30:20 +0200 Subject: Do other Python GUI toolkits require this? In-Reply-To: References: <462697A6.6010007@codebykevin.com> <465B30B4-5BA0-459A-BE6F-1038874FA74B@jedimindworks.com> Message-ID: <58rq32F2fo980U1@mid.uni-berlin.de> Antoon Pardon schrieb: > On 2007-04-19, Steve Holden wrote: >> Antoon Pardon wrote: >>> On 2007-04-19, Steve Holden wrote: >>>> Michael Bentley wrote: >>>>> On Apr 19, 2007, at 4:11 AM, Antoon Pardon wrote: >>>>> >>>>>> On 2007-04-19, Michael Bentley wrote: >>>> [...] The >>>>>>> learning curve is rather steep IMO, but worth it. >>>>>> Just a throw in remark, that you may ignore if you wish, but a steep >>>>>> learning curve means that the subject is easily familiarized and that >>>>>> the learning period is short. >>>>>> >>>>>> You seem to use it as if it is the opposite. >>>>> Mathematical absurdities aside, it's the common usage -- but perhaps >>>>> you knew that. >>>>> >>>>> >>>> Perhaps in Belgium they prefer climbing mountains over walking up and >>>> down gentle hills? Or possibly they will simply pick any nit that is >>>> carelessly left within range? >>> If it is just a nit, why don't you ignore my remark as I suggested? >>> >> Because I suffer from the quixotic urge to help stamp out obsessive >> compulsive behavior on c.l.py? This is self-defeating, of course, since >> it makes me appear obsessive compulsive in my own right ... >> >>> Now suppose I give you a graph that shows you how different people >>> are making progress. Would you prefer the rather flat curves instead >>> of the steep curves because the latter gives you the idea of someone >>> having to conquer huge obstacles or would you choose the steep curve >>> because they show you someone is getting results fast? >>> >> Suppose I should you a hill you have to climb? Would you rather don >> mountain boots and crampons to climb 3,000 feet up a vertical cliff or >> would you rather amble up, say, Ben Lomond with the other tourists? > > So if you have the choice between a steep or a shalow income curve > you will prefer the shalow curve because a steep curve makes you > think about verticale clifs and such? > > The analogy with a walk is just silly because curves are not like walks. > Nobody will say something like: I won't invest in that company because > it has a steep profit curve or the reverse: I'll invest in this company > because it has an easy looking downhill going profit curve. Your whole argumentation bases on the fact that the result of the learning process, and the success of it, has something to do with the reached height - or y-axis-value - of your climb. Which is nonsense. The goal is to go from A - ignorance - to B - knowledge - which both lie on the X-Axis. And you really argue that having to go 2 miles OVER THE GROUND on a shallow slope is worse than walking 2 miles OVER GROUND with the mount everest between you and your goal? Diez From robin at reportlab.com Wed Apr 4 10:04:52 2007 From: robin at reportlab.com (Robin Becker) Date: Wed, 04 Apr 2007 15:04:52 +0100 Subject: An error of matrix inversion using NumPy In-Reply-To: <4613AF19.4090501@chamonix.reportlab.co.uk> References: <1175692530.364381.77110@n59g2000hsh.googlegroups.com> <4613AF19.4090501@chamonix.reportlab.co.uk> Message-ID: <4613B084.6000800@chamonix.reportlab.co.uk> Robin Becker wrote: > lancered wrote: h. If > your matrix is symmetric then you should certainly be using .... a qr decomposition I meant to say :) -- Robin Becker From skip at pobox.com Fri Apr 13 18:18:54 2007 From: skip at pobox.com (skip at pobox.com) Date: Fri, 13 Apr 2007 17:18:54 -0500 Subject: Portably generating infinity and NaN In-Reply-To: References: Message-ID: <17952.462.393481.648386@montanaro.dyndns.org> Michael> What's the best way to portably generate binary floating point Michael> infinity and NaNs? I take it this isn't portable even though it works on Mac, Linux and Solaris across a number of different Python versions and a couple GCC versions: % python Python 2.4.2 (#1, Feb 23 2006, 12:48:31) [GCC 3.4.1] on sunos5 Type "help", "copyright", "credits" or "license" for more information. >>> import struct >>> struct.pack("f", float("NaN")) '\xff\xff\xff\x7f' >>> struct.pack("f", float("Inf")) '\x00\x00\x80\x7f' $ python Python 2.5 (release25-maint:53536, Jan 23 2007, 18:15:37) [GCC 3.4.6 20060404 (Red Hat 3.4.6-3)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import struct >>> struct.pack("f", float("NaN")) '\x00\x00\xc0\x7f' >>> struct.pack("f", float("Inf")) '\x00\x00\x80\x7f' % python Python 2.6a0 (trunk:54264M, Mar 10 2007, 15:19:48) [GCC 4.0.1 (Apple Computer, Inc. build 5367)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> import struct >>> struct.pack("f", float("Inf")) '\x7f\x80\x00\x00' >>> struct.pack("f", float("NaN")) '\x7f\xc0\x00\x00' (Note the absence of a demonstration on Windows.) Can't the above be blessed as the One True Way and wormed around in floatmodule.c for those platforms where float'ing "NaN" or "Inf" doesn't currently work? Skip From steve at REMOVE.THIS.cybersource.com.au Sun Apr 15 06:48:07 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Sun, 15 Apr 2007 20:48:07 +1000 Subject: combination function in python References: <1176615838.830315.160210@b75g2000hsg.googlegroups.com> <1176629911.409257.149780@l77g2000hsb.googlegroups.com> Message-ID: On Sun, 15 Apr 2007 02:38:31 -0700, bearophileHUGS wrote: > DanielJohnson: >> Please help, I couldnt find the function through help. > > You can't find it because it's not there: > > def factorial(n): > """factorial(n): return the factorial of the integer n. > factorial(0) = 1 > factorial(n) with n<0 is -factorial(abs(n)) > """ > result = 1 > for i in xrange(1, abs(n)+1): > result *= i > if n >= 0: > return result > else: > return -result > > def binomial(n, k): > """binomial(n, k): return the binomial coefficient (n k).""" > assert n>0 and isinstance(n, (int, long)) and isinstance(k, (int, > long)) > if k < 0 or k > n: > return 0 > if k == 0 or k == n: > return 1 > return factorial(n) // (factorial(k) * factorial(n-k)) That's a naive and slow implementation. For even quite small values of n and k, you end up generating some seriously big long ints, and then have to (slowly!) divide them. A better implementation would be something like this: def binomial(n, k): if not 0 <= k <= n: return 0 if k == 0 or k == n: return 1 # calculate n!/k! as one product, avoiding factors that # just get canceled P = k+1 for i in xrange(k+2, n+1): P *= i # if you are paranoid: # C, rem = divmod(P, factorial(n-k)) # assert rem == 0 # return C return P//factorial(n-k) There's probably even a really clever way to avoid that final division, but I suspect that would cost more in time and memory than it would save. -- Steven. From paddy3118 at googlemail.com Wed Apr 25 02:23:30 2007 From: paddy3118 at googlemail.com (Paddy) Date: 24 Apr 2007 23:23:30 -0700 Subject: Advocacy: "Python up, Ruby down". Message-ID: <1177482210.379942.201930@n35g2000prd.googlegroups.com> I found this blog post on one users migration to Python. It states one users frustrations but the comments section is quite good too. http://blog.cbcg.net/articles/2007/04/22/python-up-ruby-down-if-that-runtime-dont-work-then-its-bound-to-drizzown The time and effort the developers spend on the balance between fixing what we have over adding new features is hard, but it did pay off for this programmer who was lured over by a more robust implementation and good documentation. - Paddy. From anton.vredegoor at gmail.com Thu Apr 19 18:09:28 2007 From: anton.vredegoor at gmail.com (Anton Vredegoor) Date: Fri, 20 Apr 2007 00:09:28 +0200 Subject: multirember&co In-Reply-To: <1177010211.252779.83620@y5g2000hsa.googlegroups.com> References: <1176768854.720234.23320@w1g2000hsg.googlegroups.com> <1176790588.024371.119360@n76g2000hsh.googlegroups.com> <1176850352.999231.79260@n59g2000hsh.googlegroups.com> <1176921030.330467.76860@o5g2000hsb.googlegroups.com> <1176925857.535835.130010@b58g2000hsg.googlegroups.com> <1177010211.252779.83620@y5g2000hsa.googlegroups.com> Message-ID: attn.steven.kuo at gmail.com wrote: > Um, no. That one stops prematurely if > your input sequence is: > > L = 1, 2, 3, 'a', 'a' Ah, thanks! > You get points for persistence, however. :) Maybe this one is better? from collections import deque from itertools import chain, repeat def xsplitter(seq, pred): Q = deque(),deque() sentinel = object() it = chain(seq,repeat(sentinel)) def gen(p): for x in it: if pred(x) != p and x is not sentinel: Q[~p].append(x) for x in gen(p): yield x else: while Q[p]: yield Q[p].popleft() if pred(x) == p: yield x else: break return gen(1),gen(0) def test(): L = 1, 2, 3, 'a', 'a' # L = 'a', 1, 2, 'a' # L = 1, 'a', 3, 'a', 4, 5, 6, 'a' it1, it2 = xsplitter(L, lambda x: x == 'a') print it1.next() print it2.next() print it1.next() print it2.next() if __name__=='__main__': test() A. From mail at timgolden.me.uk Mon Apr 30 07:54:28 2007 From: mail at timgolden.me.uk (Tim Golden) Date: Mon, 30 Apr 2007 12:54:28 +0100 Subject: Dict Copy & Compare In-Reply-To: <000e01c78b18$03457cb0$09d07610$@rawlins@thinkbluemedia.co.uk> References: <00da01c78b01$3e80b900$bb822b00$@rawlins@thinkbluemedia.co.uk> <4635AB95.4010309@timgolden.me.uk> <000601c78b06$b9fb0950$2df11bf0$@rawlins@thinkbluemedia.co.uk> <4635B38E.5020606@timgolden.me.uk> <000701c78b10$1e8aa9d0$5b9ffd70$@rawlins@thinkbluemedia.co.uk> <4635C473.4010109@timgolden.me.uk> <000e01c78b18$03457cb0$09d07610$@rawlins@thinkbluemedia.co.uk> Message-ID: <4635D8F4.5010308@timgolden.me.uk> Robert Rawlins - Think Blue wrote: > On[e] quick question, how can I order a dict by > the 'values' (not keys) before looping? Is that possible? Depends on what you want to do. You can loop on the sorted values very easily: d1 = dict (a=2, b=1) for value in sorted (d1.values): print value but inferring the equivalent key is, in effect, not possible since more than one key might correspond to that value. Depending on what you're after, the following technique might be of use: import operator d = dict (a=2, b=1, c=-1, d=4) for k, v in sorted ( d.items (), key=operator.itemgetter (1) ): print k, "=>", v It may look a bit hairy, but break it down: d.items () returns a list of 2-tuples, each one corresponding to a key-value pair from the dict. In our case, that'll be: [('a', 2), ('b', 1), ('c', -1), ('d', 4)] Although I've written them out like that, the order they'll come in is undefined. sorted () will return a sorted version of whatever iterable you chuck at it. Under normal Python semantics, sorted() on the list above will return no change since I've listed things out in alphanumeric order. The extra key= parameter tells the sorted routine to call the function you provide against each of the items in the list (in our case that means against each of the 2-tuples) and using the result of that function as the sorting order. The operation.itemgetter (1) bit is a touch complicated unless you're already familiar with partial functions, but it basically returns *another* function which takes the item you give it and returns the -- in this case -- 1st item. Just believe me: it works. So, in summary: + Get a list of key-value pairs + Sort them according to the 1st item (Python-style) which in this case is the value. + Do something with the result Before the key= param was introduced into sort/sorted, people used to do the same thing with what's often called DSU (short for decorate-sort-undecorate), a technique which here would look something like this: items = d.items () sortable_items = [(i[1], i) for i in items] sortable_items.sort () sorted_items = [i[-1] for i in sortable_items] I mention this because (a) you still see it around a fair bit and (b) there are occasions where it's still useful, for example where a simple function call can't really cope. (Did I answer the question, or was I just rambling?) TJG From aisaac at american.edu Thu Apr 12 20:50:44 2007 From: aisaac at american.edu (Alan Isaac) Date: Fri, 13 Apr 2007 00:50:44 GMT Subject: Several images onto one 2D-plot in matplotlib? References: <1176405713.392944.6860@b75g2000hsg.googlegroups.com> Message-ID: http://matplotlib.sourceforge.net/screenshots.html esp http://matplotlib.sourceforge.net/screenshots/axes_demo.py hth, Alan Isaac From sjmachin at lexicon.net Mon Apr 23 18:26:22 2007 From: sjmachin at lexicon.net (John Machin) Date: 23 Apr 2007 15:26:22 -0700 Subject: script for seconds in given month? In-Reply-To: References: <1176740556.859125.221980@l77g2000hsb.googlegroups.com> <1hwokmz.1ropcwj17pg55dN%aleax@mac.com> <1176796031.889407.323950@b75g2000hsg.googlegroups.com> <1177360091.516469.77830@l77g2000hsb.googlegroups.com> Message-ID: <1177367182.942889.314430@y5g2000hsa.googlegroups.com> On Apr 24, 6:39 am, Carsten Haese wrote: > On Mon, 2007-04-23 at 13:28 -0700, edfialk wrote: > > Alex, very nice. That should be good enough for me. > > The rest of you as well, thanks for all the help. > > > I, unfortunately, failed to realize the actual platform the script is > > for is IronPython. When trying to import calendar in IronPython, I > > get: > > > SyntaxError: future feature is not defined: with_statement (c: > > \Python25\Lib\calendar.py, line 8) > > > so, incompatible. I have moved my question over to the IronPython > > group, but if anyone is familiar with IronPython and knows how to > > perform the same function, that's what I'm looking for now. :) > > Try this on for size: > > def seconds_in_month(mo,yr): > import datetime > start_date = datetime.date(yr,mo,1) > mo += 1 > if mo==13: mo=1; yr += 1 > end_date = datetime.date(yr,mo,1) > delta = end_date - start_date > return 24*60*60*delta.days > Look, Ma, no imports, no function calls, no attribute lookups, no table lookups :-) def days_in_month(year, month): assert 1 <= month <= 12 if month >= 3: return (month * 13 + 1) // 5 - (month * 13 + 3) // 5 + 31 if month == 1: return 31 if year % 4: return 28 if year % 100: return 29 if year % 400: return 28 return 29 | >>> [days_in_month(yyyy, 2) for yyyy in (2007, 2008, 2100, 2000)] | [28, 29, 28, 29] | >>> [days_in_month(2007, mm) for mm in range(1, 13)] | [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] From eurleif at ecritters.biz Mon Apr 2 14:00:53 2007 From: eurleif at ecritters.biz (Leif K-Brooks) Date: Mon, 02 Apr 2007 14:00:53 -0400 Subject: YouTube showing repr() of a tuple In-Reply-To: <1175528018.544324.177390@y66g2000hsf.googlegroups.com> References: <460b9f48$0$30100$4d3efbfe@news.sover.net> <460bc895$0$30091$4d3efbfe@news.sover.net> <1175528018.544324.177390@y66g2000hsf.googlegroups.com> Message-ID: <461144d4$0$30101$4d3efbfe@news.sover.net> Paul Boddie wrote: > On 2 Apr, 16:19, Steve Holden wrote: >> Both fixed by the time I managed to follow the links. > > There wasn't much to see, and putting apostrophes into the input > didn't seem to cause "proper" repr() behaviour. So I suspect that the > Python resemblance was coincidental. The apostrophes were being HTML-escaped (into ') before repr() was called. The second example I found used a Unicode character, and caused YouTube to show the repr() of a Unicode string, escape codes and all. From khemkaamit at gmail.com Mon Apr 16 06:13:48 2007 From: khemkaamit at gmail.com (Amit Khemka) Date: Mon, 16 Apr 2007 15:43:48 +0530 Subject: How to generate a continuous string In-Reply-To: <1176717806.754728.9600@y80g2000hsf.googlegroups.com> References: <1176717806.754728.9600@y80g2000hsf.googlegroups.com> Message-ID: <1360b7230704160313i418c40ecs8afbd224b2d4c4d2@mail.gmail.com> On 16 Apr 2007 03:03:26 -0700, ??????????????? wrote: > How to generate a continuous string, like this > "aaaaaaaaaaaaaaaaaaaaaaa" > the number of characters is dynamic. Is there a module or function > implement this string ? > such as: duplicate_string(char, num) mystr = mychar*n n: Integer (number of times you want to duplicate) 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 torbenm at app-5.diku.dk Mon Apr 16 07:19:33 2007 From: torbenm at app-5.diku.dk (Torben =?iso-8859-1?Q?=C6gidius?= Mogensen) Date: Mon, 16 Apr 2007 13:19:33 +0200 Subject: is laziness a programer's virtue? References: <1176654319.273907.167280@q75g2000hsh.googlegroups.com> <1176663615.592055.45720@l77g2000hsb.googlegroups.com> Message-ID: <7z8xcs1s8q.fsf@app-5.diku.dk> rpw3 at rpw3.org (Rob Warnock) writes: > Daniel Gee wrote: > +--------------- > | You fail to understand the difference between passive laziness and > | active laziness. Passive laziness is what most people have. It's > | active laziness that is the virtue. It's the desire to go out and / > | make sure/ that you can be lazy in the future by spending just a > | little time writing a script now. It's thinking about time > | economically and acting on it. > +--------------- > > Indeed. See Robert A. Heinlein's short story (well, actually just > a short section of his novel "Time Enough For Love: The Lives of > Lazarus Long") entitled "The Tale of the Man Who Was Too Lazy To > Fail". It's about a man who hated work so much that he worked > very, *very* hard so he wouldn't have to do any (and succeeded). You can also argue that the essence of progress is someone saying "Hey, there must be an easier way to do this!". Torben From wswilson at gmail.com Wed Apr 18 15:09:31 2007 From: wswilson at gmail.com (wswilson) Date: 18 Apr 2007 12:09:31 -0700 Subject: Iterate through a dictionary of lists one "line" at a time In-Reply-To: <1176922475.420167.57490@p77g2000hsh.googlegroups.com> References: <1176921542.567121.248820@b58g2000hsg.googlegroups.com> <1176922475.420167.57490@p77g2000hsh.googlegroups.com> Message-ID: <1176923371.007795.38970@b75g2000hsg.googlegroups.com> On Apr 18, 2:54 pm, Arnaud Delobelle wrote: > On Apr 18, 7:39 pm, wswilson wrote: > > > > > Here is my code: > > > listing = {'id': ['a', 'b', 'c'], 'name': ['Joe', 'Jane', 'Bob']} > > > I need to output: > > > id name > > a Joe > > b Jane > > c Bob > > > I could do: > > > print 'id', 'name' > > for id, name in zip(listing['id'], listing['name']): print id, name > > > but that only works if there are two entries in the dictionary, id and > > name, and I know what they are. My problem is I don't know how many of > > these entries there will be. Thanks for any help you can give! > > You can use zip(*sequence_of_sequences) > eg zip(*[[1,2,3],[4,5,6]) returns [[1,4], [2,5], [3,6]] > (You can think of it as a transposition function) > > For example: > > keys, item_lists = zip(*listing.iteritems()) > print " ".join(keys) > for items in zip(*item_lists): > print " ".join(items) > > would work. > > HTH > > -- > Arnaud That works perfectly. Thanks so much. From 12cc104 at gmail.com Sun Apr 29 02:23:00 2007 From: 12cc104 at gmail.com (proctor) Date: 28 Apr 2007 23:23:00 -0700 Subject: regex question In-Reply-To: References: <1177655637.717863.93920@o40g2000prh.googlegroups.com> <1177659238.159411.40640@c18g2000prb.googlegroups.com> <1177683018.566343.105620@c18g2000prb.googlegroups.com> Message-ID: <1177827780.944296.138520@e65g2000hsc.googlegroups.com> On Apr 27, 8:26 am, Michael Hoffman wrote: > proctorwrote: > > On Apr 27, 1:33 am, Paul McGuire wrote: > >> On Apr 27, 1:33 am,proctor<12cc... at gmail.com> wrote: > >>> rx_test = re.compile('/x([^x])*x/') > >>> s = '/xabcx/' > >>> if rx_test.findall(s): > >>> print rx_test.findall(s) > >>> ============ > >>> i expect the output to be ['abc'] however it gives me only the last > >>> single character in the group: ['c'] > > >> As Josiah already pointed out, the * needs to be inside the grouping > >> parens. > > so my question remains, why doesn't the star quantifier seem to grab > > all the data. > > Because you didn't use it *inside* the group, as has been said twice. > Let's take a simpler example: > > >>> import re > >>> text = "xabc" > >>> re_test1 = re.compile("x([^x])*") > >>> re_test2 = re.compile("x([^x]*)") > >>> re_test1.match(text).groups() > ('c',) > >>> re_test2.match(text).groups() > ('abc',) > > There are three places that match ([^x]) in text. But each time you find > one you overwrite the previous example. > > > isn't findall() intended to return all matches? > > It returns all matches of the WHOLE pattern, /x([^x])*x/. Since you used > a grouping parenthesis in there, it only returns one group from each > pattern. > > Back to my example: > > >>> re_test1.findall("xabcxaaaxabc") > ['c', 'a', 'c'] > > Here it finds multiple matches, but only because the x occurs multiple > times as well. In your example there is only one match. > > > i would expect either 'abc' or 'a', 'b', 'c' or at least just > > 'a' (because that would be the first match). > > You are essentially doing this: > > group1 = "a" > group1 = "b" > group1 = "c" > > After those three statements, you wouldn't expect group1 to be "abc" or > "a". You'd expect it to be "c". > -- > Michael Hoffman thank you all again for helping to clarify this for me. of course you were exactly right, and the problem lay not with python or the text, but with me. i mistakenly understood the text to be attempting to capture the C style comment, when in fact it was merely matching it. apologies. sincerely, proctor From jstroud at mbi.ucla.edu Wed Apr 25 00:08:50 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Tue, 24 Apr 2007 21:08:50 -0700 Subject: Python Screen Scraper In-Reply-To: References: Message-ID: James Stroud wrote: > Hello, > > Does anyone know of an example, however modest, of a screenscraper > authored in python? I am using Firefox. > > Basically, I am answering problems via my browser and being scored for > each problem. I have a tendency to go past my peak for training > efficiency, so I would like to scrape the result page for each problem I > answer, compile statistics, and have a program alert me when I should > stop (based on score and accuracy--assuming training value is related to > changes in these metrics). > > I have no idea how to go about writing such a beast and I am hoping that > I could get some pointers or an example that could get me going in the > right direction. > > Parsing, etc, is not a problem, but I'm not exactly sure how I might > interface python with Firefox, forwarding scraped pages to my browser > (or forwarding from the browser to the scraper). > > Thanks in advance for any help or advice. > > James Thanks to everyone for your suggestions. James From aahz at pythoncraft.com Sun Apr 29 16:29:44 2007 From: aahz at pythoncraft.com (Aahz) Date: 29 Apr 2007 13:29:44 -0700 Subject: Any Good tools to create CSV Files? References: <1177811756.255774.315260@q75g2000hsh.googlegroups.com> Message-ID: In article , Carsten Haese wrote: >On Sat, 2007-04-28 at 18:55 -0700, johnny wrote: >> >> Any Good tools to create CSV Files? ReportLab only creates pdf >> files. I need something to create CSV files. > >You mean something like the csv module that is part of Python's standard >library? > >>>> import csv In all fairness, the csv module is new in Python 2.3, and I'm sure I'm not the only person still using Python 2.2 for production. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "...string iteration isn't about treating strings as sequences of strings, it's about treating strings as sequences of characters. The fact that characters are also strings is the reason we have problems, but characters are strings for other good reasons." --Aahz From aleax at mac.com Thu Apr 5 00:37:55 2007 From: aleax at mac.com (Alex Martelli) Date: Wed, 4 Apr 2007 21:37:55 -0700 Subject: Getting word frequencies from files which are in folder. References: <1175710660.753453.205000@n76g2000hsh.googlegroups.com> <4613f24f$0$327$e4fe514c@news.xs4all.nl> <1175717246.781352.178090@e65g2000hsc.googlegroups.com> Message-ID: <1hw2ecv.2jcdeqa5h4syN%aleax@mac.com> wrote: > > This sounds suspiciously like a homework assignment. > > I don't think you'll get much help for this one, unless > > you show some code you wrote yourself already with a specific > > question about problems you're having.... > > Well you have some right. I will make it more specific. > I have got something like that: > > import os, os.path > > def wyswietlanie_drzewa(dir_path): > #function is reading folders and sub folders until it gets to a file. > for name in os.listdir(dir_path): > full_path = os.path.join(dir_path, name) > print full_path > if os.path.isdir(full_path): > wyswietlanie_drzewa(full_path) > > My question is how to get word frequencies from this files? > I will be glad to get any help. You may want to consider os.walk as an alternative way to get all files; it's easy to wrap it into a generator yielding all files in the subtree. This, I would think, is the proper factoring in Python: have a generator yielding each file, and a function taking a file and returning the word frequencies for that one file. This neatly separates the two halves of the task -- and you can easily factor things down further... Give a text file, you can iterate on it: the items are the lines. Given a line, you can extract all words in it and iterate on those: look at the re module, and the \w feature of regular-expression pattern strings. So, a generator that turns a file into a stream of words is also an easy sub-task to accomplish. Given a stream of words, and a set of "interesting words", it's easy to count the occurrences of interesting words. There, I'll supply that part, to entice you to write the others, and thereby perhaps learn some Python...: def count_interesting_words(all_words, interesting_words): d = dict.fromkeys(interesting_words, 0) for word in all_words: if word in d: d[word] += 1 return d Alex From grante at visi.com Thu Apr 12 19:26:17 2007 From: grante at visi.com (Grant Edwards) Date: Thu, 12 Apr 2007 23:26:17 -0000 Subject: Binary To File References: <695408014765593209@unknownmsgid> Message-ID: <131tg0p19gmkd4b@corp.supernews.com> On 2007-04-12, Daniel Nogradi wrote: >> Is there an easy way to take binary data and build it into a file? Generally >> this will be BLOB data drawn from a database, the data will be for jpg >> images, I want to take the blob data and build it into a physical .jpg file. >> >> >> >> Is there a simple function for doing this in python? Like binary2file() or >> something along those lines? > > myblob = ......... # let's say you got it from your database somehow > myjpeg = open( 'image.jpg', 'w' ) myjpeg = open( 'image.jpg', 'wb' ) > myjpeg.write( myblob ) > myjpeg.close( ) > > > Daniel -- Grant Edwards grante Yow! NOW, I'm supposed at to SCRAMBLE two, and HOLD visi.com th' MAYO!! From bruno.42.desthuilliers at wtf.websiteburo.oops.com Fri Apr 27 06:07:39 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Fri, 27 Apr 2007 12:07:39 +0200 Subject: My python annoyances so far In-Reply-To: <1177603623.774892.230390@t38g2000prd.googlegroups.com> References: <1177541453.471959.120830@c18g2000prb.googlegroups.com> <59bf34F2k27v5U1@mid.individual.net> <1177603623.774892.230390@t38g2000prd.googlegroups.com> Message-ID: <4631cb4a$0$772$426a74cc@news.free.fr> flifus at gmail.com a ?crit : (snip) > > Well, why do some things in the library have to be functions, and > other things have to be class methods? > Why aren't they all just either functions or class methods? like > perhaps ruby. > If I tell you that Python's functions are in fact static methods of their module, will this make you happy ? Because, while not technically true, this is conceptually equivalent. Or if you prefer to stick to technical truth, python's methods are nothing more than a thin decorator around a function object (yes, Python's functions *are* objects) - so in fact, there are *only* functions - sometimes wrapped into a method object, sometimes not, depending on how you access them. In both cases, the fact that you don't have enough knowledge of a language to understand it's design, and/or the fact that this design is different from other one you already know, doesn't by itself make this design an "annoyance". From a.schmolck at gmail.com Sun Apr 8 06:27:24 2007 From: a.schmolck at gmail.com (Alexander Schmolck) Date: 08 Apr 2007 11:27:24 +0100 Subject: itertools, functools, file enhancement ideas References: <7xveg7rhc7.fsf_-_@ruckus.brouhaha.com> <1hw7lfg.112hjgqyt48vN%aleax@mac.com> Message-ID: aleax at mac.com (Alex Martelli) writes: > > 4. functools enhancements (Haskell-inspired): > > Let f be a function with 2 inputs. Then: > > a) def flip(f): return lambda x,y: f(y,x) > > b) def lsect(x,f): return partial(f,x) > > c) def rsect(f,x): return partial(flip(f), x) > > > > lsect and rsect allow making what Haskell calls "sections". Example: > > # sequence of all squares less than 100 > > from operator import lt > > s100 = takewhile(rsect(lt, 100), (x*x for x in count())) > > Looks like they'd be useful, but I'm not sure about limiting them to > working with 2-argument functions only. How's from mysterymodule import resect from operator import lt takewhile(rsect(lt, 100), (x*x for x in count())) better than takewhile(lambda x:x<100, (x*x for x in count())) Apart from boiler-plate creation and code-obfuscation purposes? 'as From plutoinchina at gmail.com Wed Apr 4 06:46:55 2007 From: plutoinchina at gmail.com (autin) Date: 4 Apr 2007 03:46:55 -0700 Subject: bool value 'False' no memory address? In-Reply-To: <1175683317.458791.275270@d57g2000hsg.googlegroups.com> References: <1175682972.507206.29000@n76g2000hsh.googlegroups.com> <1175683317.458791.275270@d57g2000hsg.googlegroups.com> Message-ID: <1175683615.036627.96560@w1g2000hsg.googlegroups.com> Python 2.4.4 Linux debian 2.6.8-3-386 any wrong? > > --- > > how to desc it? > >>> b = False > >>> id(b) > 135311308 > > python 2.4, FreeBSD 6.2 From larry.bates at websafe.com Tue Apr 17 16:10:12 2007 From: larry.bates at websafe.com (Larry Bates) Date: Tue, 17 Apr 2007 15:10:12 -0500 Subject: How to Passs NULL as a IDispatch Pointer to method? In-Reply-To: <1176783870.081696.278100@l77g2000hsb.googlegroups.com> References: <1176783870.081696.278100@l77g2000hsb.googlegroups.com> Message-ID: <462529A4.40507@websafe.com> ZhaoYingpu at gmail.com wrote: > Hello,all > I am using win32com to use com. and invoke a method as follows: > void AddShapeInfo(LPCTSTR name, LONG type, IDispatch* pDisp); > but i pass 0 or None to third parameter and get error info: > >>>> x.AddShapeInfo("who", 10, 0) > > Traceback (most recent call last): > File "", line 1, in > x.AddShapeInfo("who", 10, 0) > File "", line 2, in AddShapeInfo > com_error: (-2147352571, 'Type mismatch.', None, 3) > > or > >>>> x.AddShapeInfo("who",0,None) > > Traceback (most recent call last): > File "", line 1, in > x.AddShapeInfo("who",0,None) > File "", line 2, in AddShapeInfo > com_error: (-2147352571, 'Type mismatch.', None, 3) > Maybe Mark Hammond will chime in here, but I'll make at least an attempt to help. If I'm reading this correctly the 3rd argument should be and pointer to an IDispatch object. Passing null or zero wouldn't make any sense. This looks like a pointer to a callback function for this shape. To get one you would need to define a Python COM class and wrap it with win32com.server.util.wrap() possibly something like: class who: _public_methods_=['somemethod'} # # I don't know what method AddShapeInfo is going to call so # change this to the appropriate method. # def somemethod(self): # # Put this method's code here # pass # # In your program # id=win32com.server.util.wrap(who()) x.AddShapeInfo("who",0,id) I could be way off base here, but I hope that this helps. -Larry From liqfemail at gmail.com Sat Apr 7 23:38:25 2007 From: liqfemail at gmail.com (liqfemail at gmail.com) Date: 7 Apr 2007 20:38:25 -0700 Subject: Why does not my wx.html.HtmlWindow work? Message-ID: <1176003505.794328.62170@n76g2000hsh.googlegroups.com> Below are my source code: import wx import wx.html class MyHtmlFrame(wx.Frame): def __init__(self, parent, title): wx.Frame.__init__(self, parent, -1, title, size=(600,400)) html = wx.html.HtmlWindow (self) if "gtk2" in wx.PlatformInfo: html.SetStandardFonts() html.LoadPage(" http://www.pythonthreads.com/articles/python/incorporating-into-wxpython-part-1.html") app = wx.PySimpleApp() frm = MyHtmlFrame(None, "Simple HTML Browser") frm.Show() app.MainLoop() It is just an example in the book "wxPython in action". But every time when I try to get it run, my CPU is fully occupied, and there is no frame that comes into existence. Why? From steveo at syslang.net Fri Apr 27 16:46:24 2007 From: steveo at syslang.net (Steven W. Orr) Date: Fri, 27 Apr 2007 16:46:24 -0400 (EDT) Subject: how to create/ref globals in an alternate namespace? Message-ID: I have two seperate modules doing factory stuff which each have the similar function2: In the ds101 module, def DS101CLASS(mname,data): cname = mname+'DS101' msg_class = globals()[cname] msg = msg_class(data) return msg and in the fdu module, def FDUCLASS(mname,data): cname = mname+'FDU' msg_class = globals()[cname] msg = msg_class(data) return msg I was thinking I'd be clever and create a common function: def procCLASS(mname, objname, data): cname = mname+objname msg_class = globals()[cname] msg = msg_class(data) return msg but the call to globals fouls it all up. Is there a way to write it so that the call to globals can be parameterized to be in the context of a specific module? Also, I need to go the other way, a la, globals()[name] = nclass Is this doable? 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 Leo.Kislov at gmail.com Sun Apr 1 18:02:45 2007 From: Leo.Kislov at gmail.com (Leo Kislov) Date: 1 Apr 2007 15:02:45 -0700 Subject: shutil.copy Problem In-Reply-To: References: <1174970535.061022.141230@l77g2000hsb.googlegroups.com> Message-ID: <1175464965.079090.80070@y66g2000hsf.googlegroups.com> On Mar 28, 7:01 am, David Nicolson wrote: > Hi John, > > That was an excellent idea and it was the cause problem. Whether this > is a bug inshutilI'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") Note, there is no backslash after C:. shutil will try to make an absolute file name and concatenate it with a current directory name (C: \Documents and Settings\G?stav) that contains non-ascii characters. Because of backward compatibility the absolute name won't be unicode. On the other hand data coming from registry is unicode. When shutil tries to compare those two file names it fails. To avoid the problem you need either make both file names unicode or both file names byte- strings. However one thing is still mystery to me. Your source code contains backslash but your traceback doesn't: > >shutil.copy(xmlfile,"C:\iTunes Music Library.xml") > > Theshutilline needed to be changed to this to be successful: > > >shutil.copy(xmlfile.encode("windows-1252"),"C:\iTunes Music > > Library.xml" It will work only in some European locales. Using of locale module you can make it work for 99% of world users, but it will still fail in cases like German locale and Greek characters in file names. Only using unicode everywhere in your program is a complete solution. Like shutil.copy(xmlfile, u"C:\iTunes Music Library.xml") if you use constant or make sure your file name is unicode: dest = unicode(....) shutil.copy(xmlfile, dest) -- Leo. From steve at holdenweb.com Tue Apr 24 13:07:52 2007 From: steve at holdenweb.com (Steve Holden) Date: Tue, 24 Apr 2007 13:07:52 -0400 Subject: Socket exceptions aren't in the standard exception hierarchy In-Reply-To: References: Message-ID: John Nagle wrote: > Steve Holden wrote: >> John Nagle wrote: >> [socket.error bug report] >> >>>> Where did you get this information? If true it would certainly need >>>> to be logged as a bug, but under Windows on 2,4 I see >>>> >>>> >>> issubclass(socket.gaierror, Exception) >>>> True >>>> >>> >>>> >>>> and the same under Cygwin 2.5. I am presuming most other users will >>>> see the same thing. >>>> >>>> regards >>>> Steve >>> >>> Ah. "socket.error" is a subclass of "Exception", but not >>> of "StandardError". >>> >>> issubclass(socket.error,StandardError) >>> >>> is False. >>> >> Right, so this *is* a bug, as long as Brett Cannon's upcoming (further) >> reorganization of the standard exception hierarchy doesn't stamp on it. >> It probably *was* overlooked in the reorganization of the hierarchy, and >> this implies there may be other extensions that also make the same error. >> >> It should be logged as a bug in the tracker - the fix is probably pretty >> simple, but it'll need some consideration of the forward compatibility >> considerations. >> >> regards >> Steve > > The bug tracker shows quite a number of problems related to > socket exceptions. Searching for "socket AND exception" returns > 45 results. These seem to be the most relevant ones: > > [ 805194 ] Inappropriate error received using socket timeout > [ 1019808 ] wrong socket error returned > [ 1571878 ] Improvements to socket module exceptions > [ 708927 ] socket timeouts produce wrong errors in win32 > > None of them quite cover this new issue, but it's clear > that the area needs some work. Should this new issue > be added as a new bug or as an added comment to one of the > above? > > Just figuring out what exceptions can be raised from > the socket module is tough. I've seen exceptions > derived from "socket.error", exceptions from IOError, > and exceptions from the SSL layer, which patches the > sockets module when loaded. These are non-bug > exceptions; that is, the problem is out in the network, > external to the program. I'm still not sure I have all > the possibilities covered. > > Retrying on unknown exceptions isn't the answer; > that leads to exception loops if there's a program bug. > The most important distinction with sockets is "external > network problem" vs. "local program program". I'd like > to see a "NetworkException" in the exception hierarchy, > with all the things that can go wrong due to conditions > external to the local machine under that exception. > > I'd suggest the following: > > 1. Add "NetworkError" under "IOError" in > the exception hierarchy. > > 2. Put the existing "socket.error" under "NetworkError". > Since "socket.error" needs to be reparented anyway (it's currently > a direct descendant of "Exception") this provides a good place for it. > > 3. Find any places where the socket module can raise IOError > or OSError due to an external network condition, and make them raise > something under NetworkError instead. Code that catches IOError > will still work. > > 4. Put all errors in the various SSL modules (SSLError, etc.) > which can be raised due to external network conditions under "NetworkError". > > 5. Move "urllib2.URLError", which is currently under IOError, to be > under NetworkError. > > 6. Move the misc. errors from "urllib", like "ContentTooShortError", > which are currently under IOError, down a level under NetworkError. > > Then, programs that catch NetworkError could be sure of catching > all network trouble conditions, but not local code bugs. > > John Nagle All these notes should be included in the bug report, as I suspect the module would benefit from additional clarity. I believe socket just grew up as a clever way of making as much use of the platform socket library as possible, and that the approach's deficiencies have become more obvious as time has gone by and Python has matured. The work you describe is not insignificant, so it should be fully described if it's to stand any chance of being implemented. I *do* think it would rationalize things considerably, but that's only me ... regards Steve -- Steve Holden +1 571 484 6266 +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 aahz at pythoncraft.com Wed Apr 25 18:27:31 2007 From: aahz at pythoncraft.com (Aahz) Date: 25 Apr 2007 15:27:31 -0700 Subject: Namespaces/introspection: collecting sql strings for validation References: <1921780.hifcbgjtIO@beaureve.gmx.net> <1hwzkoo.118nt2f1htv72tN%aleax@mac.com> <1hx1epp.80dkmd1wjozaaN%aleax@mac.com> Message-ID: In article <1hx1epp.80dkmd1wjozaaN%aleax at mac.com>, Alex Martelli wrote: >Aahz wrote: >>Alex: >>> >>>But don't put such black magic in production. The completely different >>>way is: just don't. >> >> Could you expand on that? After all, that's exactly what we do to >> implement a super() that works with classic classes -- and it's certainly >> production code. > >Personally, I'd much rather give up super (not a big loss) and classic >classes (a substantial net gain:-) than have to maintain such "black >magic" in a production environment. Explicit is better than implicit, >&c. This application was started with Python 1.4. We still use Python 2.2, which has some subtle but critical differences with the way new-style classes are handled in 2.3+. Using super() makes our plugin model work; otherwise, we'd have to switch to a non-cooperative mechanism for calling plugin hooks. That would have some advantages, of course, but so much code would need rewriting, and managing the calling of plugin hooks would require creating an API registry. The world is not always a simple place.... -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "...string iteration isn't about treating strings as sequences of strings, it's about treating strings as sequences of characters. The fact that characters are also strings is the reason we have problems, but characters are strings for other good reasons." --Aahz From gagsl-py2 at yahoo.com.ar Sat Apr 28 16:37:25 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sat, 28 Apr 2007 17:37:25 -0300 Subject: How to pass in argument to timeit.Timer References: <1177786091.049008.278400@o5g2000hsb.googlegroups.com> Message-ID: En Sat, 28 Apr 2007 15:48:11 -0300, silverburgh.meryl at gmail.com escribi?: > I have a function in my python like this: > def callFunc(line, no): > # some code > > And I want to do a performance test like this: > for line in f: > for i in range(int(count)): > t1 = timeit.Timer("callFunc(line, i)","from __main__ > import callFunc") > r1 = t1.timeit(); > print r1; > > but when I run it, it can't recognize the parameter 'line' and 'i', > can you please tell me how to fix it? i get this error: They go in the "setup" parameter, like this: t1 = timeit.Timer("callFunc(line, i)","from __main__ import callFunc; line=%r; i=%d" % (line, i)) If it gets much longer, try this: setup = """ from __main__ import callFunc line = %r i = %d""" % (line, i) stmt = "callFunc(line, i)" t1 = timeit.Timer(stmt, setup) -- Gabriel Genellina PS: Please leave out the final ; - this is Python, not C nor ... PS2: Perhaps the only place where I've used ; is with timeit. And even then you can avoid them as in the last example. From godzillaismad at gmail.com Tue Apr 10 00:10:32 2007 From: godzillaismad at gmail.com (Godzilla) Date: 9 Apr 2007 21:10:32 -0700 Subject: Queue get timeout parameter question Message-ID: <1176178232.836311.19390@p77g2000hsh.googlegroups.com> Dear all, I have been using the queue module for a multithreaded environment and things seem to work well... until we had a requirement for the application to be able to time sync to the server. With the time sync, it actually disorientated the timeout in the queue's get() method... e.g. get(item, 2.0) After the time sync, say 15 seconds backward, the thread is sitting on that get() method for a total of 17 seconds. We can only sync the device once per day and the time can drift up to 15 seconds per day!! I had tried to get around this problem by having a sleep(2) (sleep is not local system time dependant) just before the get(), but that will slow down the application too much. Anyone knows a solution to this problem or an alternative method? From deets at nospam.web.de Mon Apr 2 09:05:57 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 02 Apr 2007 15:05:57 +0200 Subject: Clean "Durty" strings References: <1175463083.135907.128480@y80g2000hsf.googlegroups.com> <57bt02F2c9fpuU2@mid.uni-berlin.de> Message-ID: <57cddlF2bsqdbU2@mid.uni-berlin.de> > > If the OP is constrained to standard libraries, then it may be a > question of defining what should be done more clearly. The extraneous > spaces can be removed by tokenizing the string and rejoining the > tokens. Replacing portions of a string with equivalents is standard > stuff. It might be preferable to create a function that will accept > lists of from and to strings and translate the entire string by > successively applying the replacements. From what I've seen so far, > that would be all the OP needs for this task. It might take a half- > dozen lines of code, plus the from/to table definition. The OP had
-tags in his text. Which is _more_ than a half dozen lines of code to clean up. Because your simple replacement-approach won't help here:
foo
bar
Which is perfectly legal HTML, but nasty to parse. Diez From timr at probo.com Wed Apr 4 03:07:26 2007 From: timr at probo.com (Tim Roberts) Date: Wed, 04 Apr 2007 07:07:26 GMT Subject: Math with unicode strings? References: <1175540961.679578.199370@o5g2000hsb.googlegroups.com> Message-ID: "erikcw" wrote: > >What do I need to do to extract the intergers from these unicode >strings (or better yet, parse them as intergers in the first place.). >I'm using the SAX method attrs.get('cls1',"") to parse the xml. Can I >"cast" the string into an interger? When I see a typo once, I figure it's a typo, but when I see it three times, I figure it is a misunderstanding. The word is "integer", not "interger". -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From nyamatongwe+thunder at gmail.com Sat Apr 21 02:18:55 2007 From: nyamatongwe+thunder at gmail.com (Neil Hodgson) Date: Sat, 21 Apr 2007 06:18:55 GMT Subject: Python's handling of unicode surrogates In-Reply-To: <1177062758.289618.24630@y80g2000hsf.googlegroups.com> References: <0QXVh.16735$M.14016@news-server.bigpond.net.au> <1177062758.289618.24630@y80g2000hsf.googlegroups.com> Message-ID: Paul Boddie: > Do we have a volunteer? ;-) I won't volunteer to do a real implementation - the Unicode type in Python is currently around 7000 lines long and there is other code to change in, for example, regular expressions. Here's a demonstration C++ implementation that stores an array of surrogate positions for indexing. For text in which every character is a surrogate, this could lead to requiring 3 times as much storage (with a size_t requiring 64 bits for each 32 bit surrogate pair). Indexing is reasonably efficient, using a binary search through the surrogate positions so is proportional to log(number of surrogates). Code (not thoroughly tested): /** @file surstr.cxx ** A simple Unicode string class that stores in UTF-16 ** but indexes by character. **/ // Copyright 2007 by Neil Hodgson // This source code is public domain. #include #include class surstr { public: typedef wchar_t codePoint; enum { SURROGATE_LEAD_FIRST = 0xD800 }; enum { SURROGATE_LEAD_LAST = 0xDBFF }; enum { measure_length=0xffffffffU}; codePoint *text; size_t length; size_t *surrogates; // Memory use would be decreased by allocating text and // surrogates as one block but the code is clearer this way size_t lengthSurrogates; static bool IsLead(codePoint cp) { return cp >= SURROGATE_LEAD_FIRST && cp <= SURROGATE_LEAD_LAST; } void FindSurrogates() { lengthSurrogates = 0; for (size_t i=0; i < length; i++) { if (IsLead(text[i])) { lengthSurrogates++; } } surrogates = new size_t[lengthSurrogates]; size_t surr = 0; for (size_t i=0; i < length; i++) { if (IsLead(text[i])) { surrogates[surr] = i - surr; surr++; } } } size_t LinearIndexFromPosition(size_t position) const { // For checking that the binary search version works for (size_t i=0; i= position) { return position + i; } } return position + lengthSurrogates; } size_t IndexFromPosition(size_t position) const { // Use a binary search to find index in log(lengthSurrogates) if (lengthSurrogates == 0) return position; if (position > surrogates[lengthSurrogates - 1]) return position + lengthSurrogates; size_t lower = 0; size_t upper = lengthSurrogates-1; do { size_t middle = (upper + lower + 1) / 2; // Round high size_t posMiddle = surrogates[middle]; if (position < posMiddle) { upper = middle - 1; } else { lower = middle; } } while (lower < upper); if (surrogates[lower] >= position) return position + lower; else return position + lower + 1; } size_t Length() const { return length - lengthSurrogates; } surstr() : text(0), length(0), surrogates(0), lengthSurrogates(0) {} // start and end are in code points surstr(codePoint *text_, size_t start=0, size_t end=measure_length) : text(0), length(0), surrogates(0), lengthSurrogates(0) { // Assert text_[start:end] only contains whole surrogate pairs if (end == measure_length) { end = 0; while (text_[end]) end++; } length = end - start; text = new codePoint[length]; memcpy(text, text_, sizeof(codePoint) * length); FindSurrogates(); } // start and end are in characters surstr(const surstr &source, size_t start=0, size_t end=measure_length) { size_t startIndex = source.IndexFromPosition(start); size_t endIndex; if (end == measure_length) endIndex = source.IndexFromPosition(source.Length()); else endIndex = source.IndexFromPosition(end); length = endIndex - startIndex; text = new codePoint[length]; memcpy(text, source.text + startIndex, sizeof(codePoint) * length); if (start == 0 && end == measure_length) { surrogates = new size_t[source.lengthSurrogates]; memcpy(surrogates, source.surrogates, sizeof(size_t) * source.lengthSurrogates); lengthSurrogates = source.lengthSurrogates; } else { FindSurrogates(); } } ~surstr() { delete []text; text = 0; delete []surrogates; surrogates = 0; } void print() { for (size_t i=0;i ", a.Length(), a.length); a.print(); printf("\n"); for (size_t pos = 0; pos < a.Length(); pos++) { if (a.IndexFromPosition(pos) != a.LinearIndexFromPosition(pos)) { printf(" Failed at position %d -> %d", pos, a.IndexFromPosition(pos)); } printf(" [%0d] ", pos); surstr b(a, pos, pos+1); b.print(); printf("\n"); } } int main() { surstr n(L""); slicer(n); surstr a(L"a"); slicer(a); surstr b(L"a\u6C348\U0001D11E-\U00010338!"); slicer(b); printf("\n"); surstr c(L"a\u6C348\U0001D11E\U0001D11E-\U00010338!" L"\U0001D11E\U0001D11Ea\u6C348\U0001D11E-\U00010338!"); slicer(c); printf("\n"); } Test run: Length in characters = 0, code units = 0 ==> Length in characters = 1, code units = 1 ==> a [0] a Length in characters = 7, code units = 9 ==> a\u6c348\ud834\udd1e-\ud800\udf38! [0] a [1] \u6c34 [2] 8 [3] \ud834\udd1e [4] - [5] \ud800\udf38 [6] ! Length in characters = 17, code units = 24 ==> a\u6c348\ud834\udd1e\ud834\udd1e-\ud800\udf38!\ud834\udd1e\ud834\udd1ea\u6c348\ud834\udd1e-\ud800\udf38! [0] a [1] \u6c34 [2] 8 [3] \ud834\udd1e [4] \ud834\udd1e [5] - [6] \ud800\udf38 [7] ! [8] \ud834\udd1e [9] \ud834\udd1e [10] a [11] \u6c34 [12] 8 [13] \ud834\udd1e [14] - [15] \ud800\udf38 [16] ! Neil From whamil1 at entergy.com Thu Apr 26 14:59:47 2007 From: whamil1 at entergy.com (Hamilton, William ) Date: Thu, 26 Apr 2007 13:59:47 -0500 Subject: Python keywords In-Reply-To: <1177613379.115009.23430@r3g2000prh.googlegroups.com> Message-ID: <588D53831C701746A2DF46E365C018CE01D2CA7C@LITEXETSP001.etrsouth.corp.entergy.com> > -----Original Message----- > From: python-list-bounces+whamil1=entergy.com at python.org [mailto:python- > list-bounces+whamil1=entergy.com at python.org] On Behalf Of gtb > Sent: Thursday, April 26, 2007 1:50 PM > To: python-list at python.org > Subject: Re: Python keywords > > On Apr 26, 10:16 am, Larry Bates wrote: > > http://docs.python.org/ref/keywords.html > > > > in keyword is a general one and can be used for many objects. > > > > x in 'xyz' > > > > y in ['a','b','c','y','z''] > > > > z in ('a','b','c','y','z'] > > > > key in {'key1':1, 'key2': 2} > > > > The in you see with a for isn't associated with the for loop > > but rather the sequence you are iterating over > > > > for i in range(10): > > > > -Larry > > Thanks Larry. I saw that page you referenced above and that is how I > knew it was a keyword. But I still have found nodocumentation that > supports the examples you provided. http://docs.python.org/ref/comparisons.html#l2h-438 This information is 2 clicks away from any page in the reference: click the index link, then scroll down to the link to "in operator". --- -Bill Hamilton From nobody at invalid.com Wed Apr 18 12:35:40 2007 From: nobody at invalid.com (Erik Johnson) Date: Wed, 18 Apr 2007 10:35:40 -0600 Subject: array{uint32} References: <1527208137037646615@unknownmsgid> Message-ID: <462648a3$1@nntp.zianet.com> "Daniel Nogradi" wrote in message news:mailman.6660.1176906192.32031.python-list at python.org... > > I have a function that returns a array{uint32}, is there any way to output > > that to screen in a more user friendly format? At the moment when I print it > > by itself it appears as [65541L], which isn't much used to anyone. > > I'm not sure I understand your question precisely but this might help: > > >>> mylist = [65541L] > >>> mylist > [65541L] > >>> mylist[0] > 65541L > >>> int(mylist[0]) > 65541 > >>> Right, so getting rid of the 'L' is one improvement. You might also check out the pprint module: >>> l = range(30) >>> l [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 2 2, 23, 24, 25, 26, 27, 28, 29] >>> from pprint import pprint >>> pprint(l) [0, 1, 2, 3, 28, 29] >>> You can use C-like print formatting statements: >>> l = [-3, 0, 101320, 67] >>> pprint(l) [-3, 0, 101320, 67] >>> for i in l: ... print i ... -3 0 101320 67 >>> for i in l: ... print '%6i' % i ... -3 0 101320 67 >>> # the above probably doesn't disply correctly unless you are viewing with a monospaced font) You could sort the list, then split it up into N separate lists so that you can format multiple columns of sorted integers... You haven't given any real information about your idea of a "user friendly format", but maybe this will help also. -ej From gagsl-py2 at yahoo.com.ar Sun Apr 15 16:41:05 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sun, 15 Apr 2007 17:41:05 -0300 Subject: reading from sys.stdin References: <1176366058.261031.111870@p77g2000hsh.googlegroups.com> <1176387908.406115.270630@w1g2000hsg.googlegroups.com> <1176438754.995753.50190@d57g2000hsg.googlegroups.com> <1176454871.538968.176620@n76g2000hsh.googlegroups.com> <1176457007.589050.285400@d57g2000hsg.googlegroups.com> <1176538930.891355.230880@n59g2000hsh.googlegroups.com> <1176577574.338733.325790@n59g2000hsh.googlegroups.com> <1176666672.619314.98640@d57g2000hsg.googlegroups.com> Message-ID: En Sun, 15 Apr 2007 16:51:12 -0300, 7stud escribi?: > I just typed in 700 lines of text, and the iteration hasn't begun > yet. Should I keep going? How much text each line? Python uses an 8K buffer. -- Gabriel Genellina From hlubenow2 at gmx.net Thu Apr 5 20:00:06 2007 From: hlubenow2 at gmx.net (hlubenow) Date: Fri, 06 Apr 2007 02:00:06 +0200 Subject: Extract zip file from email attachment References: <1175815907.434721.274190@w1g2000hsg.googlegroups.com> Message-ID: <65fge4-j15.ln1@athlon.my> erikcw wrote: > Hi all, > > I'm trying to extract zip file (containing an xml file) from an email > so I can process it. But I'm running up against some brick walls. > I've been googling and reading all afternoon, and can't seem to figure > it out. > > Here is what I have so far. > > p = POP3("mail.server.com") > print p.getwelcome() > # authentication, etc. > print p.user("USER") > print p.pass_("PASS") > print "This mailbox has %d messages, totaling %d bytes." % p.stat() > msg_list = p.list() > print msg_list > if not msg_list[0].startswith('+OK'): > # Handle error > exit(1) > > for msg in msg_list[1]: > msg_num, _ = msg.split() > resp = p.retr(msg_num) > if resp[0].startswith('+OK'): > #print resp, '=======================\n' > #extract message body and attachment. > parsed_msg = email.message_from_string('\n'.join(resp[1])) > payload= parsed_msg.get_payload(decode=True) > print payload #doesn't seem to work > else: > pass# Deal with error retrieving message. > > How do I: > a) retrieve the body of the email into a string so I can do some > processing? (I can get at the header attributes without any trouble) > b) retrieve the zip file attachment, and unzip into a string for xml > processing? > > Thanks so much for your help! > Erik Hi, some weeks ago I wrote some code to extract attachments from emails. It's not that long, so maybe it could be of help for you: ------------------------------------------- #!/usr/bin/env python import poplib import email import os import sys import string # # attsave.py # Check emails at PROVIDER for attachments and save them to SAVEDIR. # PROVIDER = "pop.YourMailProvider.de" USER = "YourUserName" PASSWORD = "YourPassword" SAVEDIR = "/home/YourUserDirectory" def saveAttachment(mstring): filenames = [] attachedcontents = [] msg = email.message_from_string(mstring) for part in msg.walk(): fn = part.get_filename() if fn <> None: filenames.append(fn) attachedcontents.append(part.get_payload()) for i in range(len(filenames)): fp = file(SAVEDIR + "/" + filenames[i], "wb") fp.write(attachedcontents[i]) print 'Found and saved attachment "' + filenames[i] + '".' fp.close() try: client = poplib.POP3(PROVIDER) except: print "Error: Provider not found." sys.exit(1) client.user(USER) client.pass_(PASSWORD) anzahl_mails = len(client.list()[1]) for i in range(anzahl_mails): lines = client.retr(i + 1)[1] mailstring = string.join(lines, "\n") saveAttachment(mailstring) client.quit() ------------------------------------------- See you H. From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Fri Apr 27 07:41:34 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Fri, 27 Apr 2007 13:41:34 +0200 Subject: My python annoyances so far References: <1177541453.471959.120830@c18g2000prb.googlegroups.com> Message-ID: <59e5reF2h4qrtU1@mid.individual.net> James Stroud wrote: > Here is something on which to meditate: classes become functions > when you get the quantum mechanics just so! s/become/can behave like/ :) Regards, Bj?rn -- BOFH excuse #27: radiosity depletion From aleax at mac.com Sat Apr 14 21:29:36 2007 From: aleax at mac.com (Alex Martelli) Date: Sat, 14 Apr 2007 18:29:36 -0700 Subject: Python Feature Request: Allow changing base of member indices to 1 References: <1176546465.632410.52630@w1g2000hsg.googlegroups.com> <1176579205.948684.171640@q75g2000hsh.googlegroups.com> <1176584444.335732.111740@n76g2000hsh.googlegroups.com> Message-ID: <1hwkok3.1kmipey1iv5ldzN%aleax@mac.com> Sherm Pendley wrote: > "Paddy" writes: > > > I don't think we should add it to Python > > because it would make porting VB code easier. > > Great Cthulhu no! > > I chimed in because your first comment regarding Perl implied that it's > commonplace for Perl programmers to fiddle with the index base. It can > be done, for historical reasons, but it's far from common. Reminds me of APL's worst blunder -- "quadIO" (with IO standing for Index Origin, NOT Input/Output) could be set to 0 or 1, with global effect. I worked a lot with APL and mostly loved it (APL2 even more so), and I'm saddened to read that the ACM wants to disband the APL SIG for lack of activity (though no doubt it's a reasonable decision, it badly tickles my nostalgia for years and decades gone) -- but the quadIO design decision was a truly major design blunder, and made it hell to integrate APL code from multiple sources. Alex From http Sat Apr 14 18:03:00 2007 From: http (Paul Rubin) Date: 14 Apr 2007 15:03:00 -0700 Subject: Useful decorator Message-ID: <7xtzvik417.fsf@ruckus.brouhaha.com> In the course of writing a bunch of generator-oriented code I kept wanting to temporarily truncate the output of generators for debugging, i.e. I might have a function like def generate_bazillion_items(): for line in bazillion_line_file: yield itemify(line) where I wanted to test the program on just the first 20 lines of the file. After a number of rounds of editing the program to wrap an xrange(20) loop I went to using islice(bazillion_line_file, 20), but even more handy was to write this decorator: def truncate(n): from itertools import islice def trunc(gen): # truncate generator to n items return lambda *a,**kw: islice(gen(*a,**kw), n) return trunc Then to chop bazillion_items to 20 items, I just write: @truncate(20) def generate_bazillion_items(): for line in bazillion_line_file: yield itemify(line) When I want to run the whole file, I comment out the @truncate line, and if I want to debug again, I just uncomment it. From paul at boddie.org.uk Thu Apr 5 12:37:44 2007 From: paul at boddie.org.uk (Paul Boddie) Date: 5 Apr 2007 09:37:44 -0700 Subject: AttributeError: 'tuple' object has no attribute 'encode' In-Reply-To: <1175787095.862712.297480@n76g2000hsh.googlegroups.com> References: <1175787095.862712.297480@n76g2000hsh.googlegroups.com> Message-ID: <1175791064.256896.240090@b75g2000hsg.googlegroups.com> erikcw wrote: > > I'm trying to build a SQL string > > sql = """INSERT INTO ag ('cid', 'ag', 'test') VALUES(%i, %s, %d)""", > (cid, ag, self.data[parent][child]['results']['test']) This makes a tuple, though: the first element is the SQL string; the second element contains a tuple of parameters. > It raises this error: AttributeError: 'tuple' object has no attribute > 'encode' What does? I imagine that this error comes from a call to a cursor object's execute method. In other words, I imagine that you may be doing something like this: cursor.execute(*sql) Not that there would be anything obviously wrong with that: you are keeping the string and its parameters separate, after all. However, you'd have to show us the full error (a traceback including lines of code from the database library) for us to really see what's going on. > Some of the variables are unicode (test and ag) - is that what is > causing this error? What do I need to do to make it work? Show us more of the error! ;-) Paul From bblais at bryant.edu Fri Apr 27 15:50:21 2007 From: bblais at bryant.edu (Brian Blais) Date: Fri, 27 Apr 2007 15:50:21 -0400 Subject: python and COM Message-ID: <463253FD.8000707@bryant.edu> Hello, I am trying to communicate to a Reuters feed using Python, using a particular set of libraries called the Adfin Real Time library. I have VB code, and am trying to port it to python, and admit I really do not understand COM objects and being a Linux guy mainly, I don't use VB at all. I've had some marginal success, but am coming up empty when it comes to setting up callbacks. For example, this works: import win32com.client import time symb='GOOG.O' mylist=win32com.client.Dispatch('AdfinXRTLib.AdxRtList') mylist.Source="IDN_RDF" mylist.RegisterItems(symb,"ASK") mylist.StartUpdates(4) # Mode Image while mylist.ItemStatus(symb): pass for i in range(100): m=mylist.Value(symb,"ASK") print m time.sleep(2) but to get it to automatically updated quotes, in VB they do something like #================ Public Class Form1 # Dimension a Public Real Time list object that is capable of handling events # note from me: not sure what this line does really Dim WithEvents AdxList As New AdfinXRTLib.AdxRTList Public Sub AdxList_OnUpdate( ) Handles AdxList.OnUpdate do stuff with the updated data End Sub Private Sub Button1_Click() do stuff with button click End Sub End Class #================ It seems as if the important part is the "Handles AdxList.OnUpdate", which I assume is basically saying "call me when AdxList.OnUpdate is called". I have no idea how to get this to point to a python function, so I can make the AdxList.OnUpdate call python code. Is there a tutorial somewhere about this stuff, or is there a proper place to ask such questions? thanks, Brian Blais -- ----------------- bblais at bryant.edu http://web.bryant.edu/~bblais From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Sun Apr 22 17:34:12 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Sun, 22 Apr 2007 23:34:12 +0200 Subject: python style guide inconsistencies References: Message-ID: <5922mkF2i88dhU1@mid.individual.net> Darren Dale wrote: > I was just searching for some guidance on how to name packages and > modules, and discovered some inconsistencies on the > www.python.org. http://www.python.org/doc/essays/styleguide.html > says "Module names can be either MixedCase or lowercase." That > page also refers to PEP 8 at > http://www.python.org/dev/peps/pep-0008/, which says "Modules > should have short, all-lowercase names. ... Python packages should > also have short, all-lowercase names ...". > > Which is most up to date? The priority is, IMHO, clear. The old style guide essay says, at the beginning: | This style guide has been converted to several PEPs (Python | Enhancement Proposals): PEP 8 for the main text, PEP 257 for | docstring conventions. See the PEP index. So PEP 8 is the most recent. Regards, Bj?rn -- BOFH excuse #216: What office are you in? Oh, that one. Did you know that your building was built over the universities first nuclear research site? And wow, aren't you the lucky one, your office is right over where the core is buried! From tomchilton at hotmail.com Wed Apr 25 11:49:07 2007 From: tomchilton at hotmail.com (Tom Chilton) Date: Wed, 25 Apr 2007 08:49:07 -0700 (PDT) Subject: Bibus/python locale not supported problem Message-ID: <10183538.post@talk.nabble.com> Hi, I am running Gentoo Linux. I have emerge'd Bibus and everything seemed to go well. When I try to start it from a shell I get: tom at linuxbox ~ $ bibus Traceback (most recent call last): File "/usr/share/bibus/bibus.py", line 63, in ? locale.setlocale(locale.LC_ALL,'en_US') # use english if any problem File "/usr/share/bibus/locale.py", line 381, in setlocale return _setlocale(category, locale) locale.Error: unsupported locale setting and it does not run. Can anyone suggest why? I am in the UK and where I get the option I choose en_GB. If this isn't a python problem sorry for bothering you all... I am not subscribed to this list but I will check nabble for replies. Thanks Tom -- View this message in context: http://www.nabble.com/Bibus-python-locale-not-supported-problem-tf3646227.html#a10183538 Sent from the Python - python-list mailing list archive at Nabble.com. From "enquiring mind" at braindead.com Sun Apr 1 19:48:35 2007 From: "enquiring mind" at braindead.com (enquiring mind) Date: Sun, 01 Apr 2007 23:48:35 GMT Subject: Pygame Q (linux) beginner References: <460F28F2.D91DB67A@braindead.com> Message-ID: <461052EB.D56FE6DD@braindead.com> Gabriel Genellina wrote: > > En Sat, 31 Mar 2007 23:37:16 -0300, enquiring mind <"enquiring > mind"@braindead.com> escribi?: > > > Running 2.4.1 Python (learning) > > Running SUSE Linux 10 > > > > Am learning from a new books that mostly deals with windows python and > > Pygames called "Game Programming" by Randy Harris (2007) His books > > references Python 2.4.2 and Pygame 1.7.1 with these comments: > > > > "If you are using a Linux machine, you probably won't have the simple > > installer that came with the windows version. Follow the instructions > > at http://pygame.org/install. You may have to run a couple of scripts > > to make everything work, but just follow the directions and you will be > > fine." > > > > Could anybody suggest or make a helpful comment in view of what > > information I have supplied. At Chapter 5 is where the Pygame module is > > introduced so I have a little time before I have to figure out what I > > have to download and install. > > First: read that page. > I don't use SUSE myself, but the first hit on Google for "pygame SUSE" > goes into the Novell site, and SUSE 10.1 appears to include pygame > 1.7.1release14 (or at least, you should be able to download and install > the RPM from Novell) > > -- > Gabriel Genellina Thanks, Gabriel. I only googled pygame and not SUSE. The next post says it is already included so I will ask my programmer buddy to help me. From carsten at uniqsys.com Wed Apr 18 08:42:51 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Wed, 18 Apr 2007 08:42:51 -0400 Subject: Signals In-Reply-To: <002001c7818c$af280ab0$0d782010$@rawlins@thinkbluemedia.co.uk> References: <002001c7818c$af280ab0$0d782010$@rawlins@thinkbluemedia.co.uk> Message-ID: <1176900171.3424.16.camel@dot.uniqsys.com> On Wed, 2007-04-18 at 08:39 +0100, Robert Rawlins - Think Blue wrote: > Hello Chaps, > > > > I posted about this the other day but I?m still struggling to get any > form of result from it. Basically I have the following piece of code, > and according to its API is produces singals when particular events > occur, but i have no idea how to list for events, I?ve tried all sorts > of combinations using the signal module but haven?t been able to get > it working. > [...] > import dbus, signal > [...] > > Now here is a copy of the API documentation that lists the signals > thrown by the API, this is the one I?m trying to listen for. > > > > void RemoteDeviceFound(string address, uint32 class, int16 > rssi) > > > > This signal will be send every time an inquiry result > > has been found by the service daemon. In general they > > only appear during a device discovery. > > > > Basically I?m just looking to run a function that will print those > details to screen. Can anyone help with working out how to listen for > this signal? The signal module is for handling process signals the operating system sends to your python process. The API you're using (dbus, a crucial detail you neglected to mention before) doesn't send this kind of signal. Googling for 'python dbus documentation' brings up http://dbus.freedesktop.org/doc/dbus-python/api/ , which seems to explain everything you need. You need to get an instance of dbus.Interface, which you seem to have done, and call its connect_to_signal() method, which you don't seem to have done. > I?d also like to know how i can keep the application running until I > decided to stop it manually, as the DiscoverDevices() can take a while > to complete and send out several RemoteDeviceFound() signals in that > period. The very first section of the above mentioned documentation talks about needing a main loop for receiving signals, and it provides example boilerplate code for how to set up a main loop. Hope this helps, Carsten. From webbfamily at DIESPAMDIEoptusnet.com.au Sun Apr 29 03:58:02 2007 From: webbfamily at DIESPAMDIEoptusnet.com.au (Peter Webb) Date: Sun, 29 Apr 2007 17:58:02 +1000 Subject: OT: Re: Video: Professor of Physics Phd at Cal Tech says: 911 Inside Job In-Reply-To: <1177778685.506101.201540@h2g2000hsg.googlegroups.com> References: <1177467203.719625.93920@u32g2000prd.googlegroups.com> <1177778685.506101.201540@h2g2000hsg.googlegroups.com> Message-ID: <4634500c$0$11788$afc38c87@news.optusnet.com.au> > Why do you all have to avoid the topic and rather go on a character > assassination which is totally abhorent to scientific method? Because *you are a complete flake, *there is nothing scientific about the 9/11 conspiracy theories, *this is off-topic, and * nobody could be bothered to discuss it with you, and we hope that if we say "fuck off, idiot" you actually will. Fuck off, idiot. From kyosohma at gmail.com Thu Apr 5 11:52:43 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: 5 Apr 2007 08:52:43 -0700 Subject: snippet manager idea In-Reply-To: <1175784093.094255.3630@y66g2000hsf.googlegroups.com> References: <1175784093.094255.3630@y66g2000hsf.googlegroups.com> Message-ID: <1175788363.946069.211810@l77g2000hsb.googlegroups.com> On Apr 5, 9:41 am, "franka... at gmail.com" wrote: > Hi. > I am writing a opensource code snippet manager in python (pyqt4). > The idea is that users can upload their snippets to remote subversion > server, (if they choose) and add comments to existing snippets, vote > for snippet deletion, add flags to snippets: (tested, working, not > working... etc) > The snippets are stored locally in a sqlite3 database. > > So far i have a working application that use a small Soap client/ > server to upload snippets to a remote server. The client sends a dict > to the server, the server writes the dict as a text file and adds it > to the svn server. On the client a local svn repo is downloaded and > parsed into the database. > The client Ui has syntaxhighlighting(only cplusplus and python at the > moment), an "add snippet form", treewidget for snippet listing. > > My personal conserns are: > > individual snippet licensing > > I was wondering if anyone could comment on this idea. And perhaps come > with some ideas. You could have some kind of legalese for them to read and accept (i.e. electronically sign), preferably something that is an open source license agreement like Python's or BSD or maybe that new Creative Commons thing. Regardless, you need to let the coders know what their rights are one way or the other. Mike From carl at personnelware.com Sat Apr 14 13:42:02 2007 From: carl at personnelware.com (Carl K) Date: Sat, 14 Apr 2007 12:42:02 -0500 Subject: Python editor/IDE on Linux? In-Reply-To: References: Message-ID: Jack wrote: > I wonder what everybody uses for Python editor/IDE on Linux? > I use PyScripter on Windows, which is very good. Not sure if > there's something handy like that on Linux. I need to do some > development work on Linux and the distro I am using is Xubuntu. > > I use spe - it is in universe. Has some rough edges, but in general I like it enough to recommend it. Carl K From http Sun Apr 22 18:33:37 2007 From: http (Paul Rubin) Date: 22 Apr 2007 15:33:37 -0700 Subject: [re.finditer] Getting all occurences in one go? References: Message-ID: <7xy7kkf39a.fsf@ruckus.brouhaha.com> Gilles Ganault writes: > for match in matches: > if mytable[item]=="": > mytable[item]= match.group(1) > else: > mytable[item]= mytable[item] + "," + match.group(1) # > ----------- END > ======================= > > Can the lines between BEGIN/END be simplified so I can copy all the > items into the mytable[] dictionary in one go, instead of getting each > one in a row, and append them with a comma, eg. Yes, look at the string.join method and generator expressions. You'd say: mytable[item] = ','.join(m.group(1) for m in matches) From zhonghua.m.yang at gmail.com Tue Apr 3 13:40:49 2007 From: zhonghua.m.yang at gmail.com (ZMY) Date: 3 Apr 2007 10:40:49 -0700 Subject: Numeric compiling problem under QNX 4.25 In-Reply-To: References: <1175578324.426293.21970@y80g2000hsf.googlegroups.com> Message-ID: <1175622049.939184.28670@d57g2000hsg.googlegroups.com> On Apr 3, 10:22 am, Robert Kern wrote: > ZMY wrote: > > Dear all, > > > I am a real newbie for both python and QNX, but I am still trying to > > compile Numeric-24.2 under QNX4.25 with python 2.2. I got following > > error message: > > > $ sudo python setup.py install > > Password: > > running install > > ... > > building '_numpy' extension > > skipping Src/_numpymodule.c (build/temp.qnx-O-PCI-2.2/_numpymodule.o > > up-to-date) > > skipping Src/arrayobject.c (build/temp.qnx-O-PCI-2.2/arrayobject.o up- > > to-date) > > skipping Src/ufuncobject.c (build/temp.qnx-O-PCI-2.2/ufuncobject.o up- > > to-date) > > ld build/temp.qnx-O-PCI-2.2/_numpymodule.o build/temp.qnx-O-PCI-2.2/ > > arrayobject.o build/temp.qnx-O-PCI-2.2/ufuncobject.o -o build/lib.qnx- > > O-PCI-2.2/_numpy.so > > unable to execute ld: No such file or directory > > error: command 'ld' failed with exit status 1 > > It looks like it can't find the command ld. Can you compile any other extension > modules? > > -- > 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 Is "ld" part of make command? I am not familiar with compiling with make in general. Most other extensions (including math, os, struct, cPickle) from Python 2.2 works when I install python on QNX. Thanks a lot to all of you. -ZMY From spradml at gmail.com Thu Apr 26 10:16:30 2007 From: spradml at gmail.com (Pradnyesh Sawant) Date: Thu, 26 Apr 2007 19:46:30 +0530 Subject: passing tuple with pyqt4 signal/slot mechanism Message-ID: <80628d680704260716r7eda5c8va695a25b1db70490@mail.gmail.com> Hello, I have a pyqt4 code in which i'm trying the signal/slot mechanism. The (stripped) code is as follows: class D(QtCore.QThread): def __init__(self): QtCore.QThread.__init__(self) tpl = ("Primary", "priSec") print "tpl:", tpl self.emit(QtCore.SIGNAL("setLabel"), tpl) class Gui(QtGui.QDialog): def __init__(self, parent = None): QtGui.QDialog.__init__(self, parent) def setLabel(self, tpl): print "####tpl:", tpl print "**********tpl:", str(tpl) return if __name__ == "__main__": app = QtGui.QApplication(sys.argv) dialog = Gui() d = D() QtCore.QObject.connect(d, QtCore.SIGNAL("setLabel"), dialog.setLabel, QtCore.Qt.QueuedConnection) sys.exit(dialog.exec_()) The output i'm getting is as follows: tpl: ('Primary', 'priSec') ####tpl: (,) **********tpl: ((((((((,),),),),),),),) Can anyone kindly tell me what's happening here? Why is the tuple ("Primary", "priSec") getting converted to this thingy? And what is this thingy anyways (It looks to be a deeply nested tuple, but am not sure). Thanks a lot! -- warm regards, Pradnyesh Sawant -- Be yourself, everyone else is taken. --Anon From kyosohma at gmail.com Thu Apr 5 11:41:37 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: 5 Apr 2007 08:41:37 -0700 Subject: AttributeError: 'tuple' object has no attribute 'encode' In-Reply-To: <1175787095.862712.297480@n76g2000hsh.googlegroups.com> References: <1175787095.862712.297480@n76g2000hsh.googlegroups.com> Message-ID: <1175787697.717321.290600@e65g2000hsc.googlegroups.com> On Apr 5, 10:31 am, "erikcw" wrote: > Hi, > > I'm trying to build a SQL string > > sql = """INSERT INTO ag ('cid', 'ag', 'test') VALUES(%i, %s, %d)""", > (cid, ag, self.data[parent][child]['results']['test']) > > It raises this error: AttributeError: 'tuple' object has no attribute > 'encode' > > Some of the variables are unicode (test and ag) - is that what is > causing this error? What do I need to do to make it work? > > Thanks! > Erik It sounds like you're not calling the "encode" method correctly. But it's hard to say when you didn't include that bit of code. You may need to check your database's docs to make sure it accepts unicode strings and if so, what types (utf-8, 16, 32). See this post for a similar problem: http://lists.modevia.com/archives/py-transports/2005-December/001719.html and this link details tuple usage: http://www.faqs.org/docs/diveintopython/odbchelper_tuple.html Mike From bdesth.quelquechose at free.quelquepart.fr Wed Apr 11 16:07:19 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Wed, 11 Apr 2007 22:07:19 +0200 Subject: descriptor object for an attribute? In-Reply-To: <1176304695.336308.151810@n76g2000hsh.googlegroups.com> References: <1176304695.336308.151810@n76g2000hsh.googlegroups.com> Message-ID: <461d36d5$0$27802$426a34cc@news.free.fr> Eric Mahurin a ?crit : > Is there a standard way to get a descriptor object for an arbitrary > object attribute - independent of whether it uses the descriptor/ > property protocol or not. I want some kind of handle/reference/ > pointer to an attribute. I'm not sure to understand what you want exactly. A concrete example would probably help. But from what I understood, you could just use a thin wrapper like: _marker = object() class Accessor(object): def __init__(self, obj, name): self._obj = obj self._name = name def __call__(self, new_val=_marker): if new_val is _marker: return getattr(self._obj, self._name) else: setattr(self._obj, self._name, new_val) class Foo(object): def __init__(self, bar, baak=42): self.bar = bar self.baak = baak foo = Foo('allo') bar = Accessor(foo, 'bar') assert bar() == foo.bar == 'allo' bar(42) assert bar() == foo.bar == 42 If that doesn't answer your question, please pardon my stupidity and provide some more concrete example. From tjreedy at udel.edu Mon Apr 2 16:02:31 2007 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 2 Apr 2007 16:02:31 -0400 Subject: How do you escape % when formatting a string? References: <1175543459.131630.96650@y80g2000hsf.googlegroups.com> Message-ID: "erikcw" wrote in message news:1175543459.131630.96650 at y80g2000hsf.googlegroups.com... | Hi, | | I'm trying to format a string like so: | | string = "You have a 75% chance of success with %s, don't use %s" %(a, | b) | | This gives me: | TypeError: not enough arguments for format string | | I've tried 75\%, but that doesn't seem to help. What am I missing? The reference manual? From hat at se-126.se.wtb.tue.nl Tue Apr 24 07:12:56 2007 From: hat at se-126.se.wtb.tue.nl (A.T.Hofkamp) Date: Tue, 24 Apr 2007 13:12:56 +0200 Subject: adjust References: <1177412489.683970.45320@u32g2000prd.googlegroups.com> Message-ID: On 2007-04-24, saif.shakeel at gmail.com wrote: > Hi, > How do i right adjust my output using python.I need a output > something like this: > DID= 0x01,0x02,0x03,0x05,0x06,0x07,0x2B,0x30,0x31,0x4D,0x4E, > 0x51,0x52,0x53,0x55, > minlength= 3, 3, 4, 2, 10, 10, 40, 2, 150, 4, 1, > 2, 2, 1, 2, 1, 6, 3, 17, 1, > maxlength= 3, 3, 4, 2, 10, 10, 40, 2, 150, 4, 1, > 2, 2, 1, 2, 30, 6, 3, 17, 20 > > I am printing from a list, and the values shld print below each id > like shown. > Thx Collect the data to print in rows underneath each other in a list for each column, decide how wide each column should become, and finally, print out each line using the computed widths. Albert From fuzzyman at gmail.com Thu Apr 26 16:31:29 2007 From: fuzzyman at gmail.com (Fuzzyman) Date: 26 Apr 2007 13:31:29 -0700 Subject: My python annoyances so far In-Reply-To: <1177541453.471959.120830@c18g2000prb.googlegroups.com> References: <1177541453.471959.120830@c18g2000prb.googlegroups.com> Message-ID: <1177619488.907127.177670@t39g2000prd.googlegroups.com> On Apr 25, 11:50 pm, fli... at gmail.com wrote: > Hi all. I'm learning python these days. I'm going to use this thread > to post, from time to time, my annoyances with python. I hope someone > will clarify things to me where I have misunderstood them. > > Annoyances: > > 1. Underscores! What's the deal with that? Especially those double > underscores. The best answer I read on this is that the double > underscores denotes special methods that the interpreter may > automatically use. For example, 4+4 get expanded by the interpreter to > 4.__add__(4). > I can understand this one. I don't have a problem with this myself, but a lot of people find the proliferation of underscores in Python bewildering. All I can say about it is that you soon get used to it - and the separation is a good enough reason for me. Fuzzyman http://www.voidspace.org.uk/ironpython/index.shtml > 2. There are modules, there are functions, and there are classes- > methods! Wouldn't it have been easier had everything either been a > function or a class method? From cjw at sympatico.ca Sat Apr 14 11:57:34 2007 From: cjw at sympatico.ca (Colin J. Williams) Date: Sat, 14 Apr 2007 11:57:34 -0400 Subject: Pydoc Rewrite Discussion at doc-sig list. In-Reply-To: <461F9E9C.2070901__24323.6438873739$1176477461$gmane$org@ronadam.com> References: <461F9E9C.2070901__24323.6438873739$1176477461$gmane$org@ronadam.com> Message-ID: Ron Adam wrote: > If anyone is interested in participating in discussing the details of the > PyDoc rewrite/refactoring I've been working on, a discussion is being > started on the doc-sig list. > > Doc-Sig at python.org > > The goal of this discussion will be to get it to a final finished form so a > patch can be submitted and a final discussion can take place on the > python-dev list at a later date. > > Thanks and Regards, > Ron Adam > Are there features which exist or planned for Pydoc and which are not available with epydoc? Colin W. From collinstocks at gmail.com Mon Apr 16 01:56:51 2007 From: collinstocks at gmail.com (subscriber123) Date: 15 Apr 2007 22:56:51 -0700 Subject: working of round() In-Reply-To: <1176682019.215351.114560@y80g2000hsf.googlegroups.com> References: <1176682019.215351.114560@y80g2000hsf.googlegroups.com> Message-ID: <1176703010.963628.44050@n59g2000hsh.googlegroups.com> On Apr 15, 8:06 pm, Krishna.K.1... at gmail.com wrote: > Does round() always perfectly return the output expected or are there > some artifacts which don't allow perfect functionality > > Using python 2.5: > > >>> round(12.234, 2) > 12.23 > >>> round(12.234, 3) > 12.234 > >>> round(12.234, 1) > 12.199999999999999 > > but was expecting 12.2 > > Also, for round(x,n), can't 'x' be an expression > > round(5.25/2, 2) > > was expecting 2.62 , but > > >>> round(5.25/2, 2) > > 2.6299999999999999 The problem is that floats are encoded as fractions where the denominator is an exponent of 2. 2.63 is not representable as such a fraction. 2.629999999999999999999999999999999999... is the closest fraction. Rounding this number will only give you the same thing. If you want decimals to act as expected, use the Decimal class in module decimal. It works as expected, but is much slower. From steve at REMOVEME.cybersource.com.au Tue Apr 3 03:08:34 2007 From: steve at REMOVEME.cybersource.com.au (Steven D'Aprano) Date: Tue, 03 Apr 2007 17:08:34 +1000 Subject: pyc file [Newbie Question] References: Message-ID: On Mon, 02 Apr 2007 23:44:41 -0700, Jim Aikin wrote: > Working through the tutorial, I created a file called fibo.py in my text > editor, and imported it into Idle. It worked as expected. I then edited the > file and resaved it. I used del fibo, followed by import fibo. That probably won't cause a full re-import. del fibo will only delete the reference called "fibo". The underlying module object will still exist until it is garbage-collected. It will only be garbage-collected if it isn't being used. Chances are, the module *is* being used somewhere, so when you call "import fibo" the import machinery simply gives you a new reference to the old module object. The correct way to do what you want is to simply say "reload(fibo)". But don't forget that any old objects from the module will NOT pick up the new behaviour. They will keep their old behaviour, so after a reload() you have to recreate all the objects you created. For example: import fibo # imports the module as it exists *now* x = fibo.SomeClass() # x is an instance defined in fibo # now edit the fibo module and change the behaviour of SomeClass reload(fibo) # now the module fibo has picked up the new behaviour # but the object x still has the code belonging to the OLD module x = fibo.SomeClass() # recreate x with new code [snip] > One point of possible confusion here is in the line in the following > paragraph of 6.1.2, "Whenever spam.py is successfully compiled...." My > question is, is it compiled when being imported? I didn't spot any mention > in the Tutorial of when or how a .py file might be (or would automatically > be) compiled, so I'm assuming that it's automatically compiled while being > imported. If this is a bad assumption, then maybe it's the root of my > misunderstanding. Maybe I have to _do_ something to fibo.py in order to > create a new version of fibo.pyc. Just import it, or reload(). -- Steven D'Aprano From marcpp at gmail.com Thu Apr 12 06:07:17 2007 From: marcpp at gmail.com (Marcpp) Date: 12 Apr 2007 03:07:17 -0700 Subject: Pyqt programming question In-Reply-To: References: <1176369822.364743.243700@n76g2000hsh.googlegroups.com> Message-ID: <1176372437.336751.75840@d57g2000hsg.googlegroups.com> On 12 abr, 11:48, Phil Thompson wrote: > On Thursday 12 April 2007 10:23 am, Marcpp wrote: > > > I have a program (python + pyqt), with a button I'll would to open a > > new dialog window to input text, when press save or ok, this text is > > returned to the principal program. > > I've seek in internet but i don't find anything. > > Use QInputDialog.getText() > > Phil I can't do it, have you any example? Thank you. From robert.kern at gmail.com Mon Apr 23 12:42:16 2007 From: robert.kern at gmail.com (Robert Kern) Date: Mon, 23 Apr 2007 11:42:16 -0500 Subject: matplotlib basic question In-Reply-To: <8xcj5m2c.fsf@wgmail2.gatwick.eur.slb.com> References: <1177016327.543985.34500@o5g2000hsb.googlegroups.com> <1177092157.763869.77600@o5g2000hsb.googlegroups.com> <8xcj5m2c.fsf@wgmail2.gatwick.eur.slb.com> Message-ID: Pete Forman wrote: > Robert Kern writes: > > > Colin J. Williams wrote: >>> I'm not sure that scipy has been updated to Python 2.5 > > ? scipy certainly works with 2.5. Are you referring to something > > else perhaps? > > Yes, the Python Enthought Edition was being discussed and it is > currently based on Python 2.4.3. > > http://code.enthought.com/enthon/ I'm quite familiar with Python Enthought Edition as I work at Enthought. I was confused because Colin referenced scipy specifically rather than simply saying that the current version of Python Enthought Edition was not based on 2.5. -- 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 rokkamraja at gmail.com Tue Apr 24 18:50:10 2007 From: rokkamraja at gmail.com (Raja) Date: 24 Apr 2007 15:50:10 -0700 Subject: Overriding Sys.Settrace Message-ID: <1177455010.109307.309400@u32g2000prd.googlegroups.com> Hi, I want to override the sys.settrace() call, create a way to trace the execution of a python program. Keep track of all objects created and destroyed. Keep track of the call pattern throughout the execution of the program and output a simplified "call graph" to standard out. Can anyone please tell me how to do this ? Thank You, From steve at holdenweb.com Sun Apr 15 20:37:53 2007 From: steve at holdenweb.com (Steve Holden) Date: Sun, 15 Apr 2007 20:37:53 -0400 Subject: Portably generating infinity and NaN In-Reply-To: <7xhcrh2pxy.fsf@ruckus.brouhaha.com> References: <462008d1$0$11763$9b622d9e@news.freenet.de> <7xhcrh2pxy.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > skip at pobox.com writes: >> But PEP 754 will only work for architectures supporting IEEE 754. I realize >> that's the vast majority of systems, but aren't there still a few Crays and >> VMS machines out there? (Do those architectures support NaN and Inf?) > > I wouldn't worry about it. There are Python subsystems (like threads) that > don't work on certain OS's, fine, total portability means not being able to > rely on them, and that's ok. I doubt any Crays are still running, or at least > running any numerical code written in Python. Same for VMS. Think again. 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 carsten at uniqsys.com Thu Apr 26 22:43:25 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Thu, 26 Apr 2007 22:43:25 -0400 Subject: I25 barcode generator? In-Reply-To: <20070427020406.M99949@uniqsys.com> References: <46311C0B.10506@fmed.uba.ar> <20070427020406.M99949@uniqsys.com> Message-ID: <20070427023710.M69649@uniqsys.com> On Thu, 26 Apr 2007 22:12:54 -0400, I wrote > On Thu, 26 Apr 2007 18:39:23 -0300, Gerardo Herzig wrote > > Hi. Im looking for an I25 barcode generator.[...] > > [...]it shouldn't be too hard to make one. > And it wasn't: def i25(x): """i25(x) -> string Encode string of digits into I25 barcode. The input string must consist of an even number of digits. The output string represents the I25 barcode of the input string with N = narrow bar, W = wide bar, n = narrow space, w = wide space. """ alphabet = ( "NNWWN", "WNNNW", "NWNNW", "WWNNN", "NNWNW", "WNWNN", "NWWNN", "NNNWW", "WNNWN", "NWNWN" ) if not x.isdigit(): raise ValueError, "Input string must consist of digits." if len(x)%2!=0: raise ValueError, "Input string must be of even length." bars = "".join(alphabet[int(c)] for c in x[0::2]) spaces = "".join(alphabet[int(c)] for c in x[1::2]).lower() interleaved = "".join(t[0]+t[1] for t in zip(bars,spaces)) return "NnNn"+interleaved+"WnN" Rendering the resulting string into the desired graphical format is left as an exercise for the reader. HTH, Carsten. From carsten at uniqsys.com Sat Apr 28 22:07:46 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Sat, 28 Apr 2007 22:07:46 -0400 Subject: Any Good tools to create CSV Files? In-Reply-To: <1177811756.255774.315260@q75g2000hsh.googlegroups.com> References: <1177811756.255774.315260@q75g2000hsh.googlegroups.com> Message-ID: <1177812466.3625.12.camel@localhost.localdomain> On Sat, 2007-04-28 at 18:55 -0700, johnny wrote: > Any Good tools to create CSV Files? ReportLab only creates pdf > files. I need something to create CSV files. You mean something like the csv module that is part of Python's standard library? >>> import csv >>> help(csv) Help on module csv: NAME csv - CSV parsing and writing. FILE /usr/lib/python2.4/csv.py MODULE DOCS http://www.python.org/doc/current/lib/module-csv.html DESCRIPTION This module provides classes that assist in the reading and writing of Comma Separated Value (CSV) files [...] -Carsten From cjlesh at gmail.com Tue Apr 24 13:03:45 2007 From: cjlesh at gmail.com (cjl) Date: 24 Apr 2007 10:03:45 -0700 Subject: Simple sqlite3 question Message-ID: <1177434225.721012.271040@r35g2000prh.googlegroups.com> P: I am using python 2.5.1 on windows. I have the following code: conn = sqlite3.connect('.\optiondata') c = conn.cursor() try: c.execute('''create table options (ssymbol text, strike real, osymbol text, bid real, mpp real, upp real)''') except sqlite3.OperationalError: pass I am hoping the above code creates a new database file named 'optiondata' with a single table named 'options', or connects to it if already created. Am I off the mark here? I also have a function that does the following: c.execute("""insert into options values (?,?,?,?,?,?)""",data) When I run the script and there is no file named optiondata, one is created and the correct data is added to it. If I run the script again then the data from the first run seems to be replaced with the data from the second run. I expected that the data from the second run would be appended to the database file, not replace it. Can anyone point me in the right direction to get the expected behavior? -cjl From larry.bates at websafe.com Wed Apr 11 15:56:10 2007 From: larry.bates at websafe.com (Larry Bates) Date: Wed, 11 Apr 2007 14:56:10 -0500 Subject: Reading the first line of a file (in a zipfile) In-Reply-To: <1176318822.811661.115730@q75g2000hsh.googlegroups.com> References: <1176318822.811661.115730@q75g2000hsh.googlegroups.com> Message-ID: mike.aldrich at gmail.com wrote: > Hi folks, > I am trying to read the first occurence of non-whitespace in a file, > within a zipfile. Here is my code: > > zipnames = glob.glob("*") > for zipname in zipnames: > z = zipfile.ZipFile(zipname, "r") > for filename in z.namelist(): > count = len(z.read(filename).split('\n')) > if fnmatch.fnmatch(filename, "*AUDIT*"): > test = filename.split(' ') > print 'File:', test[0], > bytes = z.read(filename) > print 'has', len(bytes), 'bytes' > print 'and', count, 'lines' > > The first line in the file I am examining will be a number followed by > more whitespace. Looks like I cannot split by whitespace? > You have told split to split on single blank space not whitespace. To split on whitespace use .split() (e.g. no arguments) -Larry From tjreedy at udel.edu Wed Apr 11 12:46:03 2007 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 11 Apr 2007 12:46:03 -0400 Subject: bittorent References: <1eb3a0e10704110922v17f83f79se5972dce07415a5@mail.gmail.com> Message-ID: "Linus Nordstr?m" wrote in message news:1eb3a0e10704110922v17f83f79se5972dce07415a5 at mail.gmail.com... | Hello | Im planing playing a bit whit bittorrent, but I'm having some trouble | about where to start. So if anyone could point me in the right | direction it would be much appreciated. | The best would be if there are some already written modules that | handle downloading and seeding torrents, but if that cant be found a | good source on how one dose to build some sort of bitorrent client | would be nice. Bittorrent, the program, is written in Python. From mail at microcorp.co.za Sat Apr 28 03:07:49 2007 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Sat, 28 Apr 2007 09:07:49 +0200 Subject: Now() References: <000301c78728$ba634ce0$2f29e6a0$@rawlins@thinkbluemedia.co.uk><033801c787ce$f7a755a0$03000080@hendrik> <1177592051.3437.6.camel@dot.uniqsys.com> Message-ID: <000401c78a22$91716f40$03000080@hendrik> "Carsten Haese" wrote: > On Thu, 2007-04-26 at 08:42 +0200, Hendrik van Rooyen wrote: > > Robert Rawlins - Think Blue wrote: > > >With time depicted to the nearest second, from my background in ColdFusion > > development we used to have a >datetimeformat() function that I could use as > > > > > >DateTimeFormat(now(), yyyy-mm-dd HH:mm:ss) > > > > > >Which would give the current time a mask. > > > > Here is a hack that does more or less what you want: > > [snip horrible hack...] > > Please tell me you're not seriously suggesting this hack as a solution. *grin* it is a cut and paste from some of the first python code I wrote. It has the sole merit that it actually works as advertised, and it shows the OP that you can actually help yourself if you try... As I understood it, he was happy with the date - time string he got back, except that he did not like the microseconds at the end. I thought that showing him the formatting process from a completely different start point might encourage him to simply trim off the end bit that he did not need. - Hendrik From grante at visi.com Wed Apr 11 00:35:39 2007 From: grante at visi.com (Grant Edwards) Date: Wed, 11 Apr 2007 04:35:39 -0000 Subject: Check for keypress on Linux xterm ? References: Message-ID: <131opcrgb01sd9c@corp.supernews.com> On 2007-04-11, hlubenow wrote: > I wrote: > >> Hello, >> >> I'd like to check, if a single key is pressed on a Linux xterm. >> My problem is, I don't want my program to wait for the keypress. >> I just want to check, if a key is currently pressed and if not, I'd like >> to continue with my program (like "INKEY$" in some BASIC-dialects). > > Ok, here's the code I use now. Thanks to Grant Edwards for pointing me into > the right direction: > > ---------------------------------------------------------- > > #!/usr/bin/env python > > import os > import sys > import tty > import termios > import fcntl > import time > > fd = sys.stdin.fileno() > > oldterm = termios.tcgetattr(fd) > oldflags = fcntl.fcntl(fd, fcntl.F_GETFL) > > tty.setcbreak(sys.stdin.fileno()) > newattr = termios.tcgetattr(fd) > newattr[3] = newattr[3] & ~termios.ICANON & ~termios.ECHO > > > def oldTerminalSettings(): > termios.tcsetattr(fd, termios.TCSAFLUSH, oldterm) > fcntl.fcntl(fd, fcntl.F_SETFL, oldflags) > > > def newTerminalSettings(): > termios.tcsetattr(fd, termios.TCSANOW, newattr) > fcntl.fcntl(fd, fcntl.F_SETFL, oldflags | os.O_NONBLOCK) > > > def checkKey(): > > try: > c = sys.stdin.read(1) > return ord(c) > > except IOError: > return 0 Ah, but how do you tell "no key" from ctrl-@ (which has a ordinal value of 0)? If I were you, I'd return None in the case where there is nothing to return: def checkKey(): try: return ord(sys.stdin.read(1)) except IOError: return None I'm also not sure if there are other possible causes for the IOError exception that you'd need to watch out for. Ideally, you'd check to make sure its an EAGAIN. > print > print "Ok, in 3 seconds, I'll check 100 times, which key you press." > print > > # Initializing: Things like "raw_input()" won't work after that: > newTerminalSettings() > > time.sleep(3) > > for i in range(100): > a = "Key pressed: " > > key = checkKey() > > if key: And here, you'd have this: if key is not None: > a += chr(key) > a += "." > else: > a += "Nothing pressed." > > print a -- Grant Edwards grante Yow! When you get your at PH.D. will you get able to visi.com work at BURGER KING? From deets at nospam.web.de Wed Apr 25 06:46:04 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 25 Apr 2007 12:46:04 +0200 Subject: q: how to output a unicode string? References: <596qd4F2k129kU1@mid.uni-berlin.de> Message-ID: <598prcF2ihs92U1@mid.uni-berlin.de> > So why is it that in the first case I got UnicodeEncodeError: 'ascii' > codec can't encode? Seems as if, within Idle, a utf-8 codec is being > selected automagically... why should that be so there and not in the > first case? I'm a bit confused on what you did when.... the error appears if you try to output a unicode-object without prior encoding - then the default encoding (ascii) is used. >>> Then, in the hope of being able to write the string to a file if not to >>> stdout, I also tried >>> >>> >>> import codecs >>> f = codecs.open("out.txt", "w", "utf-8") >>> f.write(s2) >>> >>> but got >>> >>> UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 1: >>> ordinal not in range(128) >> >> Instead of writing s2 (which is a byte-string!!!), write s1. It will >> work. > > OK, many thanks, I got this to work! > >> The error you get stems from f.write wanting a unicode-object, but s2 is >> a bytestring (you explicitly converted it before), so python tries to >> encode the bytestring with the default encoding - ascii - to a unicode >> string. This of course fails. > > I think I have a better understanding of it now. If the terminal hadn't > fooled me, I probably wouldn't have assumed that the code I originally > wrote (following the first examples I found) was wrong! I assume that > when you say "bytestring" you mean "a string of bytes in a certain > encoding (here utf-8) that can be used as an external representation for > the unicode string which is instead a sequence of code points". Yes. That is exactly the difference. Diez From thorsten at thorstenkampe.de Sun Apr 1 15:22:51 2007 From: thorsten at thorstenkampe.de (Thorsten Kampe) Date: Sun, 1 Apr 2007 20:22:51 +0100 Subject: I18n issue with optik References: Message-ID: * Thorsten Kampe (Sun, 1 Apr 2007 20:08:39 +0100) > * Thorsten Kampe (Sun, 1 Apr 2007 19:45:59 +0100) > > Yes, I could do that but I'd rather know first if my code is wrong or > > the optparse code. > > It might be the bug mentioned in > http://mail.python.org/pipermail/python-dev/2006-May/065458.html > > The patch although doesn't work. From my unicode-charset-codepage- > codeset-challenged point of view the encoding of sys.stdout doesn't > matter. The charset is defined in the .po/.mo file (but of course > optparse can't know if the message has been translated by gettext > ("_"). If I "patch" line 1648 (the one mentioned in the traceback) of optparse.py from file.write(self.format_help().encode(encoding, "replace")) to file.write(self.format_help()) ...then everything works and is displayed fine (even without the "unicode = True" parameter to gettext.install). But the "patch" might make other things fail, of course... Thorsten From david at boddie.org.uk Tue Apr 24 18:46:47 2007 From: david at boddie.org.uk (David Boddie) Date: Wed, 25 Apr 2007 00:46:47 +0200 Subject: Do other Python GUI toolkits require this? References: <462697A6.6010007@codebykevin.com> <57C90994-391D-4350-A2F2-29C1590A3335@jedimindworks.com> Message-ID: <38579$462e88d8$54d1d767$18488@news.chello.no> On Monday 23 April 2007 15:55, Kevin Walzer wrote: > I had originally thought that learning PyObjC might preclude me from > having to learn Objective-C, but that seems not to be the case. I have > previously found the same to be true with PyQt and wxPython--not knowing > the toolkits as they are implemented in C++ is a serious handicap. I'm not so sure about that. Certainly, it's useful to be able to read C++ example code, but none of the examples you see should require more than a basic proficiency in C++. I started using PyQt before I had more than basic C++ skills, and I don't think it slowed me down too much. > I've even found this to be the case with Tkinter: understanding the Tcl > implementation of Tk (which I do, because I am also a Tcl developer) is > a huge advantage. > > Am I wrong to conclude that, if you want to do GUI programming in > Python, then some level of proficiency with another language is not just > recommended, but almost required? This is the case at least in my > experience. When I first started learning Python a couple of years ago, > I spun my wheels with it for months, because I couldn't figure out where > to get started with GUI programming. Of the common toolkits and frameworks, I started using Tkinter because that's what came with Python, but I can't say that I'm comfortable with it. Once I started using PyQt, I started to forget Tkinter, and now I don't have a reason to go back to using it. > Finally I set Python aside and took > up Tcl/Tk for awhile--its simplicity in building GUI's is more > beginner-friendly. (No "there's more than one way to do it"--there's > only one way to do it, and that's Tk.) > > Now, coming back to Python with the Tk model of GUI development burned > in my brain, I appreciate the breadth of functions that Python > supports--but I still find myself "dropping down into Tcl" (!) to > assemble elements of my GUI's--either to write a Python wrapper, or > figure out how to implement something in pure Python. While this is one of the strengths of Tcl/Tk/Tkinter, I think this is a relatively rare thing to do with other toolkits and frameworks. For example, there are people writing wrappers around Qt-based classes, but the only people writing wrappers for Qt or KDE classes are the bindings authors themselves. > I understand the argument for Python having lots of bindings to > different GUI toolkits. If you are already proficient with a GUI toolkit > in a compiled language (Gtk, wxWidgets, Cocoa, Qt) then presumably > switching to Python will speed up your development--learning Python is > easy if you already know C++, for instance, and usually the Python > bindings are just a "thin wrapper" over the compiled bits. Yes and no. The bindings may be thin, but there are often other advantages that make the bindings subtly different/better to use than the underlying toolkit/framework. :-) >From memory, PyGTK is more natural to use the GTK+ on its own because Python provides the object-oriented features that you don't get in C, though there are C++ bindings to GTK+ as well. Another example would be the way PyQt handles Qt's signals and slots. In C++ you need to declare these with specific signatures at compile time, but that would be a bit restrictive in Python. The result is that PyQt lets you define and connect arbitrary signals, slots and normal Python methods at run-time. (Actually, you don't even need to define signals.) So, even the thin wrappers contain some value other than simply enabling you to use Python. :-) > But if you come to Python from the other direction--you're a relative > beginner and you want to learn GUI programming without the complexities of > compiled languages--then it's a lot harder to get started, ironically. > Even Tkinter is a challenge for someone who doesn't know Tcl. The basics > are easy enough--buttons, menus, labels, images--but doing anything > sophisticated, such as trees, column views, drag-and-drop, and so on, > requires extensions that may or may not be implemented in Python. I think that's a specific Tkinter problem in many ways. However, the expectations of many new users have also increased since I wrote my first GUI program in Python, and that also influences the way people respond to the different solutions on offer. David From gagsl-py2 at yahoo.com.ar Sun Apr 15 17:03:33 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sun, 15 Apr 2007 18:03:33 -0300 Subject: split and regexp on textfile References: <1176451192.364949.8260@w1g2000hsg.googlegroups.com> <1176453634.577706.326170@y80g2000hsf.googlegroups.com> <1176454505.336514.90910@p77g2000hsh.googlegroups.com> <1176455681.424814.223830@q75g2000hsh.googlegroups.com> <1176456611.648400.254850@q75g2000hsh.googlegroups.com> <1176458885.245615.319070@n76g2000hsh.googlegroups.com> Message-ID: En Fri, 13 Apr 2007 07:08:05 -0300, Flyzone escribi?: > A little question: the pat.split can split without delete the date? No, but instead of reading the whole file and splitting on dates, you could iterate over the file and detect block endings: def split_on_dates(ftoparse): block = None for line in ftoparse: if fancy_date_regexp.match(line): # a new block begins, yield the previous one if block is not None: yield current_date, block current_date = line block = [] else: # accumulate lines for current block block.append(line) # don't forget the last block if block is not None: yield current_date, block for date, block in split_on_dates(ftoparse): # process block -- Gabriel Genellina From robert.rawlins at thinkbluemedia.co.uk Mon Apr 30 07:09:18 2007 From: robert.rawlins at thinkbluemedia.co.uk (Robert Rawlins - Think Blue) Date: Mon, 30 Apr 2007 12:09:18 +0100 Subject: Dict Copy & Compare In-Reply-To: <4635C473.4010109@timgolden.me.uk> References: <00da01c78b01$3e80b900$bb822b00$@rawlins@thinkbluemedia.co.uk> <4635AB95.4010309@timgolden.me.uk> <000601c78b06$b9fb0950$2df11bf0$@rawlins@thinkbluemedia.co.uk> <4635B38E.5020606@timgolden.me.uk> <000701c78b10$1e8aa9d0$5b9ffd70$@rawlins@thinkbluemedia.co.uk> <4635C473.4010109@timgolden.me.uk> Message-ID: <000e01c78b18$03457cb0$09d07610$@rawlins@thinkbluemedia.co.uk> Thanks for that Tim, Don't feel guilty mate, I've learned a little something from you anyway, whether its applied here or not. On quick question, how can I order a dict by the 'values' (not keys) before looping? Is that possible? Thanks, Rob -----Original Message----- From: python-list-bounces+robert.rawlins=thinkbluemedia.co.uk at python.org [mailto:python-list-bounces+robert.rawlins=thinkbluemedia.co.uk at python.org] On Behalf Of Tim Golden Sent: 30 April 2007 11:27 Cc: python-list at python.org Subject: Re: Dict Copy & Compare Robert Rawlins - Think Blue wrote: > Hello Tim, > > Sorry, that 'value' was a slip up on my part, we're just dealing with keys > here. > > I get that a dict stores unique keys only but we're comparing the two dicts, > so when I say 'unique keys in dict 1' I basically mean all those keys that > are in dict one but not in dict 2. So imagine my 2 dicts with the following > keys. > > Dict 1 Dict 2 > ------ ------- > 00:00:00:00 00:00:00:00 > 11:11:11:11 11:11:11:11 > 22:22:22:22 33:33:33:33 > 44:44:44:44 44:44:44:44 > 55:55:55:55 > > Now, 22:22:22:22 and 55:55:55:55 is unique to dict one, and 33:33:33:33 is > unique to dict 2, does that make sense? Sorry for not explaining this stuff > very well, being so new to dicts its easy to get confused with my terms. > > I then want to pass those keys as a string value into my function as an > argument, like. > > thisFunction('22:22:22:22') > thisFunction('55:55:55:55') > > thatFunction('33:33:33:33') > > I'm hoping that your method will work for me, I've just got to spend my time > understanding what each step of it does. Well I feel a bit guilty now I look back at your original post, because I've probably given you a more complex solution than you really need. Your initial approach is probably quite adequate. Python dicts are highly tuned beasts so unless you're doing something really big or bizarre, you can sensibly do: d1 = { "00:00:00:00" : None, "11:11:11:11" : None, "22:22:22:22" : None, "44:44:44:44" : None, "55:55:55:55" : None } d2 = { "00:00:00:00" : None, "11:11:11:11" : None, "33:33:33:33" : None, "44:44:44:44" : None } for k in d1: if d1 not in d2: thisFunction (d1) for k in d2 if d2 not in d1: thatFunction (k) But even if this is adequate for your purposes, it's always good to be aware of what's in your programming toolbox and there's always the danger you'll end up implementing sets in dicts (which is what everyone did before Python 2.3). TJG -- http://mail.python.org/mailman/listinfo/python-list From mail at microcorp.co.za Wed Apr 25 02:05:01 2007 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Wed, 25 Apr 2007 08:05:01 +0200 Subject: Python un-plugging the Interpreter References: <1hwu415.1yyvbo61efn1uqN%aleax@mac.com> Message-ID: <000901c78706$4c439700$03000080@hendrik> "Jorgen Grahn" wrote: > On Thu, 19 Apr 2007 20:39:57 -0700, Alex Martelli wrote: > > Steve Holden wrote: > > > >> A long time ago Greg Stein produced a patch that removed the need for > >> the GIL, but nobody seemed to want to pay the penalty it extracted in > >> speed reduction, so it languished unadopted. > > > > Perhaps the current wave of dual-core and quad-core CPUs in cheap > > consumer products would change people's perceptions -- I wonder... > > Maybe it would change /perceptions/, but would normal users suddenly > start running things that are (a) performance-critical, (b) written in > Python and (c) use algorithms that are possible to parallellize? > > I doubt it. (But I admit that I am a bit negative towards thread > programming in general, and I have whined about this before.) > I find this last statement interesting, because it differs so much from my own attitude - getting a thread running was one of the first things I did when I started getting to grips with python. Do you mind "whining" some more - maybe I can learn something - threads seem to me to make a lot of things so much easier and more natural, as I see them as sequences that run "at the same time", and I find this immensely useful for all sorts of things, as it enables me to think in a simple linear fashion about parts of complicated things. And if you add queues, you have something in your hand that you can do quite fancy stuff with in a robust, simple manner... *grin* before I discovered the queue module, I was using named pipes to communicate between threads... So you could say I am a threading freak if you want to, and I won't argue. But I would like to hear the opposite viewpoint.. - Hendrik From iansan at gmail.com Wed Apr 11 14:57:56 2007 From: iansan at gmail.com (IamIan) Date: 11 Apr 2007 11:57:56 -0700 Subject: Nested dictionaries trouble Message-ID: <1176317876.917874.58040@n59g2000hsh.googlegroups.com> Hello, I'm writing a simple FTP log parser that sums file sizes as it runs. I have a yearTotals dictionary with year keys and the monthTotals dictionary as its values. The monthTotals dictionary has month keys and file size values. The script works except the results are written for all years, rather than just one year. I'm thinking there's an error in the way I set my dictionaries up or reference them... import glob, traceback years = ["2005", "2006", "2007"] months = ["01","02","03","04","05","06","07","08","09","10","11","12"] # Create months dictionary to convert log values logMonths = {"Jan":"01","Feb":"02","Mar":"03","Apr":"04","May":"05","Jun":"06","Jul":"07","Aug":"08","Sep":"09","Oct":"10","Nov":"11","Dec":"12"} # Create monthTotals dictionary with default 0 value monthTotals = dict.fromkeys(months, 0) # Nest monthTotals dictionary in yearTotals dictionary yearTotals = {} for year in years: yearTotals.setdefault(year, monthTotals) currentLogs = glob.glob("/logs/ftp/*") try: for currentLog in currentLogs: readLog = open(currentLog,"r") for line in readLog.readlines(): if not line: continue if len(line) < 50: continue logLine = line.split() # The 2nd element is month, 5th is year, 8th is filesize # Counting from zero: # Lookup year/month pair value logMonth = logMonths[logLine[1]] currentYearMonth = yearTotals[logLine[4]][logMonth] # Update year/month value currentYearMonth += int(logLine[7]) yearTotals[logLine[4]][logMonth] = currentYearMonth except: print "Failed on: " + currentLog traceback.print_exc() # Print dictionaries for x in yearTotals.keys(): print "KEY",'\t',"VALUE" print x,'\t',yearTotals[x] #print " key",'\t',"value" for y in yearTotals[x].keys(): print " ",y,'\t',yearTotals[x][y] Thank you, Ian From tiarno at sas.com Mon Apr 16 13:36:00 2007 From: tiarno at sas.com (Tim Arnold) Date: Mon, 16 Apr 2007 13:36:00 -0400 Subject: subprocess confusion Message-ID: Hi, Just discovered that my subprocess call with the preexec_fn wasn't doing what I thought. If 'machine' value is different than the current machine name, I want to remsh the command to that machine, but obviously I misunderstood the preexec_fn arg. Should I just put the remsh in the actual command instead of preexec_fn? thanks, --Tim Arnold ------------------------------- if machine == socket.gethostname(): shname = None else: shname = lambda :'/bin/remsh %s ' % (machine) p = subprocess.Popen(preexec_fn = shname, shell = True, args = command, stderr = subprocess.STDOUT, stdout = log, env = env, ) try: p.wait() if log: log.close() except: pass ------------------------------- From steveo at syslang.net Sun Apr 15 21:30:34 2007 From: steveo at syslang.net (Steven W. Orr) Date: Sun, 15 Apr 2007 21:30:34 -0400 (EDT) Subject: How to initialize a table of months. Message-ID: I'm reading a logfile with a timestamp at the begging of each line, e.g., Mar 29 08:29:00 I want to call datetime.datetim() whose arg2 is a number between 1-12 so I have to convert the month to an integer. I wrote this, but I have a sneaky suspicion there's a better way to do it. mons = {'Jan':1, 'Feb':2, 'Mar':3, 'Apr':4, 'May':5, 'Jun':6, 'Jul':7, 'Aug':8, 'Sep':9, 'Oct':10, 'Nov':11, 'Dec':12 } def mon2int( mon ): global mons return mons[mon] Is there a generator expression or a list comprehension thingy that would be *betterer*? (I realize it's probably not that important but I find lots of value in learning all the idioms.) 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 jstroud at mbi.ucla.edu Wed Apr 4 23:03:32 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Wed, 04 Apr 2007 20:03:32 -0700 Subject: Prevent Modification of Script? In-Reply-To: <1175735097.856840.177510@e65g2000hsc.googlegroups.com> References: <1175735097.856840.177510@e65g2000hsc.googlegroups.com> Message-ID: ts-dev wrote: > The root of my question is verifying the integrity of the application > and the scripts being run. Google "md5sum". Then google "birthday attack". James From bdesth.quelquechose at free.quelquepart.fr Wed Apr 11 18:19:54 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Thu, 12 Apr 2007 00:19:54 +0200 Subject: ValueError: too many values to unpack In-Reply-To: References: <1176311618.617765.120560@p77g2000hsh.googlegroups.com> <1176319688.666986.183980@o5g2000hsb.googlegroups.com> Message-ID: <461d55e7$0$15447$426a34cc@news.free.fr> Laszlo Nagy a ?crit : (snip) > Try this instead: > > lineno = 0 > for values in csvreader: > try: > lineno += 1 Laszlo, may I suggest using enumerate() here instead ?-) for lineno, row in enumerate(csvreader): print "line %s" % lineno+1 # want 1-based numbering From adam at atlas.st Mon Apr 16 17:24:51 2007 From: adam at atlas.st (Adam Atlas) Date: 16 Apr 2007 14:24:51 -0700 Subject: Compare regular expressions In-Reply-To: <58hrabF2g9sfqU1@mid.uni-berlin.de> References: <58hrabF2g9sfqU1@mid.uni-berlin.de> Message-ID: <1176758691.558817.295880@p77g2000hsh.googlegroups.com> On Apr 16, 1:50 pm, "Diez B. Roggisch" wrote: > It's not. For the simplest of expressions one might come up with a > relation between them, but even that would be hard. General case? No chance. I wouldn't say there's 'no chance'. It would require external parsing, for sure, but if anything, it may only be impossible for unusual cases. (Maybe I'll try this the next time I feel like writing parsers for fun (which is surprisingly frequently).) From apardon at forel.vub.ac.be Tue Apr 17 02:47:51 2007 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 17 Apr 2007 06:47:51 GMT Subject: Queue enhancement suggestion References: <7x4pngluel.fsf_-_@ruckus.brouhaha.com> Message-ID: On 2007-04-17, Hendrik van Rooyen wrote: > "Antoon Pardon" wrote: > > >> The problem is this doesn't work well if you have multiple producers. >> One producer can be finished while the other is still putting values >> on the queue. >> >> The solution I have been thinking on is the following. >> >> Add an open and close operation. Only threads that have the queue >> open can access it. The open call should specify whether you >> want to read or write to the queue or both. When all writers >> have closed the queue and the queue is empty a q.get will >> raise an exception. This may be done by putting a sentinel >> on the queue when the last writer closed the queue. >> > > This is beginning to look like a named pipe to me. > > The nice thing about queues is that there is currently so little > BS about them - you just import the module, create one by binding > a name to it, and you are in business, and anyone can read and/or > write to it. And if you are not carefull you have a deadlock. I tried queues in a threaded gui application. Al the advise you get about such applications tell you to have one thread doing all the gui-stuff. So you basically have n producers and one consumer. Unfortunatly the gui thread sometimes has things of its own it want to show. So when the gui thread wants to put things on the queue you risk a deadlock. > If I were faced with the sort of thing addressed by this thread, I would > probably use some sort of time out to decide when the end has happened. > After all - if the task is long running, it never stops (hopefully), and if its > a batch type job, it runs out of input and stops putting stuff on the queue. This is unworkable for worker threads in a gui environment. -- Antoon Pardon From robert.kern at gmail.com Sun Apr 15 20:19:11 2007 From: robert.kern at gmail.com (Robert Kern) Date: Sun, 15 Apr 2007 19:19:11 -0500 Subject: Portably generating infinity and NaN In-Reply-To: <7xhcrh2pxy.fsf@ruckus.brouhaha.com> References: <462008d1$0$11763$9b622d9e@news.freenet.de> <7xhcrh2pxy.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > I doubt any Crays are still running, or at least > running any numerical code written in Python. You are wrong. > Same for VMS. Also wrong. -- 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 nogradi at gmail.com Wed Apr 18 10:23:09 2007 From: nogradi at gmail.com (Daniel Nogradi) Date: Wed, 18 Apr 2007 16:23:09 +0200 Subject: array{uint32} In-Reply-To: <1527208137037646615@unknownmsgid> References: <1527208137037646615@unknownmsgid> Message-ID: <5f56302b0704180723j470d8df9v6a306c1171588171@mail.gmail.com> > I have a function that returns a array{uint32}, is there any way to output > that to screen in a more user friendly format? At the moment when I print it > by itself it appears as [65541L], which isn't much used to anyone. I'm not sure I understand your question precisely but this might help: >>> mylist = [65541L] >>> mylist [65541L] >>> mylist[0] 65541L >>> int(mylist[0]) 65541 >>> From apardon at forel.vub.ac.be Mon Apr 23 08:38:24 2007 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 23 Apr 2007 12:38:24 GMT Subject: Tutorial creates confusion about slices Message-ID: The following is part of the explanation on slices in the tutorial: The best way to remember how slices work is to think of the indices as pointing between characters, with the left edge of the first character numbered 0. Then the right edge of the last character of a string of n characters has index n, for example: +---+---+---+---+---+ | H | e | l | p | A | +---+---+---+---+---+ 0 1 2 3 4 5 -5 -4 -3 -2 -1 This is all very well with a simple slice like: "HelpA"[2:4] => "lp" But it give the wrong idea when using the following extended slice: "HelpA"[4:2:-1] => "Ap" So this doesn't result in the reverse of the previous expression while the explanation above suggest it does. So I suggest to drop this. -- Antoon Pardon From bignose+hates-spam at benfinney.id.au Tue Apr 3 05:57:10 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Tue, 03 Apr 2007 19:57:10 +1000 Subject: cli user interface ala cisco IOS or JUNOS References: <1175588673.340855.130230@q75g2000hsh.googlegroups.com> Message-ID: <87ircdhjbd.fsf@benfinney.id.au> phil.aerts.tln at gmail.com writes: > for one of my python projects I need an user interface similar to that > of cisco IOS or even better Juniper JUNOS. > Does anyone know of existing python modules that gives this kind of > functionality? I suspect you've not checked the standard library index: Python Library Reference which lists the 'cmd' module: cmd -- Support for line-oriented command interpreters If that doesn't meet your needs, you might need to be more specific about what you're looking for. -- \ "Success is going from one failure to the next without a loss | `\ of enthusiasm." -- Winston Churchill | _o__) | Ben Finney From jeba.ride at gmail.com Sat Apr 14 10:20:19 2007 From: jeba.ride at gmail.com (Clement) Date: 14 Apr 2007 07:20:19 -0700 Subject: Option Explicit Message-ID: <1176560418.992348.70200@b75g2000hsg.googlegroups.com> Is there any command like Option Explicit[In visual basic]......... From tjreedy at udel.edu Wed Apr 4 16:55:58 2007 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 4 Apr 2007 16:55:58 -0400 Subject: operator overloading References: <1175679412.741899.45990@l77g2000hsb.googlegroups.com> <1175711246.488717.262560@e65g2000hsc.googlegroups.com> Message-ID: "Ziga Seilnacht" wrote in message news:1175711246.488717.262560 at e65g2000hsc.googlegroups.com... | This looks like a bug in Python. It works for all the other | operators: | | >>> class MyInt(int): | ... __sub__ = int.__add__ | ... __mul__ = int.__add__ | ... __div__ = int.__add__ | ... __truediv__ = int.__add__ | ... __floordiv__ = int.__add__ | ... __mod__ = int.__add__ | ... __lshift__ = int.__add__ | ... __rshift__ = int.__add__ | ... __and__ = int.__add__ | ... __xor__ = int.__add__ | ... __or__ = int.__add__ | ... __pow__ = int.__add__ | ... | >>> i = MyInt(42) | >>> i + 3 | 45 | >>> i - 3 | 45 | >>> i * 3 | 45 | >>> i / 3 | 45 | >>> i // 3 | 45 | >>> i % 3 | 45 | >>> i << 3 | 45 | >>> i >> 3 | 45 | >>> i & 3 | 45 | >>> i ^ 3 | 45 | >>> i | 3 | 45 | >>> i ** 3 | 74088 | | You should submit a bug report to the bug tracker: | | http://sourceforge.net/bugs/?group_id=5470 Nice test. I thought maybe __pow__ might be different in not having a reverse form, but indeed, int has an __rpow__ method. Before submitting, make sure that this does not work in 2.5, and then say so in the bug report. In fact, copy the version/system info that the interactive interpreter puts up when it starts. tjr From cam.ac.uk at mh391.invalid Thu Apr 26 14:35:17 2007 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Thu, 26 Apr 2007 19:35:17 +0100 Subject: Dedicated CPU core for Python? In-Reply-To: <1177607759.916727.180950@t39g2000prd.googlegroups.com> References: <1177607759.916727.180950@t39g2000prd.googlegroups.com> Message-ID: Louise Hoffman wrote: > I was wondering, if Python in the foerseeable future will allocate one > CPU core just for the interpreter, so heavy Python operations does > slow down the OS? When running scripts, or loading modules, Python does not really behave as an interpreter. Instead it compiles the human-readable code to a bytecode which it then runs on a virtual machine. -- Michael Hoffman (no relation) From ask at me Tue Apr 17 23:00:03 2007 From: ask at me (alf) Date: Tue, 17 Apr 2007 22:00:03 -0500 Subject: wx and SOAPpy interaction In-Reply-To: References: <7KSdndOfrr1uQYPbnZ2dnUVZ_vmqnZ2d@comcast.com> Message-ID: Amaury Forgeot d'Arc wrote: > alf a ?crit : > >> Hi, >> >> there is problem when I import (python 2.4) wx and SOAPpy at the same >> time. I narrowed the problem to following (on Linux): >> >> >>import wx >> >>import pyexpat >> >> Traceback (most recent call last): >> File "", line 1, in ? >> ImportError: >> /apps/public/python_2.4.4/lib/python2.4/lib-dynload/pyexpat.so: >> undefined symbol: XML_StopParser >> >> >> any insight? > > > It seems that the process is trying to load two versions of the "expat" > XML library: > > http://mail.python.org/pipermail/python-list/2006-April/377070.html > > The problem is that wxWidgets embeds its own copy of expat. You may have > to recompile either python or wxWidgets so that they use the same expat > version. > For the record, on my mandriva 2006 box with wxpython and python 2.4 installed out of distribution DVD this works fine. Problem is with python2.4 installed onsome older version of RedHad server edition. A. From steve at holdenweb.com Sat Apr 28 11:11:19 2007 From: steve at holdenweb.com (Steve Holden) Date: Sat, 28 Apr 2007 11:11:19 -0400 Subject: Tutorial creates confusion about slices In-Reply-To: References: <1177496078.319400.324720@r30g2000prh.googlegroups.com> Message-ID: Antoon Pardon wrote: > On 2007-04-26, Steve Holden wrote: [...] > >> Warning: this is an explicit test to see whether you can sit on your >> hands and refrain from replying. It's hard to find a thread where you >> don't make the last comment on every branch you get involved in. > > Well I guess I failed. > Yes, that just about says it all. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden ------------------ Asciimercial --------------------- Get Python in your .sig and on the web. Blog and lens holdenweb.blogspot.com squidoo.com/pythonology tag items: del.icio.us/steve.holden/python All these services currently offer free registration! -------------- Thank You for Reading ---------------- From irstas at gmail.com Tue Apr 3 16:47:58 2007 From: irstas at gmail.com (irstas at gmail.com) Date: 3 Apr 2007 13:47:58 -0700 Subject: how to remove multiple occurrences of a string within a list? In-Reply-To: <1175627593.307674.11280@w1g2000hsg.googlegroups.com> References: <1175624433.206953.214290@n59g2000hsh.googlegroups.com> <1175625098.269660.184790@o5g2000hsb.googlegroups.com> <1175627593.307674.11280@w1g2000hsg.googlegroups.com> Message-ID: <1175633278.370582.175940@p77g2000hsh.googlegroups.com> On Apr 3, 10:13 pm, "bahoo" wrote: > On Apr 3, 2:31 pm, "Matimus" wrote: > > > It depends on your application, but a 'set' might really be what you > > want, as opposed to a list. > > > >>> s = set(["0024","haha","0024"]) > > >>> s > > > set(["0024","haha"])>>> s.remove("0024") > > >>> s > > > set(["haha"]) > > This sounds cool. > But is there a command I can convert the "set" back to a "list"? Beware that converting a list to set and then back to list won't preserve the order of the items, because the set-type loses the order. From rockmode at gmail.com Sun Apr 29 16:16:15 2007 From: rockmode at gmail.com (rockmode at gmail.com) Date: 29 Apr 2007 13:16:15 -0700 Subject: Counting In-Reply-To: References: <1177873864.502180.283390@u30g2000hsc.googlegroups.com> Message-ID: <1177877775.780666.222080@p77g2000hsh.googlegroups.com> That's a short, abridged version of my code :) But, what I want is to count total# of keywords per line and print 'em. Rather than printing : The word 'and' belongs in line num: 1 The word 'del' belongs in line num: 1 The word 'from' belongs in line num: 1 I want to print " Line #1 has 3 keywords" ;) > You probably want something that goes a little like this: > > for i,line in enumerate(linelist): > for k in line.split(): > if keyword.iskeyword(k): > total += line.count(k) > print "The word '%s' belongs in line num: %d" % (k, i+1) > > print "Total keyords are: %d" % total > > James From andrea.valle at unito.it Thu Apr 5 18:03:05 2007 From: andrea.valle at unito.it (Andrea Valle) Date: Fri, 6 Apr 2007 00:03:05 +0200 Subject: ascii-unicode replacement In-Reply-To: References: Message-ID: Many thanks Gabriel > Convert to unicode right there, using > read_text.decode("ascii"). You have unicode now. That's exactly what I was searching for. This new line: text = text.decode("ascii") solved my problem. Best -a- -------------------------------------------------- Andrea Valle -------------------------------------------------- CIRMA - DAMS Universit? degli Studi di Torino --> http://www.cirma.unito.it/andrea/ --> andrea.valle at unito.it -------------------------------------------------- I did this interview where I just mentioned that I read Foucault. Who doesn't in university, right? I was in this strip club giving this guy a lap dance and all he wanted to do was to discuss Foucault with me. Well, I can stand naked and do my little dance, or I can discuss Foucault, but not at the same time; too much information. (Annabel Chong) -------------- next part -------------- An HTML attachment was scrubbed... URL: From arkanes at gmail.com Mon Apr 16 12:57:24 2007 From: arkanes at gmail.com (Chris Mellon) Date: Mon, 16 Apr 2007 11:57:24 -0500 Subject: tuples, index method, Python's design In-Reply-To: References: Message-ID: <4866bea60704160957j1191b68aw631536d6d8f84972@mail.gmail.com> On 4/12/07, Alan Isaac wrote: > Chris Mellon said: > > Sure. I have never done this. In fact, I have only ever written code > > that converted a tuple to a list once, and it was because I wanted > > pop(), not index() > > Well then you apparently made a *mistake*: you chose a tuple when you > wanted a mutable object. That is really beside the point. > The tuple in question was function varargs. Yes, I wanted a mutable object, thats why I made a list out of it. Whether varargs should be a list or a tuple to begin with is open to debate, but it's not likely you'd want to use index() on it either way. > And you missed the point of my query. It is not that existing code will > contain such a conversion to get access to the index method. It is that > if you choose tuples to represent immutable sequences, sooner or later > you will find you need to change your code to use a list not because you > really want a mutable sequence but because you want the ``index`` method. > That may have been your point, but it's not what you said. I've never converted a tuple to a list because I needed index(). I've never used a list where a tuple would be "more natural" soley because I needed to search it, either. I have never used index() in a situation where the sequence in question wasn't both a) mutable and b) actually was mutated in the course of program. > Note that it has become clear that some people do not use tuples hardly > ever, regardless whether their sequence is naturally mutable or > immutable. Why? Because they want access the the list methods. > **All** of these people fall in the category I am talking about. > I do not really care if you reach mentally and then fix or actually type it. > The avoidance of tuples, so carefully defended in other terms, > is often rooted (I claim) in habits formed from need for list methods like > ``index`` and ``count``. Indeed, I predict that Python tuples > will eventually have these methods and that these same people > will then defend *that* status quo. > I use tuples all the time. There are more incidences of tuple usage than list usage in my current codebase. My opinions on tuples still stand. I use tuples when I already know what goes into them and in what order. index() and count() are totally useless when you use tuples (or, indeed, any sequence) in this manner. From robert.rawlins at thinkbluemedia.co.uk Mon Apr 16 10:18:48 2007 From: robert.rawlins at thinkbluemedia.co.uk (Robert Rawlins - Think Blue) Date: Mon, 16 Apr 2007 15:18:48 +0100 Subject: Writing Log CSV (Efficiently) In-Reply-To: <17955.33861.211843.361355@montanaro.dyndns.org> References: <7554276584215132819@unknownmsgid> <6e42ec490704160700i20469453j6af39db62dd6b427@mail.gmail.com> <17955.33861.211843.361355@montanaro.dyndns.org> Message-ID: <002a01c78032$27190620$754b1260$@rawlins@thinkbluemedia.co.uk> Hello Guys, Thanks for the advice on this one. I'm running Debian Linux as an OS, if that makes any major differences. That inbuilt CSV stuff looked pretty tidy, as does the logging. I'd be keen to learn a little more about that performance wise though. The log at its highest rate of write may be looking at an operation a second, I've not got much experience with this kind of thing so I'm not sure if that's 'a lot' or not, it just seems like it at the moment. It might not get as busy as that, I'm not sure and its difficult to simulate as this isn't likely to be a steady flow of traffic, they'll come in big fat lumps every now and then. Thanks, Rob -----Original Message----- From: skip at pobox.com [mailto:skip at pobox.com] Sent: 16 April 2007 15:12 To: Dave Borne Cc: Robert Rawlins - Think Blue; python-list at python.org Subject: Re: Writing Log CSV (Efficiently) Dave> Python has built in logging support. It's pretty flexible as far Dave> as formatting output. I can get a bit complicated to set up, but Dave> it will handle traffic well. Really? I've found it to be a dog in heavy logging situations. Skip From yinglcs at gmail.com Sun Apr 29 21:52:22 2007 From: yinglcs at gmail.com (yinglcs at gmail.com) Date: 29 Apr 2007 18:52:22 -0700 Subject: Chart drawing tool in python Message-ID: <1177897942.532255.317000@y80g2000hsf.googlegroups.com> Hi, In Perl, there is a GD module to draw custom chart. http://www-128.ibm.com/developerworks/opensource/library/os-perlgdchart/?ca=dgr-lnxw01Perl-GD-Charts Can you please tell me if there is an equivalent library in python? Thank you. From jzgoda at o2.usun.pl Fri Apr 27 08:01:06 2007 From: jzgoda at o2.usun.pl (Jarek Zgoda) Date: Fri, 27 Apr 2007 14:01:06 +0200 Subject: Re-ocurring Events In-Reply-To: References: <3891950377467154133@unknownmsgid> <003001c7889c$f1fb6a50$d5f23ef0$@rawlins@thinkbluemedia.co.uk> <4631B8FE.8000405@limsi.fr> <004901c788a9$b42c2130$1c846390$@rawlins@thinkbluemedia.co.uk> Message-ID: Robert Rawlins - Think Blue napisa?(a): > and I need to do and conditional that ensures start is before today's > date/time and end is after today's date/time. > > The string looks like: '2007-01-01 00:00:00' > > Do I have to convert this to a proper time object to do the comparison? Or > can I do it as a string? In the very specific case of string formatted as above, the string comparison will give the same results as in the case of datetime objects comparison. You just have to compare the same kinds of things. ;) -- Jarek Zgoda "We read Knuth so you don't have to." From james.p.news at gmail.com Mon Apr 30 20:08:34 2007 From: james.p.news at gmail.com (james.p.news at gmail.com) Date: 30 Apr 2007 17:08:34 -0700 Subject: logging SMTPHandler and Authentication Message-ID: <1177978114.284934.27140@l77g2000hsb.googlegroups.com> I'm new to Python, but I've been thrown into coding a pretty complicated regression testing script. I need to email the log of the daily test to the code owners. I thought I could use SMTPHandler for this, but our email system requires authentication. I have not been able to figure out how to log in using SMTPHandler. I found the following post on comp.lang.python: http://groups.google.com/group/comp.lang.python/browse_frm/thread/ef873c79157b8624/cdb67687e507c974?lnk=gst&q=SMTPHandler+authentication&rnum=1#cdb67687e507c974 However, I haven't been able to translate this to anything I can use. I've also looked at the source code for the SMTPHandler, but I don't want to edit that. Has anyone else dealt with this? Thanks much, James From steve at holdenweb.com Thu Apr 12 09:39:51 2007 From: steve at holdenweb.com (Steve Holden) Date: Thu, 12 Apr 2007 09:39:51 -0400 Subject: reading from sys.stdin In-Reply-To: <200704121446.14303.maric@aristote.info> References: <1176366058.261031.111870@p77g2000hsh.googlegroups.com> <586984F2g0ejiU1@mid.uni-berlin.de> <200704121446.14303.maric@aristote.info> Message-ID: Maric Michaud wrote: > Le jeudi 12 avril 2007 10:34, Diez B. Roggisch a ?crit : >> I presume this is an OS thing. The first lines aren't communicated to >> the process until either the file is closed - C-d - or the buffer the OS >> puts before the stream is filled. You can switch to unbuffered behviour >> somehow, google for it. Termios should be in your query. > > I don't know if this a python or OS thing, but I know that iterating over a > file is not like applying successive call to readline method. You should try > to use readline instead. > That, of course, is because files are iterators. > The following work exactly the same on windows and Linux (python2.4) : > >>>> f=open('txt') >>>> l=f.readline() >>>> while(l) : > ... print l, > ... print "rest : " + f.read() > ... l=f.readline() > ... > foo > rest : bar > baz > > works as expected, while : > >>>> f=open('txt') >>>> for l in f : > ... print l, > ... print "rest : " + f.read() > ... > foo > rest : > bar > rest : > baz > rest : > > doesn't, it seems that file iteratiion itself use a buffer. In python 2.5, you > just can't do this : > > Python 2.5 (release25-maint, Dec 9 2006, 14:35:53) > [GCC 4.1.2 20061115 (prerelease) (Debian 4.1.1-20)] on linux2 > Type "help", "copyright", "credits" or "license" for more information. >>>> f=open('txt') >>>> for l in f : > ... print l, > ... print "rest : " + f.read() > ... > foo > Traceback (most recent call last): > File "", line 3, in > ValueError: Mixing iteration and read methods would lose data > But you *can* do this (untested): for l in f: print l, print "rest:", f.next() Of course there are always edge cases. In this particular instance I suspect that the handling of files with odd numbers of lines might be slightly different, but I can't work up enough enthusiasm to actually run this code. The error method pretty much explains what the problem is: you have to iterate over files or read them, you shouldn't try and do both on the same file. 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 carsten at uniqsys.com Wed Apr 11 01:06:24 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Wed, 11 Apr 2007 01:06:24 -0400 Subject: tuples, index method, Python's design In-Reply-To: <7xirc3czen.fsf@ruckus.brouhaha.com> References: <1175867771.114540.61810@n76g2000hsh.googlegroups.com> <1175884427.779950.267220@y80g2000hsf.googlegroups.com> <1176210960.3430.20.camel@dot.uniqsys.com> <740c3aec0704100810g5f962e8eu614fbaedecf3608e@mail.gmail.com> <7xirc3czen.fsf@ruckus.brouhaha.com> Message-ID: <1176267984.3330.6.camel@localhost.localdomain> On Tue, 2007-04-10 at 21:23 -0700, Paul Rubin wrote: > Carsten Haese writes: > > You have a point. Here is my revised solution: > > > > assert current_player in p > > opponents = tuple(x for x in p if x is not current_player) > > Still wrong on two counts. First, assert is a no-op if optimization > is turned on. Right. I already responded to this when Bjorn made the same objection. Please try to keep up. > Second, your version returns a different result from > the original if current_player occurs in p more than once. First of all, in the use case we're talking about, current_player shouldn't occur in p more than once. And if it did, is it really reasonable to demand that that player be their own opponent? I don't think so. So yes, the result is different because it's correct, and the tuple.index-based solution is actually incorrect in this case. -Carsten From paddy3118 at googlemail.com Sat Apr 14 23:38:22 2007 From: paddy3118 at googlemail.com (Paddy) Date: 14 Apr 2007 20:38:22 -0700 Subject: Getting started with python In-Reply-To: <1176598011.463543.96990@q75g2000hsh.googlegroups.com> References: <1176598011.463543.96990@q75g2000hsh.googlegroups.com> Message-ID: <1176608302.928513.274400@y5g2000hsa.googlegroups.com> On Apr 15, 1:46 am, "Eric" wrote: > Hello, after reading some of the book Programming Python it seems that > python is something I would like to delve deeper into. The only thing > is, I have no idea what I should try and write. So I was hoping that > someone here could help point me to a group/project that would be a > good starting place for a person with limited python knowledge, but > that is willing to learn whatever is necessary. I'm hoping that with a > goal I can start to learn python instead of just playing around with > it. Thanks. Hi Eric, Somas1. Try: http://www.google.co.uk/search?source=ig&hl=en&q=beginners+programming-problems&btnG=Google+Search&meta= Some of the sites have beginners problems meant for another language, but in a lot of cases that doesn't matter. You might need to be a fair way through the Python tutorial though before you attempt thhem so you know the basics of Python first. On a different tack, from: http://tickletux.wordpress.com/2007/01/24/using-fizzbuzz-to-find-developers-who-grok-coding/ It seems you need to learn how to write a Fizz-Buzz program to get a job now-a-days :-) - Paddy. From grante at visi.com Tue Apr 24 18:31:10 2007 From: grante at visi.com (Grant Edwards) Date: Tue, 24 Apr 2007 22:31:10 -0000 Subject: Generate report containing pdf or ps figures? References: <132pnp6r4qg0lc2@corp.supernews.com> <1177350202.388337.131110@d57g2000hsg.googlegroups.com> <132q0cpkpgt0ud1@corp.supernews.com> Message-ID: <132t19e6jp517d4@corp.supernews.com> On 2007-04-24, hlubenow wrote: > Grant Edwards wrote: > >> On 2007-04-23, Kjell Magne Fauske wrote: >> >>>> Is there a PDF generation library that can place EPS or PDF >>>> figures on a page? > > What about > > http://pybrary.net/pyPdf/ > > It does some very interesting things. But I'm not really sure, if it does > what you're after. At least it can merge one page onto another. It's close to what I was looking for, except I'd like to be able to scale and translate pages (e.g. so I can print them 2-up). Based on the documentation and examples, it looks like it can only rotate and crop. Still, it's probably closer than the other options, so it's worth a closer look. -- Grant Edwards grante Yow! This is a NO-FRILLS at flight -- hold th' CANADIAN visi.com BACON!! From grante at visi.com Sat Apr 21 22:44:44 2007 From: grante at visi.com (Grant Edwards) Date: Sun, 22 Apr 2007 02:44:44 -0000 Subject: No speedup on multi-processor machine? References: <1177189332.916296.205280@d57g2000hsg.googlegroups.com> Message-ID: <132lj0sekj10542@corp.supernews.com> On 2007-04-21, danfan1981 at yahoo.com wrote: > I am using Python Thread library for my parallel processing > course project. I am doing matrix convolution on a > multi-processor machine running Solaris. I just found out that > no speed-up is obtained with threading. It is probably because > of something called GIL in Python. How can I get around that > GIL and get speed-up? Not much of a parallel processing course. It appears they haven't taught you anything about parallel processing. http://wiki.python.org/moin/ParallelProcessing -- Grant Edwards grante Yow! There's a SALE on at STRETCH SOCKS down at the visi.com "7-11"!! From eight02645999 at yahoo.com Mon Apr 16 21:05:16 2007 From: eight02645999 at yahoo.com (eight02645999 at yahoo.com) Date: 16 Apr 2007 18:05:16 -0700 Subject: list insertion question Message-ID: <1176771916.236282.206500@n59g2000hsh.googlegroups.com> hi i have a list (after reading from a file), say data = [ 'a','b','c','d','a','b','e','d'] I wanted to insert a word after every 'a', and before every 'd'. so i use enumerate this list: for num,item in enumerate(data): if "a" in item: data.insert(num+1,"aword") if "d" in item: data.insert(num-1,"dword") #this fails but the above only inserts after 'a' but not before 'd'. What am i doing wrong? is there better way?thanks From xah at xahlee.org Tue Apr 3 15:23:06 2007 From: xah at xahlee.org (Xah Lee) Date: 3 Apr 2007 12:23:06 -0700 Subject: Requirements For A Visualization Software System For 2010 Message-ID: <1175628186.459945.290750@d57g2000hsg.googlegroups.com> REQUIREMENTS FOR A VISUALIZATION SOFTWARE SYSTEM FOR 2010 Xah Lee, 2007-03-16 In this essay, i give a list of requirements that i think is necessary for a software system for creating scientific visualization for the next decade (2007-2017). (for a HTML version with images, please see http://xahlee.org/3d/viz.html ) For the past 10 years, i have been strongly interested in mathematical visualization. I'm not a professor, and am not doing it for the educational purposes per se. Geometry has just been beautiful for me, and i'm also a professional programer. Programing computers to visualize geometric theorems or geometric objects, has been a immense personal pleasure. A particular aspect of visualization, is to design it so that when viewed, it forces a immediate and crystal clear understanding of the object or theorem, to its viewers. I have for the past couple years sought for a software platform/system where i can build 3D objects, with abilities to do interactive manipulation (such as moving a slider to change a parametric surface's parameter), dynamic rotation (viewing from different angles instantaneously), animations (such as morphing that shows geometric processes), and most of all, walk-thru in it as if it is a building (e.g. the perception of actually walking on a moebius strip? or Klein bottle? is vastly different than just viewing it.). -------- Requirement: Real-Time 3D Rotation For math visualization, it is absolutely necessary to be able to rotate the object in real-time. For example, when viewing a complex surface, a molecule structure, or the design of a complex device. This requirement is so basic it warrants no further explanation. above: The Chen Gackstatter minimal surface as shown by the software 3D-XplorMath ?. This surface has several 3-fold symmetries, but a static image does not show this. (Live Rotation with Java Applet) -------- Requirement: Real-time Interactivity The programer should be able to build buttons and sliders that change parameters and have the object reflect these changes visually right away. This real-time interactivity is frequently needed. For example, most math visualizations involve a function, a process, or a geometric object, that varies by parameters, and the key to the visualization is showing how the parameter effect the graph or object. Some Examples follows. Example: Moebius Transformation above: A software that plots a complex function (the Moebius transformation?), by showing the pre-image and post-image of the function. The function is keyed by various parameters that can be represented as points in the plane. Dragging these points will change the image interactively. Source: MoeApplet by Paul Murray ? Example: Regular Polytopes above: a Java applet showing a slice of 4-dimensional symmetric polytopes? , with sliders that change the polytope's parameters. Dragging the polytope will rotate it in real-time. Hyperstar Java Applet by Mark Newbold ?. Example: Plane Geometry above: A interactive plane geometry software showing a Equiangular Spiral and its inverse curve , with respect to a point O. Equiangular spiral is a family of curves varying by a parameter ?, from 0 to ?/2. This parameter can be changed by dragging the point E of the angle DAE, and the corresponding curve will be shown (blue). Its inverse curve with respect to the point O is shown in pink. Dragging the point O will change the position of O, and corresponding inverse curve will be shown in real-time. above: A plane geometry software demonstrating Bezier curve. User can drag the poins to very the input, and see the polynomial change shape in real-time. Java Applet version. Example: Conic Sections Computing power today are some 50 times faster than a decade ago. However, math visualizations, have hardly advanced. For example, let's consider the simple task of plotting of polynomial equations. As we know, 2nd degree polynomials of 2 variables are conic sections. It would nice, that the program can show the general form A x^2 + B x y + C y^2 + D x + E y + F == 0 and let users change the constants by sliders, and have the graph change on the fly. Such a application would give immense feedback that reinforces learning, which is what visualization is about. Similiarly, this can be done for 3rd degree polynomials, and the visualization of polynomials of 3 variables. There are tens, if not hundreds, elementary equation and function graphing software. However, it is almost impossible to find one that shows the power of interactivity described above. Apple Computer Inc, bundled with OS X as current as of March 2007, a plotting software (called Grapher?) that has zero interactivity features. And Mathematica's abilities for plotting polynomial equations in as late as 2005, is basically the same as 1996. Its ability for visual experiment and learning of polynomials of 3 variables is practically zero. I have personally played with perhaps over 20 major plotting software over the past 15 years, and i only know one that has this feature. (see Nucalc?) -------- Requirement: easy-to-create, real-time animation The software system must have the capabilities for programers to build animations, and view the animation interactively in real-time (as opposed to generating the animation once and save it as a movie). For example, once a programer has coded the animation, she should easily play it forward and backward in the program, as well as changing parameters and re-run the new animation without going thru some compilation or export process. For example, if the animation involves a 3D object, the system should also allow the user to rotate it while the animation is on-going, all in real-time. For example, this system should allow programer to easily create a animation that morphs a sphere into a cube, or a bunch of spheres flying in space as a swarm of flies or in some artificial formation like a 3D-kaleidoscope. Example: Cycloidal Curves above: A movie generated by a math software, showing how the cycloid curve is generated by rolling a circle. (cycloidGen.mov). In this example, you can see the trace by a point on the boundary of the circle. What happens if the tracing point is nearer to the center of the circle? This is a example where a interactive slider will help. As a user adjust the slider, the animation should show its effects in real-time. Example: Cellular Automaton above: A software that computes the cellular automaton?known as Game Of Life, showing it as a animation as it evolves. At any point in time, a user can add more cells to it by clicking in the window, and continue the animation to see its effects. Example: Helicoid-catenoid Surface Family above: A frame of a software generated animation, showing the isometry property of the surface family helicoid-catenoid. (helicoid- catenoid.mov) This is a example where it shows the importance of being able to rotate the object in real-time in a on-going animation. Example: Sphere-eversion above: The classic Sphere-eversion visualization problem, visually demonstrating how a sphere can be turned inside-out without creating any crease. (Source: John Sullivan et al. ?. image source ?, accessed on 2007-03-18.) (For detail about this problem, see: Smale's paradox?) Examples of system that do NOT satisfy this requirement would be: Mathematica (up to version 5), 3D-XplorMath, most CAD systems. Most of these systems allow animations, but usually for a generate-once and save-as-static-movie-file, not designed for interactive view. Example: Stereographic Projection above: A illustration showing stereographic projection. (source) To create visualization for stereographic projection, ideally, the user should be able to rotate the whole plane, or move it up and down in relation to the sphere, as to see the effect on the mapping. Also, the user should be able to rotate the sphere and see the mapping change on the plane. The user should also be able to move a single projection line to see mappings of arbitrary points. Lastly, it is ideal in this visualization to let users change the pattern on plane or on the sphere to arbitrary images. For example, the plane should have a default set containing rectangular grids and polar grids. (showing the important property of circles mapping to circles/lines) The sphere should have standard projection of platonic solids. (showing the important concept of platonic solids as networks) And, the user should be able to put the graph of arbitrary complex function on the plane or a Riemann sphere? on the sphere. Today, it is non-trivial to create a visualization such as this. For example, the above image is created in Mathematica. One has to write a function that plots riemann sphere in the first place, to create the image of the sphere. The system also needs to have animation and interactive slider abilities, as to be able to make the sphere and plane rotate or reposition independently in real-time, and the moving of the projection line. Examples of visualization systems that do satisfy the animation requirement to various degrees discussed in this section would be: Macromedia Flash, VPython, 3D Game Engines. -------- Requirement: Walk-thru The software system should have the capability of walk-thru or fly- thru. That is, allow the programer precise control of the camera position and orientation in real-time. The most obvious application of this requirement is in CAD systems that are specialized for architecture. For example, if i build a fancy 3D-maze or elaborate cathedral, i should be able to say, walk inside it, so as to view the object from inside and as well as getting the real experience of perceiving such a building. The ability to do walk-thrus has significant applications in math visualization too, however, it is seldom realized. Here are some examples of its application. Example: Walking on Surfaces above: A hyperbolic-paraboloid, with a human character standing on top of it. (from the computer graphics virtual world Second Life. Credit: Henry Segerman?, aka Seifert Surface.) Compare the above image with the following abstract rendering that is commonly found in math visualization software. above: a abstract rendering of the hyperbolic-paraboloid. Java Applet Perhaps due to the evolution of our perception system, the experience of actually walking on or inside a math object, is vastly different than just seeing it as zero-thickness abstract lines and sheets rotating around its center. Although, the virtual world created by computer graphics only fake the experience of actually being there, still, such a virtual world experience throws a impact on understanding. Imagine, demonstrating the one-sidedness property of surfaces such as the moebius strip? or Klein bottle? thru a live rotation and explanation, compared to having the student inadvertently taking a walk inside such a object and suddenly felt the single-sided oddity. A person experiencing such a situation will probably remember it as part of his life's memory. Example: 3D-Lattices The ability to do walk-thrus also fits well in visualizations involving 3-dimensional lattices, such as Crystallographic group?, 3D- tilings (sphere packing), or visualizing periodic minimal surfaces. For example, the following images of periodic minimal surfaces are shown in the way they are traditionally presented, as a few representative patchs of the periodic surface, and users can rotate the surfaces in real-time: above: Periodic minimal surfaces?. Source: Richard Palais, Karcher Hermann. ?) As they are shown, their periodic structure is not visually clear, especially those non-rectangular ones. (e.g. the last 3) It also takes some effort to imagine how they actually fill the space. Now, imagine these shown in a walk-thru system, where a portion of space is filled with its repetitions, and the user effectively becomes a bee, flying about in it, able to observe detail in a close-up on any point of the surface from any angle, or getting a bird's eye's overview of the surface's lattice symmetry. Example: 3-Manifolds above: Screenshot of Jeff Week's Curved Space ? software. This program lets users fly-thru various 3-manifolds? . There is basically no other way of visualizing 3-manifolds other than the techniques of walk-thru. There is effectively no visualization system that lets programers easily code interactive walk-thrus. The possible exception is 3D Game Engines?, however, it requires a specialized programer with years of dedicated experience to create any thing in it, and the work is rather tedious. Some such game engines have higher level (scripting) languages that let the user (players) create objects or scenes in- world. (A example is the Linden Scripting Language? of Second Life?. ) -------- Requirement: Easy To Use For Average Programers The system must be easy to use for average programers or scientists. For example, a person who had just a year of programing experience, should be able to code a variety of visualization projects with the system. Often, these high-level languages are called scripting languages. Mathematica?, Lisps (Logo?, Scheme?, Tcl/tk? ), Visual Basic?, VPython?, Macromedia Flash?, CAD systems (AutoLISP? ), Linden Scripting Language? are examples of high-level systems. On the other hand, low-level language such as Java?, C sharp?, or, systems such as OpenGL? and Game Engines?, or application programing systems such as Cocoa (API)? and X Window System?, all require professional programers with years of experience to create a non- trivial application. These are not useful to most scientists or engineers. -------- Requirement: A Set of Basic Geometric Shapes The system must have a set of basic primitives or shapes that serve as building blocks. For example, spheres, torus, cubes, as well as meshes of triangles. Of course, the system should also have the following common elements: various coordinates systems, projection systems, lighting and camera control, build-in manifold by parametric surfaces and algebraic equations, and a whole set of 2D and 3D transformation functions (which can also work on n-dimensional coordinates). For a system aimed for math visualization, it would also be necessary to have access to a full range of math functions, such as integration, derivative, higher-order functions. [Continues on page 2] ----- This post is archived at I'm still working on the second part. Your opinions and comments on existing systems are welcome. Thanks. Xah xah at xahlee.org ? http://xahlee.org/ From mail at timgolden.me.uk Fri Apr 13 09:02:52 2007 From: mail at timgolden.me.uk (Tim Golden) Date: Fri, 13 Apr 2007 14:02:52 +0100 Subject: Arrays, Got Me Confused In-Reply-To: <001c01c77dca$67232210$35696630$@rawlins@thinkbluemedia.co.uk> References: <000101c77dc3$d4152a00$7c3f7e00$@rawlins@thinkbluemedia.co.uk> <461F7712.2040201@timgolden.me.uk> <001c01c77dca$67232210$35696630$@rawlins@thinkbluemedia.co.uk> Message-ID: <461F7F7C.6080906@timgolden.me.uk> Robert Rawlins - Think Blue wrote: > Hello Guys, > > Wider fragments of code don't really exists at this moment in time :-D this > is just a bit of a 'tester' class for me to get used to the methods. > Basically I'm trying to create a class that contains an array of MAC > address, these look something like this 'FD:E4:55:00:FG:A9. I want the class > to have the following methods for easy manipulation of the array. > > addDevice(Address) - Pass in the MAC address and have it add it to the > array. > > removeDevice(Address) - Finds a device with that address in the array and > removes it. > > isFirewalled(Address) - looks for that address in the array and returns > true/false dependant on whether it finds it. > > Clear() - empty the array of all its contents. OK, it's easy enough to do this, but you might find that you don't actually need to do too much of it yourself. Python has two central datastructures built in: lists and dictionaries. There are loads of tutorials around (and if you join the python-tutor list, the welcome message points you towards several) so I won't go into the details, but it looks like you want a dict here. You could wrap it in a class if you wanted, but the great thing about Python is that you don't have to. *Very* rough example code: macs = {} # create an empty dict incoming_mac = 'FD:E4:55:00:FG:A9' macs[incoming_mac] = True example_mac = 'a:b:c:d' if example_mac in macs: mac_is_firewalled = macs[example_mac] If you really wanted to go with a class (for the exercise or because of wider requirements) you could do something like this: class Firewalled: def __init__ (self): self.macs = {} def addDevice (address): self.macs[address] = True def removeDevice (address): del self.macs[address] def isFirewalled (address): return address in self.macs # or return self.macs.get (address, False) but as you can see, in this form you're just wrapping Python with Python. > Sorry for the sloppy code so far, I'm really new to Python so it's a steep > learning curve for me, I'm by no means a programming numpty and allot of the > principles are the same, but the languages I'm used to are more robust and > vague so I don't have to define what type of data i'm storing the array and > things. Ummm... in Python you don't have to define what type of data you're storing. Welcome to the language in any case: you'll find that people around here are generally quite friendly but if you want, you might try the tutor list where people are very used to dealing with newcomers: http://mail.python.org/mailman/listinfo/tutor TJG From gagsl-py2 at yahoo.com.ar Thu Apr 12 06:16:48 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 12 Apr 2007 07:16:48 -0300 Subject: redirecting stdout to a file as well as screen References: <1176362072.527678.201150@l77g2000hsb.googlegroups.com> <1176368478.301318.35210@q75g2000hsh.googlegroups.com> Message-ID: En Thu, 12 Apr 2007 06:01:18 -0300, SamG escribi?: > On Apr 12, 1:00 pm, "Gabriel Genellina" > wrote: >> En Thu, 12 Apr 2007 04:14:32 -0300, SamG escribi?: >> >> > How could i make, from inside the program, to have the stdout and >> > stderr to be printed both to a file as well the terminal(as usual). >> >> class Tee(file): >> others = () >> >> def write(self, data): >> file.write(self, data) >> for f in others: >> f.write(data) >> > > This is only creating an out.log file and all the stdout and stderr > are logged there. Sorry, `for f in others:` should read `for f in self.others:` -- Gabriel Genellina From bcb at undisclosedlocation.net Tue Apr 17 22:29:11 2007 From: bcb at undisclosedlocation.net (Bruce C. Baker) Date: Tue, 17 Apr 2007 21:29:11 -0500 Subject: is laziness a programer's virtue? References: <1176757271.282365.319740@n76g2000hsh.googlegroups.com> <1176797558.403629.53140@b75g2000hsg.googlegroups.com> <1176823224.099381.4630@n59g2000hsh.googlegroups.com> Message-ID: "Lew" wrote in message news:eZedncJsovLSw7jbnZ2dnUVZ_r7inZ2d at comcast.com... > Markus E Leypold >>> Trying to correct Xah's behaviour is probably impossible. > > Ingo Menger wrote: >> Perhaps somebody could ask the chinese government to put him in jail >> for "hurting international society" :) > > Y'know, even in jest, calling for an oppressive regime to suppress even > wrong-headed and self-serving garbage self-expression is immoral and > horrible. How dare you? > > Free speech, free press and free expression of ideas is not something to > take so lightly. That's right! Momma don't allow no levity around here! Off with Markus' head! :-D > > -- > Lew From dickinsm at gmail.com Sun Apr 15 12:26:03 2007 From: dickinsm at gmail.com (Mark Dickinson) Date: 15 Apr 2007 09:26:03 -0700 Subject: combination function in python In-Reply-To: References: <1176615838.830315.160210@b75g2000hsg.googlegroups.com> <1176629911.409257.149780@l77g2000hsb.googlegroups.com> Message-ID: <1176654363.696340.283330@d57g2000hsg.googlegroups.com> On Apr 15, 8:37 am, Jussi Piitulainen wrote: > def choose(n, k): > if 0 <= k <= n: > ntok = 1 > ktok = 1 > for t in xrange(1, min(k, n - k) + 1): > ntok *= n > ktok *= t > n -= 1 > return ntok // ktok > else: > return 0 It might be even better to do the divisions as you go, rather than leaving them all to the end. That way the intermediate results stay smaller. So (leaving out the bounds checking) one just does: def choose(n, k): ntok = 1 for t in xrange(min(k, n-k)): ntok = ntok*(n-t)//(t+1) return ntok Mark From steve at holdenweb.com Wed Apr 4 13:55:11 2007 From: steve at holdenweb.com (Steve Holden) Date: Wed, 04 Apr 2007 13:55:11 -0400 Subject: try... except SyntaxError: unexpected EOF while parsing In-Reply-To: <1175708304.034078.139020@e65g2000hsc.googlegroups.com> References: <1175708304.034078.139020@e65g2000hsc.googlegroups.com> Message-ID: oscartheduck wrote: > I have a small script for doing some ssh stuff for me. I could have > written it as shell script, but wanted to improve my python skills > some. > > RIght now, I'm not catching a syntax error as I'd like to. > > Here's my code: > > #!/usr/bin/env python > import sys > import os > > port = input("Please enter a port to connect on. If you're unsure or > just want the default of port 2024 just hit enter -- ") > > > try: > if port > 65535: > print "That's not a valid port number, sorry. Between 0 and 65535 > is cool." > sys.exit() > else: > cmd = 'su root -c "/usr/sbin/sshd -p %s"' % port > except SyntaxError: > cmd = 'su root -c "/usr/sbin/sshd -p 2024;exit"' > > os.system(cmd) > > > I'm under the impression that the except should catch the syntax error > and execute the "default" command, but hitting enter at the input > value doesn't lead to that. Any ideas what's going wrong? > Yes. SyntaxError is raised when the interpreter is compiling the Python into byetcodes ready for execution. This *can* happen at run time, but usually it's when you are importing a module and so it gets transmogrified into an ImportError, though you can trigger it with, for example, eval: >>> eval("print < m s q") Traceback (most recent call last): File "", line 1, in File "", line 1 print < m s q ^ SyntaxError: invalid syntax >>> However, if you run your program and give it an invalid port number surely the resulting traceback would *tell* you what exception you need to trap if you used a %d substituion rather than a %s. Since pretty much anything is valid for a %s substitution the problem is that you will be calling os.system() on a command with a non-numeric port number and not catching the resulting exception. Using input(), by the way, is a recipe for disaster with non-trustworthy users. I'd much prefer to use raw_input() and convert explicitly to integer. The easiest way to proceed would then be to perform sensible error checking on the port number before proceeding: port = raw_input("Port # (enter for 2204 default: ") if port == "": port = 2204 try: port = int(port) except ValueError: raise ValueError("Port number must be numeric") or something like that. Really you should be in a loop which terminated when you get an acceptable port number. 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 bvukov at teletrader.com Tue Apr 17 16:47:47 2007 From: bvukov at teletrader.com (bvukov at teletrader.com) Date: 17 Apr 2007 13:47:47 -0700 Subject: Binary file output using python In-Reply-To: References: <1176833258.851804.63740@p77g2000hsh.googlegroups.com> Message-ID: <1176842867.830521.28550@n76g2000hsh.googlegroups.com> On Apr 17, 10:30 pm, Thomas Dybdahl Ahle wrote: > Den Tue, 17 Apr 2007 11:07:38 -0700 skrev kyosohma: > > > On Apr 17, 12:41 pm, Chi Yin Cheung wrote: > >> Hi, > >> Is there a way in python to output binary files? I need to python to > >> write out a stream of 5 million floating point numbers, separated by > >> some separator, but it seems that all python supports natively is > >> string information output, which is extremely space inefficient. > > I don't understand. To me it seams like there is no space difference: > > [thomas at localhost ~]$ python > Python 2.4.4 (#1, Oct 23 2006, 13:58:00) > [GCC 4.1.1 20061011 (Red Hat 4.1.1-30)] on linux2 > Type "help", "copyright", "credits" or "license" for more information.>>> f = open("test2", "w") > >>> f.write(str(range(10**7))) > >>> f.close() > >>> f = open("test", "wb") > >>> f.write(str(range(10**7))) > >>> f.close() > > [thomas at localhost ~]$ ls -l test test2 > -rw-rw-r-- 1 thomas thomas 88888890 17 apr 22:28 test > -rw-rw-r-- 1 thomas thomas 88888890 17 apr 22:27 test2 > [thomas at localhost ~]$ That's OK, but he might also take a look at the 'struct' module which can solve the "stream of 5 million floating point numbers, separated by some separator" part of the issue ( if binary format is needed ). From the python docs... >>> from struct import * >>> pack('hhl', 1, 2, 3) '\x00\x01\x00\x02\x00\x00\x00\x03' >>> unpack('hhl', '\x00\x01\x00\x02\x00\x00\x00\x03') (1, 2, 3) >>> calcsize('hhl') 8 From duncan.booth at invalid.invalid Thu Apr 12 07:04:33 2007 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 12 Apr 2007 11:04:33 GMT Subject: Calling private base methods References: <1176374675.347453.89340@n76g2000hsh.googlegroups.com> Message-ID: "7stud" wrote: > On Apr 12, 2:47 am, "Jorgen Bodde" wrote: >> Is it possible to call a private base method? I come from a C++ >> background, and I liked this construction as my base class has helper >> methods so that I do not have to duplicate code. >> > > I'd like to see some C++ code that does that! > > Easy: #define private public #include #undef private then call the private methods as much as you want. From randomgeek at cyberspace.net Sun Apr 15 14:22:46 2007 From: randomgeek at cyberspace.net (Dan Bensen) Date: Sun, 15 Apr 2007 13:22:46 -0500 Subject: is laziness a programer's virtue? In-Reply-To: <1176654319.273907.167280@q75g2000hsh.googlegroups.com> References: <1176654319.273907.167280@q75g2000hsh.googlegroups.com> Message-ID: Xah Lee wrote: > Laziness, Perl, and Larry Wall > When the sorcerer Larry Wall said ?The three chief virtues of a > programmer are: Laziness, Impatience and Hubris?, he used the word > ?laziness? to loosely imply ?natural disposition that results in being > economic?. Programming by definition is the process of automating repetitive actions to reduce the human effort required to perform them. A good programmer faced with a hard problem always looks for ways to make his|her job easier by delegating work to a computer. That's what Larry means. Automation is MUCH more effective than repetition. -- Dan www.prairienet.org/~dsb/ From steve at holdenweb.com Tue Apr 17 11:17:37 2007 From: steve at holdenweb.com (Steve Holden) Date: Tue, 17 Apr 2007 11:17:37 -0400 Subject: rewrite for achieving speedup In-Reply-To: <1176821334.217154.36350@y80g2000hsf.googlegroups.com> References: <1176821334.217154.36350@y80g2000hsf.googlegroups.com> Message-ID: Johnny Blonde wrote: > Hello Group! > > I really tried hard for two hours to rewrite the following expression > (python 2.4): > -------------------------- > teilnehmer = [] > for r in Reisen.select(AND(Reisen.q.RESVON <= datum, Reisen.q.RESBIS >> = datum)): > for g in r.BUCHUNGEN: > for t in g.aktiveTeilnehmer: > teilnehmer.append(t) > -------------------------- > > to something like > -------------------------- > teilnehmer = [x for x in ........] > -------------------------- > > Reisen is a SQLObject class, Reisen.select(...), aktiveTeilnehmer and > BUCHUNGEN all are of the type SelectResults. > > unfortunately i just can?t figure it out to make it work. > i hope someone maybe can help me? > > I hope to gain performance by rewriting it... > > Thanks a lot for your help! > >>> lt = [[[1,2,3], [2,3,4]], [[3,4,5], [4,5,6]]] >>> lf = [c for a in lt for b in a for c in b] >>> lf [1, 2, 3, 2, 3, 4, 3, 4, 5, 4, 5, 6] >>> Untested: teilnehmer = [t for r in Reisen.select(AND(Reisen.q.RESVON <= datum, reisen.q.RESBIS >= datum)) for g in r.BUCHUNGEN for t in g.aktiveTeilnehmer] 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 bjourne at gmail.com Tue Apr 10 13:21:37 2007 From: bjourne at gmail.com (=?ISO-8859-1?Q?BJ=F6rn_Lindqvist?=) Date: Tue, 10 Apr 2007 19:21:37 +0200 Subject: tuples, index method, Python's design In-Reply-To: <1176219856.3430.76.camel@dot.uniqsys.com> References: <1175867771.114540.61810@n76g2000hsh.googlegroups.com> <1175884427.779950.267220@y80g2000hsf.googlegroups.com> <1176210960.3430.20.camel@dot.uniqsys.com> <740c3aec0704100810g5f962e8eu614fbaedecf3608e@mail.gmail.com> <1176219856.3430.76.camel@dot.uniqsys.com> Message-ID: <740c3aec0704101021i1fd79ef2l99eac4ced1e252d9@mail.gmail.com> On 4/10/07, Carsten Haese wrote: > > > opponents = tuple(x for x in p if x is not current_player) > > > > > Your alternative is wrong because it wont raise ValueError if > > current_player is not present in the tuple. Please revise your > > "solution." > > You have a point. Here is my revised solution: > > assert current_player in p > opponents = tuple(x for x in p if x is not current_player) > > The added advantage is that AssertionError is better than IndexError for > conveying that a severe program bug has occurred. Assertions are not checked when you run scripts with -O. Furthermore, changing the exception type and the message it produces, is quite a big deviation from list.index. -- mvh Bj?rn From jstroud at mbi.ucla.edu Sun Apr 15 17:15:15 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Sun, 15 Apr 2007 21:15:15 GMT Subject: is laziness a programer's virtue? In-Reply-To: <1176654319.273907.167280@q75g2000hsh.googlegroups.com> References: <1176654319.273907.167280@q75g2000hsh.googlegroups.com> Message-ID: Xah Lee wrote: > Laziness, Perl, and Larry Wall > > Xah Lee, 20021124 > > In the unix community there's quite a large confusion and wishful > thinking about the word laziness. In this post, i'd like to make some > clarifications. > > American Heritage Dictionary third edition defines laziness as: > ?Resistant to work or exertion; disposed to idleness.? > > When the sorcerer Larry Wall said ?The three chief virtues of a > programmer are: Laziness, Impatience and Hubris?, he used the word > ?laziness? to loosely imply ?natural disposition that results in being > economic?. As you can see now, ?Resistant to work or exertion? is > clearly not positive and not a virtue, but ?natural disposition that > results in economy? is a good thing if true. > > When Larry Wall said one of programer's virtue is laziness, he wants > the unix morons to conjure up in their brains the following > proposition as true: ?Resistant to work or exertion is a natural human > disposition and such disposition actually results behaviors being > economic?. This statement may be true, which means that human laziness > may be intuitively understood from evolution. However, this statement > is a proposition on all human beings, and is not some ?virtue? that > can be applied to a group of people such as programers. > > Demagogue Larry Wall is smart in creating a confusion combined with > wishful thinking. By making subtle statements like this, he semi- > intentionally confuses average programers to think that it is OK to be > not thorough, it is OK to be sloppy, it is OK to disparage computer > science. (like the incompetent unixers and perlers are) > > Can you see the evil and its harm in not understanding things clearly? > This laziness quote by Wall is a tremendous damage to the computing > industry. It is a source among others that spurs much bad fashion > trends and fuckups in the industry. It is more damaging than any > single hack or virus. It is social brain-washing at work, like the > diamond company De Beers' tremendously successful sales slogan: ?A > Diamond is Forever? or Apple's grammatically fantastic ?Think > Different?. > > The most fundamental explanation of why Larry Wall's sophistry are > damaging to society is simply this: What he said is not true and they > are widely spread and conceived as worthwhile. This is a form of mis- > information. This is a manifestation of Love without Knowledge as i > expounded before, with subtle but disastrous consequences (already). > > [DISCLAIMER: all mentions of real persons are opinion only.] > > ---- > This post is archived at: > http://xahlee.org/UnixResource_dir/writ/perl_laziness.html > > Xah > xah at xahlee.org > ? http://xahlee.org/ > Laziness is re-posting something dated 2002. From timr at probo.com Tue Apr 17 02:13:27 2007 From: timr at probo.com (Tim Roberts) Date: Tue, 17 Apr 2007 06:13:27 GMT Subject: Python Feature Request: Allow changing base of member indices to 1 References: <1176546465.632410.52630@w1g2000hsg.googlegroups.com> <4620b47b$0$14410$9b622d9e@news.freenet.de> <1176557999.665663.299740@y80g2000hsf.googlegroups.com> <1176559643.450533.296850@n59g2000hsh.googlegroups.com> <1176671300.119131.297370@n76g2000hsh.googlegroups.com> Message-ID: <1bp823d6qrh27gko3rticht2btlq2u2cl7@4ax.com> "Beliavsky" wrote: > >Fortran has allowed a user-specified base since at least the 1977 >standard -- see for example http://www.umiacs.umd.edu/~jhu/DOCS/SP/docs/essl/essl159.html >. You can strike "at least"; this extension was introduced in FORTRAN 77. FORTRAN 66 didn't do this. -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From gene.tani at gmail.com Sun Apr 8 10:31:24 2007 From: gene.tani at gmail.com (gene tani) Date: 8 Apr 2007 07:31:24 -0700 Subject: Custom Python Runtime In-Reply-To: <2NudnVn5jsm2QIvbnZ2dnUVZ_vqpnZ2d@comcast.com> References: <2NudnVn5jsm2QIvbnZ2dnUVZ_vqpnZ2d@comcast.com> Message-ID: <1176042684.546382.252250@o5g2000hsb.googlegroups.com> On Apr 6, 4:52 pm, "Jack" wrote: > Since the full installation of Python (from either the standard installer or > ActiveState installer) is too big for my intended use, I'd like to build a > custom distribution of Python for Windows platform, omitting some lib files, > such as audio, tk, printing, testing units, etc. > > Is there a way to customize the Windows build? In my case, there is no need > to build an installer. The best way is to have everything in a directory, as > long as I know where to find Python and Python knows where to find the > necessary libs. Any online docs describing this? Thanks! did you look at Diet Python: http://sourceforge.net/projects/dietpython From mensanator at aol.com Wed Apr 18 13:07:37 2007 From: mensanator at aol.com (mensanator at aol.com) Date: 18 Apr 2007 10:07:37 -0700 Subject: What makes an iterator an iterator? In-Reply-To: <1176910585.108044.116540@y80g2000hsf.googlegroups.com> References: <1176910585.108044.116540@y80g2000hsf.googlegroups.com> Message-ID: <1176916057.470442.307530@n59g2000hsh.googlegroups.com> On Apr 18, 10:36 am, bog... at comcast.net wrote: > > I find myself perplexed as to this behaviour. > > You can not iterate over a dead object! It's not dead, it's restin'. All shagged out over a long squak. From apardon at forel.vub.ac.be Mon Apr 23 04:18:56 2007 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 23 Apr 2007 08:18:56 GMT Subject: Dictionaries and dot notation References: <23087554.X5dcTmlj7P@beaureve.gmx.net> <462b842e$0$28548$426a74cc@news.free.fr> <2424549.70D5anvh5e@beaureve.gmx.net> Message-ID: On 2007-04-22, Martin Drautzburg wrote: > Daniel Nogradi wrote: > > >>> > What if I want to create a datastructure that can be used in dot >>> > notation without having to create a class, i.e. because those >>> > objects have no behavior at all? >>> >>> A class inheriting from dict and implementing __getattr__ and >>> __setattr__ should do the trick... >> >> >> It can do the trick but one has to be careful with attributes that are >> used by dict such as update, keys, pop, etc. Actually it's noted in a >> comment at >> http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/361668 why the >> whole idea (attribute access of dictionaries) is a bad idea and I tend >> to agree. > > Oh thank you. So all I have to do is have my object's class implement > __setattr__ and __getattr__, or derive it from a class that does so? > And I could save my "attributes" anywhere within my instance variables. > So I could even add a dictionary whose name does not conflict with what > python uses and whose key/value pairs hold the attributes I want to > access with dot notation and delegate all the python attributes to > their native positions? Oh I see, thats tricky. I still need to be > aware of the builtin stuff one way or the other. Maybe you can do the opposite and create a class that implements __getitem__ and __setitem__ in function of attribute access. The following is an example: class Rec(object): def __init__(__, **kwargs): for key,value in kwargs.items(): setattr(__, key, value) def __getitem__(self, key): return getattr(self, key) def __setitem__ (self, key, val): setattr(self, key, val) rec = Rec(a=1) print rec.a print rec["a"] rec.b = 2 print rec["b"] rec["c"] = 3 print rec.c -- Antoon Pardon From carsten at uniqsys.com Sun Apr 15 02:49:18 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Sun, 15 Apr 2007 02:49:18 -0400 Subject: proposed PEP: iterator splicing In-Reply-To: <7xirbyi5d7.fsf_-_@ruckus.brouhaha.com> References: <7xirbyi5d7.fsf_-_@ruckus.brouhaha.com> Message-ID: <20070415062021.M46534@uniqsys.com> On 14 Apr 2007 22:17:08 -0700, Paul Rubin wrote > The boilerplate > > def some_gen(): > ... > for x in some_other_gen(): > yield x > ... > > is so common (including the case where some_other_gen is the same as > some_gen, i.e. it's a recursive call) that I find myself wanting > a more direct way to express it: > > def some_gen(): > ... > yield *some_other_gen() > > comes to mind. Less clutter, and avoids yet another temp variable > polluting the namespace. > > Thoughts? Explicit is better than implicit. The explicit boilerplate code is more readable and tells the reader exactly what's going on. Since the namespace is the local namespace of your generator function, the namespace pollution is minimal. -Carsten From sickcodemonkey at gmail.com Thu Apr 5 16:07:42 2007 From: sickcodemonkey at gmail.com (Sick Monkey) Date: Thu, 5 Apr 2007 16:07:42 -0400 Subject: Looping issues In-Reply-To: <1175796069.501575.157410@w1g2000hsg.googlegroups.com> References: <1175796069.501575.157410@w1g2000hsg.googlegroups.com> Message-ID: <2adc542f0704051307x5d9fd992ofec5ad4b66358250@mail.gmail.com> Try this. NOTE: The script below will compare lines of both files (even hidden characters such as \n)... ################################################################ def fopen(fname): try: return open(fname, 'U') except IOError, detail: return fail("couldn't open " + fname + ": " + str(detail)) ################################################################ f1 = fopen('file1.txt') a = f1.readlines(); f1.close() d1 = {} for c in a: d1[c.lower()] = None #print d1 f2 = fopen('file2.txt') data = f2.readlines(); f2.close() for line in data: if d1.has_key( line ): print line ################################################################ wdh On 5 Apr 2007 11:01:09 -0700, brochu121 at gmail.com wrote: > > What I am trying to do is compare two files to each other. > > If the 2nd file contains the same line the first file contains, I want > to print it. I wrote up the following code: > > > > correct_settings = open("C:\Python25\Scripts\Output > \correct_settings.txt","r") > current_settings = open("C:\Python25\Scripts\Output\output.txt","r") > > for line in correct_settings: > for val in current_settings: > if val == line: > print line + " found." > > > correct_settings.close() > current_settings.close() > > > For some reason this only looks at the first line of the > correct_settings.txt file. Any ideas as to how i can loop through each > line of the correct_settings file instead of just looking at the first? > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From tkpmep at hotmail.com Wed Apr 4 11:58:49 2007 From: tkpmep at hotmail.com (tkpmep at hotmail.com) Date: 4 Apr 2007 08:58:49 -0700 Subject: Indentifying the LAST occurrence of an item in a list Message-ID: <1175702329.330032.250750@w1g2000hsg.googlegroups.com> For any list x, x.index(item) returns the index of the FIRST occurrence of the item in x. Is there a simple way to identify the LAST occurrence of an item in a list? My solution feels complex - reverse the list, look for the first occurence of the item in the reversed list, and then subtract its index from the length of the list - 1, i.e. LastOcc = len(x) - 1 - x[::-1].index(item) Is there a simpler solution? Thanks in advance Thomas Philips From uzi18 at o2.pl Sat Apr 28 09:37:17 2007 From: uzi18 at o2.pl (Bart) Date: Sat, 28 Apr 2007 15:37:17 +0200 Subject: python function in pipe Message-ID: <46334E0D.2000605@o2.pl> Hi everyone! Im using module that gives errors to stderr/stdout (generated by SWIG) Problem is that I need to parse this errors/information from module. os.popen3 looks nice but this executes command not function. Is there any solution? Best regards Bart. From mail at timgolden.me.uk Mon Apr 30 07:55:45 2007 From: mail at timgolden.me.uk (Tim Golden) Date: Mon, 30 Apr 2007 12:55:45 +0100 Subject: Importing a csv file In-Reply-To: <1177933040.032953.278860@o5g2000hsb.googlegroups.com> References: <1177923524.747364.182460@h2g2000hsg.googlegroups.com> <1177933040.032953.278860@o5g2000hsb.googlegroups.com> Message-ID: <4635D941.2070605@timgolden.me.uk> John Machin wrote: > On Apr 30, 7:21 pm, Tim Golden wrote: >> sagar wrote: >>> Hi all , >>> I want to read data in a csv file using the python scripts. >>> when i gave the following code : >>> import csv >>> reader = csv.reader(open("some.csv", "rb")) >>> for row in reader: >>> print row >>> it is showing : >>> Traceback (most recent call last): >>> File "csv.py", line 1, in >>> import csv >>> File "C:\Documents and Settings\meesa02\csv.py", line 2, in > > Only *almost* certainly, Tim? *Maybe*? You don't believe what the > above traceback lines are telling you? It's my natural British diffidence :) We almost never make unqualified statements. TJG From arkanes at gmail.com Thu Apr 12 16:00:27 2007 From: arkanes at gmail.com (Chris Mellon) Date: Thu, 12 Apr 2007 15:00:27 -0500 Subject: tuples, index method, Python's design In-Reply-To: References: Message-ID: <4866bea60704121300r3f00993bte4b3fde4a9ef3a01@mail.gmail.com> On 4/12/07, Alan Isaac wrote: > I am still puzzled by this discussion. > > As I said: > I doubt that *anyone* who programs in Python > has not encountered the situation where they change > a tuple to a list *solely* for the purpose of getting > access to the index method. This suggests a missing > method, does it not? Who has not done this? > Name yourself! > Sure. I have never done this. In fact, I have only ever written code that converted a tuple to a list once, and it was because I wanted pop(), not index() - I had a varargs argument that iterated over it's argument list and need to know how many arguments it had consumed, and how many were left, in order to correctly process the current argument. Using a list was (very) slightly more convenient for this than counting. Note that because I needed to preserve the original argument to compare against, *args being a list wouldn't have changed the way I wrote it even if it was technically feasible to implement it as one. > There is simply no conflict between the index method and immutability, > but at the moment one is forced to choose. Why? Nobody has > offered a real explanation of this. > There have been many. The answer is, in the cases where you need immutability, you don't need index, because an immutable structure is either unordered, so index doesn't matter, or ordered, and the order is then part of the structure. > I offered a simple use case. Consider a game, > where the *fixed* set p of players have a *fixed* order. > A tuple is natural. Now for a player you want to > construct the opponents. If I had the index i it wd > be p[:i]+p[i+1:], but how to get the index? > I would never use a tuple for this case, I would use a list. And even using the list, I wouldn't use index() to find the current player. I'd get the other players via a list comp (as shown previously in the thread) or I'd be iterating through the player list and I'd already have the other players. I find the solution you posted to be poor and if tuple not having index() has *no other effect* than to discourage the writing of code in this style I'd consider the decision justified. Depending on the exact game play, almost any data structure *except* a tuple would be a better solution. > Other use cases have also been offered on this thread. I, for one, have found none of them compelling and have said why I don't find them compelling. There is one which I think is reasonable. Manually searching the tuple or conversion to a list addresses that use case, which I don't expect to be common. > What is the basic response? "Do not worry about the > loss of immutability, just use a list." What kind of a > response is that?? This sounds to me like "I do not > really see the point of immutability", which is no > response at all. > How about "explain why you find immutability necessary in this context. If you can't explain it, then don't worry about". > Cheers, > Alan Isaac From ZhaoYingpu at gmail.com Tue Apr 17 00:24:30 2007 From: ZhaoYingpu at gmail.com (ZhaoYingpu at gmail.com) Date: 16 Apr 2007 21:24:30 -0700 Subject: How to Passs NULL as a IDispatch Pointer to method? Message-ID: <1176783870.081696.278100@l77g2000hsb.googlegroups.com> Hello,all I am using win32com to use com. and invoke a method as follows: void AddShapeInfo(LPCTSTR name, LONG type, IDispatch* pDisp); but i pass 0 or None to third parameter and get error info: >>> x.AddShapeInfo("who", 10, 0) Traceback (most recent call last): File "", line 1, in x.AddShapeInfo("who", 10, 0) File "", line 2, in AddShapeInfo com_error: (-2147352571, 'Type mismatch.', None, 3) or >>> x.AddShapeInfo("who",0,None) Traceback (most recent call last): File "", line 1, in x.AddShapeInfo("who",0,None) File "", line 2, in AddShapeInfo com_error: (-2147352571, 'Type mismatch.', None, 3) From gandalf at designaproduct.biz Thu Apr 5 12:00:52 2007 From: gandalf at designaproduct.biz (Laszlo Nagy) Date: Thu, 05 Apr 2007 18:00:52 +0200 Subject: Windows service and pyc files In-Reply-To: <1175709094.352514.64920@y66g2000hsf.googlegroups.com> References: <1175709094.352514.64920@y66g2000hsf.googlegroups.com> Message-ID: <46151D34.50608@designaproduct.biz> > > Have you tried the subprocess module for this rather than os.system? > You might be able to pipe errors to a file with it. You might be able > to use the traceback module for more verbose error catching too. > Okay, I'm tried this instead of os.system: def dumpexc(e): import sys,traceback,StringIO f = StringIO.StringIO('') ei = sys.exc_info() traceback.print_exception(ei[0],ei[1],ei[2],file=f) return f.getvalue() def spawn(): # ... setup mydir here.... os.chdir(mydir) prog = os.path.join(mydir,"Application.py") params = [sys.executable,prog] logger.info("Spawing %s",str(params)) fout = file(os.path.join(mydir,'errorlog.txt'),'wb+') try: p = subprocess.Popen(params, bufsize=1, stdout=fout.fileno(), stderr=fout.fileno()) except Exception, e: logger.error(dumpexc(e)) return -1 retcode = p.wait() logger.info("Subprocess exited, return code: %d",retcode) fout.close() return retcode When I call spawn() from a service, this is written into the logfile: 2007-04-05 17:52:53,828 INFO .Spawner Spawing ['C:\\Python25\\lib\\site-packages\\win32\\PythonService.exe', 'T:\\Python\\Projects\\Test\\Application.py'] 2007-04-05 17:52:53,828 ERROR .Spawner Traceback (most recent call last): File "T:\Python\Projects\Test\Processor.py", line 40, in spawn_downloader p = subprocess.Popen(params, bufsize=1, stdout=fout.fileno(), stderr=fout.fileno()) File "C:\Python25\lib\subprocess.py", line 586, in __init__ errread, errwrite) = self._get_handles(stdin, stdout, stderr) File "C:\Python25\lib\subprocess.py", line 681, in _get_handles p2cread = self._make_inheritable(p2cread) File "C:\Python25\lib\subprocess.py", line 722, in _make_inheritable DUPLICATE_SAME_ACCESS) TypeError: an integer is required errorlog.txt is - of course - becomes an empty file. When I call spawn() from an application, it works just fine. Any ideas? Thanks, Laszlo From steve at REMOVE.THIS.cybersource.com.au Mon Apr 9 09:03:06 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Mon, 09 Apr 2007 23:03:06 +1000 Subject: tuples are useless??? References: Message-ID: On Sun, 08 Apr 2007 22:20:45 -0700, James Stroud wrote: > Steven D'Aprano wrote: >> On Mon, 09 Apr 2007 02:26:37 +0000, James Stroud wrote: >> >>> Bart Willems wrote: >>>> James Stroud wrote: >>>>> ... It boils down to the fact that tuples are useless as a result >>>>> unless you know you really need them--and you never really NEED them. >>>> Could you clarify that for me? I use tuples *a lot* and I really *NEED* >>>> them - I'm building a lot of multi-tier reports where detail-level data >>>> is pulled out of a dictionary based on a composed key. It is impossible >>>> to build those dictionaries *without* using tuples. >>> >>> "Impossible" is a strong word, as is "need" (especially when in all caps). >>> >>> py> import md5 >>> py> class HashedList(list): >>> ... def __hash__(self): >>> ... h = md5.new() >>> ... for item in self: >>> ... h.update(str(hash(item))) >>> ... return int(h.hexdigest(), 16) >>> ... >>> py> hl = HashedList('bob', 'carol', 'ted') >>> py> {hl:3} >>> {['bob', 'carol', 'ted']: 3} >>> >>> Impossible? I wouldn't even say that this was all that difficult. >> >> Possible, if by possible you mean "broken". >> >> >>>>> D = {hl: 3} >>>>> D >> {['bob', 'carol', 'ted']: 3} >>>>> hl[0] = 'Bob' >>>>> D >> {['Bob', 'carol', 'ted']: 3} >>>>> D.keys()[0] is hl >> True >>>>> D[hl] >> Traceback (most recent call last): >> File "", line 1, in >> KeyError: ['Bob', 'carol', 'ted'] >> >> > > def __setitem__(self, *args): > raise TypeError, '%s doesn't support item assignment.' % > self.__class__.__name__ > > > Problem fixed. Next? hl.reverse() hl.sort() # if the list isn't already sorted del hl[0] hl.append() etc. Yes, you can block those as well... but by the time you've finished making your HashedList immutable, it is just a slower tuple with a different name. In other words... you can avoid using tuples by using a tuple with a different name. You might as well just do this: HashedList = tuple -- Steven. From steven.bethard at gmail.com Thu Apr 5 19:09:43 2007 From: steven.bethard at gmail.com (Steven Bethard) Date: Thu, 05 Apr 2007 17:09:43 -0600 Subject: RFC: Assignment as expression (pre-PEP) In-Reply-To: References: <1175802680.021987.39220@p77g2000hsh.googlegroups.com> <1175807326.466842.219820@p77g2000hsh.googlegroups.com> Message-ID: Steven Bethard wrote: > darklord at timehorse.com wrote: >> On Apr 5, 4:22 pm, Duncan Booth wrote: >>> Can you come up with a real example where this happens and which >>> cannot be >>> easily rewritten to provide better, clearer code without the >>> indentation? >>> >>> I'll admit to having occasionally had code not entirely dissimilar to >>> this >>> when first written, but I don't believe it has ever survived more than a >>> few minutes before being refactored into a cleaner form. I would >>> claim that >>> it is a good thing that Python makes it obvious that code like this >>> should >>> be refactored. >> >> I am trying to write a parser for a text string. Specifically, I am >> trying to take a filename that contains meta-data about the content of >> the A/V file (mpg, mp3, etc.). >> >> I first split the filename into fields separated by spaces and dots. >> >> Then I have a series of regular expression matches. I like >> Cartesian's 'event-based' parser approach though the even table gets a >> bit unwieldy as it grows. Also, I would prefer to have the 'action' >> result in a variable assignment specific to the test. E.g. >> >> def parseName(name): >> fields = sd.split(name) >> fields, ext = fields[:-1], fields[-1] >> year = '' >> capper = '' >> series = None >> episodeNum = None >> programme = '' >> episodeName = '' >> past_title = false >> for f in fields: >> if year_re.match(f): >> year = f >> past_title = True >> else: >> my_match = capper_re.match(f): >> if my_match: >> capper = capper_re.match(f).group(1) >> if capper == 'JJ' or capper == 'JeffreyJacobs': >> capper = 'Jeffrey C. Jacobs' >> past_title = True >> else: >> my_match = epnum_re.match(f): >> if my_match: >> series, episodeNum = my_match.group('series', >> 'episode') >> past_title = True >> else: >> # If I think of other parse elements, they go >> here. >> # Otherwise, name is part of a title; check for >> capitalization >> if f[0] >= 'a' and f[0] <= 'z' and f not in >> do_not_capitalize: >> f = f.capitalize() >> if past_title: >> if episodeName: episodeName += ' ' >> episodeName += f >> else: >> if programme: programme += ' ' >> programme += f >> >> return programme, series, episodeName, episodeNum, year, capper, >> ext > > Why can't you combine your regular expressions into a single expression, > e.g. something like:: > > >>> exp = r''' > ... (?P\d{4}) > ... | > ... by\[(?P.*)\] > ... | > ... S(?P\d\d)E(?P\d\d) > ... ''' > >>> matcher = re.compile(exp, re.VERBOSE) > >>> matcher.match('1990').groupdict() > {'series': None, 'capper': None, 'episode': None, 'year': '1990'} > >>> matcher.match('by[Jovev]').groupdict() > {'series': None, 'capper': 'Jovev', 'episode': None, 'year': None} > >>> matcher.match('S01E12').groupdict() > {'series': '01', 'capper': None, 'episode': '12', 'year': None} > > Then your code above would look something like:: > > for f in fields: > match = matcher.match(f) > if match is not None: > year = match.group('year') > capper = match.group('capper') > if capper == 'JJ' or capper == 'JeffreyJacobs': > capper = 'Jeffrey C. Jacobs' > series = match.group('series') > episodeNum = match.group('episode') > past_title = True I guess you need to be a little more careful here not to overwrite your old values, e.g. something like:: year = match.group('year') or year capper = match.group('capper') or capper ... STeVe From gtcopeland at gmail.com Tue Apr 17 14:19:44 2007 From: gtcopeland at gmail.com (Greg Copeland) Date: 17 Apr 2007 11:19:44 -0700 Subject: setup.py bdist_rpm help Message-ID: <1176833983.998563.313930@l77g2000hsb.googlegroups.com> Okay, I have an application which is frozen via pyinstaller. That is all working great. I now want to create an RPM using distutils' bdist_rpm facilities. I seem to be running into trouble. No matter what, I only seem to get three files within my RPM (setup.py, README.txt, and PKG_INFO). My application ('app') has a configuration file ('x.cfg') and a single directory ('data') which contains various data files used during runtime. Can someone show me an example setup.py which will create an RPM containing only the following: app, x.cfg, data/*? Please note that 'app' is the frozen application and not the normal python script (app.py). If it matters, I'm using Python 2.4.4 on Linux. Thanks! From ratchetgrid at googlemail.com Thu Apr 5 04:24:15 2007 From: ratchetgrid at googlemail.com (Nathan Harmston) Date: Thu, 5 Apr 2007 09:24:15 +0100 Subject: Requirements For A Visualization Software System For 2010 In-Reply-To: References: <1175628186.459945.290750@d57g2000hsg.googlegroups.com> <1175714617.095757.162510@y80g2000hsf.googlegroups.com> Message-ID: <676224240704050124me7c4a80yc02622d6cf21f0b2@mail.gmail.com> You could look at sage.....its all python! http://sage.scipy.org/sage/ I wish Xah Lee would stop trolling.....oh well Cheers Nathan -------------- next part -------------- An HTML attachment was scrubbed... URL: From XX.XmcX at XX.XmclaveauX.com Wed Apr 4 04:29:50 2007 From: XX.XmcX at XX.XmclaveauX.com (MC) Date: Wed, 04 Apr 2007 10:29:50 +0200 Subject: zip list with different length References: <1175673207.231212.28310@n76g2000hsh.googlegroups.com> Message-ID: Hi! Brutal, not exact answer, but: a = range(5) b = range(3) print zip(a+[None]*(len(b)-len(a)),b+[None]*(len(a)-len(b))) -- @-salutations Michel Claveau From pabloski at gmail.com Wed Apr 18 10:48:06 2007 From: pabloski at gmail.com (pabloski) Date: Wed, 18 Apr 2007 14:48:06 GMT Subject: pycurl problem Message-ID: Hi to all, I have a problem with a snippet of code that creates a Curl object the code is c = pycurl.Curl() c.key = keyCurrent c.proxy = proxyCurrent c.url = "http://www.google." + lg + "/search?hl=" + lg + "&q=" + c.key + "&meta=lr%3Dlang_" + lg + "&num=30" c.setopt(pycurl.URL, c.url) c.setopt(pycurl.PROXY, c.proxy) the last two lines raise a TypeError obviously proxyCurrent, lg and keyCurrent are parameters I noted that if I define c.proxy and c.url as costants e.g. c.url = "http://www.google.com/search?blah blah...." and c.proxy = "127.0.0.1:8080" it works However if I define them as described before pycurl raises the TypeError From mail at microcorp.co.za Wed Apr 18 00:50:17 2007 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Wed, 18 Apr 2007 06:50:17 +0200 Subject: Queue enhancement suggestion References: <7x4pngluel.fsf_-_@ruckus.brouhaha.com> Message-ID: <011e01c7817b$431727e0$03000080@hendrik> "Antoon Pardon" wrote: > The problem is that sometimes the gui thread has something to show > too. With the added problem that the code wanting to show something > doesn't know when it is executing the gui thread or an other. So > it is very difficult to avoid the gui thread putting things on the > queue. But since the gui thread is the single reader, it will dead > lock if the queue happens to be full at the moment the gui thread > want to add another item. This can happen - I suppose the cure is to have the GUI use a non blocking put in a try except checking for the full condition - its bad to block the GUI anyway because then the mouse and kbd become unresponsive. So even the reads (get) have to be non blocking, or the thing will behave like a disobedient dog, that knows what to do, but just refuses. - Hendrik From bdesth.quelquechose at free.quelquepart.fr Tue Apr 3 17:59:36 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Tue, 03 Apr 2007 23:59:36 +0200 Subject: How to check if OS is unix or pc In-Reply-To: <1175634724.398396.48720@y80g2000hsf.googlegroups.com> References: <1175634724.398396.48720@y80g2000hsf.googlegroups.com> Message-ID: <4612c563$0$1412$426a34cc@news.free.fr> bahoo a ?crit : > In Matlab, there is a "isunix" command. > Is there something similar in python? >>> import os >>> os.uname() ('Linux', 'bibi', '2.6.9', '#1 Sun Dec 5 14:54:12 CET 2004', 'i686') >>> os.name 'posix' >>> isunix = lambda: os.name == 'posix' >>> isunix() True Note that if you worry about system-specific path separators, there's the os.path module. From tjreedy at udel.edu Mon Apr 2 20:02:24 2007 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 2 Apr 2007 20:02:24 -0400 Subject: Submit patches for documentation References: Message-ID: "Kevin Walzer" wrote in message news:c18f7$46118350$4275d90a$4081 at FUSE.NET... | What's the best way to submit patches for Python documentation at the | SourceForge patch tracker if you are not writing LaTeX? I would like to | submit some simple text updates. However, if I do this, I'm not clear | what files I should run a diff against. | | Or is simply submitting the updates as a text file, with a note | indicating which documentation files they replace, sufficient? Identify the document, version (hopefully latest), and section. I have submitted informal 'diffs' like Typo: change psot to post Paragraph 3 is unclear. Suggest replacement with "qui ipsit locum....." tjr From gagsl-py2 at yahoo.com.ar Sun Apr 29 19:38:22 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sun, 29 Apr 2007 20:38:22 -0300 Subject: I can't inherit from "compiled" classes ? References: Message-ID: En Sun, 29 Apr 2007 17:27:59 -0300, Maxim Veksler escribi?: > On 4/29/07, Marc 'BlackJack' Rintsch wrote: >> > """ > from socket import socket > import select > > class PollingSocket(socket): > pass > """ > >> `select.select()` is a function: > > I understand what you are saying, and at the same time don't > understand why it doesn't work. Isn't "everything an object" in > python? And if something is an object does it not implies it's an > instance of some class? I'm not sure if your last statement is true now, and certainly it was not true before Python 2.2; there were objects that were not class instances (numbers, functions, by example). Maybe some objects still remain that are not instances of any class. Anyway, "an object" and "a class" are not the same thing, and you can't use an arbitrary object when you actually need a class. > Does this mean I can't somehow make this work: """class > PollingSocket(socket.socket, select):""" ? Those things inside () are called "base classes"; this is "class" inheritance; you create a new "class" inheriting from existing ones. That is, you cant inherit from select, because select is a function, not a class. -- Gabriel Genellina From s.mientki at id.umcn.nl Thu Apr 26 05:13:31 2007 From: s.mientki at id.umcn.nl (stef) Date: Thu, 26 Apr 2007 11:13:31 +0200 Subject: conditional print statement ? In-Reply-To: References: <2c923$462fb3e0$d443bb3a$18429@news.speedlinq.nl> Message-ID: Antoon Pardon wrote: > On 2007-04-25, Stef Mientki wrote: > >> hello, >> >> >> As part of a procedure I've a number sequences like this: >> >> >> if Print_Info: print Datafile.readline() >> else: Datafile.readline() >> >> >> Is there a more compressed way to write such a statement, >> especially I dislike the redundancy "Datafile.readline()". >> >> thanks, >> Stef Mientki >> > > You could consider the following > > def Print(arg): > print arg > > def Noop(arg): > pass > > (Print if Print_Info else Noop) (Datafile.readline()) > > thank you all for your answers, I'll play a little with the suggested solutions. cheers, Stef Mientki From s99999999s2003 at yahoo.com Wed Apr 4 03:53:27 2007 From: s99999999s2003 at yahoo.com (s99999999s2003 at yahoo.com) Date: 4 Apr 2007 00:53:27 -0700 Subject: zip list with different length Message-ID: <1175673207.231212.28310@n76g2000hsh.googlegroups.com> hi suppose i have 2 lists, a, b then have different number of elements, say len(a) = 5, len(b) = 3 >>> a = range(5) >>> b = range(3) >>> zip(b,a) [(0, 0), (1, 1), (2, 2)] >>> zip(a,b) [(0, 0), (1, 1), (2, 2)] I want the results to be [(0, 0), (1, 1), (2, 2) , (3) , (4) ] can it be done? thanks From paddy3118 at googlemail.com Sat Apr 14 23:12:56 2007 From: paddy3118 at googlemail.com (Paddy) Date: 14 Apr 2007 20:12:56 -0700 Subject: Python Feature Request: Allow changing base of member indices to 1 In-Reply-To: <1hwkok3.1kmipey1iv5ldzN%aleax@mac.com> References: <1176546465.632410.52630@w1g2000hsg.googlegroups.com> <1176579205.948684.171640@q75g2000hsh.googlegroups.com> <1176584444.335732.111740@n76g2000hsh.googlegroups.com> <1hwkok3.1kmipey1iv5ldzN%aleax@mac.com> Message-ID: <1176606776.016013.205170@p77g2000hsh.googlegroups.com> On Apr 15, 2:29 am, a... at mac.com (Alex Martelli) wrote: > Sherm Pendley wrote: > > "Paddy" writes: > > > > I don't think we should add it to Python > > > because it would make porting VB code easier. > > > Great Cthulhu no! > > > I chimed in because your first comment regarding Perl implied that it's > > commonplace for Perl programmers to fiddle with the index base. It can > > be done, for historical reasons, but it's far from common. > > Reminds me of APL's worst blunder -- "quadIO" (with IO standing for > Index Origin, NOT Input/Output) could be set to 0 or 1, with global > effect. I worked a lot with APL and mostly loved it (APL2 even more > so), and I'm saddened to read that the ACM wants to disband the APL SIG > for lack of activity (though no doubt it's a reasonable decision, it > badly tickles my nostalgia for years and decades gone) -- but the quadIO > design decision was a truly major design blunder, and made it hell to > integrate APL code from multiple sources. > > Alex So the running count is: Ayes to the left: VB compatibility. Nays to the right: QuadIO, Perl, Dijkstra paper. The nays have it! - Paddy. From attn.steven.kuo at gmail.com Sat Apr 28 12:58:59 2007 From: attn.steven.kuo at gmail.com (attn.steven.kuo at gmail.com) Date: 28 Apr 2007 09:58:59 -0700 Subject: python function in pipe In-Reply-To: References: Message-ID: <1177779539.094507.47080@h2g2000hsg.googlegroups.com> On Apr 28, 6:37 am, Bart wrote: > Hi everyone! > > Im using module that gives errors to stderr/stdout (generated by SWIG) > Problem is that I need to parse this errors/information from module. > > os.popen3 looks nice but this executes command not function. > > Is there any solution? > Perhaps you're looking for the unittest module? You can use assertRaises if an exception is raised by the function. You can also redirect sys.stderr and sys.stdout as needed and test the captured strings with assertEquals. Else you can wrap the module under test in another module: # mytest.py import module_under_test if __name__ == "__main__": module_under_test.foo() Then, using os.popen3 (or subprocess), run "python mytest.py" as your command. -- Hope this helps, Steven From xah at xahlee.org Mon Apr 16 17:01:11 2007 From: xah at xahlee.org (Xah Lee) Date: 16 Apr 2007 14:01:11 -0700 Subject: is laziness a programer's virtue? Message-ID: <1176757271.282365.319740@n76g2000hsh.googlegroups.com> 2007-03-29 Dear tech geekers, In a couple of posts in the past year i have crossed-posted (e.g. recently ?What are OOP's Jargons and Complexities?, ?is laziness a programer's virtue??, ?On Java's Interface (the meaning of interface in computer programing)? ), there are a some controversy, and lots of off-topic and careless follow ups. I think a few things today's tech geekers should remind themselves: ? If you deem something off-topic to ?your? newsgroup, and want to tech-geek by changing the ?follow-up group?, start with yourself. Please do not cross-post yourself, and tweak the follow-up, and proudly proclaim that you changed the follow-up as a benign gesture. ? Please remind yourself what is on-topic and off-topic. Unless you are the auhority of a online forum, otherwise, Meta-talk, and policing, are off-topic in general, and only tends to worsen the forum's quality. This issue is cleared up in online communications as early as early 1990s. ? The facility of cross-posting is a good thing as a progress of communication technology, and the action of cross-posting is a good thing with respect to communication. What the common tech-geekers's sensitivity to cross-posting are due to this collective's lack of understanding of social aspects of communication. Cross-posting isn't a problem. The problem is the power-struggling male nature and defensiveness in propergating the tongues of a tech geeker's own. Tech-geeker's behavior towards cross-posting over the years did nothing to enhance the content quality of newsgroups, but engendered among computing language factions incommunicado, and aided in the proliferation of unnecessary re-invention (e.g. the likes of Perl, PHP, Python, Ruby that are essentially the same) and stagnation (e.g. the lisp camp with their above-it attitude). If you are a programer of X and is learning Y or wondering about Y, please do cross-post it. If your article is relevant to X, Y, and Z, please cross post it. If you are really anti-cross-posting, please use a online forum that is more specialized with controlled communication, such as mailing lists, developer's blogs, and website- based forums. I hope that the computing newsgroups will revive to its ancient nature of verdant cross communication of quality content, as opposed to today's rampant messages focused on politics, mutual sneering, closed- mindedness, and careless postings. References: ?Tech Geekers versus Spammers? http://xahlee.org/UnixResource_dir/writ/tech_geekers_vs_spammers.html Netiquette Guidelines, 1995, by S Hambridge. (RFC 1855) http://tools.ietf.org/html/rfc1855 Xah xah at xahlee.org ? http://xahlee.org/ From nospam at nospam.com Mon Apr 23 10:36:16 2007 From: nospam at nospam.com (Gilles Ganault) Date: Mon, 23 Apr 2007 16:36:16 +0200 Subject: [re.finditer] Getting all occurences in one go? References: <7xy7kkf39a.fsf@ruckus.brouhaha.com> Message-ID: On 22 Apr 2007 15:33:37 -0700, Paul Rubin wrote: > mytable[item] = ','.join(m.group(1) for m in matches) Thanks, that did it. From grante at visi.com Wed Apr 25 12:07:00 2007 From: grante at visi.com (Grant Edwards) Date: Wed, 25 Apr 2007 16:07:00 -0000 Subject: Python not giving free memory back to the os get's me in real problems ... References: <1177510121.882503.145560@n15g2000prd.googlegroups.com> <_LidnenBcrz7-rLbnZ2dnUVZ_tCtnZ2d@comcast.com> <59990rF2ja6c7U3@mid.dfncis.de> Message-ID: <132uv54ncsspm91@corp.supernews.com> On 2007-04-25, Chris Mellon wrote: > "Returning memory to the OS" doesn't affect exhaustion of your virtual > address space. More likely, your nested loops are just creating more > objects than is possible to hold within a single process. I'm a bit fuzzy on this, but I don't think there _is_ a practical way to "return memory to the OS" in many OSes. For example in Unix the C library uses the sbrk() call to increase the size of the data segment when additional memory is needed to handle soemthing like malloc() calls. In theory, one can use brk() to reduce the size of the data segment, but I think making the segment smaller will produce undefined behavior if any of the standard C library's dynamic memory routines (e.g. malloc/free) have ever been used by the program prior to the call to brk(). -- Grant Edwards grante Yow! FEELINGS are cascading at over me!!! visi.com From 12cc104 at gmail.com Fri Apr 27 11:12:20 2007 From: 12cc104 at gmail.com (proctor) Date: 27 Apr 2007 08:12:20 -0700 Subject: regex question In-Reply-To: References: <1177655637.717863.93920@o40g2000prh.googlegroups.com> <1177659238.159411.40640@c18g2000prb.googlegroups.com> <1177683018.566343.105620@c18g2000prb.googlegroups.com> Message-ID: <1177686739.904835.51840@r30g2000prh.googlegroups.com> On Apr 27, 8:26 am, Michael Hoffman wrote: > proctor wrote: > > On Apr 27, 1:33 am, Paul McGuire wrote: > >> On Apr 27, 1:33 am, proctor <12cc... at gmail.com> wrote: > >>> rx_test = re.compile('/x([^x])*x/') > >>> s = '/xabcx/' > >>> if rx_test.findall(s): > >>> print rx_test.findall(s) > >>> ============ > >>> i expect the output to be ['abc'] however it gives me only the last > >>> single character in the group: ['c'] > > >> As Josiah already pointed out, the * needs to be inside the grouping > >> parens. > > so my question remains, why doesn't the star quantifier seem to grab > > all the data. > > Because you didn't use it *inside* the group, as has been said twice. > Let's take a simpler example: > > >>> import re > >>> text = "xabc" > >>> re_test1 = re.compile("x([^x])*") > >>> re_test2 = re.compile("x([^x]*)") > >>> re_test1.match(text).groups() > ('c',) > >>> re_test2.match(text).groups() > ('abc',) > > There are three places that match ([^x]) in text. But each time you find > one you overwrite the previous example. > > > isn't findall() intended to return all matches? > > It returns all matches of the WHOLE pattern, /x([^x])*x/. Since you used > a grouping parenthesis in there, it only returns one group from each > pattern. > > Back to my example: > > >>> re_test1.findall("xabcxaaaxabc") > ['c', 'a', 'c'] > > Here it finds multiple matches, but only because the x occurs multiple > times as well. In your example there is only one match. > > > i would expect either 'abc' or 'a', 'b', 'c' or at least just > > 'a' (because that would be the first match). > > You are essentially doing this: > > group1 = "a" > group1 = "b" > group1 = "c" > > After those three statements, you wouldn't expect group1 to be "abc" or > "a". You'd expect it to be "c". > -- > Michael Hoffman ok, thanks michael. so i am now assuming that either the book's example assumes perl, and perl is different from python in this regard, or, that the book's example is faulty. i understand all the examples given since my question, and i know what i need to do to make it work. i am raising the question because the book says one thing, but the example is not working for me. i am searching for the source of the discrepancy. i will try to research the differences between perl's and python's regex engines. thanks again, sincerely, proctor From python at hope.cz Tue Apr 24 15:29:01 2007 From: python at hope.cz (Johny) Date: 24 Apr 2007 12:29:01 -0700 Subject: PIL and font colours. Message-ID: <1177442941.190119.157230@u32g2000prd.googlegroups.com> I use PIL to write some text to a picture.The text must be seen wery clearly. I write the text to different pictures but to the same position. As pictures maybe different, colour, in the position where I write the text, is also different. Is there a way how to set the font colour so that it will be seen very clearly in the picture? For example, if the picture is bright ( for example yellow), the font colour should be dark( e.g. black) and vice versa. Can anyone help? Thanks L. From rdm at rcblue.com Sat Apr 7 11:37:08 2007 From: rdm at rcblue.com (Dick Moores) Date: Sat, 07 Apr 2007 08:37:08 -0700 Subject: Saving output of Turtle Graphics? In-Reply-To: References: Message-ID: <20070407153806.85BC21E4009@bag.python.org> At 06:50 AM 4/7/2007, =?ISO-8859-2?Q?Wojciech_Mu=B3a?= wrote: >Dick Moores wrote: > > I accidentally stumbled across the Turtle Graphics module (turtle.py) > > the other day and have been having some fun with it. > > > > Now I'm wondering if there is a way to build into a script the saving of > > each window just before it is cleared. For example, here are a couple > > that I've saved by screen capture: > > > > > >Turtle module uses Tk canvas element to draw graphics ('_canvas' >attribute). I've written module, that exports canvas graphics to SVG >file: http://wmula.republika.pl/proj/canvas2svg/ -- it may be useful >for you. I afraid I'm totally unfamiliar with SVG. Would it be possible for you or someone else on the list to show how to use your module to export the simple product of this simple script to an SVG file? =============================================== import turtle as T from random import randint T.setup(width=1000, height=700, startx=0, starty=0) T.color(1, .5, .5) T.begin_fill() # 2 connected lines will fill as a triangle for x in range(2): coord = (randint(-500,500), randint(-350,350)) T.goto(coord) T.end_fill() T.done() ================================================ Thanks, Dick Moores Win XP Pro SP2 Python 2.5 Python IDE: Ulipad 3.6 From mail at timgolden.me.uk Thu Apr 19 11:15:19 2007 From: mail at timgolden.me.uk (Tim Golden) Date: Thu, 19 Apr 2007 16:15:19 +0100 Subject: Byte-Array to String In-Reply-To: <001a01c78293$e5b58370$b1208a50$@rawlins@thinkbluemedia.co.uk> References: <000f01c7828f$8b8ce770$a2a6b650$@rawlins@thinkbluemedia.co.uk> <462782A5.5060000@timgolden.me.uk> <001a01c78293$e5b58370$b1208a50$@rawlins@thinkbluemedia.co.uk> Message-ID: <46278787.2090500@timgolden.me.uk> Robert Rawlins - Think Blue wrote: [... snip ...] > The first method, when I print its results just gives me > dbus.Array([dbus.UInt32(65547L)], signature=dbus.Signature('u')) the method > gives me that byte array and the third doesn't appear to work at all :-D > > Unfortunately nowhere seems to document what exactly those arrays contain, > so I'm trying to crack one open and find out, but as you can see, I'm not > having much luck. Perhaps this is a DBus thing, they do have a mailing list > so I'll give them a go in a while. Have you tried doing the old help (xxx) or dir (xxx) on the array objects? It might at least point to some kind of properties or structural methods? TJG From nick at craig-wood.com Tue Apr 17 10:30:07 2007 From: nick at craig-wood.com (Nick Craig-Wood) Date: Tue, 17 Apr 2007 09:30:07 -0500 Subject: subprocess confusion References: Message-ID: Tim Arnold wrote: > Just discovered that my subprocess call with the preexec_fn wasn't doing > what I thought. > If 'machine' value is different than the current machine name, I want to > remsh the command to that machine, but obviously I misunderstood the > preexec_fn arg. > > Should I just put the remsh in the actual command instead of > preexec_fn? Yes. The preexec_fn is run after the fork() but before the exec(). Ie a new process has been made, but it hasn't started your task yet. For example a classic use of preexec_fn is preexec_fn=os.setsid You seem to be thinking it is pre-pending something to your command line which isn't how it works. -- Nick Craig-Wood -- http://www.craig-wood.com/nick From cjlesh at gmail.com Fri Apr 20 14:36:08 2007 From: cjlesh at gmail.com (cjl) Date: 20 Apr 2007 11:36:08 -0700 Subject: Beautiful Soup iterator question.... Message-ID: <1177094168.548423.115730@y80g2000hsf.googlegroups.com> P: I am screen-scraping a table. The table has an unknown number of rows, but each row has exactly 8 cells. I would like to extract the data from the cells, but the first three cells in each row have their data nested inside other tags. So I have the following code: for row in table.findAll("tr"): for cell in row.findAll("td"): print cell.contents[0] This code prints out all the data, but of course the first three cells still contain their unwanted tags. I would like to do something like this: for cell1, cell2, cell3, cell4, cell5, cell6, cell7, cell8 in row.findAll("td"): Then treat each cell differently. I can't figure this out. Can anyone point me in the right direction? -CJL From kyosohma at gmail.com Mon Apr 30 13:29:49 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: 30 Apr 2007 10:29:49 -0700 Subject: Re-running script from Tk shell In-Reply-To: <1177944662.957393.306620@h2g2000hsg.googlegroups.com> References: <1177944662.957393.306620@h2g2000hsg.googlegroups.com> Message-ID: <1177954189.754975.69310@u30g2000hsc.googlegroups.com> On Apr 30, 9:51 am, gtb wrote: > I am testing a simple script by running it in the Tk shell. It imports > a class from another module. I edit and save the file from which I > import. When I want to re-run I delete the Tk window and run the > module from the Edit window (F5 - Run Module). The script that does > the importing does not see the changes to the imported class, even if > I delete the compiled files. For it to see the changes I must close > all the edit windows and re-open an Idle edit. > > Perhaps I need to de-import the class, but I have not found a method > in the tutorial or the reference (yet). > > Thanks You probably need to reload() the imported module. Check out the following thread: http://www.python.org/search/hypermail/python-1993/0342.html Hopefully that's what you meant anyway. Mike From tjreedy at udel.edu Wed Apr 4 12:55:30 2007 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 4 Apr 2007 12:55:30 -0400 Subject: Indentifying the LAST occurrence of an item in a list References: <1175702329.330032.250750@w1g2000hsg.googlegroups.com> Message-ID: wrote in message news:1175702329.330032.250750 at w1g2000hsg.googlegroups.com... | For any list x, x.index(item) returns the index of the FIRST | occurrence of the item in x. Is there a simple way to identify the | LAST occurrence of an item in a list? My solution feels complex - | reverse the list, look for the first occurence of the item in the | reversed list, and then subtract its index from the length of the list | - 1, i.e. | | LastOcc = len(x) - 1 - x[::-1].index(item) | | Is there a simpler solution? Unless I wanted the list reversed, I would simply iterate backwards, parhaps in a utility function. def rindex(lis, item): for i in range(len(lis)-1, -1, -1): if item == lis[i]: return i else: raise ValueError("rindex(lis, item): item not in lis") t=[0,1,2,3,0] print rindex(t,3) print rindex(t,0) print rindex(t,4) # prints 3, 4, and traceback Terry Jan Reedy From gnewsg at gmail.com Thu Apr 26 09:05:02 2007 From: gnewsg at gmail.com (billiejoex) Date: 26 Apr 2007 06:05:02 -0700 Subject: Modules for peer-to-peer chat program In-Reply-To: <1177437083.702888.4480@r3g2000prh.googlegroups.com> References: <1177437083.702888.4480@r3g2000prh.googlegroups.com> Message-ID: <1177592702.423902.259460@u32g2000prd.googlegroups.com> On 24 Apr, 19:51, "Viewer T." wrote: > I would like to know which modules I would need in order to create > peer-to-peer chat program in python using Tkinter. > > If I would need modules that do not come packaged with python, I would > appreciate information on where I can get them. > > Thanks. Some options: - socket - asyncore - asynchat - twisted - twisted with support for tkinter ( http://twistedmatrix.com/projects/core/documentation/howto/choosing-reactor.html#auto13 ) From guettli.usenet at thomas-guettler.de Tue Apr 10 10:01:29 2007 From: guettli.usenet at thomas-guettler.de (Thomas Guettler) Date: 10 Apr 2007 14:01:29 GMT Subject: Broken pipe with os.popen3() References: <1176212359.463506.105120@n76g2000hsh.googlegroups.com> Message-ID: <581jlpF2eismjU1@mid.individual.net> Christoph Krammer wrote: > Hello everybody, > > I try to use an external OCR tool to convert some binary image data to > text. The image is in one variable, the text should be converted to > another. I use the following code: > > (si, so, se) = os.popen3('ocrad') > si.write(frame) > si.close() > messagetext += so.read() If you use popen you should use *one* filehandle. The app hangs because the buffer is full. See http://docs.python.org/lib/popen2-flow-control.html -- Thomas G?ttler, http://www.thomas-guettler.de/ http://www.tbz-pariv.de/ E-Mail: guettli (*) thomas-guettler + de Spam Catcher: niemand.leermann at thomas-guettler.de From gagsl-py2 at yahoo.com.ar Wed Apr 11 03:06:39 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 11 Apr 2007 04:06:39 -0300 Subject: Universal Feed Parser issue References: <1176227922.910993.36910@y80g2000hsf.googlegroups.com> <1176267073.787216.80170@n76g2000hsh.googlegroups.com> Message-ID: En Wed, 11 Apr 2007 01:51:13 -0300, i3dmaster escribi?: > On Apr 10, 6:45 pm, "Gabriel Genellina" > wrote: >> En Tue, 10 Apr 2007 14:58:42 -0300, i3dmaster >> escribi?: >> >> > >> > ... >> > >> > >> > >> >> > After parsed by feedparser, the timezone element does not get the >> > attribute "America/Mountain". Same thing on status element. This does >> > not sound an expected result. I am wondering if it should be >> > considered a bug... >> >> Usually it's a good idea to read the documentation... >> http://www.feedparser.org/docs/namespace-handling.html > > I did. Perhaps its because of not 100% atom compatible of my feed > format? See if I use gnosis xml utility to parse it, it works fine > though... The link above answers *exactly* your question - have you actually read the page? -- Gabriel Genellina From pecora at anvil.nrl.navy.mil Wed Apr 4 09:52:51 2007 From: pecora at anvil.nrl.navy.mil (Lou Pecora) Date: Wed, 04 Apr 2007 09:52:51 -0400 Subject: An error of matrix inversion using NumPy References: <1175692518.282887.3040@y66g2000hsf.googlegroups.com> Message-ID: In article <1175692518.282887.3040 at y66g2000hsf.googlegroups.com>, "lancered" wrote: > Hi dear all, > I am using Python2.4.2+NumPy1.0.1 to deal with a parameter > estimation problem with the least square methods. During the > calculations, I use NumPy package to deal with matrix operations, > mostly matrix inversion and trasposition. The dimentions of the > matrices used are about 29x19,19x19 and 29x29. > > During the calculation, I noticed an apparent error of > inverion of a 19x19 matrix. Denote this matrix as KK, U=KK^ -1, I > found the product of U and KK is not equivalent to unit matrix! This > apparently violate the definition of inversion. The inversion is > through the function linalg.inv(). > > I have checked that det(KK)=-1.2E+40. At first, I thought the > error may be caused by such a large determinant, so I scaled it as > LL=KK/100, then invert LL. Since det(LL)=11.5 and all its elements are > within -180.0 to 850.0, this seems easier. But the result is still not > correct, the product of LL^-1 thus obtained and LL still not unit > matrix ... At the same time, the inversion results of some 29x19 > matrices are correct. > > So, can you tell me what goes wrong? Is this a bug in > Numpy.linalg? How to deal with this situation? If you need, I can > post the matrix I used below, but it is so long,so not at the moment. > > Thanks in advance! > Changing the overall scaling won't help unless the numbers themselves are near the double floating point boundary (perhaps). The real number you want to calculate is the condition number of the matrix. Roughly the ratio of the largest to the smallest eigenvalue. If that's large, then you're attempt at inversion is dealing with differences between very large and very small numbers and/or very small differences between two large numbers which probably goes beyond the number of digits (bits) the machine can provide to represent floating point numbers. No rescaling of the original matrix will change that. Do a google on "condition number". -- Lou Pecora (my views are my own) REMOVE THIS to email me. From gagsl-py2 at yahoo.com.ar Thu Apr 5 14:40:32 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 05 Apr 2007 15:40:32 -0300 Subject: way to extract only the message from pop3 References: <1175628970.874615.127020@y80g2000hsf.googlegroups.com> <4c0048df0704051109j24e24457v453cd68136e0096a@mail.gmail.com> Message-ID: En Thu, 05 Apr 2007 15:09:18 -0300, Collin Stocks escribi?: > message=whole_message[len(headers):None] > > You can omit the word None: it is just there for clarity purposes. Uhm... I can't find any usage of slices including an explicit None in code.google.com (except on the Python test suite), and really I don't consider that to be more readable than whole_message[len(headers):] But of course this is just a stylistic issue. -- Gabriel Genellina From steve at REMOVE.THIS.cybersource.com.au Fri Apr 20 22:18:45 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Sat, 21 Apr 2007 12:18:45 +1000 Subject: Newbie question regarding string.split() References: <1177095062.826018.63590@n59g2000hsh.googlegroups.com> <1177096533.564349.285930@q75g2000hsh.googlegroups.com> Message-ID: On Fri, 20 Apr 2007 12:15:33 -0700, kyosohma wrote: > One hack to make it work is to add the following line right before you > print "projectOptions": > > projectOptions.pop(0) # pop the first element out of the list Which will introduce a nice bug into the Original Poster's code when the input string doesn't start with a "2". -- Steven. From bj_666 at gmx.net Fri Apr 27 16:37:22 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Fri, 27 Apr 2007 22:37:22 +0200 Subject: Memory addressing References: <1177702902.156596.52510@n35g2000prd.googlegroups.com> <1177703803.179501.95300@n35g2000prd.googlegroups.com> Message-ID: In <1177703803.179501.95300 at n35g2000prd.googlegroups.com>, Simon Berube wrote: > In short, how do I used strings to recreate > a an object. You already got the answer: you can't. Either you still have a reference to that object, or the memory address is not guaranteed to point to the object anymore even if you could get an object from a "raw" memory address. Ciao, Marc 'BlackJack' Rintsch From gagsl-py2 at yahoo.com.ar Thu Apr 5 15:57:59 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 05 Apr 2007 16:57:59 -0300 Subject: ascii-unicode replacement References: Message-ID: En Thu, 05 Apr 2007 14:28:20 -0300, Andrea Valle escribi?: > I scripted some text files with another language which cannot handle > unicode. > As I need special character in the resulting text files (IPA > extension), my idea was to define some special ascii sequences in the > text files, open the text files in Python, replace the special > sequences with unicode and encode in utf8. I made some tests with > consolle and everything seemed fine. > > But my script keeps on raising exceptions related to encoding. You are mixing Unicode and strings all the way. I prefer to use standard file objects, with explicit decoding/encoding right where the data is being read/written, rather than the codecs.open approach. Your source file is ASCII, right? So read it using the builtin open() + read(). You get a string. Convert to unicode right there, using read_text.decode("ascii"). You have unicode now. Do all the processing and replacements in Unicode. At the LAST stage, encode the text using .encode("utf-8") just before writing the output file. -- Gabriel Genellina From dherring at at.tentpost.dot.com Mon Apr 16 17:58:52 2007 From: dherring at at.tentpost.dot.com (D Herring) Date: Mon, 16 Apr 2007 17:58:52 -0400 Subject: [OT] Re: is laziness a programer's virtue? In-Reply-To: <1176757271.282365.319740@n76g2000hsh.googlegroups.com> References: <1176757271.282365.319740@n76g2000hsh.googlegroups.com> Message-ID: <96adnb0sJ8PubL7bnZ2dnUVZ_gednZ2d@comcast.com> Xah Lee wrote: > In a couple of posts in the past year i have crossed-posted (e.g. > recently ?What are OOP's Jargons and Complexities?, ?is laziness a > programer's virtue??, ?On Java's Interface (the meaning of interface > in computer programing)? ), there are a some controversy, and lots of > off-topic and careless follow ups. Please don't dismiss so many posts as being "off-topic and careless". > I think a few things today's tech geekers should remind themselves: > > ? If you deem something off-topic to ?your? newsgroup, and want to > tech-geek by changing the ?follow-up group?, start with yourself. > Please do not cross-post yourself, and tweak the follow-up, and > proudly proclaim that you changed the follow-up as a benign gesture. ... A few more points: - I know many geeks but not so many geekers... http://www.urbandictionary.com/define.php?term=geeker - Please topquote snippets from the threads about which you are commenting. - Please set your newsreader to prepend "Re: " or somesuch when replying to a toplevel post. - Please don't preach about "meta-talk and policing" in a post which is mostly meta-talk and preaching. Thanks, Daniel From missive at frontiernet.net Mon Apr 9 17:44:40 2007 From: missive at frontiernet.net (Lee Harr) Date: Mon, 09 Apr 2007 21:44:40 GMT Subject: How can I import functions from another python file References: <1176152771.761958.310740@w1g2000hsg.googlegroups.com> Message-ID: On 2007-04-09, yinglcs at gmail.com wrote: > Hi, > i have 2 python files in *different directory* , how can I import > python functions from 1 python file to another? > > i get this error: > import task > ImportError: No module named task/ > The directory that module is in must by on your python path in order to import it. You can do it by modifying sys.path or by setting the PYTHONPATH env variable. $ mkdir otherdir $ cat > otherdir/amod.py def afunc(): return 'found' $ python >>> import amod Traceback (most recent call last): File "", line 1, in ? ImportError: No module named amod >>> import sys >>> sys.path.append('otherdir') >>> import amod >>> amod.afunc() 'found' From bbxx789_05ss at yahoo.com Sun Apr 15 23:30:57 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: 15 Apr 2007 20:30:57 -0700 Subject: How to initialize a table of months. In-Reply-To: References: Message-ID: <1176694257.338172.217660@y80g2000hsf.googlegroups.com> On Apr 15, 7:30 pm, "Steven W. Orr" wrote: > I'm reading a logfile with a timestamp at the begging of each line, e.g., > > Mar 29 08:29:00 > > I want to call datetime.datetim() whose arg2 is a number between 1-12 so I > have to convert the month to an integer. > I wrote this, but I have a sneaky suspicion there's a better way to do it. > > mons = {'Jan':1, 'Feb':2, 'Mar':3, 'Apr':4, 'May':5, 'Jun':6, > 'Jul':7, 'Aug':8, 'Sep':9, 'Oct':10, 'Nov':11, 'Dec':12 } > > def mon2int( mon ): > global mons > return mons[mon] > > Is there a generator expression or a list comprehension thingy that would > be *betterer*? (I realize it's probably not that important but I find lots > of value in learning all the idioms.) > > 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 Just in case you're still interested(despite not needing to per John Zenger's solution), you could do this: import calendar months = calendar.month_abbr #returns an array with the 0 element empty #so the month names correspond to indexes 1-12 d = {} for i in range(1, 13): d[months[i]] = i print d From spytips at yahoo.com.sg Mon Apr 2 17:20:13 2007 From: spytips at yahoo.com.sg (Spytips) Date: 2 Apr 2007 14:20:13 -0700 Subject: Buy, sell and rent Singapore real estate: private property, Message-ID: <1175548813.494884.306590@y80g2000hsf.googlegroups.com> Buy, sell and rent Singapore real estate: private property, residential apartments, commercial and industrial properties. HDB flats for sale and rental. Foreign investors, buyers, tenants or relocating expats can easily find their ideal landed house, bungalow, semi-d, terrace, condominium, townhouse, private apartment, HDB, HUDC, office, shop, factory, warehouse & land right here. http://singapore.freewebsites.com/singapore.htm http://singapore.freewebsites.com/property.htm http://singapore.freewebsites.com/expat.htm http://singapore.freewebsites.com/job.htm http://singapore.freewebsites.com/agent.htm http://singapore.freewebsites.com/land.htm http://singaporefreewebsites.com/developer.htm http://singapore.freewebsites.com/business.htm http://singaporefreewebsites.com/financial.htm http://singapore.freewebsites.com/investment.htm http://singapore.freewebsites.com/invest.htm http://singapore.freewebsites.com From kyosohma at gmail.com Thu Apr 26 10:11:47 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: 26 Apr 2007 07:11:47 -0700 Subject: simplest install procedure for Python + packages under winXP ? In-Reply-To: References: <617df$46306f26$83aef404$8949@news2.tudelft.nl> Message-ID: <1177596707.835728.147590@n35g2000prd.googlegroups.com> On Apr 26, 4:41 am, Laurent Pointal wrote: > stef a ?crit : > > > > > hello, > > > I'm still in the transition of going from MatLab to Scipy, > > and installed previous week a SciPy on a PC twice, > > through the new "Enstaller". > > It's a pitty that there will be no old installer versions anymore > > (although I can understand why). > > > Although I succeeded, the behavior of the Enstaller was different both > > times, and you can clearly see it's an alpha version. > > (I already wrote my experiences with the first install, > > the second install had the weird phenomena that none of the succesful > > installed packages was detected). > > > As a spoiled windows user, which by the way are most people in my > > surrounding, I'm used to a "one-button-install", > > so I wonder if it's possible to make a much simpler install procedure. > > > I don't know anything about what's required for a good install, > > what kind of things things should be stored in the windows registry, > > but as Python is an interpretor, > > I would expect there should be a very easy procedure: > > - Install it on one machine, > > - copy the complete subdirectory to another computer > > Does this work for Python + Scipy ? > > (If so, I can use Inno, which I'm familiar with) > > Maybe take a look at:http://www.portablepython.com/http://www.voidspace.org.uk/python/movpy/ > > Dont know for scipy. I regularly test packages on my WinXP machine and if they work correctly, I just copy them to the Debian box we're using. Probably not the best way to do things, but so far it works well. I don't think Python adds much to the registry. Mostly file associations and maybe registering that python dll file. I don't think very many of the packages add anything to the registry. The win32 ones might... You can certainly try it. At worst, you'll just have to delete the directory and install the normal way. Mike From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Thu Apr 26 07:00:52 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Thu, 26 Apr 2007 13:00:52 +0200 Subject: My python annoyances so far References: <1177541453.471959.120830@c18g2000prb.googlegroups.com> Message-ID: <59bf34F2k27v5U1@mid.individual.net> flifus at gmail.com wrote: > Hi all. I'm learning python these days. I'm going to use this > thread to post, from time to time, my annoyances with python. I > hope someone will clarify things to me where I have misunderstood > them. > > Annoyances: > > 1. Underscores! What's the deal with that? Especially those double > underscores. The best answer I read on this is that the double > underscores denotes special methods that the interpreter may > automatically use. That's right. But what's the annoyance here? It's a clear seperation. A bigger annoyance would be if the method name were, e. g., "add". Now you define your own class, don't think about this and define a method "add" yourself, and you wonder why your class behaves strangely. > 2. There are modules, there are functions, and there are classes- > methods! You forgot static methods and types. And all of them are objects. > Wouldn't it have been easier had everything either been a > function or a class method? IMHO no (this isn't Java). Why should I have to define a class if I just code a little script with a few functions? That would be forcing the programmer into using a programming paradigm. Will you ask why there is no StringBuffer in Python? :) Regards, Bj?rn -- BOFH excuse #385: Dyslexics retyping hosts file on servers From steve at holdenweb.com Tue Apr 24 12:01:52 2007 From: steve at holdenweb.com (Steve Holden) Date: Tue, 24 Apr 2007 12:01:52 -0400 Subject: Generate report containing pdf or ps figures? In-Reply-To: References: <132pnp6r4qg0lc2@corp.supernews.com> Message-ID: Cameron Laird wrote: > In article <132pnp6r4qg0lc2 at corp.supernews.com>, > Grant Edwards wrote: >> I need to be able to generate a PDF report which consists >> mostly of vector images (which I can generate as encapsulated >> Postscript, PDF, or SVG). What I need is a way to combine >> these figures into a single PDF document. Right now the >> reports consist entire of these figures, so I just write the >> figures out to temp files and then use os.system() to run >> ghostscript with appropriate options to combine them into a >> single PDF file. >> >> I'd like to be able to add some text and/or place the figures >> in a manner other than one per page in the output document. >> >> I've looked at ReportLab's documentation, but although it >> appears to be able to use bitmap images (e.g jpeg) it doesn't >> appear to be able to use vector images (EPS/PDF/SVG). >> >> Is there a PDF generation library that can place EPS or >> PDF figures on a page? > . > . > . > You're stuck. > > If I understand what you're after, you're probably going to > end up finding a way to leverage Ghostscript. There are a > lot of ways to move forward in this area, but GS has most of > 'em beat, despite all its liabilities. > > That's my summary. I've done quite a bit in this area, and > am happy to talk about specifics. > > I have two recommendations: see if anything in http://phaseit.net/claird/comp.text.pdf/PDF_converters.html > > resonates with you; and e-mail the nice folks at http://www.pdf-tools.com/ >. > > I've taken the liberty of cross-posting to c.t.p. Python > alone isn't big enough (yet) to solve your problem. In fairness to ReportLab I'd like to say that their *commercial* products can do everything the OP asks for and more besides, but unfortunately they are mostly targeted at the "enterprise" (read: big money) market. regards Steve -- Steve Holden +1 571 484 6266 +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 jakub.stolarski at gmail.com Wed Apr 4 06:41:57 2007 From: jakub.stolarski at gmail.com (Jakub Stolarski) Date: 4 Apr 2007 03:41:57 -0700 Subject: bool value 'False' no memory address? In-Reply-To: <1175682972.507206.29000@n76g2000hsh.googlegroups.com> References: <1175682972.507206.29000@n76g2000hsh.googlegroups.com> Message-ID: <1175683317.458791.275270@d57g2000hsg.googlegroups.com> On Apr 4, 12:36 pm, "autin" wrote: > such as:>>>b = False > >>>id(b) > > Traceback (most recent call last): > File "", line 1, in ? > TypeError: 'bool' object is not callable > > --- > how to desc it? >>> b = False >>> id(b) 135311308 >>> python 2.4, FreeBSD 6.2 From bbxx789_05ss at yahoo.com Fri Apr 13 14:27:20 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: 13 Apr 2007 11:27:20 -0700 Subject: Python editor/IDE on Linux? In-Reply-To: References: Message-ID: <1176488840.672572.101830@y80g2000hsf.googlegroups.com> Jack wrote: > I wonder what everybody uses for Python editor/IDE on Linux? > I use PyScripter on Windows, which is very good. Not sure if > there's something handy like that on Linux. I need to do some > development work on Linux and the distro I am using is Xubuntu. Everybody uses vim. From paul at boddie.org.uk Wed Apr 4 16:46:47 2007 From: paul at boddie.org.uk (Paul Boddie) Date: 4 Apr 2007 13:46:47 -0700 Subject: BeautifulSoup vs. real-world HTML comments In-Reply-To: References: Message-ID: <1175719607.647155.265670@e65g2000hsc.googlegroups.com> John Nagle wrote: > The syntax that browsers understand as HTML comments is much less > restrictive than what BeautifulSoup understands. I keep running into > sites with formally incorrect HTML comments which are parsed happily > by browsers. Here's yet another example, this one from > "http://www.webdirectory.com". The page starts like this: > > > > > Anything based on libxml2 and its HTML parser will handle such broken HTML just fine, even if they just ignore such erroneous attempts at comments, discarding them as the plain nonsense they clearly are. Certainly, libxml2dom seems to deal with the page: import libxml2dom d = libxml2dom.parseURI("http://www.webdirectory.com", html=1, htmlencoding="iso-8859-1") I guess lxml and the original libxml2 bindings work at least as well. Note that some browsers won't be as happy if you give them such content as XHTML. Paul From bbxx789_05ss at yahoo.com Wed Apr 11 14:41:21 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: 11 Apr 2007 11:41:21 -0700 Subject: Hellow World:) In-Reply-To: References: <765964.71169.qm@web63102.mail.re1.yahoo.com> Message-ID: <1176316880.787202.218800@y80g2000hsf.googlegroups.com> If I were you, I would consider obtaining the book Learning Python. I have the newer edition of Pratical Python, which is called Beginning Python: From Novice to Professional, and I wouldn't recommend it. I think Learning Python would be ideal except that it's a couple of years old, and therefore doesn't cover recent additions to python. Dive into Python is meant for experienced programmers. From stevesnow at stevesnowsresume.com Wed Apr 4 21:01:08 2007 From: stevesnow at stevesnowsresume.com (stevesnow) Date: Wed, 04 Apr 2007 18:01:08 -0700 Subject: Resume of Steve Snow : Database SQL Applications Programmer Message-ID: ---------------------------------------------- Please forward this work experience & skills summary to your Database & software development, MIS/IT/Software Department for review. ---------------------------------------------- Here is my full resume in Microsoft Word format. To use, click your RIGHT-mouse button on this link: http://www.sworde.com/resume2.doc "Open in new Window", then print this word document. ---------------------------------------------- Resume of Steve Snow ---------------------------------------------- Database SQL Applications Programmer ---------------------------------------------- Phone: 970-300-4770 ---------------------------------------------- stevesnow10 at hotmail.com ---------------------------------------------- Work Experience: * 20+ Years Database & Software Application developer * References available on request. * Create/Fix/Change/Convert Databases. * Display your data on your website, any number of pages in html/PHP/ASP. * Graphs, Maps, Charts, Diagrams, Pictures, Photos, and Graphics in Database and Reports. * Mail Merge of Databases/Information/Spreadsheets/Programs. * Create reports from Data such as PDF, Spreadsheet or HTML. * Sales leads for clients using Internet Resources. * Solving almost any job any data from any program source. * Fill out Website Forms automatically, or gather intelligence from them. * Exchange data from any number of programs, including websites. * Create inter office communication between cities/locations using Internet. * Inventory, Sales Lead, Accounting, Statistical Database Creation. * Meetings with employees to understand their needs/solution they wanted. * Training of personnel in all above systems. * Write software to perform the above jobs. * Problem solve any data question/problem you may have. * Transfer data between any number of unrelated programs, including websites. * Merge Data from unrelated programs and databases. * Test your entire website for errors by automatically filling in all your webforms on all your webpages. * Screenscrape, Webscraping, and Datamining from the internet straight to your custom databases. * Chief Developer and programmer for above with 30 years experience. Here is my full resume: http://www.sworde.com/resume2.doc ---------------------------------------------- Skills: * All VB/VBA,COM/ActiveX,DOM,SOAP, .NET * All SQL programming, Oracle (incl. PL/SQL),MS Access,SQL Server,Sybase * XML,HTML * All database access methods, ADO (ActiveX Data Objects),DAO (Data Access Objects),Microsoft Jet, ODBC * Operating systems, Windows NT 4.0 / 2000 / XP,Windows 95 / 98,ndows 3.1 / 3.11 ---------------------------------------------- Availability: * By the job or task/requirement (bid). * Contract or Independent Consultant * Full or part time Employee. * Can fly in and be available for "Live" meetings on short notice. * Remote desktop (anywhere in the world, using XP Pro and above). ---------------------------------------------- Bondable/References * SECRET Clearance (US Government) * Fully bondable * Non-disclosure/Confidentiality Agreements. ---------------------------------------------- Education * US Military, includes "SECRET" Clearance, University, Trade Schools & Certifications. ---------------------------------------------- Citizenship * Us Citizen. ---------------------------------------------- Vehicle/License * Class "A" License ---------------------------------------------- Special Mention * Can sign a waiver to not use your Company's Medical Insurance Policy (Already covered by US Veteran's Administration Medical Insurance) Here is my full resume: http://www.sworde.com/resume2.doc From a.wyrwa at gmx.de Tue Apr 10 00:29:08 2007 From: a.wyrwa at gmx.de (=?ISO-8859-1?Q?Andr=E9?= Wyrwa) Date: Tue, 10 Apr 2007 14:29:08 +1000 Subject: confirm password for logged in user Message-ID: <1176179348.7668.10.camel@callisto.io> Hei, I know this kind of stuff has probably been asked a couple of times already, and did quite a bit of googling about it, but the answers i found were either unsatisfying or not specific enough to what i want to do: I'm writing on a (Linux only) python daemon that runs as regular user. Under certain conditions the daemon should create a total screen lock as in gksu and should require input of the users password to release the lock. This is similar to what xscreensavers oder gnome-screensavers screenlock features do. The problem kicks in because it should work with shadowed passwords. I understand that shadowed passwords can be retrieved in Python 2.5, but only if the program runs as superuser (or has the necessary privileges for some other reason). This creates two problems: I'd like it to work in Python 2.4 and the daemon doesn't and shouldn't run as superuser. I'm wondering, though, if there isn't ANY way to have the password confirmed for the user that is already logged in. Please note the difference, i don't want to write some kind of login functionality. The user is already authenticated, i just want to have a typed in password checked agains the already logged in users password. Isn't there any way? A simple bash trick would help as well, but i couldn't find one. I don't have much of a clue about PAM, but i got the notion that it could be done via PyPAM? It's a pretty old package, which refrained me from looking into this option so far. Thanks for any help, Andr?. -------------- 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 jstroud at mbi.ucla.edu Tue Apr 10 06:24:02 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Tue, 10 Apr 2007 10:24:02 GMT Subject: Why is __getslice__ still implemented? In-Reply-To: <87irc4wpxp.fsf@wilson.homeunix.com> References: <87irc4wpxp.fsf@wilson.homeunix.com> Message-ID: <6BJSh.7607$u03.5881@newssvr21.news.prodigy.net> Torsten Bronger wrote: > Hall?chen! > > According to , > __getslice__ is deprecated. At the moment, I derive an own class > from unicode and want to implement my own slicing. I found that I > have to override __getslice__ since __getitem__ isn't called when I > have something like my_instance[a:b] in my code. > > According to > , this may > have efficiency reasons, however, I agree with > news:1102645919.114898.139820 at f14g2000cwb.googlegroups.com that this > is quite confusing. It forces people to implement a deprecated > function after all. I think the docs should say that you still have > to override __getslice__ when subclassing from a built-in type, > unless I really don't understand the issue correctly. > > Tsch?, > Torsten. > Which version of python are you using? chernev 20% /sw/bin/python Python 2.5 (r25:51908, Oct 10 2006, 03:45:47) [GCC 4.0.1 (Apple Computer, Inc. build 5363)] on darwin Type "help", "copyright", "credits" or "license" for more information. py> class Bob(object): ... def __getitem__(self, *args): ... print args ... py> b = Bob() py> b[4:21:2] (slice(4, 21, 2),) py> b[5:18:21,2:9:2,8,14:4] ((slice(5, 18, 21), slice(2, 9, 2), 8, slice(14, 4, None)),) From bearophileHUGS at lycos.com Mon Apr 2 07:05:23 2007 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 2 Apr 2007 04:05:23 -0700 Subject: Shed Skin Python-to-C++ Compiler 0.0.21, Help needed In-Reply-To: <1175509861.292455.226280@b75g2000hsg.googlegroups.com> References: <576vhbF2ca1guU1@mid.individual.net> <1175376373.241744.6220@y80g2000hsf.googlegroups.com> <1175413310.295953.230840@e65g2000hsc.googlegroups.com> <1175455529.936887.249170@e65g2000hsc.googlegroups.com> <1175496721.899984.193690@n76g2000hsh.googlegroups.com> <1175509861.292455.226280@b75g2000hsg.googlegroups.com> Message-ID: <1175511923.323321.30220@n76g2000hsh.googlegroups.com> Paul Boddie: > the author's frustration with the state of the standard library: > something which almost always gets mentioned in people's pet Python > hates, but something mostly ignored in the wider enthusiasm for > tidying up the language. There is some possibility that Python 3.1 will have what you ask for: http://www.python.org/dev/peps/pep-3108/ Bye, bearophile From 12cc104 at gmail.com Mon Apr 23 02:57:27 2007 From: 12cc104 at gmail.com (proctor) Date: 22 Apr 2007 23:57:27 -0700 Subject: recursion depth problem In-Reply-To: References: <1177267774.416169.276780@e65g2000hsc.googlegroups.com> <1177275314.846022.249000@e65g2000hsc.googlegroups.com> <1177276111.720137.315710@b75g2000hsg.googlegroups.com> <1177282027.798037.48210@o5g2000hsb.googlegroups.com> <90679236-0D2C-42EF-B93F-06A1DD561944@jedimindworks.com> Message-ID: <1177311447.366904.248130@l77g2000hsb.googlegroups.com> On Apr 22, 5:51 pm, Michael Bentley wrote: > Oops! Note to self: *ALWAYS* try code before posting to a public > forum :-( > > def binary(val, width): > print '%10s = the sum of' % val > for i in [2 ** x for x in range(width - 1, -1, -1)]: > a = val / i > print ' ' * 13 + '%s * (2 ** %s)' % (a, width) > val -= i * a > width -= 1 > > binary(233, 8) hi michael, just a quick clarification... it seems to me that the self-documenting part of the code should be more like this: print ' ' * 13 + '%s * (2 ** %s)' % (a, width-1) instead of print ' ' * 13 + '%s * (2 ** %s)' % (a, width) is this correct, or am i mixed? sincerely, proctor From jjl at pobox.com Sat Apr 14 06:33:38 2007 From: jjl at pobox.com (John J. Lee) Date: Sat, 14 Apr 2007 10:33:38 GMT Subject: Double backslash in filepaths ? References: <700ec$46209de2$d443bb3a$21603@news.speedlinq.nl> Message-ID: <87y7kvb5yv.fsf@pobox.com> Stef Mientki writes: > It looks like sometimes a single backslash is replaced by a double backslash, > but sometimes it's not ??? > See the error message below, > the first backslash is somewhere (not explicitly in my code) replaced, > but the second is not ??? > Is it in general better to use double backslash in filepaths ? [...] > IOError: [Errno 2] No such file or directory: 'D:\\data_to_test\test_global.pd' '\t' is the tab character. '\d' is not a valid escape sequence, so the backslash there survives intact. repr() normalises the string on output, so the (single!) backslash in '\d' is displayed, as always in the repr of strings, as '\\'. You should either use this: 'D:\\data_to_test\\test_global.pd' Or this: r'D:\data_to_test\test_global.pd' See also: http://www.python.org/doc/faq/general/#why-can-t-raw-strings-r-strings-end-with-a-backslash Or even this, which will work unless you're using crufty software that doesn't like slash path separators (cmd.exe being one of those pieces of software): 'D:/data_to_test/test_global.pd' John From steve at holdenweb.com Sat Apr 28 10:32:03 2007 From: steve at holdenweb.com (Steve Holden) Date: Sat, 28 Apr 2007 10:32:03 -0400 Subject: Python CGI and Browser timeout In-Reply-To: <9e2f512b0704261601s39e0772fp39636ff09b98521e@mail.gmail.com> References: <1177624109.532664.105840@t39g2000prd.googlegroups.com> <9e2f512b0704261601s39e0772fp39636ff09b98521e@mail.gmail.com> Message-ID: Sebastian Bassi wrote: > On 26 Apr 2007 14:48:29 -0700, skulka3 at gmail.com wrote: >> In order to work around this problem, I started printing empty strings >> (i.e. print "") so that the browser does not timeout. > > How do you print something while doing the query and waiting for the results? > I saw some pages that display something like: "This page will be > updated in X seconds to show the results" (X is an estimated time > depending of server load), after a JS countdown, it refresh itself and > show the result or another "This page will be updated in X seconds to > show the results". The usual way is by "client pull": send the content you want the user to see, and include a Refresh: header - the easiest way is to include a META tag in the html content section like So the page can continually check whether the user's job is finished, if it isn't just sending out the same content and then when it is printing the details. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden ------------------ Asciimercial --------------------- Get Python in your .sig and on the web. Blog and lens holdenweb.blogspot.com squidoo.com/pythonology tag items: del.icio.us/steve.holden/python All these services currently offer free registration! -------------- Thank You for Reading ---------------- From S.Mientki-nospam at mailbox.kun.nl Fri Apr 6 05:49:59 2007 From: S.Mientki-nospam at mailbox.kun.nl (Stef Mientki) Date: Fri, 06 Apr 2007 11:49:59 +0200 Subject: ANN: PyPE 2.8.5 In-Reply-To: References: Message-ID: <7c92b$46161783$d443bb3a$25778@news.speedlinq.nl> Josiah Carlson wrote: > === What is PyPE? === > PyPE (Python Programmers' Editor) was written in order to offer a > lightweight but powerful editor for those who think emacs is too much > and idle is too little. Syntax highlighting is included out of the box, > as is multiple open documents via tabs. Very beautiful, Josiah ! Not only very nice as an IDE, but also to show the possibilities (and some of the limitations) of wxPython, wxWidgets. A few remarks, - example macros are placed one level to deep, so you won't see them - you didn't include the "run current Python script" macro - why not (also) place this announcement in the python-announce-list at python.org -- cheers, Stef Mientki http://pic.flappie.nl From jstroud at mbi.ucla.edu Sat Apr 21 06:08:27 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Sat, 21 Apr 2007 03:08:27 -0700 Subject: TK-grid problem, please help In-Reply-To: <3CgWh.23821$PL.17381@newsread4.news.pas.earthlink.net> References: <3CgWh.23821$PL.17381@newsread4.news.pas.earthlink.net> Message-ID: Ray wrote: > hi, I have a question about how to use .grid_forget (in python/TK) > > I need to work on grid repeatly. everytime when a button is pressed, > the rows of grid is different. such like, first time, it generate 10 > rows of data. > 2nd time, it maybe only 5 rows. so I need a way to RESET the grid data > every time. how can I do it? by grid_forger()?, then would anyone can > help on > how to use grid_forget() > the sample code as following: > > #####begin of program############### > > from Tkinter import * > def mygrid(text): > ######## how to use grid_forget() to clean the grid??########### > rows = [] > count=int(text) > for i in range(count): > cols = [] > for j in range(4): > e = Entry(frame3, relief=RIDGE) > e.grid(row=i, column=j, sticky=NSEW) > e.insert(END, '%d.%d' % (i, j)) > cols.append(e) > rows.append(cols) > > > root=Tk() > > frame1=Frame(root, width=150, height=100) > frame1.pack() > > text=Entry(frame1) > text.pack(side=LEFT) > > button=Button(frame1, text='generate grid', command=(lambda: > mygrid(text.get()))) > > button.pack() > > frame2=Frame(root, width=150, height=100) > frame2.pack() > > button2=Button(frame2, text='exit', command=root.quit) > button2.pack() > > frame3=Frame(root, width=150, height=300) > frame3.pack() > > root.mainloop() > > #####end of program############### Using grid_forget() is probably optimization overkill, but may be handy for slower computers where you can watch the widgets appear one by one (older than about 5 years--for example original mac ibook). Also, you should get a good book on Tkinter because your design here will pretty difficult to maintain and is not very flexible. But...if you want to know how it might be done with grid_forget using the code you already have (i.e. making widgets only if necessary): #START# from Tkinter import * from tkMessageBox import showerror def mygrid(text): ######## how to use grid_forget() to clean the grid??########### numrows = len(frame3.rows) try: count=int(text) except: showerror('Entry Error', '''Hey, "%s" don't make an int, Fool!''' % text, parent=frame3) return 'break' for i in range(count): if i < numrows: cols = frame3.rows[i] else: cols = [Entry(frame3, relief=RIDGE) for j in range(4)] frame3.rows.append(cols) for j in range(4): e = cols[j] e.grid(row=i, column=j, sticky=NSEW) e.delete(0,END) e.insert(END, '%d.%d' % (i, j)) for i in range(i+1, numrows): for e in frame3.rows[i]: e.grid_forget() root=Tk() frame1=Frame(root, width=150, height=100) frame1.pack() text=Entry(frame1) text.pack(side=LEFT) button=Button(frame1, text='generate grid', command=(lambda: mygrid(text.get()))) button.pack() frame2=Frame(root, width=150, height=100) frame2.pack() button2=Button(frame2, text='exit', command=root.quit) button2.pack() frame3=Frame(root, width=150, height=300) # adding an attribute here frame3.rows = [] frame3.pack() root.mainloop() #END# Notice also the necessity for the "e.delete(0, END)" line to get the desired text in the entries. Also demonstrated is how to handle poor input. *Note* Remember to always call the user "Fool" when he does something stupid. James From hg at nospam.org Sat Apr 7 09:50:50 2007 From: hg at nospam.org (hg) Date: Sat, 07 Apr 2007 15:50:50 +0200 Subject: Pyserial example program error: win32file.SetupComm reports 'Incorrect function.' References: <5LPRh.37770$Ng1.19596@newsfe19.lga> <2oRRh.19303$PL.18140@newsread4.news.pas.earthlink.net> Message-ID: Dennis Lee Bieber wrote: > On Sat, 07 Apr 2007 11:36:05 +0200, hg declaimed the > following in comp.lang.python: > >> >> I am now facing your problem ... on a machine that used to work fine. >> >> Have you figured it out ? >> >> Could it be a conflict between pyserial and pywin32 ? >> > > The test still runs on my system -- which is still running the > ActiveState 2.4.3 build*... So that probably clears M$ of any > malfeasance (via various and sundry patches). > > The closest a google search came up with was someone trying to > control a serial port printer getting failures on setupcomm (and /not/ > via Python). I think the gist was that any port except the one the > printer was connected to was okay. > > So... Is there some device connected to the port in question? > Possibly a device that has a system level driver (ie, a Windows printer > entry) that might be preventing changes... > > > > > > * Too many 3rd-party modules still aren't available in 2.5 versions > for my tastes... > -- > Wulfraed Dennis Lee Bieber KD6MOG > wlfraed at ix.netcom.com wulfraed at bestiaria.com > HTTP://wlfraed.home.netcom.com/ > (Bestiaria Support Staff: web-asst at bestiaria.com) > HTTP://www.bestiaria.com/ My fault, I actually _had_ the issue with python 2.4 I removed everything and reinstalled python 2.4.4, pywin( lastest) and pyserial (latest) ... the problem is gone. hg From gagsl-py2 at yahoo.com.ar Thu Apr 26 03:07:03 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 26 Apr 2007 04:07:03 -0300 Subject: If Dict Contains a particular key References: <000001c78695$ed321540$c7963fc0$@rawlins@thinkbluemedia.co.uk> <1177436682.3441.15.camel@dot.uniqsys.com> <1177565430.992904.149450@n35g2000prd.googlegroups.com> Message-ID: En Thu, 26 Apr 2007 03:56:17 -0300, John Nagle escribi?: >>>>> On Tue, 2007-04-24 at 18:28 +0100, Robert Rawlins - Think Blue wrote: >>>>>> I'm Looking to build a quick if/else statement that checks a >>>>>> dictionary for a key like follows. > > It would be useful if there was some direct way to get the value > associated with a key, and None if there's not one. Such wonderful method exists since immemorial ages -at least since Python 1.5- and its magic name is "get": py> d = {'a': 1, 'b': 2} py> print d.get("a") 1 py> print d.get("z") None -- Gabriel Genellina From soren.skou.nielsen at gmail.com Mon Apr 16 09:13:31 2007 From: soren.skou.nielsen at gmail.com (Soren) Date: 16 Apr 2007 06:13:31 -0700 Subject: Boost Problem! Boost.Build not found In-Reply-To: <1176726516.333233.4890@y80g2000hsf.googlegroups.com> References: <1176719740.525832.132610@e65g2000hsc.googlegroups.com> <1176720813.976821.237610@w1g2000hsg.googlegroups.com> <1176722688.351441.303410@w1g2000hsg.googlegroups.com> <1176726516.333233.4890@y80g2000hsf.googlegroups.com> Message-ID: <1176729210.962818.251180@d57g2000hsg.googlegroups.com> On 16 Apr., 14:28, "Rob Wolfe" wrote: > Soren wrote: > > > Try to create boost-build.jam file like this: > > > > # boost-build.jam > > > boost-build C:\boost\boost_1_33_1\tools\build\v1 ; > > > Hi Rob, Thanks for the answer! > > > It did solve the error.. but produced a new one: > > > C:\boost\boost_1_33_1\libs\python\example\tutorial>bjam -sTOOLS=vc-8_0 > > Unable to load Boost.Build: could not find build system. > > --------------------------------------------------------- > > C:\boost\boost_1_33_1\libs\python\example\boost-build.jam attempted to > > load the > > build system by invoking > > > 'boost-build C:/boost/boost_1_33_1/tools/build/v1 ;' > > > but we were unable to find "bootstrap.jam" in the specified directory > > or in BOOST_BUILD_PATH (searching C:\boost\boost_1_33_1, C:/boost/ > > boost_1_33_1/t > > ools/build/v1). > > There is something wrong with your boost installation. > Do you have subdirectory tools/build/v1 in your installation? > > > > > What is bootstrap.jam? .. Haven't seen that one in the short > > tutorial... > > It is essential for boost build system that the file bootstrap.jam > could be found. > > -- > HTH, > Rob Hi Rob! Thanks for the help! It turned out the installation had not installed all files... .. but gave no error!!?? .. anyway, I redownloaded and installed and now it works! Wouldn't have guessed it if you haven't said the installation was corrupt. thanks! Cheers, Soren From p.edelman at gmail.com Thu Apr 26 03:04:30 2007 From: p.edelman at gmail.com (Pieter Edelman) Date: 26 Apr 2007 00:04:30 -0700 Subject: Access to raw command line? Message-ID: <1177571070.229968.155710@t39g2000prd.googlegroups.com> Hi, I'm currently writing a command-line program in Python, which takes commands in the form of: ./myprog.py [OPTIONS] ARGS So pretty standard stuff. In my case, ARGS is a list of image files. One of the possible options is to specify a file holding information about the photos. You'd specify it with (in this particular case) the - t switch, and you can specify multiple files by repeating this switch: ./myprog.py -t info1.gpx -t info2.gpx -t info3.gpx *jpg Now, one of the users has quite a lot of info files, and asked me if it's possible to use a wildcard in specifying these, so he would just have to do: ./myprog.py -t *.gpx *.jpg This seems like a sensible option at first sight, but it's difficult to implement because the wildcard is expanded by the shell, so sys.argv gets a list containing "-t", all .gpx files and all .jpg files. With this list, there's no way to tell which files belong to the "-t" switch and which are arguments (other than using the extension). One possible way to work around this is to get the raw command line and do the shell expansions ourselves from within Python. Ignoring the question of whether it is worth the trouble, does anybody know if it is possible to obtain the raw (unexpanded) command line? Alternatively, does anybody have suggestion of how to do this in a clean way? Thanks, Pieter From kyosohma at gmail.com Mon Apr 16 16:40:11 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: 16 Apr 2007 13:40:11 -0700 Subject: Printing Using Python In-Reply-To: <1176750825.770991.141640@y80g2000hsf.googlegroups.com> References: <1176750825.770991.141640@y80g2000hsf.googlegroups.com> Message-ID: <1176756011.755933.176690@d57g2000hsg.googlegroups.com> On Apr 16, 2:13 pm, "Raja" wrote: > Hi, > Attached is the code . I want my program to save the current printer > job properties and , when I reconnect the printer at a latter date , i > need to print the saved job . Can you please help with my code ? How > to print a document at a later stage and any errors in my code ? > > import win32ui > import win32con > > myprinter_name = "" > # get the name from your Printers folder > > printer_properties=[] > > def save(): > pHandle = win32print.OpenPrinter(myprinter_name) > properties = win32print.GetPrinter(pHandle, 2) > pDevModeObj = properties["pDevMode"] > printer_properties.append(pDevModeObj.FormName) > printer_properties.append(pDevModeObj.PaperSize) > printer_properties.append(pDevModeObj.Orientation) > printer_properties.append(pDevModeObj.Color) > printer_properties.append(pDevModeObj.Copies) > printer_properties.append(pDevModeObj.DefaultSource) > win32print.ClosePrinter(pHandle) > > def apply(): > hprinter = win32print.OpenPrinter(myprinter_name) > > devmode = win32print.GetPrinter(hprinter, 2)["pDevMode"] > devmode.FormName=printer_properties[0] > devmode.PaperSize=printer_properties[1] > devmode.Orientation=printer_properties[2] > devmode.Color=printer_properties[3] > devmode.Copies=printer_properties[4] > devmode.DefaultSource=printer_properties[5] > > hdc = win32gui.CreateDC("WinPrint",myprinter_name,devmode) > dc = win32ui.CreateDCFromHandle(hdc) > > dc.StartDoc('My Python Document') > dc.StartPage() > dc.EndPage() > dc.EndDoc() > del dc > > You help is greatly appreciated. > > Thank You, > Raja. This sounds like a job for the pickle: http://docs.python.org/lib/module-pickle.html I would try "pickling" the printer_properties list and when you later need the pickled printer properties, unpickle them. Mike From ZeeGeek at gmail.com Sun Apr 15 18:18:12 2007 From: ZeeGeek at gmail.com (ZeeGeek) Date: 15 Apr 2007 15:18:12 -0700 Subject: Standardizing XML In-Reply-To: References: <1176625793.392269.24060@n59g2000hsh.googlegroups.com> <462215bc$1@griseus.its.uu.se> <1176660139.990518.239470@l77g2000hsb.googlegroups.com> Message-ID: <1176675492.346257.83160@o5g2000hsb.googlegroups.com> On Apr 15, 1:13 pm, ZeD wrote: > ZeeGeek wrote: > > in the code returned by Live Space, they use
instead of
so > > that Blogger will complain that this tag is not valid because it > > doesn't have a closing tag. Another example is that the contents of a > > lot of the tag attributes like "color" and "size" are not surrounded > > by quotes. > > Are you sure it's xml? It sounds to me like "old" HTML Yeah, I realized this after I read the first reply to my post. That was a big mistake to word it XML. From jzgoda at o2.usun.pl Fri Apr 13 16:07:14 2007 From: jzgoda at o2.usun.pl (Jarek Zgoda) Date: Fri, 13 Apr 2007 22:07:14 +0200 Subject: Python editor/IDE on Linux? In-Reply-To: <1176488840.672572.101830@y80g2000hsf.googlegroups.com> References: <1176488840.672572.101830@y80g2000hsf.googlegroups.com> Message-ID: 7stud napisa?(a): >> I wonder what everybody uses for Python editor/IDE on Linux? >> I use PyScripter on Windows, which is very good. Not sure if >> there's something handy like that on Linux. I need to do some >> development work on Linux and the distro I am using is Xubuntu. > > Everybody uses vim. Except for those who use PIDA (but they use Vim already). :D -- Jarek Zgoda http://jpa.berlios.de/ From ptmcg at austin.rr.com Mon Apr 30 10:40:35 2007 From: ptmcg at austin.rr.com (Paul McGuire) Date: 30 Apr 2007 07:40:35 -0700 Subject: Restricting the alphabet of a string In-Reply-To: <1177941629.309093.97400@y5g2000hsa.googlegroups.com> References: <1177941629.309093.97400@y5g2000hsa.googlegroups.com> Message-ID: <1177944035.844725.171010@n76g2000hsh.googlegroups.com> On Apr 30, 9:00 am, 7stud wrote: > On Apr 30, 5:53 am, "Nathan Harmston" > wrote: > > > > > > > Hi, > > > I ve being thinking about playing around with bit strings but use in > > some encoding problems I m considering and was trying to decide how to > > implement a bit string class. Is there a library out there for doing > > basic things with bit strings already is my first question? > > > I know that I can extend string to bit string, but is there anyway I > > can force the alphabet to be restricted to 1's and 0's (or even 1, 0 > > and -1, as an extension to from trinary strings). > > > class Binary_String(String): > > pass > > > Many Thanks > > > Nathan > > You could do something like this: > > class Binary_String(str): > def __init__(self, val): > i = 0 > for char in val: > if char not in "-101": > raise ValueError("illegal character at index " + > str(i) + "\nOnly -1,0,1 allowed.") > > i+=1 > self.val = val > > b = Binary_String("1a0101") > > --output:-- > Traceback (most recent call last): > File "test1.py", line 13, in ? > b = Binary_String("1a100") > File "test1.py", line 6, in __init__ > raise ValueError("illegal character at index " + str(i) > ValueError: illegal character at index 1 > Only -1,0,1 allowed.- Hide quoted text - > > - Show quoted text - Your character test only needs to check if the character is in "-10", not "-101". In fact, this is a little misleading, since it appears to check for "-1" but is really only checking for "-"s and "1"s (and "0"s too, of course). This code accepts "1-0101" also, but what is -0? -- Paul -- Paul From tim at tdw.net Sat Apr 7 12:53:28 2007 From: tim at tdw.net (Tim Williams) Date: Sat, 7 Apr 2007 17:53:28 +0100 Subject: Can't Get Email Interface Working In-Reply-To: References: Message-ID: <9afea2ac0704070953o6a1b8abbjcce6b6789e809088@mail.gmail.com> On 07/04/07, Eric Price wrote: > Good grief! And they call a 722-line program "simple"?! LOL! > I did what I need to do with a __one_line_shell_script__ LOL! > Naw, if I have to go through all that, I'll skip on python this time around, > thank you very much! > Eric Yup, its not so simple Your problem is : File "/usr/local/lib/python2.4/mimetools.py", line 130, in choose_boundary hostid = socket.gethostbyname(socket.gethostname()) socket.gaierror: (8, 'hostname nor servname provided, or not known') What do you get if you do the following in your interpreter? >>> import socket >>> socket.gethostname() 'twilliams' >>> socket.gethostbyname(socket.gethostname()) '194.129.107.254' >>> From tjreedy at udel.edu Tue Apr 10 21:09:39 2007 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 10 Apr 2007 21:09:39 -0400 Subject: tuples, index method, Python's design References: <1175867771.114540.61810@n76g2000hsh.googlegroups.com><1175884427.779950.267220@y80g2000hsf.googlegroups.com><1175953520.316208.241490@o5g2000hsb.googlegroups.com><7xzm5igbrb.fsf@ruckus.brouhaha.com><1176200361.260546.280510@n76g2000hsh.googlegroups.com><1176215231.002726.148960@y5g2000hsa.googlegroups.com> <1176220636.297496.21440@o5g2000hsb.googlegroups.com> Message-ID: "Paul Boddie" wrote in message news:1176220636.297496.21440 at o5g2000hsb.googlegroups.com... | always enlightening/entertaining to see the rationales given for the | rejection of this and other features, in contrast to things like "y if | x else z" which just seem to mysteriously acquire momentum and then | power their way in regardless. No mystery. It was Guido's initial proposal and he never changed his mind. From kyosohma at gmail.com Tue Apr 3 12:11:43 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: 3 Apr 2007 09:11:43 -0700 Subject: Stack experiment In-Reply-To: <5QuQh.152$9L1.108@read3.inet.fi> References: <5QuQh.152$9L1.108@read3.inet.fi> Message-ID: <1175616703.386553.147830@w1g2000hsg.googlegroups.com> On Apr 3, 10:57 am, t... at finland.com wrote: > Hi! Im new to Python and doing exercise found from internet. It is > supposed to evaluate expression given with postfix operator using > Stack() class. > > class Stack: > def __init__(self): > self.items = [] > > def push(self, item): > self.items.append(item) > > def pop(self): > return self.items.pop() > > def isEmpty(self): > return (self.items == []) > > def evaluatePostfix(expr): > import re > tokenList = re.split(" ([^0-9])", expr) > stack = Stack() > for token in tokenList: > if token == '' or token == ' ': > continue > if token == '+': > sum = stack.pop() + stack.pop() > stack.push(sum) > elif token == '*': > product = stack.pop() * stack.pop() > stack.push(product) > else: > stack.push(int(token)) > return stack.pop() > > print evaluatePostfix("56 47 + 2 *") > > Errormsg: > Traceback (most recent call last): > File "C:\*\postfix1.py", line 31, in > print evaluatePostfix("56 47 + 2 *") > File "C:\*\postfix1.py", line 28, in evaluatePostfix > stack.push(int(token)) > ValueError: invalid literal for int() with base 10: '56 47' > > How can I avoid the error and get desired result? I don't know why you're using the "re" module. For this, I would skip it. Change your code so that it looks like this: def evaluatePostfix(expr): tokenList = expr.split(" ") stack = Stack() for token in tokenList: if token == '' or token == ' ': continue if token == '+': sum = stack.pop() + stack.pop() stack.push(sum) elif token == '*': product = stack.pop() * stack.pop() stack.push(product) else: stack.push(int(token)) return stack.pop() # this worked for me. There may be something wrong with the "re" code in your example, but I don't know enough about that to help in that area. Mike From gregcorradini at gmail.com Wed Apr 18 14:36:59 2007 From: gregcorradini at gmail.com (Greg Corradini) Date: Wed, 18 Apr 2007 11:36:59 -0700 (PDT) Subject: Help Understanding mx.ODBC Error Message-ID: <10063746.post@talk.nabble.com> Hello All, A few weeks ago, I wrote two scripts using mx.ODBC on an Access DB. Among other things, both scripts create new tables, perform a query and then populate the tables with data in a dictionary that I've uploaded from elsewhere. These scripts have run hundreds of times in the last few weeks with no problems. But recently they continue to bail on the mycursor.execute('An SQL Statement') after the table has been created. I get the following error message: Traceback (most recent call last): File "C:\Documents and Settings\marv1shi\Desktop\Workspace\Existence Script\DBF Checker\Access_SQL.py", line 35, in ? curse.execute(sql) ProgrammingError: ('07001', -3010, '[Microsoft][ODBC Microsoft Access Driver] Too few parameters. Expected 4.', 4612) The real stinker, however, is that after it bails I can manually call mycursor.execute('An SQL Statement'), then call my insert statement in the Python Shell and it works fine. I just can't figure out how to reconcile this problem. Has anybody run into this before? Thanks Greg Corradini -- View this message in context: http://www.nabble.com/Help-Understanding-mx.ODBC-Error-tf3602497.html#a10063746 Sent from the Python - python-list mailing list archive at Nabble.com. From steve at holdenweb.com Wed Apr 4 17:46:37 2007 From: steve at holdenweb.com (Steve Holden) Date: Wed, 04 Apr 2007 17:46:37 -0400 Subject: Why NOT only one class per file? In-Reply-To: References: <1175721799.714907.52770@o5g2000hsb.googlegroups.com> Message-ID: Jarek Zgoda wrote: > Chris Lasher napisa?(a): > >> A friend of mine with a programming background in Java and Perl places >> each class in its own separate file in . I informed him that keeping >> all related classes together in a single file is more in the Python >> idiom than one file per class. He asked why, and frankly, his valid >> question has me flummoxed. >> >> I tried to rationalize this Python idiom by claiming a file--a single >> module--makes for a great container of code which is logically tied >> together, such as a class and its subclasses. He posited that >> directories (packages) can tie the files together just as well, and by >> having the classes as separate files, he can "diff" them to see how >> they differ, something he wouldn't be able to do with the code all in >> one file. > > I'd not try to rationalize it, it's just natural. The requirement to > have only one public class per module needs rationalization (other than > limitation of compiler), not the freedom to have as much of classes in > module as is needed by program's architecure. > The fact that your friend find being able to diff his classes valuable implies that he isn't taking much advantage of modularity anyway but instead using copy-and-paste techniques. Of course I may be doing him a disservice. In Java *everything* has to be in a class, unlike in Python. The module seems a much more natural unit of storage to me, and to force us to put each class in its own module would seem unnatural. 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 aisaac at american.edu Thu Apr 12 17:56:48 2007 From: aisaac at american.edu (Alan Isaac) Date: Thu, 12 Apr 2007 21:56:48 GMT Subject: tuples, index method, Python's design References: Message-ID: Chris Mellon said: > Sure. I have never done this. In fact, I have only ever written code > that converted a tuple to a list once, and it was because I wanted > pop(), not index() Well then you apparently made a *mistake*: you chose a tuple when you wanted a mutable object. That is really beside the point. And you missed the point of my query. It is not that existing code will contain such a conversion to get access to the index method. It is that if you choose tuples to represent immutable sequences, sooner or later you will find you need to change your code to use a list not because you really want a mutable sequence but because you want the ``index`` method. Note that it has become clear that some people do not use tuples hardly ever, regardless whether their sequence is naturally mutable or immutable. Why? Because they want access the the list methods. **All** of these people fall in the category I am talking about. I do not really care if you reach mentally and then fix or actually type it. The avoidance of tuples, so carefully defended in other terms, is often rooted (I claim) in habits formed from need for list methods like ``index`` and ``count``. Indeed, I predict that Python tuples will eventually have these methods and that these same people will then defend *that* status quo. Bottom line: I do not consider being forced to disregard the natural mutability or immutability of an object as a "good thing". If you do not like my toy example, look at some of the others that have been offered. Getting information about point tuples has been my favorite so far. Btw, the tendency in this debate to ask if a tuple is "necessary" is both a red herring and obvious evidence of thoughtlessness. How many coding practices are "necessary"? The question is just whether we will be allowed to treat sequences that are naturally immutable as immutable or will be forced for no real reason (I believe the "code maintenance" issue has been dealt with) to treat them differently. Cheers, Alan Isaac From jimmyetouma at earthlink.net Mon Apr 9 06:24:52 2007 From: jimmyetouma at earthlink.net (Jimmy E Touma) Date: Mon, 09 Apr 2007 10:24:52 GMT Subject: Crypto Suggestion/Help In-Reply-To: <7xveg68a9k.fsf@ruckus.brouhaha.com> References: <7xveg68a9k.fsf@ruckus.brouhaha.com> Message-ID: Paul, Thanks for the reply. Yes the shop has only one machine and many users use it to perform transactions. Maybe a basic Linux/Unix permissions will do as Thomas Kruger suggested in the thread following you. --Jimmy Paul Rubin wrote: > Jimmy E Touma writes: >> I need some advise on doing the following. I have a Linux application >> that allows users to access it via a code (password). At the end of the >> day, I gather a log of activities of the users and zip the file and >> would like to encrypt it so that the users can not access it or tamper >> with it. Only manager should. If I use a private/public key for doing so >> I have to store the private key on my computer. What is a good way to >> encrypt a file and have the key well hidden on the same computer? If you >> have any other way to do, like MD5 or similar, please let me know. > > Are you saying you have a desktop app that's running on the user's own > machine and you're trying to prevent the user from getting at the log > data? That is impossible if the user has control over the machine and > is willing and able to hack the software. If you just want to make an > encrypted file that the user can't decrypt, use a public key on the > user's machine, and only have the secret key on the manager's machine. From apardon at forel.vub.ac.be Fri Apr 27 05:01:16 2007 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 27 Apr 2007 09:01:16 GMT Subject: Tutorial creates confusion about slices References: <1177496078.319400.324720@r30g2000prh.googlegroups.com> Message-ID: On 2007-04-26, Steve Holden wrote: > Antoon Pardon wrote: >> On 2007-04-25, Steve Holden wrote: > [...] >>>> >>> Most people reading a tutorial are aware that they are being given the >>> knowledge they need to put the subject matter to immediate use, and that >>> there may well be refinements that are glossed over or covered in detail >>> later or elsewhere. >> >> I agree with that. >> >> However there is a difference between information that will help you >> on the way now that will be refined later and information that will >> help you on the way now and will be contradicted later. >> >> I also understand that the line between the two is rather fuzzy. >> >> In my opinion the text in the tutorial as it stands now, is more >> of the latter than of the former type and that is why I would >> prefer a change. >> > I had already deduced that from your arguments so far in this thread. Do > you *have* to make every trivial conclusion explicit? Well my problem was I had the feeling your remark totally ignored that. I honestly don't understand what you thought your remark would contribute if you had deduced the above. It is very possible that this is a failing of mine in recognizing when people have understood the point I am trying to make. > Warning: this is an explicit test to see whether you can sit on your > hands and refrain from replying. It's hard to find a thread where you > don't make the last comment on every branch you get involved in. Well I guess I failed. -- Antoon Pardon From stefan.behnel-n05pAM at web.de Sun Apr 22 09:24:55 2007 From: stefan.behnel-n05pAM at web.de (Stefan Behnel) Date: Sun, 22 Apr 2007 15:24:55 +0200 Subject: Dictionaries and dot notation In-Reply-To: <23087554.X5dcTmlj7P@beaureve.gmx.net> References: <23087554.X5dcTmlj7P@beaureve.gmx.net> Message-ID: <462B6227.5070405@web.de> Martin Drautzburg wrote: > This may be pretty obvious for most of you: > > When I have an object (an instance of a class "Foo") I can access > attributes via dot notation: > > aFoo.bar > > however when I have a dictionary > > aDict = {"bar":"something"} > > I have to write > > aDict["bar"] > > What if I want to create a datastructure that can be used in dot > notation without having to create a class, i.e. because those objects > have no behavior at all? > > I know that accessing an instance variable via bracket notation would > really have to be written as: > > aFoo.__dict__['bar'] > > but this does not bring me any further, because I would still have to > plug in that __dict__ thing into my datastructure, which leads us to > the same question as above. > > Can anyone tell me what I am missing here? This? http://docs.python.org/ref/attribute-access.html Stefan From nagle at animats.com Tue Apr 24 00:39:06 2007 From: nagle at animats.com (John Nagle) Date: Tue, 24 Apr 2007 04:39:06 GMT Subject: Does socket.setdefaulttimeout affect the timeouts in MySQLdb? Message-ID: Does setting "socket.setdefaulttimeout" affect the timeout in MySQLdb for connections to the database? I'm getting database connection timeouts on a local (same machine) connnection, and I've been setting "socket.setdefaulttimeout" to 15 seconds so web page opens don't hang. But MySQLdb uses the MySQL C library, which doesn't use Python opens. John Nagle From petercable at gmail.com Sat Apr 28 13:54:21 2007 From: petercable at gmail.com (petercable at gmail.com) Date: 28 Apr 2007 10:54:21 -0700 Subject: Beginner Ping program In-Reply-To: <1177739647.737759.32610@u30g2000hsc.googlegroups.com> References: <1177739647.737759.32610@u30g2000hsc.googlegroups.com> Message-ID: <1177782861.332626.169020@n76g2000hsh.googlegroups.com> On Apr 27, 10:54 pm, Linus Cohen wrote: > Hi all, > I'm a newbie to python and programming in general, so I wanted a > simple project to start off. What I'm trying to do here is write a > python command-line ping program, much like the Unix and Windows ping > programs. I've got this much worked out already: > > class ping > def PING(IP, pings, size): I agree with Marc here, probably no reason for a class here. As well, if you are creating classes, generally class names should be capitalized, methods should be lower case, i.e. class Ping(object): def ping(self, ip, pings, size): .... But, there really is no need for a class here, placeholder or otherwise. > > and that's where I stop, because I realize I have no idea how to make > python send ICMP request packets. My previous project(an email reader > using poplib)used the stuff in section 18 of the modules > index(internet protocols) but I can't seem to find an equivalent for > ICMP packets. If anyone has help on this, I would really appreciate > it. There is no (that I am aware of) ICMP module in the standard library. See http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/409689 for an example of a Python implementation of ping. > > Cheers, > Linus HTH, Pete From martin at v.loewis.de Thu Apr 12 17:24:48 2007 From: martin at v.loewis.de (=?ISO-8859-15?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Thu, 12 Apr 2007 23:24:48 +0200 Subject: How to copy a file on Windows while preserving permissions In-Reply-To: References: Message-ID: <461EA3A0.4010907@v.loewis.de> > Can someone who is more familiar than I with the vagaries of Windows file > protection and the Python interfaces available to it point me in a useful > direction? To copy a file along with its attributes, try SHFileOperation. Alternatively, if you have backup privileges, open the file for backup, then use BackupRead/BackupWrite. HTH, Martin From kyosohma at gmail.com Fri Apr 27 09:13:33 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: 27 Apr 2007 06:13:33 -0700 Subject: Multiple select in wx.GenericDirCrtl In-Reply-To: <1177677090.037403.209940@n15g2000prd.googlegroups.com> References: <1177677090.037403.209940@n15g2000prd.googlegroups.com> Message-ID: <1177679613.209726.90510@s33g2000prh.googlegroups.com> On Apr 27, 7:31 am, Soren wrote: > Hi! > > Is it possible to do multiple file selections in a wx.GenericDirCtrl?? > > Thanks, > Soren I'm not finding anything. I do know you can select multiple files using the FileDialog. You should email the wxPython users group though. They may have a custom control or they will likely be able to point you in the right direction. http://www.wxpython.org/maillist.php Mike From gagsl-py2 at yahoo.com.ar Wed Apr 11 14:35:26 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 11 Apr 2007 15:35:26 -0300 Subject: THREADS use 100 % CPU all the time References: <1176284321.528102.112740@o5g2000hsb.googlegroups.com> <1176291417.888693.107050@w1g2000hsg.googlegroups.com> Message-ID: En Wed, 11 Apr 2007 08:36:57 -0300, A.B., Khalid escribi?: > On Apr 11, 2:38 am, matthiasja... at gmx.net wrote: >> I have a application where I use different threads. actually all is >> working - BUT I just discovered that the [b]CPU is always 100 % [/ >> b]used. >> > You need your program to sleep a while to allow a switch to other > tasks. Like so: > > t = TestThread() > t.start() > > while (True): > time.sleep(0.01) > pass If all you want is to wait until the thread finishes, use t.join() instead of that infinite loop. -- Gabriel Genellina From jon+usenet at unequivocal.co.uk Fri Apr 20 12:54:31 2007 From: jon+usenet at unequivocal.co.uk (Jon Ribbens) Date: 20 Apr 2007 16:54:31 GMT Subject: I need a string/list/generator/comprehension incantation. References: Message-ID: In article , Steven W. Orr wrote: > Now I want something that's going to give me a string whose value is the > set of all of the first letters of months. Order is not important. "".join(set(m[0] for m in calendar.month_abbr[1:])) > And for extra credit, I need the string whose value is the set of all of > the letters of months minus the first letter. "".join(set("".join(m[1:] for m in calendar.month_abbr[1:]))) Those are the ways that are obvious to me anyway, maybe there are better ways. If you actually want a set not a string, remove the outer-most "".join(). From steve at REMOVE.THIS.cybersource.com.au Mon Apr 9 09:08:06 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Mon, 09 Apr 2007 23:08:06 +1000 Subject: Is there a simple function to generate a list like ['a', 'b', 'c', ... 'z']? References: <1176107364.000517.68580@q75g2000hsh.googlegroups.com> <1176108191.558918.196040@d57g2000hsg.googlegroups.com> Message-ID: On Mon, 09 Apr 2007 01:43:11 -0700, 7stud wrote: >> Is there a simple function to generate a list like ['a', 'b', 'c', ... >> 'z']? ? The range() just can generate the numeric list. > > Not very simple, but how about a list comprehension: > > import string > > lst = [char for char in string.letters[:26] ] > print lst Anytime you write a list comp like [x for x in thing] that should be a warning that you shouldn't be writing a list comp. lst = list(string.letters[:26]) -- Steven. From aleax at mac.com Mon Apr 9 02:29:07 2007 From: aleax at mac.com (Alex Martelli) Date: Sun, 8 Apr 2007 23:29:07 -0700 Subject: Exec Statement Question References: Message-ID: <1hw9ybw.14iarm5c1ej4xN%aleax@mac.com> Gregory Pi?ero wrote: > I'm curious why this code isn't working how I expect it to: > > import sys > d=3 > > def func1(a,b,c): > print a,b,c,d > print sys.path > > exec "func1(1,2,3)" in {'func1':func1} > > ---- > returns: > 1 2 3 3 > [ sys.path stuff ....] > > Since I'm telling exec to operate only within the context of the > dictionary I give it, why does it still see sys.path and d? I figured > it would throw a NameError. > > Is there a way to call exec such that it won't have access to any more > objects than I explicitly give it? func1 accesses its globals through func1.func_globals (which you can't reassign -- it's a read-only attribute). You may make a new function object w/ a different globals dict...: >>> g = type(func1)(func1.func_code, {}) and that will fail (even when called directly, but similarly if exec'd) as it's missing key 'd' in its globals: >>> g(1, 2, 3) 1 2 3 Traceback (most recent call last): File "", line 1, in File "", line 2, in func1 NameError: global name 'd' is not defined The globals dict you pass to exec is the globals at the time of CALL, not the globals seen from INSIDE func1; that's always going to be the func_globals attribute of the function object, so you need to control that (by suitably building a new function object as you require). Alex From rpdooling at gmail.com Wed Apr 18 11:08:06 2007 From: rpdooling at gmail.com (BartlebyScrivener) Date: 18 Apr 2007 08:08:06 -0700 Subject: Wanted: Email Client with GUI In-Reply-To: References: <1176905369.228287.224870@l77g2000hsb.googlegroups.com> Message-ID: <1176908886.768562.54240@p77g2000hsh.googlegroups.com> On Apr 18, 9:25 am, Franz Steinhaeusler wrote: > >> What I want is a program (it doesn't have to be so sophisticated > >> as thunderbird) written totally in python and using a gui > >> toolkit like pyqt, pygtk, wxpyhton or tkinter. Why reinvent the wheel? Why not use Mutt and then call any Python script you want from within Mutt. Or use Python modules written for Mutt. See, e.g., http://pyropus.ca/software/ rd From carsten at uniqsys.com Thu Apr 19 14:28:26 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Thu, 19 Apr 2007 14:28:26 -0400 Subject: Python COM iterator In-Reply-To: References: <46279B56.4020901@websafe.com> Message-ID: <1177007306.3411.108.camel@dot.uniqsys.com> On Thu, 2007-04-19 at 12:49 -0400, Steve Holden wrote: > Larry Bates wrote: > > Carsten Haese wrote: > [iterative acess to COM objects] > > I tested in VB and by golly it works! What is odd is that this looks > > NOTHING like what we got from the docs earlier. No GetEnumerator > > method, no MoveNext method. I'm glad it works, but I'm a little > > puzzled as to why it works. I'm glad, too. > Presumably the magic of mark Hammond's wrapper classes providing > adaptation between Python iteration and COM enumerable collection > objects. win32all is *very* Pythonic. There is some magic, but it appears to be on the client side only. This magic is what allows you to stick the win32com.client.Dispatcher object into a for-loop. If there were magic on the server side, it shouldn't be necessary to declare that IID_IEnumVARIANT is exposed, and it shouldn't be necessary to implement the _NewEnum and Next methods; it should be enough to have __iter__ present and let the magic take care of the rest. It appears that the reason why my first completely uninformed guess didn't work and my second somewhat less uninformed guess did work is that there are two different enumeration protocols in the wonderfully confusing world of Win32. I'm guessing that GetEnumerator/MoveNext is the .NET enumeration protocol and IID_IEnumVARIANT/Next is the COM enumeration protocol. -Carsten From DustanGroups at gmail.com Wed Apr 25 22:03:30 2007 From: DustanGroups at gmail.com (Dustan) Date: 25 Apr 2007 19:03:30 -0700 Subject: Where's the source code for __builtin__? In-Reply-To: <462EA63C.6080805@lexicon.net> References: <1177457545.075398.204990@r3g2000prh.googlegroups.com> <462EA63C.6080805@lexicon.net> Message-ID: <1177553009.896534.135960@t38g2000prd.googlegroups.com> On Apr 24, 7:52 pm, John Machin wrote: > On 25/04/2007 9:32 AM, Dustan wrote: > > > I've been paging through the source code for various C modules in > > python, and wanted to find the source of some of the builtin > > functions. I searched through the Modules, Objects, Python, and Parser > > folder, searched docs.python.org, searched the archived messages of > > this group, searched the web, and got absolutely nowhere in finding a > > __builtin__.c, or anything that contains the builtin source code. > > > Help? > > What's the 2nd file (in alphabetical order) in the Python folder? ast.c? But that doesn't help much... But wait! There's another file... # 4 in the Python folder, which, naturally following the explicit nature of python, is given the name "bltinmodule.c". I don't know how I managed to get more 'a' files than you did, though... Anyway, thanks for pointing me to the right folder. From bbxx789_05ss at yahoo.com Tue Apr 10 23:23:18 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: 10 Apr 2007 20:23:18 -0700 Subject: Does python have the static function member like C++ In-Reply-To: <1176260903.362329.59370@o5g2000hsb.googlegroups.com> References: <1176260903.362329.59370@o5g2000hsb.googlegroups.com> Message-ID: <1176261798.499579.158860@y5g2000hsa.googlegroups.com> On Apr 10, 9:08?pm, "???????????????" wrote: > I define the class like this: > class AAA: > ? ? counter = 0 > ? ? def __init__(self): > ? ? ? ? pass > ? ? def counter_increase(): > ? ? ? ? AAA.counter += 1 > ? ? ? ? print "couter now :", AAA.counter > > But how could I call the function "counter_incrrease" ? > > Thanks ! You can also do this: class AAA: counter = 0 def __init__(self): pass AAA.counter += 1 print AAA.counter From dwmaillist at gmail.com Wed Apr 18 10:38:51 2007 From: dwmaillist at gmail.com (Daniel Watrous) Date: Wed, 18 Apr 2007 08:38:51 -0600 Subject: python - dll access (ctypes or swig) In-Reply-To: References: Message-ID: <883e18590704180738y2efe15bxc0303602a6daa6fa@mail.gmail.com> thank you for the responses and the links. I will give these ideas a try this week and post again if I have more questions. Thanks again for being so helpful! Daniel On 4/17/07, Cameron Laird wrote: > In article , > Larry Bates wrote: > >Daniel Watrous wrote: > >> Hello, > >> > >> I am interested in using python to script access to some hardware for > >> which there are existing drivers in the form of DLLs. The DLLs each > >> have four exported functions and a host of COM Properties and COM > >> Methods. The four exported functions are as follows: > >> DllCanUnloadNow > >> DllGetClassObject > >> DllRegisterServer > >> DllUnregisterServer > >> > >> The COM methods and properties all begin with I, followed by a unique name. > >> > >> I am able to load the DLL using ctypes and it can access the exported > >> functions, but I'm not sure how to access the COM methods and > >> properties. I have read that ctypes once had support for COM but that > >> it has since been separated into its own project. I couldn't find any > >> information about how these work together. > >> > >> All help is appreciated. THANKS in advance... > >> > >> Daniel > > > >I recently learned that you can ship COM as either an .EXE or a .DLL (nobody > >has yet let me know why). You don't have a traditional .DLL that you would > >use ctypes to call methods in, you have a COM .DLL. COM methods need to be > >access with Win32com > > > >obj=win32com.client.Dispatch("typelib name"). > > > >You need to find out the COM dispatch typelib name and make sure the DLL is > >registered (regsvr32 your.dll). > > > >-Larry > > Is this--adroit use of Win32com with special-purpose DLLs--written > up anywhere? Doing this with unusual hardware that turns up in the > real world is ENTIRELY more satisfying than trying to wrangle the > Visual C bindings that vendors usually push, but, apart from Mark > and Andy's book, now over seven years old, I know of no appropri- > ately ambitious tutorial in the subject. > > Daniel, do you have what you need to make progress? Have you seen > ? > -- > http://mail.python.org/mailman/listinfo/python-list > From mail at microcorp.co.za Sat Apr 21 04:11:24 2007 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Sat, 21 Apr 2007 10:11:24 +0200 Subject: Do other Python GUI toolkits require this? (OT) References: <462697A6.6010007@codebykevin.com> <465B30B4-5BA0-459A-BE6F-1038874FA74B@jedimindworks.com> Message-ID: <01a001c783f0$68f317e0$03000080@hendrik> "Roel Schroeven" wrote: > Hendrik van Rooyen schreef: > > "Steve Holden" wrote: > > > > > >> Perhaps in Belgium they prefer climbing mountains over walking up and > >> down gentle hills? > > > > Mountains ? Hills ? In Belgium ?? > > > > Its not called the battlefield of Europe for nothing... > > I'm not sure if this adds anything of interest (well actually I'm pretty > sure it doesn't), but our king Albert I was a fanatic mountain climber, > until he died from a fall in 1934. > Thanks - I was not aware of that. Adds a whole new dimension to the phrase: "The Fall of a King" What was he climbing when he fell, btw? - Hendrik From bjourne at gmail.com Wed Apr 4 09:37:05 2007 From: bjourne at gmail.com (=?ISO-8859-1?Q?BJ=F6rn_Lindqvist?=) Date: Wed, 4 Apr 2007 15:37:05 +0200 Subject: An error of matrix inversion using NumPy In-Reply-To: <1175692518.282887.3040@y66g2000hsf.googlegroups.com> References: <1175692518.282887.3040@y66g2000hsf.googlegroups.com> Message-ID: <740c3aec0704040637i50efaaa9u1fdd5d39bcd73aca@mail.gmail.com> On 4 Apr 2007 06:15:18 -0700, lancered wrote: > During the calculation, I noticed an apparent error of > inverion of a 19x19 matrix. Denote this matrix as KK, U=KK^ -1, I > found the product of U and KK is not equivalent to unit matrix! This > apparently violate the definition of inversion. The inversion is > through the function linalg.inv(). Could it have something to do with floating point accuracy? >>> r = matrix([[random.random() * 9999 for x in range(19)] for y in range(19)]) >>> allclose(linalg.inv(r) * r, identity(19)) True > So, can you tell me what goes wrong? Is this a bug in > Numpy.linalg? How to deal with this situation? If you need, I can > post the matrix I used below, but it is so long,so not at the moment. Please post it. -- mvh Bj?rn From laurent.pointal at limsi.fr Thu Apr 26 09:09:22 2007 From: laurent.pointal at limsi.fr (Laurent Pointal) Date: Thu, 26 Apr 2007 15:09:22 +0200 Subject: Store variable name in another variable In-Reply-To: <1177592072.498517.139260@b40g2000prd.googlegroups.com> References: <1177592072.498517.139260@b40g2000prd.googlegroups.com> Message-ID: loial a ?crit : > I need to store a list of variable names in a dictionary or list. I > then later need to retrieve the names of the variables and get the > values from the named variables. The named variables will already have > been created and given a value. "Named variables will already have been created"... in what namespace ? Store a list of names -> dict/list (see tutorial) Then, use namespace.name or getattr(namespace,"name") or locals()["name"] or globals()["name"] From boris.dusek at gmail.com Thu Apr 19 15:58:14 2007 From: boris.dusek at gmail.com (=?utf-8?B?Qm9yaXMgRHXFoWVr?=) Date: 19 Apr 2007 12:58:14 -0700 Subject: Significance of "start" parameter to string method "endswith" Message-ID: <1177012694.726434.142660@q75g2000hsh.googlegroups.com> Hello, what is the use-case of parameter "start" in string's "endswith" method? Consider the following minimal example: a = "testing" suffix="ing" a.endswith(suffix, 2) Significance of "end" is obvious. But not so for "start". Let's assume the "end" parameter is not used - then the function should simple check that the last "len(suffix)" characters of "a" are equal to "ing", no matter where we start (the function does not *scan* the string from the "start", does it?) Only case where it would make difference is if we had start + len(suffix) < len(a) (excuse possible "of-by-one" error :-) Then the function would never return True. But is there a real use case when we would test for endswith like this? (knowing that it must return false?) Thanks for any ideas/experience. Boris From bill.sloman at ieee.org Tue Apr 24 12:00:56 2007 From: bill.sloman at ieee.org (bill.sloman at ieee.org) Date: 24 Apr 2007 09:00:56 -0700 Subject: *** Dr G Polya BRILLIANTLY analyses the Virgina Shooting Incident *** In-Reply-To: <1177416547.394200.314950@r3g2000prh.googlegroups.com> References: <1177266754.126153.202760@b58g2000hsg.googlegroups.com> <1177287460.376404.323520@b58g2000hsg.googlegroups.com> <1177416547.394200.314950@r3g2000prh.googlegroups.com> Message-ID: <1177430456.620057.190820@n15g2000prd.googlegroups.com> On Apr 24, 2:09 pm, Quadibloc wrote: > The Real Andy wrote: > > Makes me wonder about the credibility of any statement Dr Gideon Polya > > makes. > > . > I never thought that I would feel the urge to call someone an > edelweiss-eating Tanzanian devil, but Dr. Polya proved that I lacked > imagination. > > (Note that "Tanzanian" is pronounced Tan.zan._ee_.yan, not > Tan._zayn_.ee.an; one wouldn't want to spoil the effect.) The effect is - in fact - more severely damaged by your confusion between Tasmania - where Dr. Polya actually lives - and Tanzania which is a country in Africa with a name similar enough to confuse semi- literate Americans. Tasmania is a reasonably large island (about the same size as Ireland) a couple of hundred miles south of the Australian mainland. It is a state of Australia (not Austria, which is where you'd need to go for edelweiss). -- Bill Sloman, Nijmegen From len-l at telus.net Sun Apr 1 17:58:58 2007 From: len-l at telus.net (Lenard Lindstrom) Date: Sun, 01 Apr 2007 21:58:58 GMT Subject: Character set woes with binary data In-Reply-To: References: <1175415685.21349.79.camel@pepper.trausch.us> Message-ID: John Nagle wrote: > Michael B. Trausch wrote: >> In short: How do I create a string that contains raw binary content >> without Python caring? Is that possible? > > Given where we're now at with strings in Python, Python should > really have a "byte" type and a way to deal with arrays of bytes, > independent of the string operators. > > Efficient handling of lists of bytes would do it. > > John Nagle array.array or ctypes.create_string_buffer. Lenard Lindstrom From mansonmuni at alexandria.cc Wed Apr 25 12:53:46 2007 From: mansonmuni at alexandria.cc (Glen) Date: Wed, 25 Apr 2007 11:53:46 -0500 Subject: lowercase class names, eg., qtgui ? (PyQt4) Message-ID: Hello, In the file generated by pyuic4 from Designer's .ui file I noticed the use of lower case class names (I'm assuming these are the names of classes, not modules). For example: It imports thusly: from PyQt4 import QtGui then uses things like: self.gridlayout = qtgui.qgridlayout(dldialog) What exactly is going on here? Are these instances that are defined somewhere else (their not in the local scope.)? Can I do the same in my code when I import something? Thanks, Glen Glen From hq4ever at gmail.com Fri Apr 6 10:32:50 2007 From: hq4ever at gmail.com (Maxim Veksler) Date: Fri, 6 Apr 2007 16:32:50 +0200 Subject: low level networking in python In-Reply-To: <4613d7a2$0$331$e4fe514c@news.xs4all.nl> References: <1175615037.137052.70980@w1g2000hsg.googlegroups.com> <4613d7a2$0$331$e4fe514c@news.xs4all.nl> Message-ID: On 4/4/07, Irmen de Jong wrote: > Maxim Veksler wrote: > > > I'm trying to bind a non-blocking socket, here is my code: > > """ > > #!/usr/bin/env python > > > > import socket, select > > from time import sleep > > > > s_nb10000 = socket.socket(socket.AF_INET, socket.SOCK_STREAM) > > s_nb10000.setblocking(0) > > > > s_nb10000.bind(('192.168.2.106', 10002)) > > s_nb10000.listen(5) > > > > while 1: > > conn, addr = s_nb10000.accept() > > ready_to_read, ready_to_write, in_error = select.select([conn], [], > > [], 0) > > print (ready_to_read, ready_to_write, in_error) > > sleep(100) > > > > s_nb10000.close() > > """ > > > > And this is the exception I'm getting: > > """ > > python non_blocking_socket.py > > Traceback (most recent call last): > > File "non_blocking_socket.py", line 13, in ? > > conn, addr = s_nb10000.accept() > > File "/usr/lib/python2.4/socket.py", line 161, in accept > > sock, addr = self._sock.accept() > > socket.error: (11, 'Resource temporarily unavailable') > > """ > > > > What am I doing wrong here? > > Nothing. > Any operation on a non-blocking socket that is usually blocking > (this includes accept(), bind(), connect(), recv with MSG_WAITALL) > can possibly return a socket.error with errno set to EAGAIN. > ('resource temporarily unavailable'). > If this happens you should use a select() on the socket to > wait until it's done with the requested operation. > Hello everyone, I would like to thank you all for the helping tips so far, with your help I managed to improve the previous code to not give the error, I believe it's now working. The non blocking echo socket code: """ #!/usr/bin/env python import socket, select s_nb10000 = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s_nb10000.setblocking(0) s_nb10000.bind(('0.0.0.0', 10002)) s_nb10000.listen(5) while 1: ready_to_read, ready_to_write, in_error = select.select([s_nb10000], [], [], 0) if s_nb10000 in ready_to_read: conn, addr = s_nb10000.accept() while 1: data = conn.recv(1024) if not data: break conn.send(data) conn.close() s_nb10000.close() """ > --Irmen > Maxim. -- Cheers, Maxim Veksler "Free as in Freedom" - Do u GNU ? From apardon at forel.vub.ac.be Tue Apr 24 02:42:49 2007 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 24 Apr 2007 06:42:49 GMT Subject: Tutorial creates confusion about slices References: Message-ID: On 2007-04-23, Hamilton, William wrote: >> -----Original Message----- >> From: python-list-bounces+whamil1=entergy.com at python.org > [mailto:python- >> list-bounces+whamil1=entergy.com at python.org] On Behalf Of Antoon > Pardon >> Sent: Monday, April 23, 2007 7:38 AM >> To: python-list at python.org >> Subject: Tutorial creates confusion about slices >> >> The following is part of the explanation on slices in the >> tutorial: >> >> The best way to remember how slices work is to think of the indices as >> pointing between characters, with the left edge of the first character >> numbered 0. Then the right edge of the last character of a string of n >> characters has index n, for example: >> >> +---+---+---+---+---+ >> | H | e | l | p | A | >> +---+---+---+---+---+ >> 0 1 2 3 4 5 >> -5 -4 -3 -2 -1 >> >> This is all very well with a simple slice like: >> >> "HelpA"[2:4] => "lp" >> >> >> But it give the wrong idea when using the following extended slice: >> >> "HelpA"[4:2:-1] => "Ap" >> >> So this doesn't result in the reverse of the previous expression while >> the explanation above suggest it does. > > It makes sense if you recognize that the negative step value also flips > which "side" the index is on. > > +---+---+---+---+---+ > | H | e | l | p | A | > +---+---+---+---+---+ > 0 1 2 3 4 > -6 -5 -4 -3 -2 -1 That is a possibility. I just don't think we can expect from people reading the tutorial to recognize this. So if we conclude this is the correct explanation it should be clearly explained in the tutorial. -- Antoon Pardon From aahz at pythoncraft.com Sat Apr 28 16:54:43 2007 From: aahz at pythoncraft.com (Aahz) Date: 28 Apr 2007 13:54:43 -0700 Subject: My Python annoyances References: <1177790269.523160.276060@l77g2000hsb.googlegroups.com> Message-ID: In article <1177790269.523160.276060 at l77g2000hsb.googlegroups.com>, =?iso-8859-1?B?QW5kcuk=?= wrote: > >Programming should be more difficult than this - otherwise, how can >programmers be respected by the common folks? http://www.netfunny.com/rhf/jokes/98/May/stroustrup.html -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "...string iteration isn't about treating strings as sequences of strings, it's about treating strings as sequences of characters. The fact that characters are also strings is the reason we have problems, but characters are strings for other good reasons." --Aahz From nono240 at gmail.com Sat Apr 7 10:54:50 2007 From: nono240 at gmail.com (nono240 at gmail.com) Date: 7 Apr 2007 07:54:50 -0700 Subject: 1 Thread = 3 interpreter launched ??? Message-ID: <1175957690.323531.50820@o5g2000hsb.googlegroups.com> Hi all, and thanks for reading ! I'm using Python 2.4.2 with an embedded platform (16MB RAM) running Linux 2.6.20. My main script use a thread for some reasons (more precisely a periodic timer within a separate module). While looking at the memory consumption, here's what i found : PID USER STATUS RSS PPID %CPU %MEM COMMAND 171 root R 384 164 1.5 2.6 top 218 root R 4172 217 0.1 29.1 main_script.py 216 root S 4172 180 0.0 29.1 main_script.py 217 root S 4172 216 0.0 29.1 main_script.py When creating the thread, Python forks 2 times and thus consume me around 60% of RAM ! Is it a normal behaviour while using threads ??? It's very critical, am i missed something ? Thank U... From jstroud at mbi.ucla.edu Fri Apr 13 16:49:04 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Fri, 13 Apr 2007 13:49:04 -0700 Subject: vocab question In-Reply-To: References: Message-ID: Alan G Isaac wrote: > Pardon the vocab question; > I'm not a computer science type. > According to the Reference Manual, > a class defintion has the structure:: > > classdef ::= "class" classname [inheritance] ":" suite > > What is the entire part before the suite called? > (Just pointing to a reference is fine & helpful, > as long as its not an entire course on BNF.) > > Thanks, > Alan Isaac Signature? From a.schmolck at gmail.com Thu Apr 5 06:50:15 2007 From: a.schmolck at gmail.com (Alexander Schmolck) Date: 05 Apr 2007 11:50:15 +0100 Subject: String manipulation References: <1175699768.427986.210310@l77g2000hsb.googlegroups.com> <1175702569.161940.113040@y66g2000hsf.googlegroups.com> <1175766154.893699.300250@l77g2000hsb.googlegroups.com> Message-ID: marco.minerva at gmail.com writes: > On 4 Apr, 21:47, Alexander Schmolck wrote: > > marco.mine... at gmail.com writes: > > > Thank you very much, your code works perfectly! > > > > One thing I forgot: you might want to make the whitespace handling a bit more > > robust/general e.g. by using something along the lines of > > > > set_phrase.replace(' ', r'\w+') Oops, sorry I meant r'\s+'. > > > > 'as > > Hi! > Thanks again... But where must I insert this instruction? If you're sure the code already does what you want you can forget about my remark; I was thinking of transforming individual patterns like so: 'kindest regard' -> r'kindest\w+regard', but it really depends on the details of your spec, which I'm not familiar with. For example you clearly want to do some amount of whitespace normalization (because you use ``.strip()``), but how much? The most extreme you could go is input = " ".join(file.read().split()) # all newlines, tabs, multiple spaces -> " " In which case you don't need to worry about modifying the patterns to take care of possible whitespace variations. Another possibility is that you specify the patterns you want to replace as regexps in the file e.g. \bkind(?:est)?\b\s+regard(?:s)?\b \byours,\b ... In any case I'd suggest the following: think about what possible edge cases your input can contain and how you'd like to handle then; then write them up as unittests (use doctest or unittest and StringIO) and finally modify your code until it passes all the tests. Here are some examples of possible test patterns: - """kindest regard,""" - """kindest regard""" - """kindest\tregard""" - """kind regards" - """mankind regards other species as inferior""" - """... and please send your wife my kindest regards,""" Finally, if you're looking for a programming excercise you could try the following: rather than working on strings and using regexps, work on a "stream" of words (i.e. ["kindest", "regards", ...]) and write your own code to match sequences of words. 'as p.s. BTW, I overlooked the ``.readlines()`` before, but you don't need it -- files are iterable and you also want to hang on to the openend file object so that you can close it when you're done. From mwilson at the-wire.com Wed Apr 4 00:56:37 2007 From: mwilson at the-wire.com (Mel Wilson) Date: Wed, 04 Apr 2007 00:56:37 -0400 Subject: Need help on reading line from file into list In-Reply-To: <1175633434.823351.69800@q75g2000hsh.googlegroups.com> References: <1175630106.220186.107900@y66g2000hsf.googlegroups.com> <4612b8f2$0$28546$426a74cc@news.free.fr> <1175633434.823351.69800@q75g2000hsh.googlegroups.com> Message-ID: bahoo wrote: [ ... ] > Thanks, this helped a lot. > I am now using the suggested > map(str.strip, open('source.txt').readlines()) > > However, I am a C programmer, and I have a bit difficulty > understanding the syntax. > I don't see where the "str" came from, so perhaps the output of > "open('source.txt').readlines()" is defaulted to "str? You can do without. [x.strip() for x in open ('source.txt', 'r')] will also work. Cheers, Mel. From g.brandl at gmx.net Sun Apr 8 14:01:37 2007 From: g.brandl at gmx.net (Georg Brandl) Date: Sun, 08 Apr 2007 20:01:37 +0200 Subject: block scope? In-Reply-To: <1hw7rf0.1p2nwloex6vupN%aleax@mac.com> References: <7xr6qwal50.fsf@ruckus.brouhaha.com> <7xtzvseqzo.fsf@ruckus.brouhaha.com> <1hw72cg.115yokgarr9enN%aleax@mac.com> <1hw7kzo.1hepj3c1who5zhN%aleax@mac.com> <1hw7lxn.18itayl1fua6w0N%aleax@mac.com> <7xodlzofw2.fsf@ruckus.brouhaha.com> <1hw7rf0.1p2nwloex6vupN%aleax@mac.com> Message-ID: Alex Martelli schrieb: > Paul Rubin wrote: > >> aleax at mac.com (Alex Martelli) writes: >> > > exec? >> > option 1: that just runs the compiler a bit later ... >> >> Besides exec, there's also locals(), i.e. >> locals['x'] = 5 >> can shadow a variable. Any bad results are probably deserved ;) > >>>> locals['x']=5 > Traceback (most recent call last): > File "", line 1, in > TypeError: 'builtin_function_or_method' object does not support item > assignment > > I suspect you want to index the results of calling locals(), rather than > the builtin function itself. However: > >>>> def f(): > ... locals()['x'] = 5 > ... return x > ... >>>> f() > Traceback (most recent call last): > File "", line 1, in > File "", line 3, in f > NameError: global name 'x' is not defined > > No "shadowing", as you see: the compiler knows that x is NOT local, > because it's not assigned to (the indexing of locals() does not count: > the compiler's not expected to detect that), so it's going to look it up > as a global variable (and not find it in this case). Even assignments to real local variable names in the locals() result do normally not result in the variable having a new value. > I think that ideally there should be a runtime error when assigning an > item of locals() with a key that's not a local variable name (possibly > excepting functions containing exec, which are kind of screwy anyway). I would make the locals() result completely independent from the frame, and document that it is read only. (though, this needs some other way for trace functions to interact with the frame's local variables.) Georg From carsten at uniqsys.com Tue Apr 24 13:44:42 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Tue, 24 Apr 2007 13:44:42 -0400 Subject: If Dict Contains a particular key In-Reply-To: <000001c78695$ed321540$c7963fc0$@rawlins@thinkbluemedia.co.uk> References: <000001c78695$ed321540$c7963fc0$@rawlins@thinkbluemedia.co.uk> Message-ID: <1177436682.3441.15.camel@dot.uniqsys.com> On Tue, 2007-04-24 at 18:28 +0100, Robert Rawlins - Think Blue wrote: > Hello Guys, > > > > I?m Looking to build a quick if/else statement that checks a > dictionary for a key like follows. > > > > If myDict contains ThisKey: > > Do this... > > Else > > Do that... I'm pretty sure you'll find the answer to this question somewhere in http://docs.python.org/tut/tut.html -Carsten From tjreedy at udel.edu Sun Apr 22 17:18:30 2007 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 22 Apr 2007 17:18:30 -0400 Subject: python style guide inconsistencies References: <462BBE6F.9000007@v.loewis.de> Message-ID: ""Martin v. L?wis"" wrote in message news:462BBE6F.9000007 at v.loewis.de... | Darren Dale schrieb: | > I was just searching for some guidance on how to name packages and modules, | > and discovered some inconsistencies on the www.python.org. | > http://www.python.org/doc/essays/styleguide.html says "Module names can be | > either MixedCase or lowercase." That page also refers to PEP 8 at | > http://www.python.org/dev/peps/pep-0008/, which says "Modules should have | > short, all-lowercase names. ... Python packages should also have short, | > all-lowercase names ...". | > | > Which is most up to date? Is this the right place to point out that one of | > those pages needs to be updated? | | No - this is better discussed on python-dev. | | In any case, there isn't technically a contradiction. Module names | MUST be either MixedCase or lowercase; they SHOULD be lowercase. | | So unfortunately, for tradition, some module names are mixed case | (such as ConfigParser or StringIO). I can personally accept that as | a necessary evil, although I would prefer if all modules were | lower case. I have the impression that tradition will change in 3.0 and your preference realized. Wrong? or have you not been following? To OP. Follow the should rather than the may. tjr From grante at visi.com Thu Apr 26 12:48:36 2007 From: grante at visi.com (Grant Edwards) Date: Thu, 26 Apr 2007 16:48:36 -0000 Subject: Access to raw command line? References: <1177571070.229968.155710@t39g2000prd.googlegroups.com> Message-ID: <1331lv4rshck2e@corp.supernews.com> On 2007-04-26, Donn Cave wrote: >> One possible way to work around this is to get the raw command line >> and do the shell expansions ourselves from within Python. Ignoring the >> question of whether it is worth the trouble, does anybody know if it >> is possible to obtain the raw (unexpanded) command line? > > If you're on VMS (well, you didn't say), you're in luck. > > The UNIX shell has already expanded the file globbing by the > time your program starts up, but VMS leaves it to the application, > with the help of a handy RMS$ function or two so it gets done in > a consistent way. This allows the command line interface to > interact with the user in a little more transparent way, since > the input seen by the program is congruent with what the user > typed in. E.g., "rename *.jpeg *.jpg" is trivial on VMS, > impossible on UNIX. Typing rename '*.jpeg' '*.jpg' is impossible? -- Grant Edwards grante Yow! I'm not available at for comment.. visi.com From gilcneth at earthlink.net Thu Apr 12 13:05:15 2007 From: gilcneth at earthlink.net (Chris Nethery) Date: Thu, 12 Apr 2007 17:05:15 GMT Subject: Using python to delta-load files into a central DB Message-ID: Hello everyone, I have a challenging issue I need to overcome and was hoping I might gain some insights from this group. I am trying to speed up the process I am using, which is as follows: 1) I have roughly 700 files that are modified throughout the day by users, within a separate application 2) As modifications are made to the files, I use a polling service and mimic the lock-file strategy used by the separate software application 3) I generate a single 'load' file and bulk insert into a load table 4) I update/insert/delete from the load table This is just too time consuming, in my opinion. At present, users of the separate application can run recalculation functions that modify all 700 files at once, causing my code to take the whole ball of wax, rather than just the data that has changed. What I would like to do is spawn separate processes and load only the delta data. The data must be 100% reliable, so I'm leary of using something like difflib. I also want to make sure that my code scales since the number of files is ever-increasing. I would be grateful for any feedback you could provide. Thank you, Chris Nethery From bbxx789_05ss at yahoo.com Sat Apr 21 08:43:12 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: 21 Apr 2007 05:43:12 -0700 Subject: wx.TextCtrl.SetDefaultStyle not working? In-Reply-To: <1177123135.263882.238100@y5g2000hsa.googlegroups.com> References: <1177123135.263882.238100@y5g2000hsa.googlegroups.com> Message-ID: <1177159392.124932.218960@n76g2000hsh.googlegroups.com> On Apr 20, 8:38 pm, "bcwh... at pobox.com" wrote: > I'm running Python2.5 with wxPython v2.8.3.0 under WinXP and I cannot > get the SetDefaultStyle method to work. > > I'm trying: > > self.output.SetDefaultStyle(wx.TextAttr(wx.RED)) > self.output.AppendText(text) > self.output.SetDefaultStyle(wx.TextAttr()) > > where "self.output" is a TextCtrl window. The text appears, but it's > always black. If I print the output of > self.output.GetDefaultStyle().GetTextColour() before resetting it back > to default, I see "(255, 0, 0, 255)". After reset, it's "(-1, -1, -1, > 255)". > > The font in that window is the system default. > > Am I doing something wrong? > > -- Brian You didn't show the code that creates the TextCtrl. Is it something like this: self.output = wx.TextCtrl(myFrame, -1, style=wx.TE_MULTILINE | wx.TE_RICH2) On my platform, styling the text doesn't work for single line TextCtrl's(which seems kind of stupid), and on Windows I think you are required to specify wx.TE_RICH2 to style the text. This following code colors the entered text red for me: -------- import wx myApp = wx.App(False) myFrame = wx.Frame(None, -1, title="Test") panel = wx.Panel(myFrame, -1) my_tc = wx.TextCtrl(myFrame, -1, style=wx.TE_MULTILINE | wx.TE_RICH2) my_tc.SetDefaultStyle(wx.TextAttr("red") ) #wx.RED works too myFrame.Show() myApp.MainLoop() -------- From steve at holdenweb.com Thu Apr 19 19:01:53 2007 From: steve at holdenweb.com (Steve Holden) Date: Thu, 19 Apr 2007 19:01:53 -0400 Subject: wxPython and how to return text entry to main program? In-Reply-To: <1177011490.435609.155870@o5g2000hsb.googlegroups.com> References: <1177011490.435609.155870@o5g2000hsb.googlegroups.com> Message-ID: Tyler wrote: > Hello All: > > I am currently working on a project to create an FEM model for school. > I was thinking about using wxPython to gather the 12 input variables > from the user, then, after pressing the "Run" button, the GUI would > close, and the 12 input variables would then be available for the rest > of the program. > > So far, what I have been able to do is mostly a reverse engineering > job to get the frame to look right and return the text variable to a > dialog box. > > I have read about a "redirect" that could be used to send the values > to a file. But, then I would have to open the file and read in the > data from there. This seems crude and lacking elegance. > > Any help on how to get the program to output the data back to the main > python program and close when I press submit? My apologies if this is > something of a simple question, but I have only started in on wxPython > about a week ago, and Python this term. > > The codes I am using are below. > > Any help (or suggested reading material) is greatly appreciated. There are two basic ways to do this. The first is to pass in something that can store the values collected by the window. The second is to have the values stored as attributes of the dialog and then extract them after the user has finished interacting with the dialog but before you Destroy() it. See comments in the code. I have actually appended a version that works. Maybe not the prettiest way to achieve what you want but it works. > > Cheers, > > t. > > > MY MAIN PROGRAM > > #!/usr/bin/env python > import femGUI > app = femGUI.MyApp(False) > dlg = femGUI.FemInput() So this is where you create your FemInput object. Here's where you could pass it an object to receive the data values. Assuming you want to store them as named attributes, about the simplest thing you can use is an instance of some object. Here's an example in the interactive interpreter: >>> class O: pass ... >>> myo = O() >>> myo.a = "hello" >>> myo.b = "world" >>> myo.a 'hello' >>> So you could change that last line to class Data: pass data = Data() app = femGUI.FemInput(data) Of course this will mean edits below. > dlg.Destroy() It seems a bit strange to be destroying your dialog before you've actually called the MainLoop to start doing the windowing. I have to take your word for it that this works ... it's almost certainly the reason why you are having problems getting data out of the window. Or maybe not. I see when you run the program the window doesn't disappear when you terminate the dialog. That's probably because (unless you want to do more windowing stuff) you probably want to use ShowModal instead. This will terminate the dialog and have it return to the caller when it's finished. Hmm, the whole structure's a little bit loopy ... and a FemInput window has to be a dialog if you're going to use ShowModal() on it anyway ... that's not good. It means the top-level frame has to Destroy() itself to terminate the main loop and let you continue with the non-graphical portion. > app.MainLoop() > > # Then do something with inputs here.... > The problem at the moment is by the time you are ready to "do something with the inputs" you have terminated your graphical environment - it is, to coin a phrase, an *ex*-graphical environemnt, and it's too late to poke about in it. OK, here's a new main program for you. To make the "lines of communication" a but more obvious it includes a definition of the MyApp class. #!/usr/bin/env python import wx import femGUI class S: pass s = S() class MyApp(wx.App): "You can throw away the MyApp in femGUI." def OnInit(self): myFrame = femGUI.FemInput(s) # passes storage object in self.SetTopWindow(myFrame) myFrame.Show() return True app = MyApp(False) app.MainLoop() print dir(storage) The statement at the end is just to show you that the attributes exist. From there you can do what you want. Now it turns out you don't need to make that many modifications to your class definition. > > > THE FEMINPUT GUI CLASS > > import wx > > class FemInput(wx.Frame): > def __init__(self): The above line has to change because we have to accept, and store, a reference to the storage object we provide in the FemInput constructor. def __init__(self, storage): self.storage = storage Most if it is pretty much standard from here on, but keep reading. > wx.Frame.__init__(self, None, -1, "Options Input Interface") > panel = wx.Panel(self) > > # First create the controls > > # Title > topLbl = wx.StaticText(panel, -1, "FEM 2D Basket Put Option > ",size=(420,-1)) > topLbl.SetFont(wx.Font(18, wx.SWISS, wx.NORMAL, wx.BOLD)) > > # S1 lower and upper bounds for grid > s1label = wx.StaticText(panel, -1, "S1 Low , S2 Low: ", > size=(220,-1)) > self.s1lower = wx.TextCtrl(panel, -1, "", size=(100,-1)); > self.s2lower = wx.TextCtrl(panel, -1, "", size=(100,-1)); > > # S2 lower and upper bounds for grid > s2label = wx.StaticText(panel, -1, "S1 High, S2 High: ", > size=(220,-1)) > self.s1upper = wx.TextCtrl(panel, -1, "", size=(100,-1)); > self.s2upper = wx.TextCtrl(panel, -1, "", size=(100,-1)); > > # S1 and S2 volatility > vlabel = wx.StaticText(panel, -1, "S1 Volatility, S2 > Volatility: ", size=(220,-1)) > self.v1vol = wx.TextCtrl(panel, -1, "", size=(100,-1)); > self.v2vol = wx.TextCtrl(panel, -1, "", size=(100,-1)); > > # Risk free rate and correlation > prlabel = wx.StaticText(panel, -1, "Interest Rate, > Correlation: ", size=(220,-1)) > self.risk = wx.TextCtrl(panel, -1, "", size=(100,-1)); > self.corr = wx.TextCtrl(panel, -1, "", size=(100,-1)); > > > # Strike and Exercise Date > kTlabel = wx.StaticText(panel, -1, "Srike Price, Exercise > Date: ", size=(220,-1)) > self.strike = wx.TextCtrl(panel, -1, "", size=(100,-1)); > self.finalT = wx.TextCtrl(panel, -1, "", size=(100,-1)); > > # deltaT and deltaX > dTXlabel = wx.StaticText(panel, -1, "delta T, delta X: ", > size=(220,-1)) > self.deltaT = wx.TextCtrl(panel, -1, "", size=(100,-1)); > self.deltaX = wx.TextCtrl(panel, -1, "", size=(100,-1)); > > > # Execute program > runBtn = wx.Button(panel, -1, "Run") > self.Bind(wx.EVT_BUTTON, self.OnSubmit, runBtn) > > # Now do the layout. > > # mainSizer is the top-level one that manages everything > mainSizer = wx.BoxSizer(wx.VERTICAL) > mainSizer.Add(topLbl, 0, wx.ALL, 5) > mainSizer.Add(wx.StaticLine(panel), 0, > wx.EXPAND|wx.TOP|wx.BOTTOM, 5) > > # femSizer is a grid that holds all of the address info > femSizer = wx.FlexGridSizer(cols=2, hgap=5, vgap=5) > femSizer.AddGrowableCol(1) > > # S1 and S2 LOWER label > femSizer.Add(s1label, 0, > wx.ALIGN_RIGHT|wx.ALIGN_CENTER_VERTICAL) > # the lower and upper S1 bounds are in a sub-sizer > s1Sizer = wx.BoxSizer(wx.HORIZONTAL) > s1Sizer.Add(self.s1lower, 1) > s1Sizer.Add((10,10)) # some empty space > s1Sizer.Add(self.s2lower, 1, wx.LEFT|wx.RIGHT, 5) > femSizer.Add(s1Sizer, 1, wx.EXPAND) > > > # S1 and S2 HIGH label > femSizer.Add(s2label, 0, > wx.ALIGN_RIGHT|wx.ALIGN_CENTER_VERTICAL) > # the lower and upper S1 bounds are in a sub-sizer > s2Sizer = wx.BoxSizer(wx.HORIZONTAL) > s2Sizer.Add(self.s1upper, 1) > s2Sizer.Add((10,10)) # some empty space > s2Sizer.Add(self.s2upper, 1, wx.LEFT|wx.RIGHT, 5) > femSizer.Add(s2Sizer, 1, wx.EXPAND) > > > # Volatility label > femSizer.Add(vlabel, 0, > wx.ALIGN_RIGHT|wx.ALIGN_CENTER_VERTICAL) > # the lower and upper S1 bounds are in a sub-sizer > volSizer = wx.BoxSizer(wx.HORIZONTAL) > volSizer.Add(self.v1vol, 1) > volSizer.Add((10,10)) # some empty space > volSizer.Add(self.v2vol, 1, wx.LEFT|wx.RIGHT, 5) > femSizer.Add(volSizer, 1, wx.EXPAND) > > > # Risk free Rate and corelation > femSizer.Add(prlabel, 0, > wx.ALIGN_RIGHT|wx.ALIGN_CENTER_VERTICAL) > # the lower and upper S1 bounds are in a sub-sizer > rcSizer = wx.BoxSizer(wx.HORIZONTAL) > rcSizer.Add(self.risk, 1) > rcSizer.Add((10,10)) # some empty space > rcSizer.Add(self.corr, 1, wx.LEFT|wx.RIGHT, 5) > femSizer.Add(rcSizer, 1, wx.EXPAND) > > > # Strike and Exercise Date > femSizer.Add(kTlabel, 0, > wx.ALIGN_RIGHT|wx.ALIGN_CENTER_VERTICAL) > # the lower and upper S1 bounds are in a sub-sizer > ktSizer = wx.BoxSizer(wx.HORIZONTAL) > ktSizer.Add(self.strike, 1) > ktSizer.Add((10,10)) # some empty space > ktSizer.Add(self.finalT, 1, wx.LEFT|wx.RIGHT, 5) > femSizer.Add(ktSizer, 1, wx.EXPAND) > > > # deltaT and deltaX > femSizer.Add(dTXlabel, 0, > wx.ALIGN_RIGHT|wx.ALIGN_CENTER_VERTICAL) > # the lower and upper S1 bounds are in a sub-sizer > dtxSizer = wx.BoxSizer(wx.HORIZONTAL) > dtxSizer.Add(self.deltaT, 1) > dtxSizer.Add((10,10)) # some empty space > dtxSizer.Add(self.deltaX, 1, wx.LEFT|wx.RIGHT, 5) > femSizer.Add(dtxSizer, 1, wx.EXPAND) > > > # now add the femSizer to the mainSizer > mainSizer.Add(femSizer, 0, wx.EXPAND|wx.ALL, 10) > > # The buttons sizer will put them in a row with resizeable > # gaps between and on either side of the buttons > btnSizer = wx.BoxSizer(wx.HORIZONTAL) > btnSizer.Add((10,10)) # some empty space > btnSizer.Add(runBtn) > btnSizer.Add((10,10)) # some empty space > mainSizer.Add(btnSizer, 0, wx.EXPAND|wx.BOTTOM, 10) > > panel.SetSizer(mainSizer) > > # Fit the frame to the needs of the sizer. The frame will > # automatically resize the panel as needed. Also prevent the > # frame from getting smaller than this size. > mainSizer.Fit(self) > mainSizer.SetSizeHints(self) > > def OnSubmit(self, evt): > s1low = self.s1lower.GetValue() > s2low = self.s2lower.GetValue() > s1high = self.s1upper.GetValue() > s2high = self.s2upper.GetValue() > s1vol = self.v1vol.GetValue() > s2vol = self.v2vol.GetValue() > irate = self.risk.GetValue() > pcorr = self.corr.GetValue() > kprice = self.strike.GetValue() > totalT = self.finalT.GetValue() > delT = self.deltaT.GetValue() > delX = self.deltaX.GetValue() > wx.MessageBox('You chose: \n %s \n %s \n %s \n %s \ > \n %s \n %s \n %s' % > (s1low,s2low,s1high,s2high,s1vol,s2vol,irate)) > # I want to do something like this below.... > # return s1low,s2low,s1high,s2high,s1vol,s2vol,irate > This is the crux. Here you have to Destroy() the frame (self) for the MainLoop to terminate properly, so you have to save the values before you do that. So replace this whole method with something like def OnSubmit(self, evt): "The user has filled in the required values and want to run" self.storage.s1low = self.s1lower.GetValue() self.storage.s2low = self.s2lower.GetValue() self.storage.s1high = self.s1upper.GetValue() self.storage.s2high = self.s2upper.GetValue() self.storage.s1vol = self.v1vol.GetValue() self.storage.s2vol = self.v2vol.GetValue() self.storage.irate = self.risk.GetValue() self.storage.pcorr = self.corr.GetValue() self.storage.kprice = self.strike.GetValue() self.storage.totalT = self.finalT.GetValue() self.storage.delT = self.deltaT.GetValue() self.storage.delX = self.deltaX.GetValue() self.Destroy() > > > class MyApp(wx.App): > > def OnInit(self): > frame = FemInput() > self.SetTopWindow(frame) > frame.Show() > return True > > > # Needed if called as a module > if __name__ == '__main__': > app = MyApp(False) > app.MainLoop() > Good luck! 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 gregturn at mindspring.com Wed Apr 4 12:18:08 2007 From: gregturn at mindspring.com (Goldfish) Date: 4 Apr 2007 09:18:08 -0700 Subject: how to build a forum in Python? In-Reply-To: <1175686188.212319.292750@q75g2000hsh.googlegroups.com> References: <1175672984.836097.21610@n76g2000hsh.googlegroups.com> <1175686188.212319.292750@q75g2000hsh.googlegroups.com> Message-ID: <1175703488.290861.317760@y80g2000hsf.googlegroups.com> Sounds like phpBB (http://www.phpbb.com/) would do great. I'm not sure why you want to go write another forum management tool when others are already out there for usage. I know its not in python, but not everything has to be in python. From a.schmolck at gmail.com Sun Apr 8 05:54:08 2007 From: a.schmolck at gmail.com (Alexander Schmolck) Date: 08 Apr 2007 10:54:08 +0100 Subject: block scope? References: Message-ID: Neal Becker writes: > One thing I sometimes miss, which is common in some other languages (c++), > is idea of block scope. It would be useful to have variables that did not > outlive their block, primarily to avoid name clashes. This also leads to > more readable code. I have on occassion used lambda as a poor-man's let, but only if I needed to avoid multiple evaluation: res = (lambda x=blah(...), y=blahz(...): f(x*y,x+y))() I'm sure most people would debate it's more readable, but it's IMO superior to cleaning up manually with ``del``. I sometimes also find it useful to avoid cluttering up the interactive shell. 'as From fperez.net at gmail.com Thu Apr 5 22:32:49 2007 From: fperez.net at gmail.com (Fernando Perez) Date: Thu, 05 Apr 2007 20:32:49 -0600 Subject: ipython env References: <0Kadndcfb9O_74jbnZ2dnUVZ_hSdnZ2d@comcast.com> Message-ID: Larry Bates wrote: > Greg Donald wrote: >> Anyone know what's up with environment variables when using ipython? [...] > In Cpython you get this with: > > import os > os.environ['EDITOR'] Yup, same in ipython :) Just to clarify, env is just a convenience function in ipython that simply does this: In [4]: env?? Type: Magic function Base Class: String Form: > Namespace: IPython internal File: /home/fperez/usr/lib/python2.4/site-packages/IPython/Magic.py Definition: env(self, parameter_s='') Source: def magic_env(self, parameter_s=''): """List environment variables.""" return os.environ.data Cheers, f From abgrund at silberdrache.net Sat Apr 21 16:59:31 2007 From: abgrund at silberdrache.net (=?iso-8859-1?B?Qmr2cm4gS2VpbA==?=) Date: 21 Apr 2007 13:59:31 -0700 Subject: Returning a date as string Message-ID: <1177189171.147254.35920@n76g2000hsh.googlegroups.com> Hello pythons, I have little problem with understanding conversions in python. I've written a little class - nothing much, just to try out Python a little - containing the following method: def __repr__(self): """Serializes the note. Currently the format of notes isn't decided upon. XML output is projected.""" return "Due: " + str(self.dateDue) + \ "\nDate: " + str(self.dateCreated) + \ "\nSubject: " + self.subject + \ "\n" + self.content The fields "dateDue" and "dateCreated" contain datetime.date objects. Now when I try to serialize the whole thing: >>> myNote Traceback (most recent call last): File "", line 1, in ? File "notes.py", line 81, in __repr__ return "Due: " + str(self.dateDue) + \ TypeError: cannot concatenate 'str' and 'datetime.date' objects I tryed different variant before I wrapped "self.dateDue" in a str() constructor: I tried to put it in brackets, or call its .isoformat() method. Nothing works. It still complains that I was trying to concatenate a string with a date, but I really wanna concatenate a string with a string! Could anyone please tell me what I am doing wrong? Greetings, Bj?rn From walterbyrd at iname.com Mon Apr 30 11:47:10 2007 From: walterbyrd at iname.com (walterbyrd) Date: 30 Apr 2007 08:47:10 -0700 Subject: Can python find HW/SW installed on my PC - like Belarc? Message-ID: <1177948030.122063.48520@y5g2000hsa.googlegroups.com> Lets suppose, I want a listing of what hardware and software is installed on my windows box. Can I do that with Python? From steve at REMOVE.THIS.cybersource.com.au Sat Apr 28 20:36:43 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Sun, 29 Apr 2007 10:36:43 +1000 Subject: Numbers and truth values References: Message-ID: On Sat, 28 Apr 2007 11:35:36 -0700, John Nagle wrote: >> Python forbids very few things in comparison to other languages. The >> attitude is "We're all adults here". Because Python is such a dynamic >> language, it is often hard for the compiler to tell the difference between >> something you are doing deliberately and a mistake. > > I'd have to consider that a bug. [snip] > "True", "False", and "None" should be reserved words in Python. > "None" already is. What are you going to do about the code that pre-dates the introduction of bools that defines False = 0 True = not False at the start of the module? The Python philosophy is to break existing code as little as possible (at least until Python 3). -- Steven From jjl at pobox.com Sun Apr 1 12:24:39 2007 From: jjl at pobox.com (John J. Lee) Date: Sun, 01 Apr 2007 16:24:39 GMT Subject: Does Numpy work on QNX 4.25 with Python 2.2? References: <1174935710.642334.141790@d57g2000hsg.googlegroups.com> Message-ID: <87648gcbav.fsf@pobox.com> Robert Kern writes: > ZMY wrote: > > I am trying to convert some old Fortran code into Python program and > > get them work on a QNX 4.25 system. Since the program requires speed, > > I think using Numpy is really necessary. But I haven't found anything > > on web about using numpy on QNX 4.25 (especially the for python > > version 2.2). > > numpy requires Python 2.3+. I haven't heard of anyone trying QNX. Perhaps he could try Numeric (numpy's predecessor). John From rNOSPAMon at flownet.com Sun Apr 22 17:22:20 2007 From: rNOSPAMon at flownet.com (Ron Garret) Date: Sun, 22 Apr 2007 14:22:20 -0700 Subject: Bug in select References: <1aGdndBf1ON7UrbbnZ2dnUVZ_hjinZ2d@speakeasy.net> Message-ID: In article <1aGdndBf1ON7UrbbnZ2dnUVZ_hjinZ2d at speakeasy.net>, Erik Max Francis wrote: > Ron Garret wrote: > > > So this is clearly a bug, but surely I'm not the first person to have > > encountered this? Is there a known workaround? > > It's hard to see how this demonstrates a bug in anything, since you're > telnetting to the wrong port in your example. Geez you people are picky. Since I ran this several times I ran into the TIM_WAIT problem. Here's the actual transcript: Python 2.5 (r25:51908, Mar 1 2007, 10:09:05) [GCC 4.0.1 (Apple Computer, Inc. build 5367)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> from socket import * >>> from select import select >>> s=socket(AF_INET, SOCK_STREAM) >>> s.bind(('',8080)) Traceback (most recent call last): File "", line 1, in File "", line 1, in bind socket.error: (48, 'Address already in use') >>> s.bind(('',8081)) >>> s.listen(5) >>> f = s.accept()[0].makefile() >>> f.readline() '123\r\n' >>> select([f],[],[],1) ([], [], []) >>> f.readline() '321\r\n' From Ingo.Wolf at gmx.de Mon Apr 2 07:14:19 2007 From: Ingo.Wolf at gmx.de (iwl) Date: 2 Apr 2007 04:14:19 -0700 Subject: BUG?: Saving empty array in shelve Message-ID: <1175512459.614122.315290@b75g2000hsg.googlegroups.com> Hi, I've tryed to save some data containing empty arrays (array('f')) in a shelve. It looks like the shelve has some problems with empty arrays, get allways: TypeError: ("'NoneType' object is not iterable", , ('f', None))- Messages when dealing with the readed back shelve. Seems like I have to avoid empty arrays in a shelve. From goodTweetieBird at hotmail.com Thu Apr 26 10:56:26 2007 From: goodTweetieBird at hotmail.com (gtb) Date: 26 Apr 2007 07:56:26 -0700 Subject: Python keywords Message-ID: <1177599386.204340.65680@r35g2000prh.googlegroups.com> Have done some searching but have not found a place where I can look up python keywords. I was looking at a script that contained the following line: assert self.getResponseCode() in (200, 304, 302) I can infer the usage here but previously I had thought that "in" was only used with '"for". I looked thru 'the Python Reference Manual and found "in" is a keyword but in skimming thru I found it only with "for". The reference manual seems good but seems not to be setup for searching. Or maybe I just missed something. Thanks, gtb From steve at holdenweb.com Thu Apr 19 14:59:32 2007 From: steve at holdenweb.com (Steve Holden) Date: Thu, 19 Apr 2007 14:59:32 -0400 Subject: Python COM iterator In-Reply-To: References: <46279B56.4020901@websafe.com> Message-ID: Ross Ridge wrote: > Larry Bates wrote: >> I tested in VB and by golly it works! What is odd is that this looks >> NOTHING like what we got from the docs earlier. No GetEnumerator >> method, no MoveNext method. I'm glad it works, but I'm a little >> puzzled as to why it works. > > The documention Carsten Haese referenced earlier was for the .NET version > of VisualBasic, and shows how to use .NET's IEnumerate and IEnumerable > interfaces. > > Steve Holden wrote: >> Presumably the magic of mark Hammond's wrapper classes providing >> adaptation between Python iteration and COM enumerable collection >> objects. win32all is *very* Pythonic. > > Maybe Mark Hammond's win32all provides such a magic wrapper, but Cartsen > Haese's example didn't use it. Instead it provided it own implementation > of the COM IEnumVARIANT interface, the OLE Automation (ie. VisualBasic > 6 compatable) way implementing iteratable objects. > > Ross Ridge > So I saw when I read Carsten's reply to my post. Thanks. It's the difference between COM and .NET (something I am currently having to come to terms with myself, but strangely in C# rather than Python). 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 grante at visi.com Tue Apr 10 00:38:37 2007 From: grante at visi.com (Grant Edwards) Date: Tue, 10 Apr 2007 04:38:37 -0000 Subject: Check for keypress on Linux xterm ? References: Message-ID: <131m56dsgr7or38@corp.supernews.com> On 2007-04-09, hlubenow wrote: > My problem is, I don't want my program to wait for the keypress. > I just want to check, if a key is currently pressed and if not, I'd like to > continue with my program (like "INKEY$" in some BASIC-dialects). The answer to this frequently asked question is actually in the FAQ: http://www.python.org/doc/faq/library.html#how-do-i-get-a-single-keypress-at-a-time Google finds us further examples: http://mail.python.org/pipermail/pythonmac-sig/2004-February/010140.html http://mail.python.org/pipermail/python-list/2000-June/041251.html -- Grant Edwards grante Yow! I'm reporting for at duty as a modern person. I visi.com want to do the Latin Hustle now! From hq4ever at gmail.com Tue Apr 3 11:29:23 2007 From: hq4ever at gmail.com (Maxim Veksler) Date: Tue, 3 Apr 2007 17:29:23 +0200 Subject: low level networking in python Message-ID: Hello, I wish to do some low level network stuff using python. I've googled somewhat and came up with pylibpcap[1], trouble is I can't compile it on my Ubuntu 6.10 workstation. Can someone please suggest a way to read some bits from random ports? I'm looking to write a simple pen-testing tool that would try from one side connecting to ports and from the other side sniff traffic to see on what ports traffic is coming. For pylibpcap I'm getting: """ hq4ever at lucky:~/development/personal/pylibpcap/pylibpcap-0.5.1$ python setup.py build running build running build_ext building '_pcapmodule' extension swig -python -shadow -ISWIG -o pcap.c pcap.i pcap.i:72: Warning(124): Specifying the language name in %typemap is deprecated - use #ifdef SWIG instead. pcap.i:77: Warning(124): Specifying the language name in %typemap is deprecated - use #ifdef SWIG instead. pcap.i:82: Warning(124): Specifying the language name in %typemap is deprecated - use #ifdef SWIG instead. /usr/bin/python ./build-tools/docify.py pcap.c /usr/bin/python ./build-tools/docify-shadow.py pcap.py Traceback (most recent call last): File "./build-tools/docify-shadow.py", line 30, in ? raise 'source file doesn\'t look like swigged shadow class code' source file doesn't look like swigged shadow class code error: command '/usr/bin/python' failed with exit status 1 """ [1] http://pylibpcap.sourceforge.net/ [2] http://py.vaults.ca/apyllo.py/126307487 -- Cheers, Maxim Veksler "Free as in Freedom" - Do u GNU ? From martin at v.loewis.de Fri Apr 20 20:21:46 2007 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sat, 21 Apr 2007 02:21:46 +0200 Subject: Python's handling of unicode surrogates In-Reply-To: <1177051493.468698.176740@b75g2000hsg.googlegroups.com> References: <4628532B.5060104@v.loewis.de> <1177051493.468698.176740@b75g2000hsg.googlegroups.com> Message-ID: <4629591a$0$13629$9b622d9e@news.freenet.de> > I don't believe this specific variant has been discussed. Now that you clarify it: no, it hasn't been discussed. I find that not surprising - this proposal is so strange and unnatural that probably nobody dared to suggest it. > s[5] does not exist. You would get an IndexError indicating that it > refers to the second half of a surrogate. > [...] > > len(s[k]) would be 2 if it involved a surrogate, yes. One character, > two code units. Please consider trade-offs. Study advantages and disadvantages. Compare them. Can you then seriously suggest that indexing should have 'holes'? That it will be an IndexError if you access with an index between 0 and len(s)??????? If you absolutely think support for non-BMP characters is necessary in every program, suggesting that Python use UCS-4 by default on all systems has a higher chance of finding acceptance (in comparison). Regards, Martin From usenet423.4.fms at neverbox.com Wed Apr 25 06:41:13 2007 From: usenet423.4.fms at neverbox.com (Frank Stajano) Date: Wed, 25 Apr 2007 11:41:13 +0100 Subject: q: how to output a unicode string? In-Reply-To: <596qd4F2k129kU1@mid.uni-berlin.de> References: <596qd4F2k129kU1@mid.uni-berlin.de> Message-ID: Diez B. Roggisch wrote: > Frank Stajano wrote: > >> A simple unicode question. How do I print? >> >> Sample code: >> >> # -*- coding: utf-8 -*- >> s1 = u"h?ll? w?rld" >> print s1 >> # Gives UnicodeEncodeError: 'ascii' codec can't encode character >> # u'\xe9' in position 1: ordinal not in range(128) >> >> >> What I actually want to do is slightly more elaborate: read from a text >> file which is in utf-8, do some manipulations of the text and print the >> result on stdout. I understand I must open the file with >> >> f = codecs.open("input.txt", "r", "utf-8") >> >> but then I get stuck as above. >> >> I tried >> >> s2 = s1.encode("utf-8") >> print s2 >> >> but got >> >> h??ll?? w??rld > > Which is perfectly alright - it's just that your terminal isn't prepared to > decode UTF-8, but some other encoding, like latin1. Aha! Thanks for spotting this. You are right about the terminal (rxvt/cygwin) not being ready to handle utf-8, as I can now confirm with a cat t2.py (t2.py being the program above) which displays the source code garbled in the same way. If I do s1 = u"h?ll? w?rld" print s1 at the interactive prompt of Idle, I get the proper output h?ll? w?rld So why is it that in the first case I got UnicodeEncodeError: 'ascii' codec can't encode? Seems as if, within Idle, a utf-8 codec is being selected automagically... why should that be so there and not in the first case? >> Then, in the hope of being able to write the string to a file if not to >> stdout, I also tried >> >> >> import codecs >> f = codecs.open("out.txt", "w", "utf-8") >> f.write(s2) >> >> but got >> >> UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 1: >> ordinal not in range(128) > > Instead of writing s2 (which is a byte-string!!!), write s1. It will work. OK, many thanks, I got this to work! > The error you get stems from f.write wanting a unicode-object, but s2 is a > bytestring (you explicitly converted it before), so python tries to encode > the bytestring with the default encoding - ascii - to a unicode string. > This of course fails. I think I have a better understanding of it now. If the terminal hadn't fooled me, I probably wouldn't have assumed that the code I originally wrote (following the first examples I found) was wrong! I assume that when you say "bytestring" you mean "a string of bytes in a certain encoding (here utf-8) that can be used as an external representation for the unicode string which is instead a sequence of code points". Thanks again From brendon at christian.net Sun Apr 1 00:35:59 2007 From: brendon at christian.net (Brendon Costa) Date: Sun, 01 Apr 2007 14:35:59 +1000 Subject: Converting _node* to a Code object? Message-ID: <460F36AF.5030607@christian.net> Hi All, I have an application with an embedded python interpreter and i need to get the embedded interpreter to "import" strangely named files as python modules. Anyhow the simple part of the question is: How do i convert a _node* object returned from: PyParser_SimpleParseStringFlagsFilename() into a code object i can use as a module to import with: PyImport_ExecCodeModule() I cant seem to find any documentation about this. If you are wondering why i want to do this, then you can read on and maybe there is a much better way to achieve what i am after. Thanks, Brendon ----- What i am trying to achieve ----- Basically i want to "import" using the python C API a module from various files which may have names that do not make valid python module names. In particular i have an embedded python interpreter that is used to apply a number of operations on some data based on a user supplied "suppressions file" (*.eds). This .eds file is just a python source file designed only to be used from within this application. Now the names of these suppression files usually matche that of a library or application to which they will apply to. For example: libstdc++.so.6.0.5 : has eds file: libstdc++.so.6.0.5.eds Now i want to have my code import this eds file as a python module so that i can then use it as any other standard python module. So i need to separate the name of the module from the name of the file. I was thinking for example for the above filename i would give it a module name like: libstdc___so_6_0_5 (The name is not important just that the above one is a valid module name from what i understand and it is based on the original name) So i have some random file: /foo/bar/lib/libstdc++.so.6.0.5.eds and i want to be able to import that as a module using the Python C API so native python code can access the module like: libstdc___so_6_0_5.PostCalculation() If you have any better method of doing this, i would love to know what it is. Thanks in advance for any help, Brendon. From paddy3118 at netscape.net Wed Apr 25 12:56:46 2007 From: paddy3118 at netscape.net (Donald 'Paddy' McCarthy) Date: Wed, 25 Apr 2007 16:56:46 GMT Subject: Python not giving free memory back to the os get's me in real problems ... In-Reply-To: <1177510121.882503.145560@n15g2000prd.googlegroups.com> References: <1177510121.882503.145560@n15g2000prd.googlegroups.com> Message-ID: leuchte at gmail.com wrote: > So I read quite a few things about this phenomenon in Python 2.4.x but > I can hardly believe that there is really no solution to my problem. > > We use a commercial tool that has a macro functionality. These macros > are written in python. So far nothing extraordinary. > > Our (python-)macro uses massively nested loops which are unfortunately > necessary. These loops perform complex calculations in this commercial > tool. To give you a quick overview how long this macros runs: > > The outer loop takes 5-7 hours for one cycle. Each cycle creates one > outputfile. So we would like to perform 3-5 outer cycles en bloc. > Unfortunately one of our computers (768MB RAM) crashes after just ~10% > of the first cycle with the following error message: > > http://img2.freeimagehosting.net/uploads/7157b1dd7e.jpg > > while another computer (1GB RAM) crashes after ~10% of the fourth > loop. While the virtual memory on the 1gb machine was full to the > limit when it crashed the memory usage of the 768mb machine looked > this this: > > http://img2.freeimagehosting.net/uploads/dd15127b7a.jpg > > The moment I close the application that launched the macro, my > ressources get freed. > > So is there a way to free my memory inside my nested loops? > > thanks in advance, > tim > Could you split the program into one handling the outer loop and calling another program, with data transfer, to handle the inner loops? - Paddy. From ptmcg at austin.rr.com Thu Apr 26 17:50:38 2007 From: ptmcg at austin.rr.com (Paul McGuire) Date: 26 Apr 2007 14:50:38 -0700 Subject: My python annoyances so far In-Reply-To: References: Message-ID: <1177624238.251524.245580@n15g2000prd.googlegroups.com> More samples from that thread: fica = Percent(7) fedtax = Percent(15) medicare = Percent(3) deductions = fica + fedtax + medicare gross = 100000 net = gross - deductions print net # answer: 75000 wholesale = 10 markup = Percent(35) retail = wholesale + markup print retail # answer: 13.5 yearlyApprec = Percent(8) basis = 10000 newbasis = basis + yearlyApprec + yearlyApprec + yearlyApprec print newbasis # answer: 12597.12 -- Paul From beliavsky at aol.com Sun Apr 15 19:06:35 2007 From: beliavsky at aol.com (Beliavsky) Date: 15 Apr 2007 16:06:35 -0700 Subject: Python Feature Request: Allow changing base of member indices to 1 In-Reply-To: <1176606776.016013.205170@p77g2000hsh.googlegroups.com> References: <1176546465.632410.52630@w1g2000hsg.googlegroups.com> <1176579205.948684.171640@q75g2000hsh.googlegroups.com> <1176584444.335732.111740@n76g2000hsh.googlegroups.com> <1hwkok3.1kmipey1iv5ldzN%aleax@mac.com> <1176606776.016013.205170@p77g2000hsh.googlegroups.com> Message-ID: <1176678395.638748.174140@o5g2000hsb.googlegroups.com> On Apr 14, 10:12 pm, "Paddy" wrote: > So the running count is: > Ayes to the left: VB compatibility. > Nays to the right: QuadIO, Perl, Dijkstra paper. > > The nays have it! One-based indexing would also Python more compatible with Fortran, Matlab/Octave/Scilab, and S (the language of S-Plus and R). It appears that engineers, scientists, and statisticians, as opposed to professional programmers, like 1-based indexing. An obvious argument for 1-based indexing in the FORmula TRANslation programming language is that formulas involving arrays in textbooks almost always use 1- based indexing. Since Python has always had 0-based indexing and since a user-defined base can cause problems, as has been discussed, I think Python and extensions such as NumPy should be left as is. From ptmcg at austin.rr.com Fri Apr 27 03:33:58 2007 From: ptmcg at austin.rr.com (Paul McGuire) Date: 27 Apr 2007 00:33:58 -0700 Subject: regex question In-Reply-To: <1177655637.717863.93920@o40g2000prh.googlegroups.com> References: <1177655637.717863.93920@o40g2000prh.googlegroups.com> Message-ID: <1177659238.159411.40640@c18g2000prb.googlegroups.com> On Apr 27, 1:33 am, proctor <12cc... at gmail.com> wrote: > hello, > > i have a regex: rx_test = re.compile('/x([^x])*x/') > > which is part of this test program: > > ============ > > import re > > rx_test = re.compile('/x([^x])*x/') > > s = '/xabcx/' > > if rx_test.findall(s): > print rx_test.findall(s) > > ============ > > i expect the output to be ['abc'] however it gives me only the last > single character in the group: ['c'] > > C:\test>python retest.py > ['c'] > > can anyone point out why this is occurring? i can capture the entire > group by doing this: > > rx_test = re.compile('/x([^x]+)*x/') > but why isn't the 'star' grabbing the whole group? and why isn't each > letter 'a', 'b', and 'c' present, either individually, or as a group > (group is expected)? > > any clarification is appreciated! > > sincerely, > proctor As Josiah already pointed out, the * needs to be inside the grouping parens. Since re's do lookahead/backtracking, you can also write: rx_test = re.compile('/x(.*?)x/') The '?' is there to make sure the .* repetition stops at the first occurrence of x/. -- Paul From arkanes at gmail.com Wed Apr 25 11:25:12 2007 From: arkanes at gmail.com (Chris Mellon) Date: Wed, 25 Apr 2007 10:25:12 -0500 Subject: Python not giving free memory back to the os get's me in real problems ... In-Reply-To: <59990rF2ja6c7U3@mid.dfncis.de> References: <1177510121.882503.145560@n15g2000prd.googlegroups.com> <_LidnenBcrz7-rLbnZ2dnUVZ_tCtnZ2d@comcast.com> <59990rF2ja6c7U3@mid.dfncis.de> Message-ID: <4866bea60704250825p3a6d6e14n1bae3b77f00921bc@mail.gmail.com> On 25 Apr 2007 15:04:59 GMT, TimC wrote: > Larry Bates wrote: > > > Let's see for this I need to get out my crystal ball... > > > > If it is a commercial application, you should contact their tech > > support for a solution. The problem isn't specifically a Python > > problem but rather an implementation problem with their app. > > > > -Larry > > Well one part of the problem maybe really is on the side of this > tool. Because the implementation of the macro functionality is > really crappy. But unfortunately there are no competitive-product > we could switch too, so we have to live with this poor environment. > > But I don't think that the WHOLE problem lies inside this tool. > Because I read > > http://mail.python.org/pipermail/python-dev/2005-January/051255.html > and > http://evanjones.ca/python-memory.html > > Sadly we can't switch from Python 2.4 to 2.5 because this stupid > macro functionality only supports 2.4.x > > I really know that all this is not the best setup to get happy with > but there really is no other setup available. > > So I'm happy for every input all of you can give me. > The problem you're seeing almost certainly isn't related to the memory arena issues referenced on the list. "Returning memory to the OS" doesn't affect exhaustion of your virtual address space. More likely, your nested loops are just creating more objects than is possible to hold within a single process. That may be because you're working with very large data sets, or because you have some sort of ref cycle problem, or simply because you hold onto references you no longer need. You'll need to do more work to diagnose the exact details before you can find a fix. Contacting your vendor support would be a really good first step. It's possible that you have a degenerate case that triggers some of the arena problems (like allocation 10 million integers, and then never using them again), and thats the root of your problem. Without knowing more about the usage pattern of your application, theres no way we can determine that. If you can't upgrade to python 2.5, your only solution is going to be to rework your algorithm to not do that. Again, contacting your vendor support is going to be the first step. From Bulkan at gmail.com Tue Apr 24 07:00:25 2007 From: Bulkan at gmail.com (placid) Date: 24 Apr 2007 04:00:25 -0700 Subject: python cgi problem with textarea In-Reply-To: <17ar23drof4nsdhcdoa0jconcb6sjuljk0@4ax.com> References: <1177222084.696307.128620@n59g2000hsh.googlegroups.com> <1177247362.014926.12500@n76g2000hsh.googlegroups.com> <1177254110.057238.315240@o5g2000hsb.googlegroups.com> <1177315259.401721.62040@l77g2000hsb.googlegroups.com> <17ar23drof4nsdhcdoa0jconcb6sjuljk0@4ax.com> Message-ID: <1177412425.066398.199080@r35g2000prh.googlegroups.com> On Apr 24, 4:52 pm, Tim Roberts wrote: > placid wrote: > >On Apr 23, 1:01 am, Adrian Smith wrote: > >> On Apr 22, 10:09 pm, placid wrote: > > >> > i just tried it and its working. here it is > > >> >http://yallara.cs.rmit.edu.au/~bevcimen/form.html > > >> > maybe the internal server error is because mod_python isn't installed > >> > assuming your using Apache as your web server > > >> Yeah, but it wouldn't work *at all* in that case, would it? ATM it > >> seems to work as long as the textarea input has no spaces. > > >it doest work because the "space" character isnt interpreted > >correctly, you need to change the space characters too   > > What??? Did you even read the problem description? oops...i did read the problem description, but i when i tried the code it worked for me and when i put spaces into the TextArea it wasn't reflected correctly back. So i thought this was the problem. Adrian, can you still try replacing spaces with   via the following; #!/usr/bin/python import cgi import urllib import cgitb cgitb.enable() print "Content-type: text/html\n" form = cgi.FieldStorage() #print urllib.quote_plus(form["essay"].value) for char in form["essay"].value: if char == ' ': print " " else: print char Cheers From steven.bethard at gmail.com Sun Apr 1 12:21:40 2007 From: steven.bethard at gmail.com (Steven Bethard) Date: Sun, 01 Apr 2007 10:21:40 -0600 Subject: I18n issue with optik In-Reply-To: References: Message-ID: Thorsten Kampe wrote: > * Steven Bethard (Sat, 31 Mar 2007 20:08:45 -0600) >> Thorsten Kampe wrote: >>> I've written a script which uses Optik/Optparse to display the >>> options (which works fine). The text for the help message is localised >>> (with german umlauts) and when I execute the script with the localised >>> environment variable set, I get this traceback[1]. The interesting >>> thing is that the localised optparse messages from displays fine - >>> it's only my localisation that errors. >>> >>> From my understanding, my script doesn't put out anything, it's >>> optik/optparse who does that. My po file is directly copied from the >>> optik po file (who displays fine) and modified so the po file should >>> be fine, too. >>> >>> What can I do to troubleshoot whether the culprit is my script, optik >>> or gettext? >>> >>> Would it make sense to post the script and the mo or po files? >> Yes, probably. Though if you can reduce it to the simplest test case >> that produces the error, it'll increase your chances of having someone >> look at it. > > The most simple test.py is: > > ### > #! /usr/bin/env python > > import gettext, \ > os, \ > sys > > gettext.textdomain('optparse') > gettext.install('test') > > from optparse import OptionParser, \ > OptionGroup > > cmdlineparser = OptionParser(description = _('THIS SOFTWARE COMES > WITHOUT WARRANTY, LIABILITY OR SUPPORT!')) > > options, args = cmdlineparser.parse_args() > ### > > When I run LANGUAGE=de ./test.py --help I get the error. > > ### This is the test.de.po file > # Copyright (C) 2006 Thorsten Kampe > # Thorsten Kampe , 2006 > > msgid "" > msgstr "" > > "Project-Id-Version: Template 1.0\n" > "POT-Creation-Date: Tue Sep 7 22:20:34 2004\n" > "PO-Revision-Date: 2005-07-03 16:47+0200\n" > "Last-Translator: Thorsten Kampe \n" > "Language-Team: Thorsten Kampe \n" > "MIME-Version: 1.0\n" > "Content-Type: text/plain; charset=ISO-8859-15\n" > "Content-Transfer-Encoding: 8-bit\n" > "Generated-By: pygettext.py 1.5\n" > > msgid "THIS SOFTWARE COMES WITHOUT WARRANTY, LIABILITY OR SUPPORT!" > msgstr "DIESES PROGRAMM HAT WEDER GEW?HRLEISTUNG, HAFTUNG NOCH > UNTERST?TZUNG!" > ### > > The localisation now produces an error in the localised optik files, > too. > > Under Windows I get " File "G:\program files\python\lib\encodings > \cp1252.py", line 12, in encode > return codecs.charmap_encode(input,errors,encoding_table)" I'm not very experienced with internationalization, but if you change:: gettext.install('test') to:: gettext.install('test', unicode=True) what happens? STeVe From donn at u.washington.edu Thu Apr 12 18:05:21 2007 From: donn at u.washington.edu (Donn Cave) Date: Thu, 12 Apr 2007 15:05:21 -0700 Subject: tuples, index method, Python's design References: <1175867771.114540.61810@n76g2000hsh.googlegroups.com> <1175884427.779950.267220@y80g2000hsf.googlegroups.com> <1175953520.316208.241490@o5g2000hsb.googlegroups.com> <7xzm5igbrb.fsf@ruckus.brouhaha.com> <1176200361.260546.280510@n76g2000hsh.googlegroups.com> <1176214831.3430.49.camel@dot.uniqsys.com> Message-ID: In article , Antoon Pardon wrote: > On 2007-04-11, Marc 'BlackJack' Rintsch wrote: > > In , Antoon Pardon wrote: > > > >> On 2007-04-11, Steven D'Aprano > >> wrote: > >>> Lists are designed for sequences of homogeneous items, e.g.: > >>> > >>> L = [1, 2, 4, 8, 16, 32] > >>> while tuples are designed to be more like structs or records, with > >>> heterogeneous items, e.g.: > >>> > >>> T = ("Fred", 32, 12.789, {}, None, '\t') > >> > >> I think you are confused. Last time I heard this homogeneous items stuf, > >> it had nothing to do with the types being the same. They were homogeneous > >> because they somehow belonged together and heterogeneous because they > >> just happened to live together. Similarity of type played no part in > >> calling the data homogeneous or heterogeneous. > > > > Then you are confused. The typical use case for tuples are database > > records. The columns in the table can have completely different types but > > the values in a row, represented as a Python tuple, of course belong > > together. > > Don't blame me. I don't agree with the view. But that was sort of the > explanation that was given here last time I remember this topic came > up in defending why tuples and lists differ in a number of ways that > are less obvious. > > They wrote about lists containing homogeneous items and tuples > containing hetergenous items but stressed rather strongly that > this shouldn't be understood in terms of type similarities. Well, yes - consider for example the "tm" tuple returned from time.localtime() - it's all integers, but heterogeneous as could be - tm[0] is Year, tm[1] is Month, etc., and it turns out that not one of them is alike. The point is exactly that we can't discover these differences from the items itself - so it isn't about Python types - but rather from the position of the item in the struct/tuple. (For the person who is about to write to me that localtime() doesn't exactly return a tuple: QED) Donn Cave, donn at u.washington.edu From jeff at taupro.com Tue Apr 24 05:24:54 2007 From: jeff at taupro.com (Jeff Rush) Date: Tue, 24 Apr 2007 04:24:54 -0500 Subject: Would You Write Python Articles or Screencasts for Money? Message-ID: <462DCCE6.9060908@taupro.com> There is discussion by the Python Software Foundation of offering cash bounties or perhaps periodic awards to the "best of" for magazine articles, video/screencast clips and such. If YOU would be swayed to get involved in producing content in exchange for cash, please speak up on the advocacy mailing list and also drop an email to Steve Holden , current champion of this idea and looking for encouragement. Ideas on how to evaluate contributions, how frequently to do this and critical thresholds of cash amounts necessary to induce YOUR participation are wanted. Jeff Rush Python Advocacy Coordinator * Advocacy Mailing List http://mail.python.org/mailman/listinfo/advocacy From jeremy+complangpython at jeremysanders.net Tue Apr 24 11:14:49 2007 From: jeremy+complangpython at jeremysanders.net (Jeremy Sanders) Date: Tue, 24 Apr 2007 16:14:49 +0100 Subject: Python Screen Scraper References: Message-ID: Michael Bentley wrote: > Possibly the easiest thing will be to read from firefox' cache. > Otherwise I think your only real options are to either build a proxy > or sniff the wire... Maybe another way would be to write a firefox addon/plugin. I believe python is now supported... -- Jeremy Sanders http://www.jeremysanders.net/ From steve at holdenweb.com Fri Apr 13 08:58:19 2007 From: steve at holdenweb.com (Steve Holden) Date: Fri, 13 Apr 2007 08:58:19 -0400 Subject: favourite IDE In-Reply-To: <1176422188.006169.141100@q75g2000hsh.googlegroups.com> References: <1176422188.006169.141100@q75g2000hsh.googlegroups.com> Message-ID: azrael wrote: > Some time ago I posted a question about the favourite IDE. I finally > found it. WING IDE i the best I've ever seen for python. Code > completition is amazing, automated help, python comand line. evrything > i need. Who didnt try, doesnt know what he is missing. > > just one word: Amazing > > respect to the developers > While I too am a (very happy) Wing user I feel I should remind everyone that "best" here is a misleading term for two reasons: 1. Evaluations like this are notoriously subjective, and 2. Any IDE has many dimensions, so they can't be laid out on a linear path between "worst" and "best". Having said this, I *am* looking forward to using the new features in 3.0 for debugging threaded code. That sounds like a major step forward. 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 apardon at forel.vub.ac.be Thu Apr 19 06:54:20 2007 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 19 Apr 2007 10:54:20 GMT Subject: Do other Python GUI toolkits require this? References: <462697A6.6010007@codebykevin.com> Message-ID: On 2007-04-19, Michael Bentley wrote: > > On Apr 19, 2007, at 4:11 AM, Antoon Pardon wrote: > >> On 2007-04-19, Michael Bentley wrote: >>> >>> PyObjC is pretty slick (and since Ronald hasn't made any commits in a >>> while I'm nearly certain it'll show up in the next official >>> distribution of the devtools). About the time you gave up on PyQt on >>> the Mac and switched over to Tkinter, I switched to PyObjC. The >>> learning curve is rather steep IMO, but worth it. >> >> Just a throw in remark, that you may ignore if you wish, but a steep >> learning curve means that the subject is easily familiarized and that >> the learning period is short. >> >> You seem to use it as if it is the opposite. > > Mathematical absurdities aside, it's the common usage -- but perhaps > you knew that. I don't know how you come to the conclusion that it is a mathematical absurdity but consider this: If you find that common usage propagates something that is incorrect, should we just shrug it off or should we attemp a correction? There is always a chance that one day you find yourself exposed to a learning curve while going through a document. If you just depend on common usage you will probably draw the wrong conclusion. -- Antoon Pardon From pabloski at giochinternet.com Thu Apr 26 06:41:29 2007 From: pabloski at giochinternet.com (pabloski at giochinternet.com) Date: Thu, 26 Apr 2007 10:41:29 GMT Subject: Parsing HTML/XML documents Message-ID: I need to parse real world HTML/XML documents and I found two nice python solution: BeautifulSoup and Tidy. However I found pyXPCOM that is a wrapper for Gecko. So I was thinking Gecko surely handles bad html in a more consistent and error-proof way than BS and Tidy. I'm interested in using Mozilla DOM from inside a Python script, however I'm a bit confused about how can I use pyXPCOM to accomplish this job. Any suggestions? From gregpinero at gmail.com Tue Apr 10 03:36:11 2007 From: gregpinero at gmail.com (gregpinero at gmail.com) Date: 10 Apr 2007 00:36:11 -0700 Subject: Exec Statement Question In-Reply-To: <1176101170.066391.134010@y66g2000hsf.googlegroups.com> References: <1176099427.158621.45580@o5g2000hsb.googlegroups.com> <1176101170.066391.134010@y66g2000hsf.googlegroups.com> Message-ID: <1176190571.456862.78980@p77g2000hsh.googlegroups.com> Thanks for the responses everyone. That does make sense to me now. -Greg From jowr.pi at gmail.com Sat Apr 28 13:56:00 2007 From: jowr.pi at gmail.com (Eric Gisse) Date: 28 Apr 2007 10:56:00 -0700 Subject: Video: Professor of Physics Phd at Cal Tech says: 911 Inside Job In-Reply-To: <463384BB.26142112@earthlink.net> References: <1177467203.719625.93920@u32g2000prd.googlegroups.com> <1177780530.539758.275660@c35g2000hsg.googlegroups.com> <463384BB.26142112@earthlink.net> Message-ID: <1177782960.904619.77210@u30g2000hsc.googlegroups.com> On Apr 28, 9:30 am, "Michael A. Terrell" wrote: > Eric Gisse wrote: > > > On Apr 24, 6:13 pm, stj... at rock.com wrote: > > > Cal Tech is the ELITE of ELITE in physics. > > > "INN World Report interviewed Dr. Crockett Grabbe - professor of > > physics at the University of Iowa - regarding his thoughts on the > > 'collapses' of WTC1, WTC2, & WTC7. In this interview he lists numerous > > reasons to suspect controlled demolition and expresses support for > > alternative theories." > > > A common mistake - I frequently confuse CalTech and U of Iowa. > > >http://scholar.google.com/scholar?hl=en&lr=&safe=off&client=firefox-a... > > > That's interesting, no publications on any engineering topic. A > > professor of physics, not engineering, who claims that explosives were > > planted in not only WTC7, but WTC 1 and 2 which were trigged by the > > planes impacting the building. > > > Why is anyone listening to this loon? > > The same reason they listen to the even loonier Rosie O'donell? wait...WHAT? > > http://www.popularmechanics.com/blogs/911myths/4213805.html > > -- > Service to my country? Been there, Done that, and I've got my DD214 to > prove it. > Member of DAV #85. > > Michael A. Terrell > Central Florida From frank at chagford.com Thu Apr 26 01:32:43 2007 From: frank at chagford.com (Frank Millman) Date: 25 Apr 2007 22:32:43 -0700 Subject: Now() In-Reply-To: References: <000301c78728$ba634ce0$2f29e6a0$@rawlins@thinkbluemedia.co.uk> Message-ID: <1177565563.166728.93460@c18g2000prb.googlegroups.com> On Apr 25, 2:01 pm, Tim Golden wrote: > Robert Rawlins - Think Blue wrote: > > > I'm using the following function 'str (now)' to place a date time stamp into > > a log file, which works fine, however it writes the stamp like this. > > 2007-04-25 11:06:53.873029 > > But I need to expel those extra decimal places as they're causing problems > > with the application that parses the log data, all I need is something like > > this: > > 2007-04-25 11:06:53 > > With time depicted to the nearest second, from my background in ColdFusion > > development we used to have a datetimeformat() function that I could use as > > DateTimeFormat(now(), "yyyy-mm-dd HH:mm:ss") > > Which would give the current time a mask. > > Any equivalent for this in python? > > You want the strftime method which is documented under > the time module. > > > import datetime > print datetime.datetime.now ().strftime ("%Y-%m-%d etc.") > > > > TJG An alternative, which will work for this specific request - str(now().replace(microsecond=0)) Frank Millman From carsten at uniqsys.com Sun Apr 22 00:55:39 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Sun, 22 Apr 2007 00:55:39 -0400 Subject: Problem redefining __getitem__ for str subclass In-Reply-To: <1177212972.973086.319990@b58g2000hsg.googlegroups.com> References: <1177212972.973086.319990@b58g2000hsg.googlegroups.com> Message-ID: <20070422044023.M59810@uniqsys.com> On 21 Apr 2007 20:36:13 -0700, tsm8015 wrote > I do not think I am understanding how to redefine the getitem > function for string. Why does the following not work: > > class NStr(str): > def __getitem__(self,idx): > print "NStr:getitem",idx,type(idx) > return str.__getitem__(self,idx) > > s=NStr("abcde") > > print s[1] > print s[1:4:2] > print s[1:2] > > if I run this program (python 2.5; Mac OSX) i get: > > $ python strProb.py > NStr:getitem 1 > b > NStr:getitem slice(1, 4, 2) > bd > b > > ie the last statement (s[1:2]) with a simple slice does not call the > new __getitem__???? What am I missing. You're overriding __getitem__ just fine, but if your object has a __getslice__ method, __getslice__ will be called instead of __getitem__ to fetch simple slices. Since you are deriving from str which does implement __getslice__, you'll need to override __getslice__, too. -Carsten From paul at boddie.org.uk Wed Apr 11 06:59:22 2007 From: paul at boddie.org.uk (Paul Boddie) Date: 11 Apr 2007 03:59:22 -0700 Subject: About Trolltech QT OpenSource license. In-Reply-To: <1176285062.178372.15090@d57g2000hsg.googlegroups.com> References: <1176233376.712861.67160@o5g2000hsb.googlegroups.com> <1176237050.409742.8760@30g2000cwc.googlegroups.com> <1176285062.178372.15090@d57g2000hsg.googlegroups.com> Message-ID: <1176289162.286494.157090@d57g2000hsg.googlegroups.com> On 11 Apr, 11:51, "king kikapu" wrote: > > Ok, i see...So i can use Qt OS edition and earn money from this as > long as i explicitly say (is a reference to a GPL in a readme text > file enough for this ?) that this software is under the GPL lisence > and i have the obligation to give the source code with it. I'll leave the specifics of this case to one side and say that for any software that you intend to distribute under the GPL, you should provide references to the licence at least in some kind of text file (I use COPYING.txt for this), but also in your source files (I typically use module docstrings, but I imagine that comment lines might be better in some respects), as well as a copy of the licence (I use LICENCE.txt for this). You should find the licence text in any GPL- licensed package as well as at the FSF site: http://www.fsf.org/licensing/licenses/gpl.html The "making money" aspect can be simplified to this: you can sell copies of your software, but anyone receiving that software is entitled to the sources "at cost", and since they receive the software under the GPL, they are entitled to redistribute it under the same terms. One popular misunderstanding is that if a company is selling GPL-licensed software, they have to give the sources away to anyone who asks; in fact, only people who have received the software are entitled to the sources: http://www.fsf.org/licensing/licenses/gpl-faq.html#CanIDemandACopy Various companies do, however, give away sources to anyone but then make money out of the effort to turn such sources into executable systems. For example, Red Hat make the sources on which their products are based available to anyone, but since the effort in building them, putting everything together, testing the result, and so on is non- trivial, people pay them money to do that particular work. As has been said elsewhere in this discussion, the specific use of the term "commercial" in the case described may be aimed at a corporate mindset which equates "commercial" to "proprietary", but Free (and open source) Software can be the basis for commercial activities, too. Paul From bignose+hates-spam at benfinney.id.au Wed Apr 11 17:49:09 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Thu, 12 Apr 2007 07:49:09 +1000 Subject: Shebang or Hashbang for modules or not? References: <1176308951.932721.197630@y80g2000hsf.googlegroups.com> Message-ID: <871wiq8tuy.fsf@benfinney.id.au> "Chris Lasher" writes: > I recently heard someone argue that shebangs were only appropriate > for Python code intended to be executable (i.e., run from the > command line). Since that's the purpose of putting in a shebang line, that's what I'd argue also; specifically: - Modules intended primarily for import should be named 'foo.py' and have no shebang line. This doesn't preclude having an 'if __name__ == "__main__":' block, and running the module as 'python ./foo.py' for whatever reason. - Modules intended primarily for running as a command should have a shebang line and an 'if __name__ == "__main__":' block, and be named according to the conventions of the OS for naming command programs; on *nix, this means naming the file 'foo'. This doesn't preclude importing the module (e.g. for unit testing), though it is a little more convoluted than a simple 'import' statement. -- \ "Dad always thought laughter was the best medicine, which I | `\ guess is why several of us died of tuberculosis." -- Jack | _o__) Handey | Ben Finney From laurent.pointal at limsi.fr Thu Apr 26 10:32:30 2007 From: laurent.pointal at limsi.fr (Laurent Pointal) Date: Thu, 26 Apr 2007 16:32:30 +0200 Subject: Re-ocurring Events In-Reply-To: References: <3891950377467154133@unknownmsgid> Message-ID: Daniel Nogradi a ?crit : >> A bit more of a complex one this time, and I thought I'd get your >> opinions >> on the best way to achieve this. Basically I'm looking for a way to >> describe >> a re-occurring event, like a calendar event or appointment I guess. I'm >> likely to use an XML file for the definition of the events, but >> imagine I've >> got an event that looks something like this. >> >> > repeat="daily" >> /> May take a look at launchd (Apple) XML dialect, it may have at least the semantic for your need. For other parts... elementtree, yes. >> Now what I want to do is be able to build a class which has a function >> like >> 'getCurrentEvent()' which will return any events that should be >> occurring at >> that time. So if the current system time and date is 2007-01-03 13:00:00 >> then it will return THAT event to me, but if it was say 2007-01-03 >> 16:00:00 >> then it would not, as the event isn't 'due' to occur at that time. Make >> sense? >> >> What's the best way of handling this? I'm really a little lost as to >> how I >> might get started, checking a static date time isn't a problem, it's >> when it >> comes to these re-occurring events that I struggle a little. The idea is >> that I would have 5 core repetitions, none, daily, weekly, monthly and >> annually. > > This will not solve all your problems, but a very convenient way of > handling XML is the element tree module (that comes with python 2.5): > http://docs.python.org/lib/module-xml.etree.ElementTree.html > > HTH, > Daniel From roman.yakovenko at gmail.com Thu Apr 19 04:19:35 2007 From: roman.yakovenko at gmail.com (Roman Yakovenko) Date: Thu, 19 Apr 2007 11:19:35 +0300 Subject: Boost.Python create extra functions not in wrapped object In-Reply-To: <1176968256.066230.238940@n59g2000hsh.googlegroups.com> References: <1176968256.066230.238940@n59g2000hsh.googlegroups.com> Message-ID: <7465b6170704190119o266a8f1du31f80a4cbaa8abea@mail.gmail.com> On 19 Apr 2007 00:37:36 -0700, Stou Sandalski wrote: > > Hi, > > I have a python library created by wrapping the C++ library using > Boost.Python, the problem is that the wrappers are not very > pythonic.... so I want to add some methods that do not exist in the C+ > + implementation, that would create a better Python interface. > > For example to initialize the data in an object in the library one > must iterate through every point, setting a value for each > individually. That's the way it works in C++ but in python it would > be nice to instead just have one call that can receive a numpy array > or a tuple. I want to add a call like: setData(array) to the python > object, a call that does not exist in the C++ implementation and then > in the C++ wrappers actually use setData to iterate through the array > and set the values using the normal C++ method, say setValue(index, > value). > > Something along the lines of this (initData is not in the constructor > on purpose) C++ object: > > class Foo > { > public: > void initData(int size) > { > data = new float[size]; > }; // Create the data array > void setValue(int index, float value) // Set given value > { > data[index] = value; > } > private: > float *data; > }; > > > In python however I want to do this: > > obj = foo() > ar = array([1,2,3,4,5], dtype=float) > > foo.setData(ar) > > Or even better: > > ar = array([1,2,3,4,5], dtype=float) > obj = foo(ar) > > And have it somehow call initData() and setValue() iteration inside > the C++ code of the wrapper. I've only used SWIG and don't really > know much about Boost, I am not even sure how to label what I am > trying to do. > > Can this be done with Boost, without changing the C++ library? Take a look on next link: http://boost.org/libs/python/doc/tutorial/doc/html/python/techniques.html#python.extending_wrapped_objects_in_python Regards, > > Stou > > -- > http://mail.python.org/mailman/listinfo/python-list > -- Roman Yakovenko C++ Python language binding http://www.language-binding.net/ -------------- next part -------------- An HTML attachment was scrubbed... URL: From bytecolor at yahoo.com Tue Apr 3 06:05:21 2007 From: bytecolor at yahoo.com (bytecolor) Date: 3 Apr 2007 03:05:21 -0700 Subject: Tkinter <> and bindtags ordering In-Reply-To: <1175593732.437631.198860@n76g2000hsh.googlegroups.com> References: <1175572841.269301.275100@q75g2000hsh.googlegroups.com> <1175584600.221378.143380@n59g2000hsh.googlegroups.com> <1175589451.633609.216190@e65g2000hsc.googlegroups.com> <1175593732.437631.198860@n76g2000hsh.googlegroups.com> Message-ID: <1175594721.342934.278140@y66g2000hsf.googlegroups.com> On Apr 3, 5:48 am, "Rob Wolfe" wrote: > Have you looked at ColorDelegator.py from idlelib? > There has been done such a syntax highlighting based on Tkinter.Text. > > -- > HTH, > Rob I've been poking around it a bit. I actually use the tabpage module in my app. Guess I should take a harder look at it. Nice bit of software. -- bytecolor From collinstocks at gmail.com Thu Apr 5 14:55:51 2007 From: collinstocks at gmail.com (Collin Stocks) Date: Thu, 5 Apr 2007 14:55:51 -0400 Subject: way to extract only the message from pop3 In-Reply-To: References: <1175628970.874615.127020@y80g2000hsf.googlegroups.com> <4c0048df0704051109j24e24457v453cd68136e0096a@mail.gmail.com> Message-ID: <4c0048df0704051155v49209f24yc690e9ad4e0afe9b@mail.gmail.com> I only put None there so that the colon would be more visible: in some browser fonts, [value:] looks the same as [value] On 4/5/07, Gabriel Genellina wrote: > > En Thu, 05 Apr 2007 15:09:18 -0300, Collin Stocks > escribi?: > > > message=whole_message[len(headers):None] > > > > You can omit the word None: it is just there for clarity purposes. > > Uhm... I can't find any usage of slices including an explicit None in > code.google.com (except on the Python test suite), and really I don't > consider that to be more readable than whole_message[len(headers):] > But of course this is just a stylistic issue. > > -- > Gabriel Genellina > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From bdesth.quelquechose at free.quelquepart.fr Fri Apr 27 17:58:39 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Fri, 27 Apr 2007 23:58:39 +0200 Subject: creating an object from base class In-Reply-To: <1177677510.209111.148540@u32g2000prd.googlegroups.com> References: <1177677510.209111.148540@u32g2000prd.googlegroups.com> Message-ID: <4632686a$0$19226$426a74cc@news.free.fr> iogilvy at attglobal.net a ?crit : > i wish to have some extended functionality added to sockets > > i can create my own socket class class mysocket(socket.socket): > > and all should be fine. Except, the sockets are created for me by the > accept method, listening on port. So how can i take the standard > socket created for me and create a 'mysocket'. I need a method that > will initialise any new properties i have added in my class, but how > can i change the class of the socket created? object.__class__ = OtherClass But this may not be the wisest solution. What you want is not inheritance, it's decoration (AKA wrapping). IOW : instead of directly using accept(), use a wrapper around it that will returns socket objects wrapped in your own class. My 2 cents... From kw at codebykevin.com Wed Apr 18 16:16:04 2007 From: kw at codebykevin.com (Kevin Walzer) Date: Wed, 18 Apr 2007 16:16:04 -0400 Subject: Future Python Gui? In-Reply-To: <1176923448.998078.170760@e65g2000hsc.googlegroups.com> References: <1176859699.906386.326720@b75g2000hsg.googlegroups.com> <1176923448.998078.170760@e65g2000hsc.googlegroups.com> Message-ID: <46267C84.8040505@codebykevin.com> bcwhite at pobox.com wrote: >> Tile is available right now in Tk as an extension package, and a Tkinter >> wrapper for it can be found here: >> >> http://tkinter.unpythonic.net/wiki/TileWrapper > > That site seems to be down (500 Internal Server Error). > > >> Tile will be integrated into Tk's core when 8.5 is released. It's >> supposed to enter beta testing Real Soon Now. However, I imagine that >> Python/Tkinter will depend on Tk 8.4 for the foreseeable >> future--certainly 8.5 won't be supported officially before a full, >> stable release is made. Perhaps in Python 2.6? > > That is okay with me. It'll be a long time before I get to a point > where I'll need easy release. But knowing that it will be part of a > future release will also mean I don't have to worry about refactoring > everything if the toolkit I'm using goes out of style and is replaced > by something else. > > Out of curiosity... Did that page have install instructions for > Tile? Other pages I've seen talk about it but don't say how to > integrate it in to a python installation (under Windows or Linux). > > -- Brian > On Windows, the easiest way to install Tile is to grab it from ActiveState's Tcl distribution (http://www.activestate.com/products/activetcl/) and then place it with the Tcl/Tk bits that come with Python. The Tcl/Tk build for Windows that python.org provides doesn't ship with Tile. You'll also have to install the Tile wrapper at the site I referenced earlier in your site-packages directory. -- Kevin Walzer Code by Kevin http://www.codebykevin.com From goodTweetieBird at hotmail.com Fri Apr 27 17:08:24 2007 From: goodTweetieBird at hotmail.com (gtb) Date: 27 Apr 2007 14:08:24 -0700 Subject: if __name__ == 'main': & passing an arg to a class object Message-ID: <1177708104.277756.245360@t38g2000prd.googlegroups.com> The lines if __name__ == 'main': someClass().fn() appear at the end of many examples I see. Is this to cause a .class file to be generated? The last line of the sample below has a string parameter. When I mimicked this I got an error stating that the class constructor did not take an arg, which seems correct. Thanks, gtb # Generated by MaxQ [com.bitmechanic.maxq.generator.CompactGenerator] from CompactTest import CompactTest class MaxQTest(CompactTest): # Recorded test actions. def runTest(self): self.msg('Test started') # ^^^ Insert new recordings here. (Do not remove this line.) # Code to load and run the test if __name__ == 'main': MaxQTest('MaxQTest').Run() From ruiligc at earthlink.net Tue Apr 24 07:16:23 2007 From: ruiligc at earthlink.net (Ray) Date: Tue, 24 Apr 2007 11:16:23 GMT Subject: TK-grid problem, please help In-Reply-To: References: <3CgWh.23821$PL.17381@newsread4.news.pas.earthlink.net> Message-ID: Hi Anton, Thanks again. This is what I need! my problem already solved. Ray Anton Vredegoor wrote: > Ray wrote: > >> hi, I have a question about how to use .grid_forget (in python/TK) >> >> I need to work on grid repeatly. everytime when a button is pressed, >> the rows of grid is different. such like, first time, it generate 10 >> rows of data. >> 2nd time, it maybe only 5 rows. so I need a way to RESET the grid data >> every time. how can I do it? by grid_forger()?, then would anyone can >> help on >> how to use grid_forget() >> the sample code as following: > > I'm not sure if it solves your problem but this modification of your > code at least *looks* like it works better. The entries are completely > destroyed so that the next time you call the function they can be > recreated. > > The trick I am using is to use a list in the arguments of the function > but that is a bit of a hack, the list 'remembers' its state from the > last time the function was called, I think one should use classes for > bookkeeping such things instead. > > from Tkinter import * > > def mygrid(text,M = []): > ######## how to use grid_forget() to clean the grid??########### > while M: > x = M.pop() > x.destroy() > rows = [] > count=int(text) > for i in range(count): > cols = [] > for j in range(4): > e = Entry(frame3, relief=RIDGE) > M.append(e) > e.grid(row=i, column=j, sticky=NSEW) > e.insert(END, '%d.%d' % (i, j)) > cols.append(e) > rows.append(cols) > > > root=Tk() > > frame1=Frame(root, width=150, height=100) > frame1.pack() > > text=Entry(frame1) > text.pack(side=LEFT) > > button=Button(frame1, text='generate grid', command=(lambda: > mygrid(text.get()))) > > button.pack() > > frame2=Frame(root, width=150, height=100) > frame2.pack() > > button2=Button(frame2, text='exit', command=root.quit) > button2.pack() > > frame3=Frame(root, width=150, height=300) > frame3.pack() > > root.mainloop() > > A. From duncan.booth at invalid.invalid Fri Apr 27 11:36:20 2007 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 27 Apr 2007 15:36:20 GMT Subject: regex question References: <1177655637.717863.93920@o40g2000prh.googlegroups.com> <1177659238.159411.40640@c18g2000prb.googlegroups.com> <1177683018.566343.105620@c18g2000prb.googlegroups.com> <1177687071.378607.285070@t38g2000prd.googlegroups.com> Message-ID: proctor <12cc104 at gmail.com> wrote: >> >>> re.findall('(.)*', 'abc') >> ['c', ''] > thank you this is interesting. in the second example, where does the > 'nothingness' match, at the end? why does the regex 'run again' when > it has already matched everything? and if it reports an empty match > along with a non-empty match, why only the two? > There are 4 possible starting points for a regular expression to match in a three character string. The regular expression would match at any starting point so in theory you could find 4 possible matches in the string. In this case they would be 'abc', 'bc', 'c', ''. However findall won't get any overlapping matches, so there are only two possible matches and it returns both of them: 'abc' and '' (or rather it returns the matching group within the match so you only see the 'c' although it matched 'abc'. If you use a regex which doesn't match an empty string (e.g. '/x(.*?)x/' then you won't get the empty match. From __peter__ at web.de Tue Apr 3 03:44:43 2007 From: __peter__ at web.de (Peter Otten) Date: Tue, 03 Apr 2007 09:44:43 +0200 Subject: pyc file [Newbie Question] References: Message-ID: Jim Aikin wrote: > Just starting to learn Python and going through the Tutorial in the Help > file. FWIW, I'm a hobbyist programmer -- not extremely knowledgeable, but > not entirely clueless. > > In 6.1.2 of the Tutorial, I find this: "The modification time of the > version of spam.py used to create spam.pyc is recorded in spam.pyc, and > the .pyc file is ignored if these don't match." Either I don't understand > this, or it isn't correct. $ echo 'print "Hello, Jim"' > tmp.py $ python -c'import tmp' Hello, Jim Now let's change tmp.pyc in a way that we can see but Python won't notice: $ python -c's = open("tmp.pyc").read(); open("tmp.pyc", "w").write(s.replace("Jim", "JIM"))' $ python -c'import tmp' Hello, JIM As you can see, tmp.pyc is not recreated. But if we change the timestamp of tmp.py $ touch tmp.py $ python -c'import tmp' Hello, Jim it is. As Steven says, the behaviour you experience is caused by the module cache. That is, a module "my_module" is only imported once per session, no matter how many 'import my_module' statements you have in your application: $ python -c'import tmp; import tmp' Hello, Jim That is why the greeting above is printed only once, and why your changes don't have any immediate effect. Peter From bbxx789_05ss at yahoo.com Thu Apr 26 10:50:46 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: 26 Apr 2007 07:50:46 -0700 Subject: My python annoyances so far In-Reply-To: <1177541453.471959.120830@c18g2000prb.googlegroups.com> References: <1177541453.471959.120830@c18g2000prb.googlegroups.com> Message-ID: <1177599046.406827.5210@t38g2000prd.googlegroups.com> flifus at gmail.com wrote: > Annoyances: > Every language has annoyances. Python is no exception. Post away. Anyone that is offended can go drink a Guinness. > 1. Underscores! What's the deal with that? Especially those double > underscores. The best answer I read on this is that the double > underscores denotes special methods that the interpreter may > automatically use. For example, 4+4 get expanded by the interpreter to > 4.__add__(4). > I thought those were pretty ugly myself. Now, I am used to them. > 2. There are modules, there are functions, and there are classes- > methods! Wouldn't it have been easier had everything either been a > function or a class method? I know what you mean. I always write: someStringVar.len and then I backspace and retype: len(someString). But then again, I can never remember whether length is a member or a method in other languages. From harlinseritt at yahoo.com Mon Apr 16 12:04:23 2007 From: harlinseritt at yahoo.com (Harlin Seritt) Date: 16 Apr 2007 09:04:23 -0700 Subject: Lame wrapper for Python Message-ID: <1176739463.129242.77490@o5g2000hsb.googlegroups.com> Is there any type of lame_enc.dll wrapper for Python that's available? Thanks, Harlin Seritt From gagsl-py2 at yahoo.com.ar Thu Apr 5 17:23:52 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 05 Apr 2007 18:23:52 -0300 Subject: elementary tuple question. (sorry) References: Message-ID: En Thu, 05 Apr 2007 18:08:14 -0300, Steven W. Orr escribi?: > I have a tuple that I got from struct.unpack. Now I want to pass the data > from the returned tuple to struct.pack > >>>> fmt > 'l 10l 11i h 4h c 47c 0l' >>>> struct.pack(fmt, tup) > Traceback (most recent call last): > File "", line 1, in ? > struct.error: required argument is not an integer > > What's the idiom to pass the data in tup? Try the builtin help system: py> help(struct.pack) Help on function pack in module struct: pack(fmt, *args) Return string containing values v1, v2, ... packed according to fmt. See struct.__doc__ for more on format strings. So struct.pack(fmt, *tup) should work - try and see. -- Gabriel Genellina From kw at codebykevin.com Tue Apr 10 18:35:01 2007 From: kw at codebykevin.com (Kevin Walzer) Date: Tue, 10 Apr 2007 18:35:01 -0400 Subject: About Trolltech QT OpenSource license. In-Reply-To: <1176242640.630110.121120@y5g2000hsa.googlegroups.com> References: <1176233376.712861.67160@o5g2000hsb.googlegroups.com> <1176242640.630110.121120@y5g2000hsa.googlegroups.com> Message-ID: <3fc76$461c1116$4275d90a$24609@FUSE.NET> king kikapu wrote: > > > @ Kevin and Jarek : > thanks for the enlightening of that GPL thing. So, if i understand, i > create my Python software using Qt as my GUI, i earn the money for it > with the obligation to release my source code and somewhere in my > files i explicilty write that this software is under the GPL lisence, > is that correct ?? And i am legal all the way out ?? That's correct, as far as I know. (IANAL) > > So why these people at Trolltech have the word "Commercial" at their > mouth all the time ?? I can understand of course that money is all > about but becauce they released Qt under GPL they simply cannot > prevent anyone from gaining money using it. > In this case, "commercial" == "proprietary" == "closed-source." If your source is released in complicance with the GPL, you don't have to buy a license from Trolltech. -- Kevin Walzer Code by Kevin http://www.codebykevin.com From cam.ac.uk at mh391.invalid Sun Apr 29 22:08:30 2007 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Mon, 30 Apr 2007 03:08:30 +0100 Subject: While we're talking about annoyances In-Reply-To: <1hxchgp.7sw7efb72rh2N%aleax@mac.com> References: <1177837565.317999.244420@c35g2000hsg.googlegroups.com> <1177857049.938363.166170@p77g2000hsh.googlegroups.com> <1hxchgp.7sw7efb72rh2N%aleax@mac.com> Message-ID: Alex Martelli wrote: > Arnaud Delobelle wrote: > ... >>>>> decorated.sort() > ... >>> def index(sequence): >>> return sorted(range(len(sequence)), key=sequence.__getitem__) > ... >> But really these two versions of rank are slower than the original one >> (as sorting a list is O(nlogn) whereas filling a table with >> precomputed values is O(n) ). > > Wrong, because the original one also had a sort step, of course, so it > was also, inevitably, O(N log N) -- I've quoted the .sort step above. Well, counting the index() function that is called in both cases, the original rank() had one sort, but my version has two sorts. -- Michael Hoffman From elicriffield at gmail.com Mon Apr 9 15:17:44 2007 From: elicriffield at gmail.com (Eli Criffield) Date: 9 Apr 2007 12:17:44 -0700 Subject: recursively removing files and directories In-Reply-To: <1176145907.548336.28790@l77g2000hsb.googlegroups.com> References: <1176144250.874365.141820@n59g2000hsh.googlegroups.com> <1176145907.548336.28790@l77g2000hsb.googlegroups.com> Message-ID: <1176146264.429418.311050@d57g2000hsg.googlegroups.com> Forgot the rmdir import os import re def processFiles(args,dir,fileList): for thisFile in fileList: if re.match(r'REGEXPATTERN',thisFile): os.unlink("%s%s"dir,thisFile) os.rmdir(dir) os.path.walk("/",processFiles,None) Eli Criffield From torriem at chem.byu.edu Sun Apr 1 01:06:08 2007 From: torriem at chem.byu.edu (Michael Torrie) Date: Sat, 31 Mar 2007 23:06:08 -0600 Subject: Shed Skin Python-to-C++ Compiler 0.0.21, Help needed In-Reply-To: <7x8xdcrc13.fsf@ruckus.brouhaha.com> 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> <7x8xdcrc13.fsf@ruckus.brouhaha.com> Message-ID: <1175403968.25928.35.camel@enterprise> On Sat, 2007-03-31 at 20:47 -0700, Paul Rubin wrote: > Michael Torrie writes: > > The no-service contract version of the GPL is not the same as the > > standard GPLv2. > > I don't see how that can be--we're talking about a GCC-based compiler, > right? Well, that's beside the point anyway. The output of a program is beyond the scope of the source code license for the program. However the default is for the output to be copyrighted the author. Thus the author of a program is free to say (give license, in other words) that the output of a program can distributed. The real point is the Shed Skin author can both license the program under the GPLv2 and also say that the output from his program is not bound by any license. There's no conflict unless the author of Shed Skin wants there to be. Worst case, if indeed the GPLv2 says it covers the output of the program (which I don't believe it does), copyright law still trumps everything and the author is free at add an exemption to the license if he chooses, which is what I've seen done with Bison. Bison is also a special case because the output of bison contains code fragments that are part of the bison source code itself, which is under the GPL. Thus a special exception had to be made in this case. Anyway, the only real point is that if there is a concern about the copyright and licensing of the output of Shed Skin, then we merely need to ask the author of it to clarify matters and move on with life. With the exception of GNAT, to date no GPL'd compiler has ever placed a GPL restriction on its output. Whether this is explicit or implicit doesn't matter, so long as it's there. From duncan.booth at invalid.invalid Sat Apr 14 07:47:32 2007 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 14 Apr 2007 11:47:32 GMT Subject: Portably generating infinity and NaN References: Message-ID: skip at pobox.com wrote: > % python > Python 2.6a0 (trunk:54264M, Mar 10 2007, 15:19:48) > [GCC 4.0.1 (Apple Computer, Inc. build 5367)] on darwin > Type "help", "copyright", "credits" or "license" for more > information. > >>> import struct > >>> struct.pack("f", float("Inf")) > '\x7f\x80\x00\x00' > >>> struct.pack("f", float("NaN")) > '\x7f\xc0\x00\x00' > > (Note the absence of a demonstration on Windows.) Can't the above be > blessed as the One True Way and wormed around in floatmodule.c for > those platforms where float'ing "NaN" or "Inf" doesn't currently work? How about doing the same in reverse to generate the values on Windows? It should be pretty portable, otherwise the struct module doesn't work as advertised: >>> NaN, Inf = struct.unpack("!2f", '\x7f\xc0\x00\x00\x7f\x80\x00\x00') >>> NaN,Inf (1.#QNAN, 1.#INF) This also means you can choose which NaN you generate, although given that it compares unequal with itself it probably doesn't matter. From adam at atlas.st Mon Apr 9 22:23:17 2007 From: adam at atlas.st (Adam Atlas) Date: 9 Apr 2007 19:23:17 -0700 Subject: RFC: Assignment as expression (pre-PEP) In-Reply-To: <1175802680.021987.39220@p77g2000hsh.googlegroups.com> References: <1175802680.021987.39220@p77g2000hsh.googlegroups.com> Message-ID: <1176171797.184061.196520@b75g2000hsg.googlegroups.com> Hasn't this been discussed many many times before? I think Guido has been favourable to the idea of allowing :=, but that was a long time ago, and I don't think anything ever came of it. Personally, if anything, I'd like to see more use of the 'as' keyword as in Python 2.5's new 'with' statement. Assignment is basically what it adds to the statement, so if anything we should reuse it in other statements for consistency. if my_re1.match(exp) as temp: # do something with temp elif my_re2.match(exp) as temp: # do something with temp elif my_re3.match(exp) as temp: # do something with temp elif my_re4.match(exp) as temp: # do something with temp As others have mentioned, your particular instance is probably evidence that you need to restructure your code a little bit, but I do agree that "x = y; if x: ..." is a common enough idiom that it warrants a shortcut. And reusing "as", I think, is nice and readable, and it's an advantage that it doesn't require adding any new keywords or symbols. From hayes.tyler at gmail.com Thu Apr 19 15:38:10 2007 From: hayes.tyler at gmail.com (Tyler) Date: 19 Apr 2007 12:38:10 -0700 Subject: wxPython and how to return text entry to main program? Message-ID: <1177011490.435609.155870@o5g2000hsb.googlegroups.com> Hello All: I am currently working on a project to create an FEM model for school. I was thinking about using wxPython to gather the 12 input variables from the user, then, after pressing the "Run" button, the GUI would close, and the 12 input variables would then be available for the rest of the program. So far, what I have been able to do is mostly a reverse engineering job to get the frame to look right and return the text variable to a dialog box. I have read about a "redirect" that could be used to send the values to a file. But, then I would have to open the file and read in the data from there. This seems crude and lacking elegance. Any help on how to get the program to output the data back to the main python program and close when I press submit? My apologies if this is something of a simple question, but I have only started in on wxPython about a week ago, and Python this term. The codes I am using are below. Any help (or suggested reading material) is greatly appreciated. Cheers, t. MY MAIN PROGRAM #!/usr/bin/env python import femGUI app = femGUI.MyApp(False) dlg = femGUI.FemInput() dlg.Destroy() app.MainLoop() # Then do something with inputs here.... THE FEMINPUT GUI CLASS import wx class FemInput(wx.Frame): def __init__(self): wx.Frame.__init__(self, None, -1, "Options Input Interface") panel = wx.Panel(self) # First create the controls # Title topLbl = wx.StaticText(panel, -1, "FEM 2D Basket Put Option ",size=(420,-1)) topLbl.SetFont(wx.Font(18, wx.SWISS, wx.NORMAL, wx.BOLD)) # S1 lower and upper bounds for grid s1label = wx.StaticText(panel, -1, "S1 Low , S2 Low: ", size=(220,-1)) self.s1lower = wx.TextCtrl(panel, -1, "", size=(100,-1)); self.s2lower = wx.TextCtrl(panel, -1, "", size=(100,-1)); # S2 lower and upper bounds for grid s2label = wx.StaticText(panel, -1, "S1 High, S2 High: ", size=(220,-1)) self.s1upper = wx.TextCtrl(panel, -1, "", size=(100,-1)); self.s2upper = wx.TextCtrl(panel, -1, "", size=(100,-1)); # S1 and S2 volatility vlabel = wx.StaticText(panel, -1, "S1 Volatility, S2 Volatility: ", size=(220,-1)) self.v1vol = wx.TextCtrl(panel, -1, "", size=(100,-1)); self.v2vol = wx.TextCtrl(panel, -1, "", size=(100,-1)); # Risk free rate and correlation prlabel = wx.StaticText(panel, -1, "Interest Rate, Correlation: ", size=(220,-1)) self.risk = wx.TextCtrl(panel, -1, "", size=(100,-1)); self.corr = wx.TextCtrl(panel, -1, "", size=(100,-1)); # Strike and Exercise Date kTlabel = wx.StaticText(panel, -1, "Srike Price, Exercise Date: ", size=(220,-1)) self.strike = wx.TextCtrl(panel, -1, "", size=(100,-1)); self.finalT = wx.TextCtrl(panel, -1, "", size=(100,-1)); # deltaT and deltaX dTXlabel = wx.StaticText(panel, -1, "delta T, delta X: ", size=(220,-1)) self.deltaT = wx.TextCtrl(panel, -1, "", size=(100,-1)); self.deltaX = wx.TextCtrl(panel, -1, "", size=(100,-1)); # Execute program runBtn = wx.Button(panel, -1, "Run") self.Bind(wx.EVT_BUTTON, self.OnSubmit, runBtn) # Now do the layout. # mainSizer is the top-level one that manages everything mainSizer = wx.BoxSizer(wx.VERTICAL) mainSizer.Add(topLbl, 0, wx.ALL, 5) mainSizer.Add(wx.StaticLine(panel), 0, wx.EXPAND|wx.TOP|wx.BOTTOM, 5) # femSizer is a grid that holds all of the address info femSizer = wx.FlexGridSizer(cols=2, hgap=5, vgap=5) femSizer.AddGrowableCol(1) # S1 and S2 LOWER label femSizer.Add(s1label, 0, wx.ALIGN_RIGHT|wx.ALIGN_CENTER_VERTICAL) # the lower and upper S1 bounds are in a sub-sizer s1Sizer = wx.BoxSizer(wx.HORIZONTAL) s1Sizer.Add(self.s1lower, 1) s1Sizer.Add((10,10)) # some empty space s1Sizer.Add(self.s2lower, 1, wx.LEFT|wx.RIGHT, 5) femSizer.Add(s1Sizer, 1, wx.EXPAND) # S1 and S2 HIGH label femSizer.Add(s2label, 0, wx.ALIGN_RIGHT|wx.ALIGN_CENTER_VERTICAL) # the lower and upper S1 bounds are in a sub-sizer s2Sizer = wx.BoxSizer(wx.HORIZONTAL) s2Sizer.Add(self.s1upper, 1) s2Sizer.Add((10,10)) # some empty space s2Sizer.Add(self.s2upper, 1, wx.LEFT|wx.RIGHT, 5) femSizer.Add(s2Sizer, 1, wx.EXPAND) # Volatility label femSizer.Add(vlabel, 0, wx.ALIGN_RIGHT|wx.ALIGN_CENTER_VERTICAL) # the lower and upper S1 bounds are in a sub-sizer volSizer = wx.BoxSizer(wx.HORIZONTAL) volSizer.Add(self.v1vol, 1) volSizer.Add((10,10)) # some empty space volSizer.Add(self.v2vol, 1, wx.LEFT|wx.RIGHT, 5) femSizer.Add(volSizer, 1, wx.EXPAND) # Risk free Rate and corelation femSizer.Add(prlabel, 0, wx.ALIGN_RIGHT|wx.ALIGN_CENTER_VERTICAL) # the lower and upper S1 bounds are in a sub-sizer rcSizer = wx.BoxSizer(wx.HORIZONTAL) rcSizer.Add(self.risk, 1) rcSizer.Add((10,10)) # some empty space rcSizer.Add(self.corr, 1, wx.LEFT|wx.RIGHT, 5) femSizer.Add(rcSizer, 1, wx.EXPAND) # Strike and Exercise Date femSizer.Add(kTlabel, 0, wx.ALIGN_RIGHT|wx.ALIGN_CENTER_VERTICAL) # the lower and upper S1 bounds are in a sub-sizer ktSizer = wx.BoxSizer(wx.HORIZONTAL) ktSizer.Add(self.strike, 1) ktSizer.Add((10,10)) # some empty space ktSizer.Add(self.finalT, 1, wx.LEFT|wx.RIGHT, 5) femSizer.Add(ktSizer, 1, wx.EXPAND) # deltaT and deltaX femSizer.Add(dTXlabel, 0, wx.ALIGN_RIGHT|wx.ALIGN_CENTER_VERTICAL) # the lower and upper S1 bounds are in a sub-sizer dtxSizer = wx.BoxSizer(wx.HORIZONTAL) dtxSizer.Add(self.deltaT, 1) dtxSizer.Add((10,10)) # some empty space dtxSizer.Add(self.deltaX, 1, wx.LEFT|wx.RIGHT, 5) femSizer.Add(dtxSizer, 1, wx.EXPAND) # now add the femSizer to the mainSizer mainSizer.Add(femSizer, 0, wx.EXPAND|wx.ALL, 10) # The buttons sizer will put them in a row with resizeable # gaps between and on either side of the buttons btnSizer = wx.BoxSizer(wx.HORIZONTAL) btnSizer.Add((10,10)) # some empty space btnSizer.Add(runBtn) btnSizer.Add((10,10)) # some empty space mainSizer.Add(btnSizer, 0, wx.EXPAND|wx.BOTTOM, 10) panel.SetSizer(mainSizer) # Fit the frame to the needs of the sizer. The frame will # automatically resize the panel as needed. Also prevent the # frame from getting smaller than this size. mainSizer.Fit(self) mainSizer.SetSizeHints(self) def OnSubmit(self, evt): s1low = self.s1lower.GetValue() s2low = self.s2lower.GetValue() s1high = self.s1upper.GetValue() s2high = self.s2upper.GetValue() s1vol = self.v1vol.GetValue() s2vol = self.v2vol.GetValue() irate = self.risk.GetValue() pcorr = self.corr.GetValue() kprice = self.strike.GetValue() totalT = self.finalT.GetValue() delT = self.deltaT.GetValue() delX = self.deltaX.GetValue() wx.MessageBox('You chose: \n %s \n %s \n %s \n %s \ \n %s \n %s \n %s' % (s1low,s2low,s1high,s2high,s1vol,s2vol,irate)) # I want to do something like this below.... # return s1low,s2low,s1high,s2high,s1vol,s2vol,irate class MyApp(wx.App): def OnInit(self): frame = FemInput() self.SetTopWindow(frame) frame.Show() return True # Needed if called as a module if __name__ == '__main__': app = MyApp(False) app.MainLoop() From robert.kern at gmail.com Wed Apr 4 13:22:15 2007 From: robert.kern at gmail.com (Robert Kern) Date: Wed, 04 Apr 2007 12:22:15 -0500 Subject: Calling Fortran from Python In-Reply-To: <1175685841.847487.173440@w1g2000hsg.googlegroups.com> References: <1175640339.648190.207530@y66g2000hsf.googlegroups.com> <1175685841.847487.173440@w1g2000hsg.googlegroups.com> Message-ID: Mangabasi wrote: > Robert, > > Thanks for your prompt response. I think I got a lot closer but no > cigar yet. > > This is the output > > C:\fortrandll>f2py -c -m sample sample.pyf sample.for > numpy_info: > FOUND: > define_macros = [('NUMERIC_VERSION', '"\\"24.2\\""')] > include_dirs = ['C:\\Python24\\include'] > > running build > running config_fc > running build_src > building extension "sample" sources > creating c:\docume~1\fb\locals~1\temp\tmpcosvgv > creating c:\docume~1\fb\locals~1\temp\tmpcosvgv\src > f2py: sample.pyf > Reading fortran codes... > Reading file 'sample.pyf' > Post-processing... > Block: sample > Block: sample > Post-processing (stage 2)... > Building modules... > Building module "sample"... > Constructing wrapper function "sample"... > ierr1,ierr2,aout = sample(ain) > Wrote C/API module "sample" to file "c:\docume~1\fb > \locals~1\temp\tmpcos > vgv\src/samplemodule.c" > adding 'c:\docume~1\fb\locals~1\temp\tmpcosvgv\src\fortranobject.c' > to sources > . > adding 'c:\docume~1\fb\locals~1\temp\tmpcosvgv\src' to include_dirs. > copying C:\python24\lib\site-packages\f2py2e\src\fortranobject.c -> c: > \docume~1\ > fb\locals~1\temp\tmpcosvgv\src > copying C:\python24\lib\site-packages\f2py2e\src\fortranobject.h -> c: > \docume~1\ > fb\locals~1\temp\tmpcosvgv\src > running build_ext > No module named msvccompiler in scipy_distutils, trying from > distutils.. > error: The .NET Framework SDK needs to be installed before building > extensions f > or Python. > > I think I have a problem with distutils' msvccompiler.py. It may be > the MacroExpander in distutils guessing the visual studio path > incorrectly or something related to the registry keys. Is there a way > to specify the C compiler path to f2py so that it does not rely on the > distutils? Or maybe I am totally off base here, I don't know. What C and Fortran compilers are you trying to use? You can look at f2py's help for flags that you can use to help control where the compilers get picked up, but you can't avoid distutils. -- 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 steven.bethard at gmail.com Tue Apr 3 12:38:41 2007 From: steven.bethard at gmail.com (Steven Bethard) Date: Tue, 03 Apr 2007 10:38:41 -0600 Subject: getattr/setattr q. In-Reply-To: References: <1175573213.682671@jubilee.claranet.pt> <1175614741.823795@jubilee.claranet.pt> Message-ID: <4NSdnWz849OSHo_bnZ2dnUVZ_s_inZ2d@comcast.com> Steve Holden wrote: > You don't need setattr/getattr if you know in advance the name of the > attribute you need to access and you can get a reference to the object > whose attribute it is. So: > > >>> x = "Hello, Paulo" > >>> import sys > >>> sys.modules['__main__'].x > 'Hello, Paulo' a.k.a >>> import __main__ >>> __main__.x 'Hello, Paulo' STeVe From michael at jedimindworks.com Tue Apr 24 06:14:36 2007 From: michael at jedimindworks.com (Michael Bentley) Date: Tue, 24 Apr 2007 05:14:36 -0500 Subject: Tutorial creates confusion about slices In-Reply-To: References: Message-ID: <7AC46EFF-F34C-45A7-8AE2-61FE866F98A6@jedimindworks.com> On Apr 24, 2007, at 4:47 AM, Antoon Pardon wrote: > On 2007-04-24, Michael Bentley wrote: >> >> On Apr 24, 2007, at 1:39 AM, Antoon Pardon wrote: >> >>> I suspect that if you give this explanation to someone and explain >>> that there is also a step parameter, chances are he will answer >>> correctly if you ask him, what he thinks the following will result >>> in: >>> >>> >>> "This is an example line"[12:19:2] >>> >>> >>> >>> If you ask him what the following will result in: >>> >>> "This is an example line"[19:12:-1] >>> >>> Chances are he will give the wrong answer. >> >> To be honest, bro -- I'd expect him to have enough intelligence to >> experiment for a second and figure it out. This isn't rocket science >> -- you can plainly see what's happening -- so learn it and move >> on. > > I don't think that the possibility to experiment and see for oneself > is a good reason to keep a possible confusing explanation in a > tutorial. It's only potentially confusing if you already know more than has been presented and are in fact, *experimenting* with techniques that have yet to be presented. >> Or better yet, quietly submit a patch... > > Why should I? If the reactions would have been one of agreement that > this is confusing and that the explanation should be changed, I would > have considered submitting a patch. > > But most people that reacted seem to defend the current text in some > way or another. So if most people seem to feel there is no need for > a change why should I then submit a patch? ... or even continue the thread? From steve at REMOVEME.cybersource.com.au Fri Apr 27 07:09:15 2007 From: steve at REMOVEME.cybersource.com.au (Steven D'Aprano) Date: Fri, 27 Apr 2007 21:09:15 +1000 Subject: How to find complementary colour for pixel References: <1177578583.205643.65200@r35g2000prh.googlegroups.com> Message-ID: On Thu, 26 Apr 2007 21:17:42 -0700, James Stroud wrote: > Johny wrote: >> I use PIL to write some text to a picture.The text must be seen wery >> clearly. >> I write the text to different pictures but to the same position. As >> pictures maybe different, colour, in the position where I write the >> text, is also different. >> Is there a way how to set the font colour so that it will be seen very >> clearly in the picture? >> For example, if the picture is bright ( for example yellow), the font >> colour should be dark( e.g. black) and vice versa. >> Is there a routine in PIL available that calculates complementary >> colour for RGB pixel format? >> Can anyone help? >> Thanks >> L. >> > > Don't you just xor with black? I shouldn't think so... I always forget if black is all ones or all zeroes, so I checked here: http://www.pitt.edu/~nisg/cis/web/cgi/rgb.html >>> black = 0x000000 # RGB colours >>> white = 0xffffff >>> black^black == white False >>> white^black == black False Maybe you meant xor with white? But even so, I gather that the Original Poster is asking for something slightly different -- despite his mention of complimentary colours. (Or maybe I'm just reading too much into it?) I think he's just looking for one colour which has high contrast over a bunch of pixels in an image. I don't think that can be done, in general: it seems to me he's assuming that all the pixels in the area he wants to overlay text on are "nearly" the same colour. I think that a better solution is to draw a box around the area you want to write text into. The box should have a contrasting frame: say, a thin white border followed by a thin black border just inside it: either the white or the black will contrast with the background, no matter what colour(s) the background is, since no area can be both black and white in the same place. Then fill the frame with white, and draw black text inside it. Nice high contrast. That is probably the most readable method of placing text over an image. -- Steven D'Aprano From adrian_p_smith at yahoo.com Sun Apr 22 11:04:38 2007 From: adrian_p_smith at yahoo.com (Adrian Smith) Date: 22 Apr 2007 08:04:38 -0700 Subject: python cgi problem with textarea In-Reply-To: <1177252822.099111.66410@e65g2000hsc.googlegroups.com> References: <1177222084.696307.128620@n59g2000hsh.googlegroups.com> <1177252822.099111.66410@e65g2000hsc.googlegroups.com> Message-ID: <1177254278.336694.68710@b58g2000hsg.googlegroups.com> On Apr 22, 11:40 pm, Jim wrote: > On Apr 22, 2:08 am, Adrian Smith wrote:> ...and I > > get an internal server error if I have any spaces in the textarea, > > And what error appears in the server error log? I've just asked my web provider why I don't appear to have a server error log, as a matter of fact - I'll post it if and when they reply. From gagsl-py2 at yahoo.com.ar Wed Apr 18 18:36:44 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 18 Apr 2007 19:36:44 -0300 Subject: pycurl problem References: Message-ID: En Wed, 18 Apr 2007 11:48:06 -0300, pabloski escribi?: > I noted that if I define c.proxy and c.url as costants e.g. c.url = > "http://www.google.com/search?blah blah...." and c.proxy = > "127.0.0.1:8080" it works > > However if I define them as described before pycurl raises the TypeError Python -with its long "batteries included" tradition- comes with two powerful tools for diagnosing problems: print and repr print "c.url", type(c.url), repr(c.url) print "c.proxy", type(c.proxy), repr(c.proxy) -- Gabriel Genellina From steven.bethard at gmail.com Thu Apr 5 18:51:51 2007 From: steven.bethard at gmail.com (Steven Bethard) Date: Thu, 05 Apr 2007 16:51:51 -0600 Subject: RFC: Assignment as expression (pre-PEP) In-Reply-To: <1175807326.466842.219820@p77g2000hsh.googlegroups.com> References: <1175802680.021987.39220@p77g2000hsh.googlegroups.com> <1175807326.466842.219820@p77g2000hsh.googlegroups.com> Message-ID: darklord at timehorse.com wrote: > On Apr 5, 4:22 pm, Duncan Booth wrote: >> Can you come up with a real example where this happens and which cannot be >> easily rewritten to provide better, clearer code without the indentation? >> >> I'll admit to having occasionally had code not entirely dissimilar to this >> when first written, but I don't believe it has ever survived more than a >> few minutes before being refactored into a cleaner form. I would claim that >> it is a good thing that Python makes it obvious that code like this should >> be refactored. > > I am trying to write a parser for a text string. Specifically, I am > trying to take a filename that contains meta-data about the content of > the A/V file (mpg, mp3, etc.). > > I first split the filename into fields separated by spaces and dots. > > Then I have a series of regular expression matches. I like > Cartesian's 'event-based' parser approach though the even table gets a > bit unwieldy as it grows. Also, I would prefer to have the 'action' > result in a variable assignment specific to the test. E.g. > > def parseName(name): > fields = sd.split(name) > fields, ext = fields[:-1], fields[-1] > year = '' > capper = '' > series = None > episodeNum = None > programme = '' > episodeName = '' > past_title = false > for f in fields: > if year_re.match(f): > year = f > past_title = True > else: > my_match = capper_re.match(f): > if my_match: > capper = capper_re.match(f).group(1) > if capper == 'JJ' or capper == 'JeffreyJacobs': > capper = 'Jeffrey C. Jacobs' > past_title = True > else: > my_match = epnum_re.match(f): > if my_match: > series, episodeNum = my_match.group('series', > 'episode') > past_title = True > else: > # If I think of other parse elements, they go > here. > # Otherwise, name is part of a title; check for > capitalization > if f[0] >= 'a' and f[0] <= 'z' and f not in > do_not_capitalize: > f = f.capitalize() > if past_title: > if episodeName: episodeName += ' ' > episodeName += f > else: > if programme: programme += ' ' > programme += f > > return programme, series, episodeName, episodeNum, year, capper, > ext Why can't you combine your regular expressions into a single expression, e.g. something like:: >>> exp = r''' ... (?P\d{4}) ... | ... by\[(?P.*)\] ... | ... S(?P\d\d)E(?P\d\d) ... ''' >>> matcher = re.compile(exp, re.VERBOSE) >>> matcher.match('1990').groupdict() {'series': None, 'capper': None, 'episode': None, 'year': '1990'} >>> matcher.match('by[Jovev]').groupdict() {'series': None, 'capper': 'Jovev', 'episode': None, 'year': None} >>> matcher.match('S01E12').groupdict() {'series': '01', 'capper': None, 'episode': '12', 'year': None} Then your code above would look something like:: for f in fields: match = matcher.match(f) if match is not None: year = match.group('year') capper = match.group('capper') if capper == 'JJ' or capper == 'JeffreyJacobs': capper = 'Jeffrey C. Jacobs' series = match.group('series') episodeNum = match.group('episode') past_title = True else: if 'a' <= f[0] <= 'z' and f not in do_not_capitalize: f = f.capitalize() if past_title: if episodeName: episodeName += ' ' episodeName += f else: if programme: programme += ' ' programme += f STeVe From robert.rawlins at thinkbluemedia.co.uk Fri Apr 27 08:29:16 2007 From: robert.rawlins at thinkbluemedia.co.uk (Robert Rawlins - Think Blue) Date: Fri, 27 Apr 2007 13:29:16 +0100 Subject: Re-ocurring Events In-Reply-To: References: <3891950377467154133@unknownmsgid> <003001c7889c$f1fb6a50$d5f23ef0$@rawlins@thinkbluemedia.co.uk> <4631B8FE.8000405@limsi.fr> <004901c788a9$b42c2130$1c846390$@rawlins@thinkbluemedia.co.uk> Message-ID: <005801c788c7$ac2a6f00$047f4d00$@rawlins@thinkbluemedia.co.uk> Thanks for that tip Jarek, It worked a charm, I just created a format time string and used that in the compare against my XML and it work perfectly. Thank you, Rob -----Original Message----- From: python-list-bounces+robert.rawlins=thinkbluemedia.co.uk at python.org [mailto:python-list-bounces+robert.rawlins=thinkbluemedia.co.uk at python.org] On Behalf Of Jarek Zgoda Sent: 27 April 2007 13:01 To: python-list at python.org Subject: Re: Re-ocurring Events Robert Rawlins - Think Blue napisa?(a): > and I need to do and conditional that ensures start is before today's > date/time and end is after today's date/time. > > The string looks like: '2007-01-01 00:00:00' > > Do I have to convert this to a proper time object to do the comparison? Or > can I do it as a string? In the very specific case of string formatted as above, the string comparison will give the same results as in the case of datetime objects comparison. You just have to compare the same kinds of things. ;) -- Jarek Zgoda "We read Knuth so you don't have to." -- http://mail.python.org/mailman/listinfo/python-list From gregturn at mindspring.com Mon Apr 16 12:27:52 2007 From: gregturn at mindspring.com (Goldfish) Date: 16 Apr 2007 09:27:52 -0700 Subject: Authenticating clients and servers In-Reply-To: <462271B9.9090901@hotmail.com> References: <462271B9.9090901@hotmail.com> Message-ID: <1176740872.792897.324160@y80g2000hsf.googlegroups.com> On Apr 15, 2:40 pm, Chaz Ginger wrote: > Thomas Kr?ger wrote: > > Chaz Ginger schrieb: > >> I am writing a distributed server system using Python. I need to support > >> authentication and was wondering what approaches are available under > >> Python and what are the best practices. Spring Python has a section concerning Application Security you may be interested in. (http://springpython.python-hosting.com/wiki/ ApplicationSecurity). This offers the ability to authenticate users, but also manage what functions they can execute based on granted roles through aspect oriented programming. Right now, the current release supports flat-file user systems, but the next release will also include database user stores. There are future plans to integrate with other user stores like LDAP and so forth. From faulkner891 at gmail.com Wed Apr 25 17:02:59 2007 From: faulkner891 at gmail.com (faulkner) Date: 25 Apr 2007 14:02:59 -0700 Subject: getting scancodes In-Reply-To: References: Message-ID: <1177534979.599075.41980@b40g2000prd.googlegroups.com> On Apr 23, 8:39 pm, andma... at gmail.com wrote: > Anyone knows if its possible to get scan codes ??? > I tried with getch () but with no success, just keycodes. > May be using the something in the sys.stdin module ?? is this what you're looking for? http://cheeseshop.python.org/pypi/sysio/1.0 and sys.stdin isn't a module. it's a file. From anton.vredegoor at gmail.com Wed Apr 18 07:36:56 2007 From: anton.vredegoor at gmail.com (Anton Vredegoor) Date: Wed, 18 Apr 2007 13:36:56 +0200 Subject: multirember&co In-Reply-To: <1176850352.999231.79260@n59g2000hsh.googlegroups.com> References: <1176768854.720234.23320@w1g2000hsg.googlegroups.com> <1176790588.024371.119360@n76g2000hsh.googlegroups.com> <1176850352.999231.79260@n59g2000hsh.googlegroups.com> Message-ID: bearophileHUGS at lycos.com wrote: > I have modified, simplified and (hopefully) improved Steven's code > like this (but it may be a bit slower, because the class It is inside > the function?): Here is a yet more simple version, I wonder if it still does the same thing, whatever it is you are looking for :-) def xsplitter(iseq, pred): class It(object): def __init__(self, fun, parity): self.divert = fun self.parity = parity self.queue = collections.deque() def append(self, item): self.queue.append(item) def __iter__(self): while self.queue: yield self.queue.popleft() for item in iseq: if pred(item) == self.parity: yield item else: self.divert(item) for x in self: yield x it1 = It(lambda y: it2.append(y), True) it2 = It(lambda y: it1.append(y), False) return it1, it2 A. From nagle at animats.com Fri Apr 27 12:07:06 2007 From: nagle at animats.com (John Nagle) Date: Fri, 27 Apr 2007 09:07:06 -0700 Subject: My newbie annoyances so far In-Reply-To: <1177688082.758043.133920@r30g2000prh.googlegroups.com> References: <1177688082.758043.133920@r30g2000prh.googlegroups.com> Message-ID: <_9pYh.1787$uJ6.894@newssvr17.news.prodigy.net> Paul McGuire wrote: > Python is not VB and Python is not Java and Python is not Ruby and > Python is not any other language that is not Python. As someone who's written in too many programming languages over a long career, I'm quite pleased with Python as a programming language. It's straightforward to write, has few irregularities, and has good run-time error semantics. The weak points in Python are implementation issues. Sockets, HTTP access, SSL, and database access are all flakier than they should be for such common capabilities. The CPython implementation is unreasonably slow compared to good implementations of other dynamic languages such as LISP and JavaScript. But really, the language is in good shape. I'd rather have a faster implementation of Python 2.5 than anything being proposed as a language change. John Nagle (P.S. PEP 3117 is a joke, right?) From yossi.kreinin at gmail.com Sun Apr 1 11:41:04 2007 From: yossi.kreinin at gmail.com (yossi.kreinin at gmail.com) Date: 1 Apr 2007 08:41:04 -0700 Subject: saving Python process state for later debugging In-Reply-To: <1175428674.548997.111260@p15g2000hsd.googlegroups.com> References: <1175352493.387046.32510@q75g2000hsh.googlegroups.com> <1175382476.172386.97370@q75g2000hsh.googlegroups.com> <1175413189.156480.149640@o5g2000hsb.googlegroups.com> <1175428674.548997.111260@p15g2000hsd.googlegroups.com> Message-ID: <1175442064.201021.111880@e65g2000hsc.googlegroups.com> On Apr 1, 2:57 pm, "aspineux" wrote: > > A context in python is no more than 2 dictionaries ( globals() and > locals()). > You can easily serialize both to store them. I don't think it will work with objects defined by extension modules, except if they somehow support serialization, will it? I guess I can dump core for debugging these objects, and serialize the Python context for debugging the rest. Finding the extension objects in the core dump can be a pain though, as will be figuring out the stack with interlaced Python & native code. And then there are the lovely cases when CPython crashes, like "deletion of interned string failed. Abort (core dumped)", where you get to shovel through CPython state with a native debugger. The thing with mixing native code with Python is that when native code misbehaves, it's a big problem, and if Python code misbehaves, it's still a problem, although a smaller one (serializing the native state & navigating through it). Maybe the best way around this is to spawn sub-processes for running native code... From paul at boddie.org.uk Wed Apr 18 18:39:16 2007 From: paul at boddie.org.uk (Paul Boddie) Date: 18 Apr 2007 15:39:16 -0700 Subject: Future Python Gui? In-Reply-To: <1176909848.455264.174730@e65g2000hsc.googlegroups.com> References: <1176859699.906386.326720@b75g2000hsg.googlegroups.com> <1176863948.526051.186210@n76g2000hsh.googlegroups.com> <1176909848.455264.174730@e65g2000hsc.googlegroups.com> Message-ID: <1176935956.875561.67080@o5g2000hsb.googlegroups.com> bcwhite at pobox.com wrote: > > If Python doesn't declare an official Gui system, then it'll be > fragmented, inconsistent, and unsupportable. I don't agree. GUI frameworks are somewhat like Web frameworks, object- relational mappers, and all the other things that work in different ways, work better on various systems, appeal to different tastes and so on. There are a number of cross-platform GUI frameworks which claim some kind of native look and feel on every platform, but declaring one the winner is not going to convince the satisfied users of the others of its superiority. Meanwhile, some people don't care about more than one platform and will quite happily target their chosen platform intentionally, and it's worth remembering that anyone developing for, say, a Free desktop environment will treat such an environment as the means to provide "worthwhile" portability - targeting the Windows API, for example, becomes an irrelevance. There are a few technologies with an "official" GUI framework or APIs, with Java being one of the more notorious at delivering either a fairly weak set of features performing inconsistently across platforms (AWT) or a more ambitious set of features wrapped up in a baroque architecture, performing poorly and still managing to look alien on most platforms (Swing). And before anyone mentions Delphi/Kylix, a recent experience trying out a Kylix-based application on a Red Hat system provided enough of an explanation as to why Borland dropped that particular product. As I've said often enough on the topic of Web frameworks, picking winners gives only a temporary victory to those who want to avoid making decisions. It's better to provide people with a means of making an informed choice, and it should be realised that people will approach this choice from rather different angles. It isn't always going to be, "I want to write a Python application - what GUI should I use?" Instead, it may be, "I want to write a KDE application - can I do so in Python and what are my options?" Pretending that the answer is always the same will frequently drive people to other technologies, not attract them to a technology selling a vision that turns out to be a mirage. Paul From surekap at gmail.com Mon Apr 23 01:17:49 2007 From: surekap at gmail.com (Prateek) Date: 22 Apr 2007 22:17:49 -0700 Subject: Support for new items in set type In-Reply-To: <1hwxx1e.1un7urc1de872aN%aleax@mac.com> References: <1177211624.069474.3960@y5g2000hsa.googlegroups.com> <1hwxx1e.1un7urc1de872aN%aleax@mac.com> Message-ID: <1177305469.398817.80600@y80g2000hsf.googlegroups.com> Oh dear god, I implemented this and it overall killed performance by about 50% - 100%. The same script (entering 3000 items) takes between 88 - 109s (it was running in 55s earlier). Here is the new Set implementation: class SeaSet(set): __slots__ = ['master', 'added', 'deleted'] def __init__(self, s=None): if s is None: s = [] self.master = set(s) self.added = set() self.deleted = set() def add(self, l): if l not in self.master: self.added.add(l) try: self.deleted.remove(l) except KeyError: pass def remove(self, l): try: self.master.remove(l) self.deleted.add(l) except KeyError: try: self.added.remove(l) except KeyError: pass def __contains__(self, l): if l in self.deleted: return False elif l in self.added: return True else: return l in self.master def __len__(self): return len(self.master) + len(self.added) def __iter__(self): for x in self.master: yield x for x in self.added: yield x def __or__(self, s): return self.union(s) def __and__(self, s): return self.intersection(s) def __sub__(self, s): return self.difference(s) def union(self, s): """docstring for union""" if isinstance(s, (set, frozenset)): return s | self.master | self.added elif isinstance(s, SeaSet): return self.master | self.added | s.master | s.added else: raise TypeError def intersection(self, s): """docstring for intersection""" if isinstance(s, (set, frozenset)): return s & self.master & self.added elif isinstance(s, SeaSet): return self.master & self.added & s.master & s.added else: raise TypeError def difference(self, s): """docstring for difference""" if isinstance(s, (set, frozenset)): self.deleted |= (self.master - s) self.master -= s self.added -= s elif isinstance(s, SeaSet): t = (s.master | s.deleted) self.deleted |= self.master - t self.master -= t self.added -= t else: raise TypeError The surprising thing is that commits *ARE* running about 50% faster (according to the time column in the hotshot profiler). But, now, the longest running operations seem to be the I/O operations which are taking 10 times longer! (even if they're only reading or writing a few bytes. Could this have something to do with the set implementation being in Python as opposed to C? For instance, this method: def __readTableHeader(self, f): hdr = f.read(sz__TABLE_HEADER_FORMAT__) if len(hdr) < sz__TABLE_HEADER_FORMAT__: raise EOFError t = THF_U(hdr) #t = unpack(__TABLE_HEADER_FORMAT__, hdr) return t is now taking > 13s when it was taking less than 0.8s before! (same number of calls, nothing changed except the set implementation) sz__TABLE_HEADER_FORMAT__ is a constant = struct.calcsize(" References: <1177467203.719625.93920@u32g2000prd.googlegroups.com> <1177780530.539758.275660@c35g2000hsg.googlegroups.com> <1177788032.971421.65550@c35g2000hsg.googlegroups.com> <46351C76.33D802DF@earthlink.net> Message-ID: <1177988422.272162.55340@n59g2000hsh.googlegroups.com> the towers collapsed into a subway that most of the employees probably used to get to work, with all sorts of ancilliary services (parking, paintball facilities etc.) -- it was huge. so, shouldn't there have been some secondary effects, such as structural damage to bldg. 7, that also set it on fire? the amount of energy that's required to perform a "controlled" demolition is some orders of magnitude (NB: a hundred orders of tude is a googoltude) less than what is in a fully-fueled 757 -- get over it! > Ditto. thus: Jones' report seems to support this idea, that there was molten metal under the pile, some where. there is another thing, documented with multiple photos in his report, that seems to be related, although they weren't *still* molten. thus: if you can't prove that all Fermat numbers are pairwise coprime, again! Darfur 'Mini-Summit' http://www.larouchepub.com/other/1998/rice_2546.html thus: uh yeah; Borat wants you in Sudan, why, Baby?... Harry Potter wants you in Iran -- yeah, Baby; shag'US with a spoon? --DARFURIA CONSISTS OF ARABs & nonARABs; NEWS-ITEM: we are marching to Darfuria, Darfuria, Darfuria! Harry Potter IIX, ?Ordeal @ Oxford//Sudan ^ Aircraft Carrier! http://larouchepub.com/other/2007/3410caymans_hedges.html ALgoreTHEmovieFORpresident.COM: http://larouchepub.com/eirtoc/site_packages/2007/al_gore.html From paul at boddie.org.uk Tue Apr 10 10:27:11 2007 From: paul at boddie.org.uk (Paul Boddie) Date: 10 Apr 2007 07:27:11 -0700 Subject: tuples, index method, Python's design In-Reply-To: References: <1175867771.114540.61810@n76g2000hsh.googlegroups.com> <1175884427.779950.267220@y80g2000hsf.googlegroups.com> <1175953520.316208.241490@o5g2000hsb.googlegroups.com> <7xzm5igbrb.fsf@ruckus.brouhaha.com> <1176200361.260546.280510@n76g2000hsh.googlegroups.com> Message-ID: <1176215231.002726.148960@y5g2000hsa.googlegroups.com> On 10 Apr, 15:57, Steve Holden wrote: > > The point I am trying to make is that circumstances alter cases, and that we > can't always rely on our intuition to determine how specific methods > work, let alone whether they are available. But it's telling that by adopting precisely the implementation that we currently have for lists, we can have a tuple method which does what most people would reasonably expect. "Why are we suddenly getting single characters instead of whole strings?" people have presumably exclaimed often enough, illustrating that the sequence nature of strings is a controversial topic. Lists and tuples, however, don't have such controversial baggage. > I hear the screams of "just add the index() method to tuples and have > done with it" and, to an extent, can sympathize with them. But that way > lies creeping featurism and the next thing you know we'll have a ternary > operator in the language - oh wait, we do now! Yes, but the cost of adding index to tuples is minimal, and the mental cost to programmers is arguably negative. Meanwhile, we now have to put up with the syntactic bodge that is the ternary operator until the time comes when it gets deprecated as something that didn't work out or wasn't really necessary (in Python 4000, perhaps), meaning that we now have to read third-party code more carefully, the people writing editors and tools have to change their lexers/parsers again, and so on. Paul From mail at microcorp.co.za Sat Apr 14 04:19:37 2007 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Sat, 14 Apr 2007 10:19:37 +0200 Subject: tuples, index method, Python's design References: <1175867771.114540.61810@n76g2000hsh.googlegroups.com><1175884427.779950.267220@y80g2000hsf.googlegroups.com><1175953520.316208.241490@o5g2000hsb.googlegroups.com><7xzm5igbrb.fsf@ruckus.brouhaha.com><7x8xd2iq53.fsf@ruckus.brouhaha.com> <46208258$0$14430$9b622d9e@news.freenet.de> Message-ID: <037701c77e6d$eb99aac0$03000080@hendrik> "Martin v. L?wis" wrote: > > So to increase consistency, the .index method should be removed > from lists, as well, IMO. If you find yourself doing a linear > search, something is wrong. > I agree. You should at the very least make it a binary search. To do that you have to sort the list. Much more efficient. ; - ) Please Sir, can I have the DoubleDict I asked for elsewhere in this thread? - Hendrik From robert.rawlins at thinkbluemedia.co.uk Wed Apr 18 06:40:31 2007 From: robert.rawlins at thinkbluemedia.co.uk (Robert Rawlins - Think Blue) Date: Wed, 18 Apr 2007 11:40:31 +0100 Subject: array{uint32} Message-ID: <003501c781a5$fd40fc70$f7c2f550$@rawlins@thinkbluemedia.co.uk> Guys, I have a function that returns a array{uint32}, is there any way to output that to screen in a more user friendly format? At the moment when I print it by itself it appears as [65541L], which isn't much used to anyone. I know this is probably a REALLY dumb question but I'm a little lost with this API, its driving me nuts. Thanks again guys, Rob -------------- next part -------------- An HTML attachment was scrubbed... URL: From readability at gmail.com Sun Apr 15 03:42:32 2007 From: readability at gmail.com (readability at gmail.com) Date: 15 Apr 2007 00:42:32 -0700 Subject: Really badly structured Python Books. In-Reply-To: <1176575848.526066.254520@y80g2000hsf.googlegroups.com> References: <1176575848.526066.254520@y80g2000hsf.googlegroups.com> Message-ID: <1176622952.561601.240430@d57g2000hsg.googlegroups.com> On Apr 14, 2:37 pm, "Andre P.S Duarte" wrote: > I started reading the beginning Python book. It is intended for people > who are starting out in the Python world. But it is really > complicated, because he tries to explain, then after a bad explanation > he puts out a bad example. I really recommend NOT reading the book. > For it will make you want not to continue in Python. This is just me > letting the air out of my lungs. No need to reply this is just a > recommendation. Txs for the opportunity . My experience with technical books of all types is that often you'll find some that don't work for you at all, while they'll be great for other people. If it is the Apress volume you're talking of, I quite like it because its more practical than the Learning Python book from o'reilly. Although the one I preferred the most was the online text of Dive into Python; http://diveintopython.org/. I can see where you're coming from though. From http Sun Apr 15 23:43:30 2007 From: http (Paul Rubin) Date: 15 Apr 2007 20:43:30 -0700 Subject: Getting started with python References: <1176598011.463543.96990@q75g2000hsh.googlegroups.com> <1176608302.928513.274400@y5g2000hsa.googlegroups.com> <%LyUh.10121$YL5.5753@newssvr29.news.prodigy.net> <7x4pnh6rqi.fsf@ruckus.brouhaha.com> Message-ID: <7xmz19c7bx.fsf@ruckus.brouhaha.com> James Stroud writes: > 1. This doesn't act according to the specification if you add, for > example, (2, 'Zonk'). Now 30 gives 'ZonkFizzBuzz' and not 'FizzBuzz' > according to the specification. Correct, the original specification only had 3 and 5. I gave a longer example to illustrate how the specification might be modified. Obviously it is not the same specification any more. The i%15 approach gets messy once there are more than two numbers to check. > So, I would keep my original explicit testing: > def fizzbuzz(n): > words = ((30, 'Whammo'), (15, 'FizzBuzz'), > (5, 'Fizz'), (3, 'Buzz'), (2, 'Zonk')) > for k,v in words: > if not k % n: > return v > return n I don't think that's in the spirit of the original, which would be to print 'BuzzZonk' for n=6. From __peter__ at web.de Sat Apr 7 05:08:27 2007 From: __peter__ at web.de (Peter Otten) Date: Sat, 07 Apr 2007 11:08:27 +0200 Subject: os.path.isfile() error References: <1175936167.548551.289600@n76g2000hsh.googlegroups.com> Message-ID: 7stud wrote: > Here's the code: > ------------ > import os, os.path, pprint > > mydir = "/Users/me/2testing" > > files = [file for file in os.listdir(mydir)] > pprint.pprint(files) > > print os.path.join(mydir, "helloWorld.py") > > files = [file > for file in os.listdir(mydir) > if os.path.isfile(os.path.join(dir, file) ) That should be mydir, not dir. > ] > > pprint.pprint(files) > ----output:---------------- > > ['.DS_Store', 'cpTest', 'dir1', 'testfile1', 'xmlFile.xml'] > /Users/me/2testing/helloWorld.py > Traceback (most recent call last): > File "test1.py", line 16, in ? > files = [file > File "/System/Library/Frameworks/Python.framework/Versions/2.3/lib/ > python2.3/posixpath.py", line 62, in join > elif path == '' or path.endswith('/'): > AttributeError: 'builtin_function_or_method' object has no attribute > 'endswith' From hg at nospam.org Mon Apr 2 02:55:56 2007 From: hg at nospam.org (hg) Date: Mon, 02 Apr 2007 08:55:56 +0200 Subject: Problem with global variables References: <1311u48bqkehk24@corp.supernews.com> Message-ID: Ed Jensen wrote: > #! /usr/bin/env python > > def tiny(): > bar = [] > for tmp in foo: > bar.append(tmp) > foo = bar > > if __name__ == "__main__": > foo = ['hello', 'world'] > tiny() Like this ? #! /usr/bin/env python def tiny(): ? ? bar = [] gobal foo ? ? for tmp in foo: ? ? ? ? bar.append(tmp) ? ? foo = bar if __name__ == "__main__": ? ? foo = ['hello', 'world'] ? ? tiny() hg From brzrkr0 at gmail.com Wed Apr 18 18:34:40 2007 From: brzrkr0 at gmail.com (brzrkr0 at gmail.com) Date: 18 Apr 2007 15:34:40 -0700 Subject: comparison with None In-Reply-To: References: <3IqdnfRnCNWPC7vbnZ2dnUVZ_jqdnZ2d@rcn.net> Message-ID: <1176935680.707717.53490@y5g2000hsa.googlegroups.com> On Apr 18, 3:19 pm, Steven Howe wrote: > I've read and found that 'None' comparisons is not always a good idea. > Better to: > from types import NoneType > > x = None > if type( x ) == NoneType: > # true > < code > > else: > # false; do something else. > < more code > > > Steven Howe Is that any better than this? if x is None: # do something else: # do something else From __peter__ at web.de Mon Apr 16 05:49:17 2007 From: __peter__ at web.de (Peter Otten) Date: Mon, 16 Apr 2007 11:49:17 +0200 Subject: Method calls and stack consumption References: Message-ID: Martin Manns wrote: > Thanks for pointing out the oversimplified nature of the original > example.I hope that the following one clarifies the problem. > > (I do not know, what has to be stored on the stack, but it should not be > that much, because all recursion calls originate from inside the return > statement.) > class Node(object): > ????def?__init__(self): > ????????self.state?=?abs(randint(1,1000)) > ????def?GetDepState(self): > ????????return?self.state?+?max(s.GetDepState()?for?s?in?S[self]) > > class ConditionalBreakNode(Node): > ????def?GetDepState(self): > ????????if?randint(1,5)?>?1: > ????????????return?Node.GetDepState(self) > ????????else: > ????????????return?self.state Have you investigated the libraries available for that kind of problem? (No, I don't know them) Maybe one of them provides an implementation that does not depend on the stack. On the other hand, if the above is the "natural" expression of your problem, why not give stackless a try? Peter From carsten at uniqsys.com Wed Apr 18 23:49:05 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Wed, 18 Apr 2007 23:49:05 -0400 Subject: Python COM iterator In-Reply-To: References: Message-ID: <1176954545.3267.15.camel@localhost.localdomain> >[...] > > On Tue, 2007-04-17 at 16:54 -0500, Larry Bates wrote: > >> Does anyone know if there is a way to make a Python COM object > >> act like a proper iterator in VB/Delphi? >[...] After more googling, staring at win32com's code, and a fair bit of trial and error, I've come up with the following working example: # server.py import pythoncom class HelloWorld: _reg_clsid_ = "{CAB8BED1-9174-4AAD-ABC5-F377951CB71B}" _reg_desc_ = "Python Test COM Server" _reg_progid_ = "Python.TestServer" _public_methods_ = ['Next'] _com_interfaces_ = [pythoncom.IID_IEnumVARIANT] def __init__(self): self.numbers=[1,2,3,4,5,6,7,8] def Next(self, count): assert count==1 try: return (self.numbers.pop(0),) except IndexError: return () def _NewEnum(self): import win32com.server.util return win32com.server.util.wrap(self) if __name__=='__main__': import win32com.server.register win32com.server.register.UseCommandLine(HelloWorld) # client.py import win32com.client comobj = win32com.client.Dispatch("Python.TestServer") for x in comobj: print x This works for me on Python 2.5 and pywin32 Build 210, but I don't know whether clients in VB or Delphi are able to use this iterator. -Carsten From garrickp at gmail.com Fri Apr 20 18:53:45 2007 From: garrickp at gmail.com (garrickp at gmail.com) Date: 20 Apr 2007 15:53:45 -0700 Subject: When are immutable tuples *essential*? Why can't you just use lists *everywhere* instead? In-Reply-To: <1177108656.291537.182560@o5g2000hsb.googlegroups.com> References: <1177088796.622928.224890@d57g2000hsg.googlegroups.com> <1177089206.550423.288670@q75g2000hsh.googlegroups.com> <58sf33F2b1q8tU1@mid.individual.net> <1177103370.022138.110320@n59g2000hsh.googlegroups.com> <1177108656.291537.182560@o5g2000hsb.googlegroups.com> Message-ID: <1177109625.619171.121610@d57g2000hsg.googlegroups.com> On Apr 20, 4:37 pm, John Machin wrote: > One inessential but very useful thing about tuples when you have a lot > of them is that they are allocated the minimum possible amount of > memory. OTOH lists are created with some slack so that appending etc > can avoid taking quadratic time. Speaking of inessential but very useful things, I'm also a big fan of the tuple swap... a = 2 b = 3 (a, b) = (b, a) print a # 3 print b # 2 As well as the simple return of multiple values from a single function: c_stdout, c_stdin = popen2("ls") IMO, the biggest thing going for tuples is the syntactical sugar they bring to Python. Doing either of these using lists or other data constructs would not be nearly as clean as they are with tuples. From mdizon at gmail.com Tue Apr 24 09:39:58 2007 From: mdizon at gmail.com (miked) Date: 24 Apr 2007 06:39:58 -0700 Subject: Domain Keys in Python In-Reply-To: Message-ID: <1177421998.072451.272520@r30g2000prh.googlegroups.com> Andrew --- Saw your thread on implementing DomainKeys in Python. Could you offer me some insight into your implementation? Thanks, Mike On 20 Apr, 15:58, Andrew Veitch wrote: > --- Andrew Veitch wrote: > > > In Perl I would just use Crypt:RSA which has a sign > > method with an armour option which generates exactly > > what I want but I can't find a way of doing this in > > Python. > > I've worked it out, just for the archives the answer > is: > > import base64 > from M2Crypto import RSA > key = RSA.load_key('rsa.private') > msg='Hello world' > print base64.b64encode(key.sign(msg)) > > I will publish my DomainKey implementation shortly. > > A From codecraig at gmail.com Fri Apr 20 15:42:04 2007 From: codecraig at gmail.com (abcd) Date: 20 Apr 2007 12:42:04 -0700 Subject: regular expression for parsing an html element In-Reply-To: References: <1177097164.906533.252830@d57g2000hsg.googlegroups.com> Message-ID: <1177098124.245450.17420@n76g2000hsh.googlegroups.com> thanks, forgot that. From ptmcg at austin.rr.com Thu Apr 12 01:25:35 2007 From: ptmcg at austin.rr.com (Paul McGuire) Date: 11 Apr 2007 22:25:35 -0700 Subject: python regular expression help In-Reply-To: References: <138221.90891.qm@web58906.mail.re1.yahoo.com> Message-ID: <1176355535.420635.104570@p77g2000hsh.googlegroups.com> On Apr 11, 11:50 pm, "Gabriel Genellina" wrote: > En Wed, 11 Apr 2007 23:14:01 -0300, Qilong Ren > escribi?: > > > Thanks for reply. That actually is not what I want. Strings I am dealing > > with may look like this: > > s = 'a = 4.5 b = 'h' 'd' c = 4.5 3.5' > > What I want is > > a = 4.5 > > b = 'h' 'd' > > c = 4.5 3.5 > > That's a bit tricky. You have LHS = RHS where RHS includes all the > following text *except* the very next word before the following = (which > is the LHS of the next expression). Or something like that :) > > py> import re > py> s = "a = 4.5 b = 'h' 'd' c = 4.5 3.5" > py> r = re.compile(r"\w+\s*=\s*.*?(?=\w+\s*=|$)") > py> for item in r.findall(s): > ... print item > ... > a = 4.5 > b = 'h' 'd' > c = 4.5 3.5 > > -- > Gabriel Genellina The pyparsing version is a bit more readable, probably simpler to come back later to expand definition of varName, for example. from pyparsing import Word,alphas,nums,FollowedBy,sglQuotedString,OneOrMore realNum = Word(nums,nums+".").setParseAction(lambda t:float(t[0])) varName = Word(alphas) LHS = varName + FollowedBy("=") RHSval = sglQuotedString | realNum | varName RHS = OneOrMore( ~LHS + RHSval ) assignment = LHS.setResultsName("LHS") + '=' + RHS.setResultsName("RHS") s = "a = 4.5 b = 'h' 'd' c = 4.5 3.5" for a in assignment.searchString(s): print a.LHS, '=', a.RHS prints: ['a'] = [4.5] ['b'] = ["'h'", "'d'"] ['c'] = [4.5, 3.5] From mad.vijay at gmail.com Fri Apr 13 05:59:33 2007 From: mad.vijay at gmail.com (SamG) Date: 13 Apr 2007 02:59:33 -0700 Subject: Try problem In-Reply-To: <1176456312.752519.198130@e65g2000hsc.googlegroups.com> References: <1176455642.199343.136720@l77g2000hsb.googlegroups.com> <1176456312.752519.198130@e65g2000hsc.googlegroups.com> Message-ID: <1176458373.765057.164010@y80g2000hsf.googlegroups.com> On Apr 13, 2:25 pm, mik3l3... at gmail.com wrote: > On Apr 13, 5:14 pm, "SamG" wrote: > > > import sys > > try: > > s=1 > > if s==1: > > sys.exit(0) > > else: > > sys.exit(1) > > except SystemExit,s: > > if (s==0): > > print s > > else: > > print "Hello" > > > How come i always end up getting the "Hello" printed on the screen as > > logically i should a '0' printed? > > if you put a debug print statement, eg > > ... > except SystemExit,s: > print "s in exception " , s, type(s) > if (s==0): > .... > > you will notice 's' is an "instance". so when it reaches the if > (s==0), which you are comparing with a number, it will fail and then > hello is printed. Then how do we check the value of the s's instance? From aleax at mac.com Mon Apr 23 22:20:03 2007 From: aleax at mac.com (Alex Martelli) Date: Mon, 23 Apr 2007 19:20:03 -0700 Subject: script for seconds in given month? References: <1176740556.859125.221980@l77g2000hsb.googlegroups.com> <1hwokmz.1ropcwj17pg55dN%aleax@mac.com> <1176796031.889407.323950@b75g2000hsg.googlegroups.com> <1177360091.516469.77830@l77g2000hsb.googlegroups.com> Message-ID: <1hx1eu1.1uqmgh41wm7emdN%aleax@mac.com> edfialk wrote: > Alex, very nice. That should be good enough for me. > The rest of you as well, thanks for all the help. > > I, unfortunately, failed to realize the actual platform the script is > for is IronPython. When trying to import calendar in IronPython, I > get: > > SyntaxError: future feature is not defined: with_statement (c: > \Python25\Lib\calendar.py, line 8) > > so, incompatible. I have moved my question over to the IronPython > group, but if anyone is familiar with IronPython and knows how to > perform the same function, that's what I'm looking for now. :) Just get calendar.py from Python 2.4 instead, e.g. . Alex From sjmachin at lexicon.net Mon Apr 30 14:14:10 2007 From: sjmachin at lexicon.net (John Machin) Date: 30 Apr 2007 11:14:10 -0700 Subject: Restricting the alphabet of a string In-Reply-To: References: Message-ID: <1177956850.096236.95040@y5g2000hsa.googlegroups.com> On Apr 30, 9:53 pm, "Nathan Harmston" wrote: > Hi, > > I ve being thinking about playing around with bit strings but use in > some encoding problems I m considering and was trying to decide how to > implement a bit string class. Is there a library out there for doing > basic things with bit strings already is my first question? > > I know that I can extend string to bit string, but is there anyway I > can force the alphabet to be restricted to 1's and 0's (or even 1, 0 > and -1, as an extension to from trinary strings). > > class Binary_String(String): > pass > See if you can pick which line below is impractically different to the others: binary: 0, 1 "trinary": -1, 0, 1 octal: 0, 1, 2, 3, 4, 5, 6, 7 decimal: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 HTH, John From dillonco at comcast.net Thu Apr 19 17:17:39 2007 From: dillonco at comcast.net (DillonCo) Date: Thu, 19 Apr 2007 17:17:39 -0400 Subject: comparison with None In-Reply-To: <462792BE.906@gmail.com> References: <_JAVh.1700$jR5.897@trnddc08> <462792BE.906@gmail.com> Message-ID: <200704191717.39481.dillonco@comcast.net> On Thursday 19 April 2007, Steven Howe wrote: > > ((int(3) > int(4)) == True) == True > > > > Explicit is better than sensible, yes? > > > > *wink* > > Your example, even with the *wink*, is stupid. The language requires 3 > to be an integer, 4 to be an integer. Incidentally, the language also requires that None be unique (and the only object of type NoneType). I believe that the point of the 'example' was to show that because of the language's guarantees, both are equally pointless. > > > The point I was show is with respect to a returned variable (like from a > function or method? *wink* *wink*). > For example, if you expect an open file handle, but get a NoneType > because you didn't really open a file (having given a bad name or maybe > didn't have permission to open a file), then it would be best to test > the type of return object before using it. Then you program could handle > the error gracefully (*wink* *wink* *wink*). You don't get "a NoneType", you get None, the unique instance of NoneType. A function cannot return and object of type NoneType without it being None. Here's what happens if you try: >>> from types import ListType >>> ListType() [] >>> from types import NoneType >>> NoneType() Traceback (most recent call last): File "", line 1, in TypeError: cannot create 'NoneType' instances > As much as I love Python, it's ability to morph an object type can be a > pain. Testing before using can prevent a program from Error-ing out. Well, the thing is, that's kind of the point. In Python, type is supposed to be irrelevant. That's the idea of "duck typing". If I need to do o.quack(), I can do two things to handle the error gracefully: check if it had the quack method ("hasattr"), or catch the exception. Checking "type(o)==Duck" is wrong almost all the time. If I subclass Duck (to, say a species), it'll likely still be an appropriate object, but then type(o)!=Duck. And what if I want to use a DucklikeGoose? In that case, even "isinstance(o, Duck)" would be False, but it still implements an appropriate "quack" method. Finally, you had said before: > I love scripting languages ... but sometimes an explicit evaluation that > one would find in a compiled language is better. > Which is why I suggested using the explicit type(x) == types.NoneType as > opposed to > x is None I'll sidestep the issue of Python begin compiled to VM code (think Java)... How would you do thing in compiled code? In C, functions that return pointers indicate errors by returning NULL. Supposing you had a function that would determine the type of a pointer, would you use "type(p)==TYPE_NONE" or "p==NULL"? In Python, the "is" operator basically compares pointers, so saying "p is q" would tanslate to "p==q" in C (supposing p and q are pointers to objects). At the end of the day, "type(x) == types.NoneType" is going to be true if and only if "x is None". So, whichever way you do it is up to you, though FWIW the latter line is: Faster: No need for type() call, lookup in types Smaller: No need for types module Shorter Clearer: "is None" shows very clear intent From kbk at shore.net Fri Apr 27 23:18:38 2007 From: kbk at shore.net (Kurt B. Kaiser) Date: Fri, 27 Apr 2007 23:18:38 -0400 (EDT) Subject: Weekly Python Patch/Bug Summary Message-ID: <200704280318.l3S3Ict2023404@bayview.thirdcreek.com> Patch / Bug Summary ___________________ Patches : 356 open ( -1) / 3756 closed (+11) / 4112 total (+10) Bugs : 968 open (+10) / 6673 closed (+16) / 7641 total (+26) RFE : 254 open ( +3) / 282 closed ( +2) / 536 total ( +5) New / Reopened Patches ______________________ fixes bug #1703952 - ctypes: problem with large integers (2007-04-19) CLOSED http://python.org/sf/1703972 opened by Alexander Belopolsky minidom Level 1 DOM compliance (2007-04-20) http://python.org/sf/1704134 opened by Jason Orendorff textwrap.py mod. for jython (2007-04-20) CLOSED http://python.org/sf/1704473 opened by Tim Couper test_optparse.py mod. for jython (2007-04-20) http://python.org/sf/1704474 opened by Tim Couper Use MoveFileEx() to implement os.rename() on windows (2007-04-20) http://python.org/sf/1704547 opened by Raghuram Devarakonda interpreter crash when multiplying large lists (2007-04-20) http://python.org/sf/1704621 opened by Daniel Stutzbach Added clearerr() to clear EOF state (2007-04-23) http://python.org/sf/1706039 opened by jos Updated ASTVisitor Classes (2007-04-24) http://python.org/sf/1706323 opened by Yaakov Nemoy Implementation of @abstractmethod for PEP 3119 (2007-04-24) http://python.org/sf/1706989 opened by Guido van Rossum get status output fix for Win32 (2007-04-25) http://python.org/sf/1707753 opened by Ken Phillis Jr. Make isinstance/issubclass overloadable (2007-04-26) http://python.org/sf/1708353 opened by Guido van Rossum Patches Closed ______________ silenced a compiler warning (2007-04-18) http://python.org/sf/1703268 closed by nnorwitz missing declaration in readline.c (2007-04-18) http://python.org/sf/1703270 closed by nnorwitz ZipFile.printdir fix (2.5) (2007-04-11) http://python.org/sf/1698915 closed by nnorwitz Migrate test_minidom.py to unittest (2007-03-30) http://python.org/sf/1691032 closed by jorend fixes bug #1703952 - ctypes: problem with large integers (2007-04-20) http://python.org/sf/1703972 closed by theller Update to Macintosh library documentation (2007-04-11) http://python.org/sf/1698768 closed by gbrandl textwrap.py mod. for jython (2007-04-20) http://python.org/sf/1704473 closed by gbrandl tarfile bug when opening a file directly (2007-04-05) http://python.org/sf/1695229 closed by gustaebel stream writing support in wave.py (2007-02-05) http://python.org/sf/1652328 closed by nnorwitz PEP 3114 -- next() -> __next__() (2007-03-07) http://python.org/sf/1675363 closed by gbrandl warnings.py gets filename wrong for eval/exec (2007-04-01) http://python.org/sf/1692664 closed by nnorwitz New / Reopened Bugs ___________________ "t.join(); assert t not in threading.enumerate()" fails (2007-04-19) http://python.org/sf/1703448 opened by Andrew Bennetts have a way to ignore nonexisting locales in locale.setlocale (2007-04-19) http://python.org/sf/1703592 opened by Matthias Klose ctypes: problem with large integers (2007-04-19) http://python.org/sf/1703952 reopened by belopolsky ctypes: problem with large integers (2007-04-19) http://python.org/sf/1703952 opened by Alexander Belopolsky TarFile.addfile() throws a struct.error (2007-04-20) CLOSED http://python.org/sf/1704156 opened by K. C. Wong must run "make" before "make install" (2007-04-20) http://python.org/sf/1704287 opened by Joseph VanAndel Exception message when using subprocess.POpen (2007-04-21) CLOSED http://python.org/sf/1704790 opened by Sam Ruby incorrect return value of unicodedata.lookup() - beoynd BMP (2007-04-21) http://python.org/sf/1704793 opened by vbr contextmanager eats StopIteration (2007-04-22) http://python.org/sf/1705170 opened by Adam Olsen cannot change cursor color in IDLE (2007-04-22) http://python.org/sf/1705362 opened by zorkin 'nonlocal x' at top level crashes interpreter (2007-04-22) CLOSED http://python.org/sf/1705365 opened by John Reese Select() failure (race condition) (2007-04-22) http://python.org/sf/1705393 opened by Ron Garret Error in sys.argv documenation (2007-04-23) CLOSED http://python.org/sf/1705717 opened by Kamil Kisiel pydoc.py has typo. (2007-04-23) CLOSED http://python.org/sf/1705997 opened by charlesmchen SWIG options not being followed in all cases (2007-04-24) CLOSED http://python.org/sf/1706381 opened by Morten Lied Johansen socket.error exceptions not subclass of StandardError (2007-04-24) http://python.org/sf/1706815 opened by John Nagle tarfile fails in 2.5.1 (NoneType has no ...) (2007-04-24) CLOSED http://python.org/sf/1706850 opened by Thomas Leonard Failed to build Python 2.5.1 with sqlite3 (2007-04-24) http://python.org/sf/1706863 opened by Vitaliy Yermolenko lost global variables in main memory intensive execution (2007-04-25) http://python.org/sf/1707255 opened by Jordi Pujol Ahull? generation errors in PDF-A4 tags for lib.pdf (2007-04-25) http://python.org/sf/1707497 opened by Antoine LECA raw text can't end with backslash (2007-04-25) CLOSED http://python.org/sf/1707607 opened by lomm os.path.normpath changes path (chops of trailing slash) (2007-04-26) http://python.org/sf/1707768 opened by Robert Siemer doctest work with Windows PyReadline (2007-04-26) http://python.org/sf/1708316 opened by manuelg find_module doc ambiguity (2007-04-26) http://python.org/sf/1708326 opened by Andrew McNabb Why not sequential? (2007-04-26) CLOSED http://python.org/sf/1708362 opened by Lucas Malor TimedRotatingFileHandler's doRollover opens file in "w" mode (2007-04-27) http://python.org/sf/1708538 opened by Florian Schmidt Exact matching (2007-04-27) http://python.org/sf/1708652 opened by Tom Lynn Tutorial error (2007-04-27) CLOSED http://python.org/sf/1708710 opened by john hite Bugs Closed ___________ questionable results from IDLE, Windows, & several built-in (2007-04-15) http://python.org/sf/1700912 closed by bavantgarde314 utf-16 codec problems with multiple file append (2007-04-16) http://python.org/sf/1701389 closed by doerwalter ctypes: problem with large integers (2007-04-19) http://python.org/sf/1703952 closed by theller README is referencing obsolete? http://starship.python.net (2007-04-09) http://python.org/sf/1696740 closed by tjreedy TarFile.addfile() throws a struct.error (2007-04-20) http://python.org/sf/1704156 closed by gustaebel Exception message when using subprocess.Popen (2007-04-21) http://python.org/sf/1704790 closed by gbrandl Incorrect example for add_password() (2007-04-18) http://python.org/sf/1703110 closed by nnorwitz SSL support in socket module needs tests (2001-08-16) http://python.org/sf/451607 closed by facundobatista 'nonlocal x' at top level crashes interpreter (2007-04-23) http://python.org/sf/1705365 closed by ncoghlan Error in sys.argv documenation (2007-04-23) http://python.org/sf/1705717 closed by gbrandl Property with -> annotation triggers assert (2007-04-10) http://python.org/sf/1697248 closed by ncoghlan pydoc.py has typo. (2007-04-23) http://python.org/sf/1705997 closed by gbrandl SWIG options not being followed in all cases (2007-04-24) http://python.org/sf/1706381 closed by gbrandl Tix is not included in 2.5 for Windows (2006-09-30) http://python.org/sf/1568240 closed by loewis tarfile fails in 2.5.1 (NoneType has no ...) (2007-04-24) http://python.org/sf/1706850 closed by gbrandl raw text can't end with backslash (2007-04-25) http://python.org/sf/1707607 closed by gbrandl Why not sequential? (2007-04-26) http://python.org/sf/1708362 deleted by lucas_malor Why not sequential? (2007-04-26) http://python.org/sf/1708362 closed by lucas_malor Tutorial error (2007-04-27) http://python.org/sf/1708710 closed by gbrandl New / Reopened RFE __________________ pyunit should allow __unittest in locals to trim stackframes (2007-04-23) http://python.org/sf/1705520 opened by Robert Collins Give Partial the ability to skip positionals (2007-04-23) CLOSED http://python.org/sf/1706256 opened by Calvin Spealman access to unicodedata (via codepoints or 2-char surrogates) (2007-04-24) http://python.org/sf/1706460 opened by vbr Please add .bz2 in encodings_map (in the module mimetypes) (2007-04-25) http://python.org/sf/1707693 opened by elghinn RFE Closed __________ Feature request: Comparing regexps (2007-04-16) http://python.org/sf/1701452 closed by rhettinger Give Partial the ability to skip positionals (2007-04-24) http://python.org/sf/1706256 closed by loewis From rridge at caffeine.csclub.uwaterloo.ca Tue Apr 17 16:16:15 2007 From: rridge at caffeine.csclub.uwaterloo.ca (Ross Ridge) Date: Tue, 17 Apr 2007 16:16:15 -0400 Subject: Getting started with python References: <1176598011.463543.96990@q75g2000hsh.googlegroups.com> <1176706996.848574.196660@y5g2000hsa.googlegroups.com> Message-ID: James Stroud wrote: >py> t = timeit.Timer(stmt=s) >py> print "%.2f usec/pass" % (1000000 * t.timeit(number=100000)/100000) >40.88 usec/pass 7stud wrote: >What does this accomplish: > >1000000 * t.timeit(number=100000)/100000 > >that the following doesn't accomplish: > >10 * t.timeit(number=100000) The first example converts from seconds per 100000 passes to microseconds per pass in two steps, while the second example does it one. The first example is more easily understood and maintainable than the second example. Ross Ridge -- l/ // Ross Ridge -- The Great HTMU [oo][oo] rridge at csclub.uwaterloo.ca -()-/()/ http://www.csclub.uwaterloo.ca/~rridge/ db // From ken.carlino at gmail.com Fri Apr 20 15:52:12 2007 From: ken.carlino at gmail.com (ken) Date: 20 Apr 2007 12:52:12 -0700 Subject: urlopen.read() Message-ID: <1177098732.490602.301530@l77g2000hsb.googlegroups.com> Hi, When I call urlopen.read() like this: data = urlopen("http://localhost").read(). Does that mean I will read the whole document to data, regardless how many data being sent back? Thank you. From ecir.hana at gmail.com Mon Apr 16 22:15:55 2007 From: ecir.hana at gmail.com (ecir.hana at gmail.com) Date: 16 Apr 2007 19:15:55 -0700 Subject: yield, curry, mix-in, new.function, global, closure, .... what will work? In-Reply-To: <1176774686.328834.296410@e65g2000hsc.googlegroups.com> References: <1176657848.944538.169780@p77g2000hsh.googlegroups.com> <7xy7ktmrzn.fsf@ruckus.brouhaha.com> <1176684145.537202.68090@p77g2000hsh.googlegroups.com> <7xbqhp6sdu.fsf@ruckus.brouhaha.com> <1176730099.467774.212440@q75g2000hsh.googlegroups.com> <1176737762.629412.189270@y80g2000hsf.googlegroups.com> <1176743127.450980.236610@o5g2000hsb.googlegroups.com> <1176774686.328834.296410@e65g2000hsc.googlegroups.com> Message-ID: <1176776155.432629.209830@d57g2000hsg.googlegroups.com> On Apr 17, 3:51 am, ecir.h... at gmail.com wrote: > I'm reading the docs now and I stumbled upon something: > section "15.3 threading -- Higher-level threading interface" mensions > a class "local", in which "... Thread-local data are data whose values > are thread specific. ..." > > Does it mean, I can create global variables whose changing is thread- > safe? > More specific: > > import threading > > def change_i(arg): > global k > k.i = arg > > def change_j(arg): > global k > k.j = arg > > def changer(): > change_i('changed_i') > change_j('changed_j') > > def run(i='', j=''): > global k > k = threading.local() > k.i = i > k.j = j > changer() > i = k.i > j = k.j > return i, j > > print run() == ('changed_i', 'changed_j') > > Is this ok? I was too quick, "k = threading.local()" has to by outside of run(), right? From edfialk at gmail.com Mon Apr 16 12:22:36 2007 From: edfialk at gmail.com (edfialk) Date: 16 Apr 2007 09:22:36 -0700 Subject: script for seconds in given month? Message-ID: <1176740556.859125.221980@l77g2000hsb.googlegroups.com> Hi, does anyone happen to know of a script that would return the number of seconds in a month if I give it a month and a year? My python is a little weak, but if anyone could offer some suggestions I think I could handle it myself, or if anyone happens to know of a script already written that performs this I would be extremely grateful. Thanks! -Ed From bj_666 at gmx.net Mon Apr 9 10:30:10 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Mon, 09 Apr 2007 16:30:10 +0200 Subject: Managing a file buffer References: Message-ID: In , David Johnson wrote: > What I'd like to do is have a buffer, say 5MB in size, which I can point > GStreamer at. So every time I write 60K to the tail of the file, I'd need to > remove 60K from the head of the file. You can't remove data from the head of a file. At least not without moving all following data "down", but then the file pointer within `gstreamer` is wrong. Can't `gstreamer` be fed through a pipe? Ciao, Marc 'BlackJack' Rintsch From andre.roberge at gmail.com Mon Apr 30 10:40:37 2007 From: andre.roberge at gmail.com (=?iso-8859-1?B?QW5kcuk=?=) Date: 30 Apr 2007 07:40:37 -0700 Subject: Launching an independent Python program in a cross-platform way (including mac) In-Reply-To: <838d5$4635f634$4275d90a$5047@FUSE.NET> References: <1177889540.489960.176380@u30g2000hsc.googlegroups.com> <1177890695.308785.165580@l77g2000hsb.googlegroups.com> <838d5$4635f634$4275d90a$5047@FUSE.NET> Message-ID: <1177944037.400933.291060@l77g2000hsb.googlegroups.com> On Apr 30, 10:59 am, Kevin Walzer wrote: [snip] > > There are extension modules on the Mac for integrating Python and > AppleScript (the best one is appscript). However, if you want to limit > yourself to core Python, your best best is osascript, a system > command-tool that lets you call AppleScript code with arguments from > other programs. This can be called via os.system. > > The basis syntax for doing this from Python might look something like this: > > os.system('osascript -e \'tell app \"Terminal\" to activate\'') > > This simply launches Terminal. Note that you have to deal with quoting > issues. The equivalent syntax from AppleScript would be: > > tell app "Terminal" to activate > > If you want to Terminal to run a command-line program from AppleScript, > you can do this with the "do script" command. Code to do this could look > something like this: > > myscript = "python -e foo.py" > os.system('osascript -e '\tell app \"Terminal"\ to do script %s\'', > myscript) > > I haven't tested this, but you get the basic idea--define the script and > command-line paramaters in a string, then pass that to > AppleScript/osascript as a variable. This code should launch Terminal, > then run the external Python script. > > HTH, Thanks. I managed to get something like this to work. Later, I'll post it as an example to this thread so that other can use if for a reference if needed. Andr? > Kevin > > -- > Kevin Walzer > Code by Kevinhttp://www.codebykevin.com From rridge at caffeine.csclub.uwaterloo.ca Thu Apr 19 14:39:26 2007 From: rridge at caffeine.csclub.uwaterloo.ca (Ross Ridge) Date: Thu, 19 Apr 2007 14:39:26 -0400 Subject: Python COM iterator References: <46279B56.4020901@websafe.com> Message-ID: Larry Bates wrote: > I tested in VB and by golly it works! What is odd is that this looks > NOTHING like what we got from the docs earlier. No GetEnumerator > method, no MoveNext method. I'm glad it works, but I'm a little > puzzled as to why it works. The documention Carsten Haese referenced earlier was for the .NET version of VisualBasic, and shows how to use .NET's IEnumerate and IEnumerable interfaces. Steve Holden wrote: >Presumably the magic of mark Hammond's wrapper classes providing >adaptation between Python iteration and COM enumerable collection >objects. win32all is *very* Pythonic. Maybe Mark Hammond's win32all provides such a magic wrapper, but Cartsen Haese's example didn't use it. Instead it provided it own implementation of the COM IEnumVARIANT interface, the OLE Automation (ie. VisualBasic 6 compatable) way implementing iteratable objects. Ross Ridge -- l/ // Ross Ridge -- The Great HTMU [oo][oo] rridge at csclub.uwaterloo.ca -()-/()/ http://www.csclub.uwaterloo.ca/~rridge/ db // From http Mon Apr 16 23:45:51 2007 From: http (Paul Rubin) Date: 16 Apr 2007 20:45:51 -0700 Subject: list insertion question References: <1176771916.236282.206500@n59g2000hsh.googlegroups.com> Message-ID: <7x7isbbr4g.fsf@ruckus.brouhaha.com> eight02645999 at yahoo.com writes: > hi > i have a list (after reading from a file), say > data = [ 'a','b','c','d','a','b','e','d'] > > I wanted to insert a word after every 'a', and before every 'd'. so i > use enumerate this list: > for num,item in enumerate(data): > if "a" in item: > data.insert(num+1,"aword") > if "d" in item: > data.insert(num-1,"dword") #this fails > but the above only inserts after 'a' but not before 'd'. What am i > doing wrong? is there better way?thanks As others have said, you're mutating the list while iterating through it, which can give whacked results. Also, even if you operate on a copy of the list, that algorithm uses quadratic time because of all the insertions into the list. These days I like to write in the style def g(): for w in data: if 'd' in w: yield 'dword' yield w if 'a' in w: yield 'aword' data = list(g(data)) instead of using list.append as someone else suggested. The iterator approach is probably a bit slower but can be seen as a bit cleaner, depending on your stylistic preferences. From nospam at nospam.com Thu Apr 26 10:05:21 2007 From: nospam at nospam.com (Mark T) Date: Thu, 26 Apr 2007 07:05:21 -0700 Subject: str() and repr() question References: <1177575127.034458.243760@t38g2000prd.googlegroups.com> Message-ID: <14idndgfd9kBLK3bnZ2dnUVZ_s-dnZ2d@comcast.com> "adima" wrote in message news:1177575127.034458.243760 at t38g2000prd.googlegroups.com... > Hi All! > Sorry, my English isnt good, but get a try to describe my problem. > > Today we wrote next script: > > import os, glob, time, string > files_to_test = ( "J:\\BWNEW\\!Unerase\\test.test", "L:\\Temp\Nick\ > \test.test", "F:\\TRANSIT\\nick\\test.test") > outfile="c:\\temp\\statistic" > > > def DoTestTime(file): > StartTime = time.time() > filehandle = open(file) > alllines = filehandle.read() > filehandle.close() > > FileSize = os.path.getsize(file) > EndTime = time.time() > return time.ctime() , "\tDisk\t" , file[:3] , "\tfile size (bytes) = > \t" , FileSize , "\taccess time =\t" , EndTime - StartTime > > > if __name__ == "__main__": > out = open(outfile, 'w') > for EachFile in files_to_test: > str = DoTestTime(EachFile) > print type(str) > for s in str: > print s > out.write(str(s)) > out.close() > > When I executed it, the output was > C:\test\py>File_Stat.py > Thu Apr 26 12:08:33 2007 > > Traceback (most recent call last): > File "C:\test\py\File_Stat.py", line 26, in ? > out.write(str(s)) > TypeError: 'tuple' object is not callable > > When I replace "str" with "repr" in out.write(str(s)), script executed > normally. > > Where is the problem here? > Thanks in advance. > You might want to check out pychecker.py. Its output: Processing Script1... Warnings... Script1.py:1: Imported module (glob) not used Script1.py:1: Imported module (string) not used Script1.py:9: Local variable (alllines) not used Script1.py:20: (str) shadows builtin You've replaced the built-in function str with the return value of DoTestTime(). -Mark From gagsl-py2 at yahoo.com.ar Wed Apr 11 16:20:30 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 11 Apr 2007 17:20:30 -0300 Subject: Reading the first line of a file (in a zipfile) References: <1176318822.811661.115730@q75g2000hsh.googlegroups.com> <1176322548.710970.315610@d57g2000hsg.googlegroups.com> Message-ID: En Wed, 11 Apr 2007 17:15:48 -0300, escribi?: > The file contents have leading whitespace, then a number: > 123456 \n > I expect to return '123456' And nothing following the number? py> line = " 123456 \n" py> print line.strip() 123456 -- Gabriel Genellina From steve at holdenweb.com Tue Apr 24 10:44:48 2007 From: steve at holdenweb.com (Steve Holden) Date: Tue, 24 Apr 2007 10:44:48 -0400 Subject: Python un-plugging the Interpreter In-Reply-To: References: <1hwu415.1yyvbo61efn1uqN%aleax@mac.com> Message-ID: Jorgen Grahn wrote: > On Thu, 19 Apr 2007 20:39:57 -0700, Alex Martelli wrote: >> Steve Holden wrote: >> >>> A long time ago Greg Stein produced a patch that removed the need for >>> the GIL, but nobody seemed to want to pay the penalty it extracted in >>> speed reduction, so it languished unadopted. >> Perhaps the current wave of dual-core and quad-core CPUs in cheap >> consumer products would change people's perceptions -- I wonder... > > Maybe it would change /perceptions/, but would normal users suddenly > start running things that are (a) performance-critical, (b) written in > Python and (c) use algorithms that are possible to parallellize? > > I doubt it. (But I admit that I am a bit negative towards thread > programming in general, and I have whined about this before.) > Well there seems to be little doubt that the rise in clock speeds is reaching a plateau, so it seems like parallelization will have to be the long-term trend. It's difficult to perform a deep enough static analysis of programs in dynamic languages to automatically parallelize the code (it's hard enough for languages like Fortran), but I am sure that over the next few years languages will start to sprout features that make programmer-directed parallelization easier. I'd like to see Python leading that charge, not failing to track it. So, stop being a Luddite ;-) regards Steve -- Steve Holden +1 571 484 6266 +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 attn.steven.kuo at gmail.com Thu Apr 5 18:05:25 2007 From: attn.steven.kuo at gmail.com (attn.steven.kuo at gmail.com) Date: 5 Apr 2007 15:05:25 -0700 Subject: grandparent method with super In-Reply-To: <20070405171306.0264fb70@localhost> References: <20070405161939.694d51a1@localhost> <20070405163845.2ffa8d32@localhost> <20070405171306.0264fb70@localhost> Message-ID: <1175810725.877562.136230@l77g2000hsb.googlegroups.com> On Apr 5, 2:13 pm, Martin Manns wrote: > On Thu, 5 Apr 2007 16:55:38 -0400 > > > > "John Clark" wrote: > > >That works, but when I replace A with something else, I do not get > > >the > > grandparent anymore > > >without changing all the method calls. Basically, I would like to > > >call the > > method m in the first > > >grandparent of D. > > > >Martin > > > I think the problem you may run into is with the term "first > > grandparent" - when you look at the method resolution order of the > > class D, you will find that the MRO goes "D, C, B, A"... I think it's > > going to be difficult to figure out where the "first grandparent" is > > in the MRO. > > > For example: > > > class A(object): > > def m(self): > > pass > > class B(A): > > def m(self): > > pass > > class C(B): > > def m(self): > > pass > > class D(A): > > def m(self): > > pass > > class E(C,D): > > def m(self): > > firstgrandparent(E,self).m() #Should call B.m > > class F(D,C): > > def m(self): > > firstgrandparent(F,self).m() # Should call F.m > > > The mro for class E is going to be "E,C,B,D,A" where as the mro for > > class F is going to be "F,D,C,B,A". However, the first grandparent > > for E should be B, where as the first grandparent for F should be A. > > > Because the MRO isn't just a depth first traversal, the term "first > > grandparent" gets tricky to define... > > Not really. The first grandparent would be the first occurrence in the > list from left to right, which satisfies the requirement that its > shortest path to the current class is 2. > > The only problem: How do I get it? > > Martin class E(C,D): def m(self): for cls in E.__mro__: if cls != E and cls not in E.__bases__: cls.m(self) break ... but it's probably better that you rethink your class hierarchy. -- Hope this helps, Steven From python.technofreak at gmail.com Sat Apr 21 05:24:34 2007 From: python.technofreak at gmail.com (Parthan SR) Date: Sat, 21 Apr 2007 14:54:34 +0530 Subject: Class Not Auto-Init On Import In-Reply-To: <5458049585297349447@unknownmsgid> References: <5458049585297349447@unknownmsgid> Message-ID: <9d6d3deb0704210224m10a2ec9an9b063b11d4763d77@mail.gmail.com> On 4/21/07, Robert Rawlins - Think Blue wrote: > > Hello Guys, > > From my understanding of what I've read, the 'import' is meant to auto > Init my class ready for me to access its methods, but it doesn't appear too, > I'm having to init them myself before I can access them, like this. > > import LocationService > > Location = LocationService.LocationService() > > LocationService.setIP('192.168.1.1') > > Why is this the case? Should i not just be able to access the setIP() > method by doing LocationService.setIP('192.168.1.1') Without having to > create my own inited reference? > Did you try this, from LocationService import * LocationService.setIP('192.168.1.1') # If you have something like LocationService --> LocationService() --> setIP() This is similar to using datetime.now() of the datetime module. >>> import datetime >>> datetime.now() Traceback (most recent call last): File "", line 1, in AttributeError: 'module' object has no attribute 'now' >>> datetime.datetime.now() datetime.datetime(2007, 4, 21, 14, 49, 4, 506309) Now for the same, >>> from datetime import datetime >>> datetime.now() datetime.datetime(2007, 4, 21, 14, 45, 42, 463064) Or, >>> from datetime import * >>> datetime.now() datetime.datetime(2007, 4, 21, 14, 46, 27, 767389) -- With Regards Parthan "Technofreak" http://technofreakatchennai.wordpress.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From bbxx789_05ss at yahoo.com Sun Apr 1 03:13:37 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: 1 Apr 2007 00:13:37 -0700 Subject: re.findall() hangs in python In-Reply-To: <1175397176.567214.194810@n59g2000hsh.googlegroups.com> References: <1175397176.567214.194810@n59g2000hsh.googlegroups.com> Message-ID: <1175411617.743757.293860@p15g2000hsd.googlegroups.com> On Mar 31, 9:12 pm, "silverburgh.me... at gmail.com" wrote: > 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("(.*) re.S) > > print "before find all" > > match = re.findall(pattern, data) > > if (match): > print "match2" > > Can you please tell me why it that? It doesn't hang when I try it. Why don't you post a complete example that hangs. Also, you might consider using exterior single quotes around your string so that you don't have to escape double quotes inside the string. From rokkamraja at gmail.com Tue Apr 24 18:56:22 2007 From: rokkamraja at gmail.com (Raja) Date: 24 Apr 2007 15:56:22 -0700 Subject: Overriding Sys.Settrace Message-ID: <1177455381.838819.122880@r3g2000prh.googlegroups.com> Hi, I want to override the sys.settrace() call, create a way to trace the execution of a python program. Keep track of all objects created and destroyed. Keep track of the call pattern throughout the execution of the program and output a simplified "call graph" to standard out. Can anyone please tell me how to do this ? Thank You, From grahn+nntp at snipabacken.dyndns.org Thu Apr 19 13:58:52 2007 From: grahn+nntp at snipabacken.dyndns.org (Jorgen Grahn) Date: 19 Apr 2007 17:58:52 GMT Subject: Python Feature Request: Explicit variable declarations References: <1176546078.934340.253810@y5g2000hsa.googlegroups.com> Message-ID: On 14 Apr 2007 03:21:18 -0700, samjnaa at gmail.com wrote: ... > I would like to have something like the "option explicit" statement in > Visual Basic which turns on C-like checking for declaration of > variables. This is highly helpful for people who are coming from C/C+ > +, for people who are learning programming using Python, As a C and C++ programmer (not a C/C++ programmer), I have to say that it doesn't bother me much. An optional feature like this would just annoy me if I encountered code using it. ... > where the user has inadvertantly typed "g" before "n" and will later > wonder why his application is not working as expected. Well, he won't *wonder* -- Python will be rather explicit about it. "Later" is the key word here -- this bug may lay around waiting for ten years before someone triggers it. /Jorgen -- // Jorgen Grahn R'lyeh wgah'nagl fhtagn! From cam.ac.uk at mh391.invalid Wed Apr 18 21:24:11 2007 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Thu, 19 Apr 2007 02:24:11 +0100 Subject: Spawn/Exec with asterisk in argument In-Reply-To: <1176942943.090705.281320@l77g2000hsb.googlegroups.com> References: <1176942943.090705.281320@l77g2000hsb.googlegroups.com> Message-ID: jeremyfee at gmail.com wrote: > The spawn* and exec* functions appear to escape asterisks, I'm > guessing all shell characters too, before the spawn/exec'ed process > sees them. No. It is the shell that ordinarily processes these characters and gives them a special meaning. On most systems, ls does not give any special meaning to asterisk. > Is there a way around this? If you want to process asterisk the way the shell does, you can pass things through the shell. os.system is one way of doing that. Probably better is: subprocess.check_call("ls -l *", shell=True) Another way is using the glob module (and optionally os.path.expanduser() for tilde expansion and os.path.expandvars() for variable expansion, other things that are normally taken care of by the shell). -- Michael Hoffman From tjreedy at udel.edu Thu Apr 12 16:00:44 2007 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 12 Apr 2007 16:00:44 -0400 Subject: tuples, index method, Python's design References: Message-ID: "Alan Isaac" wrote in message news:HNuTh.2516$ok6.3 at trnddc07... | I doubt that *anyone* who programs in Python | has not encountered the situation where they change | a tuple to a list *solely* for the purpose of getting | access to the index method. This suggests a missing | method, does it not? Who has not done this? | Name yourself! Me. Not that I can remember, anyway. But perhaps I have just not done enough of the right sort of programming. | There is simply no conflict between the index method and immutability, | but at the moment one is forced to choose. Why? Nobody has | offered a real explanation of this. Where 'real' == 'one you accept as valid'. | I offered a simple use case. Consider a game, | where the *fixed* set p of players have a *fixed* order. So the natural internal identifiers of the players are 0, ..., p-1 or, if you prefer and are willing to waste a tiny bit of space, 1, ..., p. If you only access players via a sequential collection object, then you will access them by id. If you pass around player instances separate from their container, than give them an id attribute. I take it that in your game, no player, human or ai, ever gets eliminated or leaves or has a connection drop. | A tuple is natural. That is partly what is under debate. Certainly you do not need a tuple for indexing a dict. | Now for a player you want to construct the opponents. Generator approach: opponents = (op for op in players if op != player) To do it once for everyone: for player in players: player.opponents = tuple(op for op in players if op != player) | If I had the index i it wd be p[:i]+p[i+1:], but how to get the index? You either use the index to get the player or get it from the player (see above). opponents = p*[0] for i in range(p): opponents[i] = players[:i] + players[i+1:] opponents = tuple(opponents) # if you really care for player in players: i = player.id player.opponents = players[:i] + players[i+1:] It would never occur to me to get a player id by the O(n) scanning process. | Other use cases have also been offered on this thread. | What is the basic response? "Do not worry about the | loss of immutability, just use a list." What kind of a | response is that?? This sounds to me like "I do not | really see the point of immutability", which is no | response at all. The main point of immutability is hashability by value (rather than by id). Terry Jan Reedy From girodt at gmail.com Tue Apr 3 10:42:54 2007 From: girodt at gmail.com (TG) Date: 3 Apr 2007 07:42:54 -0700 Subject: numpy performance and list comprehension Message-ID: <1175611372.971235.191280@d57g2000hsg.googlegroups.com> Hi there. Reading the page on python performance ( http://scipy.org/PerformancePython ) made me realize that I can achieve tremendous code acceleration with numpy just by using "u[:,:]" kind of syntax the clever way. Here is a little problem (Oja's rule of synaptic plasticity) * W is a matrix containing the weights of connections between elements i and j * V is an array containing the values of elements I want to make W evolve with this rule : dW[i,j] / dt = alpha * (V[i] * V[j] - W[i,j] * V[i]^2) (don't pay attention to the derivate and stuff) So, how would you write it in this nifty clever way ? As a begining I wrote this : W += V.flatten().reshape((V.size,1)) * V.flatten().reshape((1,V.size)) But it is not complete and, I guess, not efficient. From spradml at gmail.com Mon Apr 9 13:22:37 2007 From: spradml at gmail.com (Pradnyesh Sawant) Date: Mon, 9 Apr 2007 22:52:37 +0530 Subject: doubt with importing module, given module name In-Reply-To: <80628d680704072327y43c349f5sf863807dea6bc345@mail.gmail.com> References: <80628d680704072327y43c349f5sf863807dea6bc345@mail.gmail.com> Message-ID: <80628d680704091022k7c350045j4787430bf9e39012@mail.gmail.com> Hello, I have a string which in reality is the name of a module to be imported. The name of the class contained in the module also has the same (although with different capitalization). My requirement is to import the module, and also create an instance of the class. eg: str = "module" #name of module is "module.py" cls = str.capitalize() #name of class is "Module" inst = cls() #create an instance of class "Module" how do i do this? Thanks a lot in advance From __peter__ at web.de Wed Apr 18 02:21:31 2007 From: __peter__ at web.de (Peter Otten) Date: Wed, 18 Apr 2007 08:21:31 +0200 Subject: Binary file output using python References: Message-ID: Chi Yin Cheung wrote: > Is there a way in python to output binary files? I need to python to > write out a stream of 5 million floating point numbers, separated by > some separator, but it seems that all python supports natively is string > information output, which is extremely space inefficient. > > I'd tried using the pickle module, but it crashed whenever I tried using > it due to the large amount of data involved. A minimalistic alternative is array.tofile()/fromfile(), but pickle should handle a list, say, of 5 million floating point numbers just fine. What exactly are you doing to provoke a crash, and what does it look like? Please give minimal code and the traceback. Peter From robert.kern at gmail.com Mon Apr 23 19:14:44 2007 From: robert.kern at gmail.com (Robert Kern) Date: Mon, 23 Apr 2007 18:14:44 -0500 Subject: Numpy problem: Arrays in a list of dictionaries In-Reply-To: <1177367679.113990.156000@q75g2000hsh.googlegroups.com> References: <1176837810.276473.55020@e65g2000hsc.googlegroups.com> <1177367679.113990.156000@q75g2000hsh.googlegroups.com> Message-ID: ZMY wrote: > Dear Robert, > > So how should I do this? I tried > >>>>> d1 = {1: array([2, 3, 4]).copy(), 2: ''} >>>>> l1 = [] >>>>> for i in range(3): l1.append(d1.copy()) > > and it still doesn't work. Of course it doesn't, for the same reason that your first attempt didn't work either. You've made a copy of an array and put the copy into the dictionary, then made copies of that dictionary. The process of making copies of the dictionary doesn't make copies of the objects it contains. > I think my problem is: how to create a new array every time I append > it to the list... import copy d1 = {1: array([2, 3, 4]), 2: ''} l1 = [] for i in range(3): l1.append(copy.deepcopy(d1)) -- 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 kyosohma at gmail.com Tue Apr 3 14:38:38 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: 3 Apr 2007 11:38:38 -0700 Subject: print the screen shot in python In-Reply-To: <1175624176.401359.137560@o5g2000hsb.googlegroups.com> References: <1175549083.627721.315170@y80g2000hsf.googlegroups.com> <1175607746.643094.193320@q75g2000hsh.googlegroups.com> <1175624176.401359.137560@o5g2000hsb.googlegroups.com> Message-ID: <1175625518.189432.251020@b75g2000hsg.googlegroups.com> On Apr 3, 1:16 pm, "gslm" wrote: > Thanks, > I use TKinter,os:Xp home,python25. > I want to print all my application's view, except the close-minimize > icons. I don't know enough about Tkinter, but you can use the graphics module according to this post that should take a screenshot: http://snippets.dzone.com/posts/show/398 You should also navigate through this series of posts on taking screenshots using PIL and the win32 module: http://mail.python.org/pipermail/python-win32/2003-January/000714.html The following post has a short script using the os module to capture a screenshot too: http://livingcode.blogspot.com/2006/03/screenshot-in-cocoa-python.html Hopefully this will give you some direction. Other than that, we'll have to wait for a Tkinter guru. Mike From bruno.42.desthuilliers at wtf.websiteburo.oops.com Thu Apr 5 10:48:08 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Thu, 05 Apr 2007 16:48:08 +0200 Subject: Why NOT only one class per file? In-Reply-To: <1175778276.603838.86500@l77g2000hsb.googlegroups.com> References: <1175721799.714907.52770@o5g2000hsb.googlegroups.com> <46142acc$0$7532$426a34cc@news.free.fr> <4614b40e$0$26843$426a74cc@news.free.fr> <1175778276.603838.86500@l77g2000hsb.googlegroups.com> Message-ID: <46150c0f$0$3184$426a74cc@news.free.fr> Nate Finch a ?crit : > So, here's a view from a guy who's not a python nut and has a long > history of professional programming in other languages (C++, C, C#, > Java) > > I think you're all going about this the wrong way. There's no reason > to *always* have one class per file. However, there's also no reason > to have 1600 lines of code and 50 classes in one file either. Nope. What matters is to have - logical grouping of code units (high cohesion) - manageable files (not too much files, not too large files - of course the balance depends on the project as well). There are quite a few professional programmers here with experience on medium to large to huge projects with different languages, you know. From goodTweetieBird at hotmail.com Thu Apr 26 20:33:31 2007 From: goodTweetieBird at hotmail.com (gtb) Date: 26 Apr 2007 17:33:31 -0700 Subject: Atribute error In-Reply-To: <59cn8bF2jtnobU1@mid.individual.net> References: <1177620754.659481.66240@s33g2000prh.googlegroups.com> <59cn8bF2jtnobU1@mid.individual.net> Message-ID: <1177634011.437068.247610@u32g2000prd.googlegroups.com> Thanks for posting. CompactTest is a class provided by MaxQ and inheritance generally works as the files below worked OK. I was trying to re-arrange things as newLogin() should be just one of many functions called by Test1. The way the inheritance is setup below seems like the tail wagging the dog especially since at some point I may no longer want to run the logon function. Thanks again, john #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # File Test1.py # Generated by MaxQ [com.bitmechanic.maxq.generator.CompactGenerator] from newLogon import newLogon class Test1(newLogon): # Recorded test actions. def runTest(self): self.msg('Test started') self.logon # ^^^ Insert new recordings here. (Do not remove this line.) # Code to load and run the test if __name__ == 'main': Test1('Test1').Run() #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # File newLogon.py # Generated by MaxQ [com.bitmechanic.maxq.generator.CompactGenerator] from CompactTest import CompactTest class newLogon(CompactTest): # Recorded test actions. def logon(self): self.msg('Test started') # ^^^ Insert new recordings here. (Do not remove this line.) # Code to load and run the test if __name__ == 'main': newLogon('newLogon').Run() From bdesth.quelquechose at free.quelquepart.fr Sat Apr 21 15:49:17 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sat, 21 Apr 2007 21:49:17 +0200 Subject: Nested dictionaries trouble In-Reply-To: <1176923772.011976.116190@p77g2000hsh.googlegroups.com> References: <1176317876.917874.58040@n59g2000hsh.googlegroups.com> <1176325715.951076.4790@w1g2000hsg.googlegroups.com> <1176923772.011976.116190@p77g2000hsh.googlegroups.com> Message-ID: <462a6150$0$31989$426a34cc@news.free.fr> IamIan a ?crit : > I am using the suggested approach to make a years list: > > years = ["199%s" % x for x in range(0,10)] > years += ["200%s" % x for x in range(0,10)] > > I haven't had any luck doing this in one line though. Is it possible? # Q, D and pretty obvious years = ["199%s" % x for x in range(0,10)] + ["200%s" % x for x in range(0,10)] # hardly more involved, and quite more generic years = ["%s%s" % (c, y) for c in ("199", "201") for y in range(10)] From jstroud at mbi.ucla.edu Tue Apr 24 21:12:43 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Tue, 24 Apr 2007 18:12:43 -0700 Subject: Do other Python GUI toolkits require this? In-Reply-To: <462a6241$0$31989$426a34cc@news.free.fr> References: <2163b$462a2d59$4275d90a$19243@FUSE.NET> <462a6241$0$31989$426a34cc@news.free.fr> Message-ID: Bruno Desthuilliers wrote: > Kevin Walzer a ?crit : > (snip) > >> Thanks to all for an illuminating thread on the mathematical >> implications of "learning curve" and other aspects. This thread has >> wandered pretty far from my original question (above) > > > Noticed this too ?-) I would have noticed, but my learning curve is rather steep. (Did I use that right? ;) From jzgoda at o2.usun.pl Tue Apr 24 04:33:26 2007 From: jzgoda at o2.usun.pl (Jarek Zgoda) Date: Tue, 24 Apr 2007 10:33:26 +0200 Subject: Ann: lastfmsvc-0.9.1 Message-ID: What's this? It's a Python library that enables interaction with artist/album/tracks metadata on Last.fm. This library tries to recreate complete functionality of LastFM Client when it comes to metadata (not streams). What's this good for? The code in this library allows performing standard operations on Last.FM metadata: * tag (track, album, artist); * recommend (track, album, artist); * add to/remove from loved (track); * ban/remove from banned (track); * remove from listened (track). Where? http://code.google.com/p/lastfmsvc/ -- Jarek Zgoda "We read Knuth so you don't have to." From mikeminer53 at hotmail.com Thu Apr 5 14:55:30 2007 From: mikeminer53 at hotmail.com (mkPyVS) Date: 5 Apr 2007 11:55:30 -0700 Subject: Indentifying the LAST occurrence of an item in a list In-Reply-To: <1175723121.298681.56600@n76g2000hsh.googlegroups.com> References: <1175702329.330032.250750@w1g2000hsg.googlegroups.com> <1175723121.298681.56600@n76g2000hsh.googlegroups.com> Message-ID: <1175799330.683339.93400@e65g2000hsc.googlegroups.com> Not sure below is better but it hacks at larger chunks (excuse the 10 second coding) m = [2,9,1,5,6,3,1,1,9,2] f = 1 temp = m location = m.index(f) gloc = location temp = m[location:] while 1: print(temp) try: location = temp.index(f) + 1 gloc += location except: break temp = temp[location:] #Remove the last 0th element gloc -= 1 print("Last location = %d" % gloc) From gagsl-py2 at yahoo.com.ar Thu Apr 5 13:39:47 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 05 Apr 2007 14:39:47 -0300 Subject: Objects, lists and assigning values References: Message-ID: En Thu, 05 Apr 2007 14:13:43 -0300, Manuel Graune escribi?: > class new_class(object): > def __init__( self, > internal_list=[]): > self.internal_list= internal_list All your instances share the *same* internal list, because default arguments are evaluated only once (when the function is defined) The usual way is to write: class new_class(object): def __init__(self, internal_list=None): if internal_list is None: internal_list = [] self.internal_list= internal_list See http://effbot.org/pyfaq/why-are-default-values-shared-between-objects.htm -- Gabriel Genellina From jstroud at mbi.ucla.edu Fri Apr 27 19:31:58 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Fri, 27 Apr 2007 16:31:58 -0700 Subject: editing scripts on a mac In-Reply-To: <1177692741.619598.191540@r3g2000prh.googlegroups.com> References: <1177692741.619598.191540@r3g2000prh.googlegroups.com> Message-ID: Thomas Nelson wrote: > On Apr 27, 11:37 am, Tommy Grav wrote: > >>>him> I do not have a text editor, but here are the answers to >>>him> questions 1-5. >> >>>Now, frankly, I don't think this answer is correct, since I know OS >>>X is >>>a UNIX derivative, but I am loathe to involve a programming noob >>>with vi >>>or something similar. So I wondered if one of the c.l.py mac users >>>could >>>give brief instructions for firing up a visual text editor of some >>>sort >>>and saving a file somewhere it can easily be accessed from a terminal >>>window (which I presume starts up in his home directory). >> > > 1) Open Finder, click "Applications", and open "TextEdit". > 2) hit shift-apple-T, or select Format -> Make Plain Text, to put you > in plaintext mode (It's .rtf by default) > 3) Make sure you save in the home directory (usually a picture of a > house). > > HTH, > Tom > I would recommend against the TextEdit recommendation. First, it is not a full-featured text editor, so you will switch soon to a real one. Second, its too easy to save as rtf, even with the txt extension--and it will take some time and frustration to realize your mistake. The best option is TextWrangler for non-vi, non-emacs people. Sometimes its even a good option for vi & emacs people. James From pythoncurious at gmail.com Mon Apr 16 12:38:46 2007 From: pythoncurious at gmail.com (pythoncurious at gmail.com) Date: 16 Apr 2007 09:38:46 -0700 Subject: C++ extension problem Message-ID: <1176741526.541997.52100@e65g2000hsc.googlegroups.com> Hi, I'm having a bit of trouble when writing a python extension. I can't seem to figure out what I did wrong. I tried to make a minimal example, but it's still quite a bit of code. It would be very appreciated if anyone could tell me what I've done wrong. First a short description of what I've done. The extension just wraps a string and the class in it will just hold the string data. A 'get' method is suppsed to just return the string value. There's a python part that will call C/C++ functions in the extension. I've tried using the same approach SWIG has, so the class in the extension doesn't really have any methods, it's all done in methods in the module. This is what it looks like when I try it out (also tried with different python version and compiler): % python Python 2.4.3 (#1, Aug 1 2006, 16:54:29) [GCC 3.4.6] on sunos5 Type "help", "copyright", "credits" or "license" for more information. >>> from example import StringWrapper >>> s = StringWrapper("S") >>> s.get() Traceback (most recent call last): File "", line 1, in ? File "example.py", line 7, in get def get(self): return _example.get(self._s) TypeError: argument 1 must be SillyString, not SillyString Now this is what confuses me: Why does it say that I have the wrong type when it's the same type as it suggests? setup.py file: ########### from distutils.core import setup, Extension module1 = Extension('_example', sources = ['_example.cc']) setup (name = 'example', ext_modules = [module1]) example.py file: ############ #!/usr/bin/env python import _example class StringWrapper(object): def __init__(self, value): self._s = _example.new_string(value) def get(self): return _example.get(self._s) and finally, the c/c++ file '_example.cc': (I need to use c++ compiler which means I couldn't use 'staticforward' and the 'cstring is used instead of 'string.h' ) ######################## #include "Python.h" #include // forward declaration extern PyTypeObject SillyStringType; typedef struct { PyObject_HEAD char s[21]; } SillyStringObject; PyObject * new_string(PyTypeObject *type, PyObject *args) { char *value = 0; if (!PyArg_ParseTuple(args, "s", &value)) return NULL; SillyStringObject *self = PyObject_NEW(SillyStringObject, &SillyStringType); if (self != NULL) { strncpy(self->s, value, 20); } return (PyObject *)self; } PyObject * get(PyTypeObject *type, PyObject *args) { SillyStringObject *o; if (!PyArg_ParseTuple(args, "O!", SillyStringType, &o)) return NULL; return (PyObject *)PyString_FromString(o->s); } PyMethodDef SillyStringMethods[] = { {"get", (PyCFunction)get, METH_VARARGS, "" }, {"new_string", (PyCFunction)new_string, METH_VARARGS, "" }, {NULL, NULL, 0, NULL} /* Sentinel */ }; PyTypeObject SillyStringType = { PyObject_HEAD_INIT(NULL) 0, /* ob_size */ (char *)"SillyString", /* tp_name */ sizeof(SillyStringObject), /* tp_basicsize */ 0, /* tp_itemsize */ (destructor)0, /* tp_dealloc */ (printfunc)0, /* tp_print */ (getattrfunc)0, /* tp_getattr */ (setattrfunc)0, /* tp_setattr */ (cmpfunc)0, /* tp_compare */ (reprfunc)0, /* tp_repr */ 0, /* tp_as_number */ 0, /* tp_as_sequence */ 0, /* tp_as_mapping */ (hashfunc)0, /* tp_hash */ (ternaryfunc)0, /* tp_call */ (reprfunc)0, /* tp_str */ 0, /* tp_getattro */ 0, /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT, /* tp_flags */ "SillyString class." /* tp_doc */ }; extern "C" { PyMODINIT_FUNC init_example(void) { PyObject* m; SillyStringType.tp_new = PyType_GenericNew; if (PyType_Ready(&SillyStringType) < 0) return; m = Py_InitModule3("_example", SillyStringMethods, "_example module."); Py_INCREF(&SillyStringType); PyModule_AddObject(m, "SillyStringObject", (PyObject *)&SillyStringType); } } From mik3l3374 at gmail.com Fri Apr 13 09:45:05 2007 From: mik3l3374 at gmail.com (mik3l3374 at gmail.com) Date: 13 Apr 2007 06:45:05 -0700 Subject: split and regexp on textfile In-Reply-To: <1176458885.245615.319070@n76g2000hsh.googlegroups.com> References: <1176451192.364949.8260@w1g2000hsg.googlegroups.com> <1176453634.577706.326170@y80g2000hsf.googlegroups.com> <1176454505.336514.90910@p77g2000hsh.googlegroups.com> <1176455681.424814.223830@q75g2000hsh.googlegroups.com> <1176456611.648400.254850@q75g2000hsh.googlegroups.com> <1176458885.245615.319070@n76g2000hsh.googlegroups.com> Message-ID: <1176471905.945870.180830@d57g2000hsg.googlegroups.com> On Apr 13, 6:08 pm, "Flyzone" wrote: > On 13 Apr, 11:30, "Flyzone" wrote: > > > all together :( > > Damn was wrong mine regexp: > pat = re.compile("[A-Z][a-z][a-z][ ][A-Z][a-z][a-z][ ][0-9| ][0-9][ ] > [0-9][0-9][:][0-9][0-9]",re.M|re.DOTALL) > > now is working! :) > Great! really thanks for the helps! > > A little question: the pat.split can split without delete the date? not that i know of. From martin at v.loewis.de Sat Apr 14 03:10:44 2007 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sat, 14 Apr 2007 09:10:44 +0200 Subject: nonstandard XML character entities? In-Reply-To: <7xfy73ae08.fsf@ruckus.brouhaha.com> References: <7xfy73ae08.fsf@ruckus.brouhaha.com> Message-ID: <46207e75$0$5795$9b622d9e@news.freenet.de> > I'm new to xml mongering so forgive me if there's an obvious > well-known answer to this. It's not real obvious from the library > documentation I've looked at so far. Basically I have to munch of a > bunch of xml files which contain character entities like ú > which are apparently nonstandard. If they contain such things, and do not contain a document type definition, they are not well-formed XML files (i.e. can't be called "XML" in a meaningful sense). It would have been helpful if you had given an example of such a document. > Basically I want to know if there's a way to supply the regular parser > (preferably xml.etree but I guess I can switch to another one if > necessary) with some kind of entity table, and/or if the info is > supposed to be found in the DTD or someplace like that. Right now I'm > ignoring the DTD and simply figuring out the doc structure by > eyeballing the xml files, maybe not a perfectly approved method but > it seems to be what most people do. If there is a document type declaration in the document, the best way is to parse it in a mode where the parser downloads the DTD when parsing it, and resolves the entity references itself. In SAX, you can put an EntityResolver into the parser, and then return a file-like object from resolveEntity. This can be used to avoid the network download; the document type declaration would still have to be present. Alternatively, you can implement a skippedEntity callback in the SAX content handler. In ElementTree, the XMLTreeBuilder has an attribute entity which is a dictionary used to map entity names in entity references to their definitions. Whether you can make the parser download the DTD itself, I don't know. Regards, Martin From tactics40 at gmail.com Sun Apr 1 21:27:59 2007 From: tactics40 at gmail.com (tac-tics) Date: 1 Apr 2007 18:27:59 -0700 Subject: How can i compare a string which is non null and empty In-Reply-To: <1175469766.979636.65020@e65g2000hsc.googlegroups.com> References: <1175469766.979636.65020@e65g2000hsc.googlegroups.com> Message-ID: <1175477279.632281.294500@e65g2000hsc.googlegroups.com> str != "" returns true if str is NOT the empty string. str is not None returns true if str is null (or None as it's called in python). To check to make sure a string is nonnull and nonempty, do: str is not None and str != "" From kyosohma at gmail.com Tue Apr 24 10:36:55 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: 24 Apr 2007 07:36:55 -0700 Subject: Would You Write Python Articles or Screencasts for Money? In-Reply-To: References: Message-ID: <1177425415.093386.86130@r3g2000prh.googlegroups.com> On Apr 24, 5:47 am, Michael Hoffman wrote: > Jeff Rush wrote: > > There is discussion by the Python Software Foundation of offering cash > > bounties or perhaps periodic awards to the "best of" for magazine articles, > > video/screencast clips and such. > > > If YOU would be swayed to get involved in producing content in exchange for > > cash, please speak up on the advocacy mailing list and also drop an email to > > Steve Holden , current champion of this idea and looking > > for encouragement. > > The very next thread I see after this one in this newsgroup is "work at > home from internet.and earn 4000USD every month." So you'll have to do > better than that for an adequate incentive. ;) > > Seems like a good idea, although I don't have any constructive > suggestions at this point. > -- > Michael Hoffman Sounds like a good idea to me as well. But I'll probably do some writing either way. Mike From Roka100 at gmail.com Sun Apr 22 00:27:48 2007 From: Roka100 at gmail.com (Jia Lu) Date: 21 Apr 2007 21:27:48 -0700 Subject: Flat DB seeking speed Message-ID: <1177216068.518970.29470@o5g2000hsb.googlegroups.com> Hello all I see there are lots of flat db or db-like modules in the standard python modules. What about the keywords seeking speed of them ? (I want to put about 10000 articles with 10000 IDs, and I can do searching keywords with them) The db-like modules are : dbm, gdbm, dbhash,anydbm, pickle(cPickle), shelve, marshal Any advice? Thank you. Jia Lu From gagsl-py2 at yahoo.com.ar Sun Apr 22 18:34:17 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sun, 22 Apr 2007 19:34:17 -0300 Subject: Vector classes References: <1177245233.573675.274580@n59g2000hsh.googlegroups.com> Message-ID: En Sun, 22 Apr 2007 09:33:53 -0300, Mizipzor escribi?: > During my coding Ive found two vector classes on the internet. Ive > modified them both a little but the do both have advantages and > disadvantages. > > vector1: http://rafb.net/p/4FVdh699.html > vector2: http://rafb.net/p/0KShGu30.html > > With 1, I can typ vec.x and vec.y, very nice. With 2, I need to do > vec.vals[0] and vec.vals[1], which makes my eyes bleed. [2] modifies the 2nd argument to __add__ and __sub__, not a good thing... The only advantage I can see over [1], is that it handles dimensions higher than 2. > But with 2, I can create a vector by supplying a list of numbers as > arguments. Same with the first one: coords = (1.2, 3.4) v1 = vector(*coords) There is even the "list" static method (not a good name!): coords = (1.2, 3.4) v1 = vector.list(coords) Anyway I'd remove the __ne__ and __lt__ methods (if you don't require it) and replace __hash__ with hash((self.x,self.y)) > Is there any way to combine the two? The ultimate would be if I > somehow could take vector2 and hook the member self.vals[0] to self.x > or something. You should try the other suggested classes, but if I had to choose among these two, I'd use the first. -- Gabriel Genellina From hlubenow2 at gmx.net Fri Apr 6 18:19:20 2007 From: hlubenow2 at gmx.net (hlubenow) Date: Sat, 07 Apr 2007 00:19:20 +0200 Subject: Hide the python-script from user Message-ID: <8ktie4-0i9.ln1@athlon.my> Hi, recently there was a thread about hiding the python-script from the user. The OP could use http://freshmeat.net/projects/pyobfuscate/ H. From louise.hoffman at gmail.com Thu Apr 26 21:10:13 2007 From: louise.hoffman at gmail.com (Louise Hoffman) Date: 26 Apr 2007 18:10:13 -0700 Subject: Dedicated CPU core for Python? In-Reply-To: <4630e90c$0$16272$88260bb3@free.teranews.com> References: <1177607759.916727.180950@t39g2000prd.googlegroups.com> <4630e90c$0$16272$88260bb3@free.teranews.com> Message-ID: <1177636213.350003.164430@c18g2000prb.googlegroups.com> > Are you talking about CPU affinity > (http://en.wikipedia.org/wiki/Processor_affinity) or an actual CPU that can > directory execute Python byte code? If the former, CPython only uses one > CPU core right now because it's threads are all internal, and do not spawn > system threads (IIRC). If the latter, I don't think that would work very > well because then, e.g., C extensions wouldn't work very well as they could > not be executed by a Python Byte-code CPU. Have I understood CPU affinity correct, that it is similar to SMP/ NUMA, only that I can force a process/thread to a cpu core? In regards to forcing the Python virtual machine (thanks Michael for the explanation=) ), is the problem that the "OS core" and the "VM core" would need to copy each others cache/exchange data too often? Hugs, Louise From oscartheduck at gmail.com Sun Apr 1 14:47:06 2007 From: oscartheduck at gmail.com (James) Date: Sun, 1 Apr 2007 12:47:06 -0600 Subject: capturing system exit status Message-ID: Hi folks, in a program I'm writing I have several commands I pass to the unix OS underneath the code. I want to perform error checking to make sure that the OS commands' exit gracefully, but I'm not seeing a simple python module to do this. The closest I can see is system(), as detailed here: http://www.python.org/doc/2.1.3/lib/os-process.html, but I can't formulate a way to use it. What I want is a simple if statement such that: if ExitStatusIsBad: sys.exit() else: go on to next code chunk James -------------- next part -------------- An HTML attachment was scrubbed... URL: From soren.skou.nielsen at gmail.com Mon Apr 16 07:24:48 2007 From: soren.skou.nielsen at gmail.com (Soren) Date: 16 Apr 2007 04:24:48 -0700 Subject: Boost Problem! Boost.Build not found In-Reply-To: <1176720813.976821.237610@w1g2000hsg.googlegroups.com> References: <1176719740.525832.132610@e65g2000hsc.googlegroups.com> <1176720813.976821.237610@w1g2000hsg.googlegroups.com> Message-ID: <1176722688.351441.303410@w1g2000hsg.googlegroups.com> On 16 Apr., 12:53, "Rob Wolfe" wrote: > Soren wrote: > > Unable to load Boost.Build: could not find "boost-build.jam" > > --------------------------------------------------------------- > > Attempted search from C:\boost\boost_1_33_1\libs\python\example > > \tutorial up to t > > he root and in these directories from BOOST_BUILD_PATH and BOOST_ROOT: > > C:\boost\boost_1_ > > 33_1. > > Please consult the documentation at 'http://www.boost.org'. > > > Can anyone please tell me what I am doing wrong?? Theres no tutorial > > on how to make a boost-build.jam file.. and as I understand I don't > > need one as long as I set BOOST_BUILD_PATH .. > > Try to create boost-build.jam file like this: > > # boost-build.jam > boost-build C:\boost\boost_1_33_1\tools\build\v1 ; > > -- > HTH, > Rob Hi Rob, Thanks for the answer! It did solve the error.. but produced a new one: C:\boost\boost_1_33_1\libs\python\example\tutorial>bjam -sTOOLS=vc-8_0 Unable to load Boost.Build: could not find build system. --------------------------------------------------------- C:\boost\boost_1_33_1\libs\python\example\boost-build.jam attempted to load the build system by invoking 'boost-build C:/boost/boost_1_33_1/tools/build/v1 ;' but we were unable to find "bootstrap.jam" in the specified directory or in BOOST_BUILD_PATH (searching C:\boost\boost_1_33_1, C:/boost/ boost_1_33_1/t ools/build/v1). What is bootstrap.jam? .. Haven't seen that one in the short tutorial... Thanks alot!, Soren From whamil1 at entergy.com Wed Apr 11 10:49:56 2007 From: whamil1 at entergy.com (Hamilton, William ) Date: Wed, 11 Apr 2007 09:49:56 -0500 Subject: passing class by reference does not work?? In-Reply-To: <1176301439.769248.247720@y5g2000hsa.googlegroups.com> Message-ID: <588D53831C701746A2DF46E365C018CE01D2CA6D@LITEXETSP001.etrsouth.corp.entergy.com> > -----Original Message----- > From: python-list-bounces+whamil1=entergy.com at python.org [mailto:python- > list-bounces+whamil1=entergy.com at python.org] On Behalf Of wswilson > Sent: Wednesday, April 11, 2007 9:24 AM > To: python-list at python.org > Subject: passing class by reference does not work?? > > Here is my code: > > class A(): > val = 0 > > def b(item, a): > a.val = a.val + 1 > return item + a.val > > def c(): > d = [1, 2, 3] > print [b(item, A()) for item in d] > > c() > > I expected this to output [2, 4, 6]. However, it outputs [2, 3, 4] > which is not what I wanted. I thought that if I passed the A() > instance in my list comprehension in c(), then the changes I made to > a.val in b() would be reflected in the A() instance next time the list > comprehension called b(). But, obviously that is not happening. I'm > kinda new at python so I may be missing something obvious here. > > Any suggestions? A() is not the class A. It calls the constructor of class A, returning an instance. If you change that line to: print [b(item, A) for item in d] you'll get the output you expected. --- -Bill Hamilton whamil1 at entergy.com From kyosohma at gmail.com Thu Apr 5 16:29:52 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: 5 Apr 2007 13:29:52 -0700 Subject: grandparent method with super In-Reply-To: <20070405161939.694d51a1@localhost> References: <20070405161939.694d51a1@localhost> Message-ID: <1175804992.189096.225300@d57g2000hsg.googlegroups.com> On Apr 5, 3:19 pm, Martin Manns wrote: > Hi, > > I have a class structure as follows and I would like to invoke the > method A.m() from D.m > > class A(object): > def m(self): > class B(A): > def m(self): > class C(A): > def m(self): > class D(B,C): > def m(self): > # Call A.m with super? > > I have readhttp://www.python.org/download/releases/2.2/descrintro/but > I am still stuck. > > Thanks in advance > > Martin I'm not sure if this is what you want, but it's my best guess: class A(object): def m(self): print "I'm the original" class B(A): def m(self): print 'B class here' class C(A): def m(self): print 'C class here' class D(B,C): def m(self): x = A() x.m() temp = D() temp.m() Mike From robert.rawlins at thinkbluemedia.co.uk Fri Apr 27 07:38:57 2007 From: robert.rawlins at thinkbluemedia.co.uk (Robert Rawlins - Think Blue) Date: Fri, 27 Apr 2007 12:38:57 +0100 Subject: what python technology for my app? In-Reply-To: <4631dc06$0$15457$426a74cc@news.free.fr> References: <4631dc06$0$15457$426a74cc@news.free.fr> Message-ID: <005701c788c0$a4aeb580$ee0c2080$@rawlins@thinkbluemedia.co.uk> Just thought I'd make a little suggestion about this, I don?t know how strict you want to be with the web development side of things, but I'm a web developer by trade and have recently started using python for my non-web type applications. If you're looking for a web based server side solution, then you can't go wrong with Adobe ColdFusion. Its and incredibly powerful and scalable development platform and yet supports a simple tag based language which makes life very easy when getting started, and yet will support much more complex OOP methodology with a whole myriad of frameworks, orm's and object factories. For a quick 'run down' of its features take a look at the simple tutorials on the adobe site, they'll demonstrate how easy it is to achieve even quite complex tasks like PDF creation, animated statistical charts an all sorts. As CF is a JAVA based technology you get the power of J2EE platform and its perfectly multi platform playing nicely with linux, unix, sun, windows or whatever server environment you wish to run it on. Just my two pence, I'm a big CF fan so my opinions are no doubt bias, but might be worth you taking a look. http://www.adobe.com/uk/products/coldfusion/ Pay attention to the 'ColdFusion Demos' at the bottom right of the main column. Rob -----Original Message----- From: python-list-bounces+robert.rawlins=thinkbluemedia.co.uk at python.org [mailto:python-list-bounces+robert.rawlins=thinkbluemedia.co.uk at python.org] On Behalf Of Bruno Desthuilliers Sent: 27 April 2007 12:19 To: python-list at python.org Subject: Re: what python technology for my app? Chris a ?crit : > I have an database containing lots of numerical data. I want to write a > browser based interface that will allow selection of various key > parameters and yield tables, plots and/or printouts of the data > according to the selections. Ultimately I want this to run on an > intranet so that others can get access via their browsers. > > The application is for in-house use only and not likely to have more > than a few users at any one time. I've managed to hack out enough > understanding of sql and sqlAlchemy over the last couple of days to > create and access an sqlite3 based database for my data. This seems to > suit my purposes for now. Now for a front end and some simple > distribution over a network. > > I have written some small Wxpython & matplotlib apps for data analysis > and display but I'm not sure how these would work in a browser based > world, or even if they are appropriate. wxPython being a GUI toolkit, it's of course not really appropriate for a web-based solution (and yes, this is an understatement). I don't have any experience with matplotlib, but according to the project's FAQ, this shouldn't be a problem: http://matplotlib.sourceforge.net/faq.html#BATCHMODE > > Any advice on what technologies I should be looking at for this? Python > based naturally, and hopefully simple and lightweight. I'm not a > programmer by trade and that's not what I really get paid for but I've > learned to love python and its myriad of modules for all the data > analysis work I need to do. If I can throw something moderately > functional together in a week or two (along with all the learning that > entails) If you don't have any experience with web programming, it might take a bit more time. > I'll be happy. Pylons (http://pylonshq.com) and turbogears are two great web frameworks. Both support SQLAlchemy. My own favourite is Pylons, but you should try both and choose the one that better fits your brain. > btw - Platform needs to be windows because that's what on my desk. Python is mostly platform independant. HTH -- http://mail.python.org/mailman/listinfo/python-list From rocky.bernstein at gmail.com Sat Apr 7 09:36:15 2007 From: rocky.bernstein at gmail.com (rocky.bernstein at gmail.com) Date: 7 Apr 2007 06:36:15 -0700 Subject: Getting Stack Trace on segfault In-Reply-To: <1175914148.105951.164250@b75g2000hsg.googlegroups.com> References: <1175914148.105951.164250@b75g2000hsg.googlegroups.com> Message-ID: <1175952975.726084.35350@d57g2000hsg.googlegroups.com> After a night's rest, I was able to add a function trace to pydb, command option --fntrace, short option -F, and set/show command "fntrace". It's still a little bit funky. (Hey, I didn't get *that* good of a rest). But it's out there in pydb's CVS in case folks want to try it. Also, following an idea given in the recipe, I've extended the 'Call' and 'Return' indicators so that we list the current stack level. For "Return" we'll also list the return value (or at least a repr() of it for strings and scalars) and/or return type. What's a little odd here is that levels from the debugger are included in the nesting count. So the top-level in the user program will be greater than 1. It's possible there will be another release around the time of the next ipython release since there is better coordination between the two with respect to colorizing lines of code. On Apr 6, 10:49 pm, "rocky.bernst... at gmail.com" wrote: > On Apr 6, 8:13 am, James Stroud wrote: > > > > > Hello All, > > > The built-in mac osx vecLib is segfaulting in some cases--A very fun > > fact to find out the hard way over two nights of work. I also spent an > > embarrassing amount of time figuring out just where. Although I'm in > > quite a self-congratulatory mood right now, in the future, I feel like I > > could save a lot of time by coercing the interpreter to spew forth > > method calls to stderr. Is this possible? > > > I would hope to produce something hauntingly reminiscent of > > > [] my_function > > [my_function] another_function > > [my_function -> another_function] yet_a_deeper_function > > > Presentation, of course, is irrelevant. > > > I read the docs onpdb, but it did not seem to do what I want--unless, > > of course, I missed something. > > > James > > pydb (http://bashdb.sf.net0has the ability to do noninteractive line > tracing. Seehttp://bashdb.sourceforge.net/pydb/pydb/lib/subsubsection-set.html > or the showmedo demo. It would be kind of neat to extend this to allow > for method/fn tracing. Alas the simple hack I tried, didn't work > because of code obscurities. (The code could stand to use a rewrite.) From johann at rocholl.net Sun Apr 1 06:52:09 2007 From: johann at rocholl.net (Johann C. Rocholl) Date: Sun, 1 Apr 2007 12:52:09 +0200 Subject: [Python-Dev] Python 3000 PEP: Postfix type declarations In-Reply-To: References: Message-ID: <8233478f0704010352q342e365eg467a1daa44c89766@mail.gmail.com> Brilliant! On 4/1/07, Georg Brandl wrote: > def foo${LATIN SMALL LETTER LAMBDA WITH STROKE}$(x${DOUBLE-STRUCK CAPITAL C}$): > return None${ZERO WIDTH NO-BREAK SPACE}$ > > This is still easy to read and makes the full power of type-annotated Python > available to ASCII believers. +1 J From gagsl-py2 at yahoo.com.ar Tue Apr 10 15:48:50 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 10 Apr 2007 16:48:50 -0300 Subject: Problem with getting an option value References: <10292-66264@sneakemail.com> Message-ID: En Tue, 10 Apr 2007 11:23:37 -0300, Lucas Malor <80xuuxk02 at sneakemail.com> escribi?: > Peter Otten wrote: >> Lucas Malor wrote: >>> >>> The problem is options is an instance, so options."delete", for >>> example, >>> is wrong; I should pass options.delete . How can I do? >> >> Use getattr(): > > Thank you. Do you know also if I can do a similar operation with > functions? I want to select with a string a certain get() function of > ConfigParser: > > if type == "int" : > funcname = "getint" > elif type == "bool" : > funcname = "getboolean" > etc. > > How can I invoke the funcion with its name in a string? Methods are searched the same way as "data" attributes, so you can apply the same technique. A first try would be (assuming cfg is a ConfigParser instance): if datatype == "int": funcname = "getint" elif datatype == "bool": funcname = "getboolean" func = getattr(cfg, funcname) value = func(section, option) (Using "type" as variable name is not a good idea - you are hiding the builtin "type".) You can even write it as: if datatype == "int": func = cfg.getint elif datatype == "bool": func = cfg.getboolean value = func(section, option) cfg.getint, by example, is a reference to the getint method of ConfigParser - bound to the cfg instance, and ready to be used as any other function. It's the same as getattr(cfg, "getint") > PS: your answers had not arrived to my mail account. Is because I'm > using a disposal address? Or simply it's because I'm not registered to > the list? I cannot tell for P. Otten, but many people (almost all, perhaps...) respond only to the list, so you may want to subscribe to it, or periodically check the last messages in some way. The list is mirrored back and forth with a newsgroup, and you can read it thru a web interfase (Google groups or gmane.org, by example). Anyway, I've noticed some problems with the posted messages; I'm using gmane news and some messages come out of order, or very delayed, or never at all (I've seen replies to messages, and not the original ones). -- Gabriel Genellina From mail at timgolden.me.uk Thu Apr 19 06:48:21 2007 From: mail at timgolden.me.uk (Tim Golden) Date: Thu, 19 Apr 2007 11:48:21 +0100 Subject: Helpbook and CHM In-Reply-To: <1176979477.204864.72900@n59g2000hsh.googlegroups.com> References: <1176979477.204864.72900@n59g2000hsh.googlegroups.com> Message-ID: <462748F5.7020006@timgolden.me.uk> Teja wrote: > how to generate CHM files in Boa(Python)??? http://www.rutherfurd.net/software/rst2chm/index.html TJG From rowen at cesmail.net Fri Apr 6 13:36:42 2007 From: rowen at cesmail.net (Russell E. Owen) Date: Fri, 06 Apr 2007 10:36:42 -0700 Subject: Welch essential for learning Tkinter well? References: <46151818.6080302@codebykevin.com> Message-ID: In article <46151818.6080302 at codebykevin.com>, Kevin Walzer wrote: > James Stroud wrote: > >This begs the > > question, is anyone truly an expert in Tkinter? > > Frederick Lundh is, if anyone is. > > http://www.pythonware.com/library/tkinter/introduction/index.htm (outdated) > http://effbot.org/tkinterbook/ (new but incomplete) I agree that this is an excellent resource. I find Welch's book and the on-line tcl/tk help very helpful for Tkinter programming--especially some of the more obscure details. But to use either of these resources comfortably you must learn the basics of Tkinter first (including understanding the simple mapping between Tkinter and Tcl/Tk). For learning the basics of Tkinter I suggest the links that Kevin listed above and/or Alex Martelli's "Python in a Nutshell" (an excellent reference in any case). Grayson's book is another reasonable alternative (and includes enough reference material to keep you from having to refer to the tcl/tk documentation very often). -- Russell From kay.schluehr at gmx.net Sun Apr 1 03:41:50 2007 From: kay.schluehr at gmx.net (Kay Schluehr) Date: 1 Apr 2007 00:41:50 -0700 Subject: Shed Skin Python-to-C++ Compiler 0.0.21, Help needed In-Reply-To: <1175376373.241744.6220@y80g2000hsf.googlegroups.com> References: <576vhbF2ca1guU1@mid.individual.net> <1175376373.241744.6220@y80g2000hsf.googlegroups.com> Message-ID: <1175413310.295953.230840@e65g2000hsc.googlegroups.com> On Mar 31, 11:26 pm, "Luis M. Gonz?lez" wrote: > On Mar 31, 8:38 am, Bjoern Schliessmann > > > 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. > I think he should be taken very seriously. Indeed. The only serious problem from an acceptance point of view is that Mark tried to solve the more difficult problem first and hung on it. Instead of integrating a translator/compiler early with CPython, doing some factorization of Python module code into compilable and interpretable functions ( which can be quite rudimentary at first ) together with some automatically generated glue code and *always have a running system* with monotone benefit for all Python code he seemed to stem an impossible task, namely translating the whole Python to C++ and created therefore a "lesser Python". I do think this is now a well identified anti-pattern but nothing that can't be repaired in this case - from what I understand. However, speaking on my part, I don't make my hands dirty with C++ code unless I get paid *well* for it. This is like duplicating my job in my sparetime. No go. Otherwise it wouldn't be a big deal to do what is necessary here and even extend the system with perspective on Py3K annotations or other means to ship typed Python code into the compiler. From steve at holdenweb.com Tue Apr 10 09:00:13 2007 From: steve at holdenweb.com (Steve Holden) Date: Tue, 10 Apr 2007 09:00:13 -0400 Subject: Hosting Companies: Help for Python Users? In-Reply-To: <%WySh.11628$M.6973@news-server.bigpond.net.au> References: <%WySh.11628$M.6973@news-server.bigpond.net.au> Message-ID: <461B8A5D.6020204@holdenweb.com> Neil Hodgson wrote: > Steve Holden: > >> Dennis Lee Beiber: >> >> > Too many 3rd-party modules still aren't available in 2.5 >> > versions for my tastes... >> >> This applies particularly (though not exclusively) to the Windows >> platform, for various reasons -- the most common one is that Linux >> developers frequently don't have a Windows machine available to help >> them test their builds and ensure that distributions are available. >> >> I am trying to address this problem, initially by making hosted Windows >> machines available for use as buildbots. > > I'd like to see this integrated in the Cheese Shop. I recently > released a small extension class and provided a source distribution and > a single binary for Python 2.5 on Windows. While I have the compilers > needed for building back to 1.5, most people don't and even when you do > it is complex to set up an environment for each version to compile > successfully. > Well, that's a great idea but it's ambitious. I'm not sure how we could give access to all the developers of Cheese Shop packages who would like to define a Windows build. Your skills and knowledge could clearly be valuable here. > It would be great if you could upload a source distribution and mark > it as containing files that need compilation for each version - or a > subset of versions if you know it requires particular features. Then the > compilation is farmed out to machines set up for each Python version and > when the compilation is finished, a status display shows the set that > are available and which failed along with a link to see the compilation > log. A unit test could be optionally included in an upload that would > contribute to whether the build is marked good. > It would indeed be great, and this was my original grand conception. Given that it will all have to be supported by volunteer effort, though, I can't commit to providing these features much as I would like to see them available - much more is needed in the way of community support before we can advertise what's effectively a compile farm for each Python version (and then we would need to take the various different Windows-supported hardware architectures into account). Please don't think I am trying to pour cold water on your enthusiasm, I really do believe that what you describe would be a great facility. I am just trying to temper the enthusiasm with a modest dose of reality. If we could get enough offers of hosted machines and buildbot management I would love to see this come to fruition. 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 nospam at invalid.com Tue Apr 3 20:52:17 2007 From: nospam at invalid.com (Jack) Date: Tue, 3 Apr 2007 17:52:17 -0700 Subject: Where to find pywin32/win32all for Python 1.5.2? Message-ID: I searched around but could not find win32all source or binaries for earlier versions of Python. Don't ask me why but I have to use Python 1.5.2 in this project :) The sourceforget page only has latest versions. ActiveState does not even have 1.5.2 for download. Is it still available somewhere? Thanks! From gagsl-py2 at yahoo.com.ar Fri Apr 27 19:51:34 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: 27 Apr 2007 16:51:34 -0700 Subject: Memory addressing In-Reply-To: <1177715277.592511.296990@h2g2000hsg.googlegroups.com> References: <1177702902.156596.52510@n35g2000prd.googlegroups.com> <1177703803.179501.95300@n35g2000prd.googlegroups.com> <1177715277.592511.296990@h2g2000hsg.googlegroups.com> Message-ID: <1177717894.219673.141920@c35g2000hsg.googlegroups.com> On 27 abr, 20:07, castiro... at gmail.com wrote: > That's what we need: a CopyMemory() routine. See the copy and pickle modules. -- Gabriel Genellina From Florian.Lindner at xgm.de Mon Apr 2 12:22:42 2007 From: Florian.Lindner at xgm.de (Florian Lindner) Date: Mon, 02 Apr 2007 18:22:42 +0200 Subject: RSS feed parser Message-ID: Hello, I'm looking for python RSS feed parser library. Feedparser http://feedparser.org/ does not seem to maintained anymore. What alternatives are recommendable? Thanks, Florian From apardon at forel.vub.ac.be Tue Apr 24 09:25:44 2007 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 24 Apr 2007 13:25:44 GMT Subject: Tutorial creates confusion about slices References: Message-ID: On 2007-04-24, Michael Hoffman wrote: > Antoon Pardon wrote: > >>> Submit a patch if you want it changed. I'm sure your valuable >>> insights will greatly improve the quality of the python documentation. >> >> Fat chance, if they reason like you. > > I don't think that Michael Bentley is the documents maintainer. Are you > trying to pick a fight with him or improve the docs? I try not to pick fights. But I don't try very hard to avoid them either. > Personally, I do not think of slices in the way this tutorial suggests, > but I think taking it out without replacement would not help. If you > want to add a more accurate replacement, I think that would be better > received than just saying that the section should be removed. Even more > so if you provide it in the form of a patch. Well people could suggest that instead of just removing the section there should be a replacement and then we could discuss how such a replacement should look like. I just started with what I see as a problem and one possible fix. Now I guess that if people would agree that there is problem but don't agree with my fix they would comment on my fix. Instead most reactions seem to suggest there is not really a problem. Now I am not going to waste my time writing a patch for something that doesn't seem to be considered a problem. -- Antoon Pardon From m.elston at advantest-ard.com Tue Apr 10 19:23:20 2007 From: m.elston at advantest-ard.com (Mark Elston) Date: Tue, 10 Apr 2007 16:23:20 -0700 Subject: About Eggs In-Reply-To: <87k5wkj77z.fsf@smsnet.pl> References: <131nspji8t6559b@corp.supernews.com> <87k5wkj77z.fsf@smsnet.pl> Message-ID: <131o6tpj6qsdudf@corp.supernews.com> * Rob Wolfe wrote (on 4/10/2007 1:38 PM): > Mark Elston writes: > >> This is probably a *really* stupid question but... >> I have looked at all the documentation I have for 2.4.3 >> and all the docs I can download for 2.5 and I simply cannot >> find anything, anywhere that documents what egg files are. >> >> I have read posts referring to them and have been able to >> deduce that they are some form of zip file for the distribution >> of modules but beyond that I cannot find *any* docs for them >> anywhere. > > Start here: > http://peak.telecommunity.com/DevCenter/setuptools > Thanks to Rob and Mike for their answers. I will bookmark these pages immediately. Mark From timr at probo.com Tue Apr 24 02:52:14 2007 From: timr at probo.com (Tim Roberts) Date: Tue, 24 Apr 2007 06:52:14 GMT Subject: python cgi problem with textarea References: <1177222084.696307.128620@n59g2000hsh.googlegroups.com> <1177247362.014926.12500@n76g2000hsh.googlegroups.com> <1177254110.057238.315240@o5g2000hsb.googlegroups.com> <1177315259.401721.62040@l77g2000hsb.googlegroups.com> Message-ID: <17ar23drof4nsdhcdoa0jconcb6sjuljk0@4ax.com> placid wrote: >On Apr 23, 1:01 am, Adrian Smith wrote: >> On Apr 22, 10:09 pm, placid wrote: >> >> > i just tried it and its working. here it is >> >> >http://yallara.cs.rmit.edu.au/~bevcimen/form.html >> >> > maybe the internal server error is because mod_python isn't installed >> > assuming your using Apache as your web server >> >> Yeah, but it wouldn't work *at all* in that case, would it? ATM it >> seems to work as long as the textarea input has no spaces. > >it doest work because the "space" character isnt interpreted >correctly, you need to change the space characters too   What??? Did you even read the problem description? -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From jorgen.maillist at gmail.com Thu Apr 12 03:38:06 2007 From: jorgen.maillist at gmail.com (Jorgen Bodde) Date: Thu, 12 Apr 2007 09:38:06 +0200 Subject: sqlite3 question Message-ID: <11e49df10704120038v17df487au402a6d9f88e28568@mail.gmail.com> Hi all, I am using sqlite3 in python, and I wonder if there is a way to know if there are valid rows returned or not. For example I have a table song with one entry in it. The ID of that entry is 1, so when I do; >>> r = c.execute('select * from song where id = 1') >>> for s in r: ... print s ... (1, u'Spikedrivers Blues', u'Mississippi John Hurt') That works. But when I can't restore the row by e.g. an ID that does not exist, I cannot see any method in 'r' (which is a SQLite.Cursor) that can tell me if I have rows. As explained in the help, r.rowcount does not give a valid result because it can't determine how many rows are restored in advance. All I can think of is a 'crappy' construction where I use the iterator to see if there was something in there, but surely, there must be a better way to know? >>> r = c.execute('select * from song where id = 2') >>> notfound = True >>> for s in r: ... notfound = False ... print s >>> if notfound: ... print 'No rows' I am pretty new with Python, maybe there are some properties of an iterator / sqlite3 I am not aware of that can tell me how many rows are there? With regards, - Jorgen From mail at microcorp.co.za Sat Apr 7 04:28:03 2007 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Sat, 7 Apr 2007 10:28:03 +0200 Subject: Why NOT only one class per file? References: <1175721799.714907.52770@o5g2000hsb.googlegroups.com> Message-ID: <012e01c778f1$1f8f87a0$03000080@hendrik> "Bart Willems" wrote: > Steven D'Aprano wrote: > > On Wed, 04 Apr 2007 14:23:19 -0700, Chris Lasher wrote: > > > >> A friend of mine with a programming background in Java and Perl places > >> each class in its own separate file in . I informed him that keeping > >> all related classes together in a single file is more in the Python > >> idiom than one file per class. He asked why, and frankly, his valid > >> question has me flummoxed. > > > > > > Hah! Writing one class per file is for wimps! When I program, I write one > > *method* per file, then import them and build the class at runtime. > > > > I have a friend who writes one *line* per file, then pulls them all > > together with exec(), but that's just being stupid. > > > > > > > I guess you're one of those sissies who uses EDLIN as an editor. > > REAL programmers use COPY CON: ... :) Naaah.. Real programmers fill in their coding sheets using indelible ink in their fountain pens, and then send them off to be punched and verified. None of this weak minded backspace stuff for us... - Hendrik From MassiveProng at thebarattheendoftheuniverse.org Tue Apr 17 18:43:02 2007 From: MassiveProng at thebarattheendoftheuniverse.org (MassiveProng) Date: Tue, 17 Apr 2007 15:43:02 -0700 Subject: retarded twits posting horseshit in technical groups References: <1176818165.135834.214220@y80g2000hsf.googlegroups.com> Message-ID: On 17 Apr 2007 06:56:05 -0700, thermate at india.com Gave us: >We know that... You're a fucking retard. From ejensen at visi.com Mon Apr 2 08:35:20 2007 From: ejensen at visi.com (Ed Jensen) Date: Mon, 02 Apr 2007 12:35:20 -0000 Subject: Problem with global variables Message-ID: <1311u48bqkehk24@corp.supernews.com> I'm having a vexing problem with global variables in Python. Please consider the following Python code: #! /usr/bin/env python def tiny(): bar = [] for tmp in foo: bar.append(tmp) foo = bar if __name__ == "__main__": foo = ['hello', 'world'] tiny() When I try to run this, I get: Traceback (most recent call last): File "./xtalk.py", line 11, in ? tiny() File "./xtalk.py", line 5, in tiny for tmp in foo: UnboundLocalError: local variable 'foo' referenced before assignment For some reason, Python can't see the global variable "foo" in the function tiny(). Why is that? If I change the code to this: #! /usr/bin/env python def tiny(): for tmp in foo: print tmp if __name__ == "__main__": foo = ['hello', 'world'] tiny() I get this: hello world All of a sudden, tiny() can see the global variable "foo". Very confusing! Why is it that tiny() sometimes can, and sometimes can't, see the global variable "foo"? If anyone can enlighten me about what's going on with Python and global variables, I would appreciate it! From datamonkey.ryan at gmail.com Thu Apr 19 23:26:05 2007 From: datamonkey.ryan at gmail.com (datamonkey.ryan at gmail.com) Date: 19 Apr 2007 20:26:05 -0700 Subject: List of Objects In-Reply-To: References: <1177037915.042476.153190@n76g2000hsh.googlegroups.com> Message-ID: <1177039565.284967.210090@n76g2000hsh.googlegroups.com> These methods work. I didn't think I could create a list of objects like that, however, I stand corrected. Thanks for your quick (and helpful) responses! On Apr 19, 11:22 pm, Steven D'Aprano wrote: > On Thu, 19 Apr 2007 19:58:35 -0700, datamonkey.ryan wrote: > > Howdy, a (possibly) quick question for anyone willing to listen. > > I have a question regarding lists and Classes; I have a class called > > "gazelle" with several attributes (color, position, etc.) and I need > > to create a herd of them. I want to simulate motion of individual > > gazelles, but I don't want to have to go through and manually update > > the position for every gazelle (there could be upwards of 50). I was > > planning to create an array of these gazelle classes, and I was going > > to iterate through it to adjust the position of each gazelle. That's > > how I'd do it in C, anyway. However, Python doesn't support pointers > > and I'm not quite sure how to go about this. Any help you can provide > > would be greatly appreciated. > > First method: create 1000 different gazelles: > > list_of_beasties = [] > for i in xrange(1000): # create 1000 beasties > args = (i, "foo", "bar") # or whatever > list_of_beasties.append(Gazelle(args)) > > Second method: create 1000 different gazelles by a slightly different > method: > > list_of_beasties = [Gazelle((i, "foo", "bar")) for i in xrange(1000)] > > Third method: create 1000 copies of a single gazelle: > > list_of_beasties = [Gazelle(args)] * 1000 > # probably not useful... > > Forth method: create identical gazelles, then modify them: > > list_of_beasties = [Gazelle(defaults) for i in xrange(1000)] > for i, beastie in enumerate(xrange(1000)): > list_of_beasties[i] = modify(beastie) > > -- > Steven D'Aprano From jeba.ride at gmail.com Wed Apr 18 09:18:23 2007 From: jeba.ride at gmail.com (Clement) Date: 18 Apr 2007 06:18:23 -0700 Subject: Help on Shelve.... In-Reply-To: References: <1176810739.765433.47470@n59g2000hsh.googlegroups.com> Message-ID: <1176902303.347071.57300@p77g2000hsh.googlegroups.com> On Apr 17, 5:52 pm, Michael Bentley wrote: > On Apr 17, 2007, at 6:52 AM, Clement wrote: > > > Can i useShelvefor storing large amount of data around 6GB.. Is it > > stable...? if any problems come, can i retrive the document.. > > Do you know for sure your filesystem handles files that big? I am using NTFS that can hold more that 500GB of data From newsgroups at nospam.nowire.org Mon Apr 2 05:34:40 2007 From: newsgroups at nospam.nowire.org (=?ISO-8859-1?Q?Thomas_Kr=FCger?=) Date: Mon, 02 Apr 2007 11:34:40 +0200 Subject: Question about text in Python In-Reply-To: <4610c366$0$15022$5a62ac22@per-qv1-newsreader-01.iinet.net.au> References: <4610c366$0$15022$5a62ac22@per-qv1-newsreader-01.iinet.net.au> Message-ID: Steve schrieb: > I've created a Python program that a user enteres one line of text which > will then create an acronym from that text. > > What I want to add to the program is the abilty to rerun this process > (where the user enteres another line of text) until the user has had > enough and enters a blank line which would then end the program. You can do this with a while loop. If the user enters a blank line you can break out of the loop: while true: (some code) if not line: break Thomas From rrr at ronadam.com Fri Apr 13 11:15:40 2007 From: rrr at ronadam.com (Ron Adam) Date: Fri, 13 Apr 2007 10:15:40 -0500 Subject: Pydoc Rewrite Discussion at doc-sig list. Message-ID: <461F9E9C.2070901@ronadam.com> If anyone is interested in participating in discussing the details of the PyDoc rewrite/refactoring I've been working on, a discussion is being started on the doc-sig list. Doc-Sig at python.org The goal of this discussion will be to get it to a final finished form so a patch can be submitted and a final discussion can take place on the python-dev list at a later date. Thanks and Regards, Ron Adam From aleax at mac.com Sat Apr 21 17:57:30 2007 From: aleax at mac.com (Alex Martelli) Date: Sat, 21 Apr 2007 14:57:30 -0700 Subject: Suggestion: str.itersplit() References: <1177160280.784224.53460@b58g2000hsg.googlegroups.com> <1177190327.236981.153770@o5g2000hsb.googlegroups.com> Message-ID: <1hwxdg3.1f6csl210x2igN%aleax@mac.com> Dustan wrote: > On Apr 21, 7:58 am, Dustan wrote: > > >From my searches here, there is no equivalent to java's > > > > StringTokenizer in python, which seems like a real shame to me. > > > > However, str.split() works just as well, except for the fact that it > > creates it all at one go. I suggest an itersplit be introduced for > > lazy evaluation, if you don't want to take up recourses, and it could > > be used just like java's StringTokenizer. > > > > Comments? > > If anybody could inform me on how to get my hands on the python source > code, I might even be able to come up with an example of how it could > be implemented. I have no idea how to unzip that tgz or tar.bz2 file > on a windows machine, though (and that's not from lack of trying). Top search hit for windows tar is , but its contents suggest using instead (it has "the ability to direcly create and manipulate .tar, .tar.gz, tar.bz2, .zip, .gz and .bz2 archives, understands the most-used options of GNU Tar, and is also much faster; for most purposes it is to be preferred to GNU Tar", to quote). Alex From gandalf at designaproduct.biz Thu Apr 5 13:42:31 2007 From: gandalf at designaproduct.biz (Laszlo Nagy) Date: Thu, 05 Apr 2007 19:42:31 +0200 Subject: Windows service and pyc files In-Reply-To: References: <1175709094.352514.64920@y66g2000hsf.googlegroups.com> <46151D34.50608@designaproduct.biz> Message-ID: <46153507.5080502@designaproduct.biz> > With a bit of guessing, I think I've found what's happening. > Since you don't provide a value for stdin, None is used. Inside > subprocess.py, method _get_handles, line 670, GetStdHandle *may* return > None; in that case _make_inheritable fails. > If you print the value of p2cread in line 670 I bet you'll get None. > The fix is to test for None in _make_inheritable (line 720): > > if handle is not None: > return DuplicateHandle(...) > > (else return None, implicit) > > >> When I call spawn() from an application, it works just fine. Any ideas? >> > > According to http://msdn2.microsoft.com/en-us/library/ms683231.aspx > GetStdHandle may return NULL (translated to None in Python) when invoked > from a service with no redirected standard handles. From an application, > there is no problem. > > Please try the simple fix above to comfirm it works; I'll submit a patch > if that's the case. > Yes, it fixed the problem. Please submit the patch. Thank you! Laszlo From eric.mahurin at gmail.com Sun Apr 8 19:31:17 2007 From: eric.mahurin at gmail.com (Eric Mahurin) Date: 8 Apr 2007 16:31:17 -0700 Subject: Debugging doctest failures Message-ID: <1176075077.909944.41400@y66g2000hsf.googlegroups.com> Noob here. Just got into python a little over a week ago... One of the (unique?) things I really like about python is the concept of doctesting. But, now I want more! Here's what I'd like to see: * easy debugging. As soon as there is a failure (unexpected exception or mismatch), drop down into the debugger in a way to isolates the bug down to the nearest test/example as much as possible. * integrated with code coverage. I'd like to be targetting 100% code coverage with doctests. With full (or a target) coverage, no additional coverage data would be needed and otherwise something that tells which lines don't have coverage would be good. A way to mark code that you don't care about covering (typically error conditions - at least initially) would also be good. * whether stdout and/or sterr should be checked. If anybody has any pointers to what I should be doing with doctest or another framework I should be using (zope.testing?), I'd appreciate it. I made a crack at the first one above (easy debugging). Here is a little script I came up with. You just give modules you want to doctest as arguments. When a normal failure occurs, it will restart the test (with verbose) and set traces before each example. When an unexpected exception occurs, it pulls up the debugger with the backtrace and continuing will restart the test just like a normal failure. I've used this a bit and it allows me to find bugs very fast without changing the code a bit for debug purposes. The implementation below is quite hacky and tied to the implementation within the doctest module. #!/usr/bin/env python import doctest import sys def trace_runner(reporter,arg3) : import sys tb = sys.exc_info()[2] while tb.tb_next : tb = tb.tb_next l = tb.tb_frame.f_locals out, test, example, arg3 = l['out'], l['test'], l['example'], l[arg3] runner = doctest.DocTestRunner(verbose=True, optionflags=doctest.NORMALIZE_WHITESPACE) getattr(runner,reporter)(out, test, example, arg3) for e in test.examples : e.source = 'pdb.set_trace();' + e.source exec 'import pdb' in test.globs return runner mod_names = [] for mod_name in sys.argv[1:] : __import__(mod_name,globals(),locals()) mod_names.append(mod_name) finder = doctest.DocTestFinder() runner = doctest.DebugRunner(optionflags=doctest.NORMALIZE_WHITESPACE) try : for mod_name in mod_names : mod = sys.modules.get(mod_name) for test in finder.find(mod, mod_name) : runner.run(test) except doctest.DocTestFailure : runner = trace_runner('report_failure','got') runner.run(test) except doctest.UnexpectedException, err : runner = trace_runner('report_unexpected_exception','exc_info') import pdb pdb.post_mortem(err.exc_info[2]) runner.run(test) From wadnerk at gmail.com Thu Apr 5 19:12:55 2007 From: wadnerk at gmail.com (Kiel W.) Date: 5 Apr 2007 16:12:55 -0700 Subject: Prevent Modification of Script? In-Reply-To: References: <1175735097.856840.177510@e65g2000hsc.googlegroups.com> <1175743177.489242.214700@w1g2000hsg.googlegroups.com> Message-ID: <1175814775.104630.244890@d57g2000hsg.googlegroups.com> On Apr 5, 2:45 am, Thomas Bellman wrote: > No. To be blunt, it is an effect of you not knowing enough about > security. Blunt is good =) I ask question because I don't know. I appreciate your honesty. From bbxx789_05ss at yahoo.com Thu Apr 19 17:12:31 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: 19 Apr 2007 14:12:31 -0700 Subject: What makes an iterator an iterator? In-Reply-To: References: <1hwr9pv.13v4ci6106qn0aN%aleax@mac.com> <1176936067.315082.17970@y80g2000hsf.googlegroups.com> <1hws6rd.u0a6hd78fhhpN%aleax@mac.com> <1176961515.450458.189530@p77g2000hsh.googlegroups.com> Message-ID: <1177017151.900443.71450@o5g2000hsb.googlegroups.com> On Apr 19, 5:37 am, Steve Holden wrote: > > It's nothing to do with the name lookup. Alex mentioned that to remind > us that the magic "double-under" names are looked up on the type rather > than the instance... P.next() vs. type(P).next() Where is the "double-under" name? From bearophileHUGS at lycos.com Fri Apr 13 18:04:09 2007 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 13 Apr 2007 15:04:09 -0700 Subject: Any way to refactor this? In-Reply-To: References: <461fe75c$0$11278$c3e8da3@news.astraweb.com> Message-ID: <1176501849.191790.264160@b75g2000hsg.googlegroups.com> James Stroud: > Probably best is to code the parameters as > a set of tuples and iterate over them. I agree. Before: def _create_3D_xhatches(...pass more parameters here...): for x in xrange(-axis_length, axis_length + 1): if x == 0: continue visual.cylinder(pos=(x, -hatch_length, 0), axis=(0, hatch_length*2, 0), radius=hatch_radius) visual.cylinder(pos=(x, 0, -hatch_length), axis=(0, 0, hatch_length*2), radius=hatch_radius) visual.cylinder(pos=(-hatch_length, x, 0), axis=(hatch_length*2, 0, 0), radius=hatch_radius) visual.cylinder(pos=(0, x, -hatch_length), axis=(0, 0, hatch_length*2), radius=hatch_radius) visual.cylinder(pos=(-hatch_length, 0, x), axis=(hatch_length*2, 0, 0), radius=hatch_radius) visual.cylinder(pos=(0, -hatch_length, x), axis=(0, hatch_length*2, 0), radius=hatch_radius) And after: def _create_3D_xhatches(...pass more parameters here...): hl2 = hatch_length * 2 for x in xrange(-axis_length, axis_length + 1): if x == 0: continue params = [[(x, -hatch_length, 0), (0, hl2, 0)], [(x, 0, -hatch_length), (0, 0, hl2)] [(-hatch_length, x, 0), (hl2, 0, 0)], [(0, x, -hatch_length), (0, 0, hl2)], [(-hatch_length, 0, x), (hl2, 0, 0)], [(0, -hatch_length, x), (0, hl2, 0)]] for pos, axis in params: visual.cylinder(pos=pos, axis=axis, radius=hatch_radius) More cleaning can be done. Bye, bearophile From nagle at animats.com Mon Apr 9 17:59:47 2007 From: nagle at animats.com (John Nagle) Date: Mon, 09 Apr 2007 14:59:47 -0700 Subject: MySQL Insert Unicode Problem In-Reply-To: <1176138716.534847.209890@n59g2000hsh.googlegroups.com> References: <1176138716.534847.209890@n59g2000hsh.googlegroups.com> Message-ID: erikcw wrote: > Hi, > > I'm trying to insert some data from an XML file into MySQL. However, > while importing one of the files, I got this error: > > Traceback (most recent call last): > File "wa.py", line 304, in ? > main() > File "wa.py", line 257, in main > curHandler.walkData() > File "wa.py", line 112, in walkData > self.cursor.execute(*sql) #try multi-execute to speed up query. > File "build/bdist.linux-i686/egg/MySQLdb/cursors.py", line 151, in > execute > File "build/bdist.linux-i686/egg/MySQLdb/connections.py", line 247, > in literal > File "build/bdist.linux-i686/egg/MySQLdb/connections.py", line 185, > in unicode_literal > UnicodeEncodeError: 'latin-1' codec can't encode character u'\u20ac' > in position 28: ordinal not in range(256) > > What do I need to change to make this work? > > Thanks! > Erik MySQL does Unicode quite well, but Unicode is not the default. Getting all the defaults right is a pain. It looks like you have MySQL, or MySQLdb, or the connection between them in "latin1" mode. The database server has to support Unicode, which is a build option and a version issue. Do a SHOW VARIABLES LIKE "character_set%" Ideally, you should see the character sets for client, connection, database, results, server, and system all as "utf8". You might not, given the problem you're having, but that can be dealt with. Those are just defaults. The field you're storing into has to be in Unicode mode, which can either be set explicitly with CREATE TABLE or can come from the default for the server, database, or table. It's usually easier to use UTF8 for everything in the database, unless you have legacy database issues. Try this in SQL: ALTER DATABASE yourdatabasename DEFAULT CHARACTER SET UTF8; If you can't execute that statement, assuming you have permissions to do so, then your MySQL isn't configured to support Unicode. (If you're on a shared server, you might have to use ALTER TABLE instead; you may not have ALTER DATABASE permission.) Once you've done that, all tables created after that point will have Unicode text fields. You can also use ALTER TABLE on existing tables, if you need to convert their format, or create tables with DEFAULT CHARACTER SET UTF8. The connection to the MySQL server has to be in Unicode mode. This is separate from the server's mode and the table mode. And MySQLdb has to be in Unicode mode, which is separate from the connection mode. MySQLdb doesn't know what the server is doing; you have to tell it what you want. Try something like this to connect to the server: db = MySQLdb.connect(host="localhost", use_unicode = True, charset = "utf8", user=username, passwd=password, db=database) You need to specify both "use_unicode" (which sets the mode in MySQLdb), and "charset" (which sets the connection mode). Once you've put all the components into these modes, you should have end-to-end Unicode database capability. John Nagle From kay.schluehr at gmx.net Sun Apr 15 10:02:22 2007 From: kay.schluehr at gmx.net (Kay Schluehr) Date: 15 Apr 2007 07:02:22 -0700 Subject: proposed PEP: iterator splicing In-Reply-To: References: <7xirbyi5d7.fsf_-_@ruckus.brouhaha.com> Message-ID: <1176645742.313412.3120@o5g2000hsb.googlegroups.com> On Apr 15, 10:23 am, Anton Vredegoor wrote: > I'm currently also fascinated by the new generator possibilities, for > example sending back a value to the generator by making yield return a > value. What I would like to use it for is when I have a very long > generator and I need just a slice of the values. That would mean running > through a loop, discarding all the values until the generator is in the > desired state and only then start doing something with the output. > Instead I would like to directly set or 'wind' -like a file- a generator > into some specific state. Maybe you should start by developing a design pattern first and publish it in the Cookbook. I have the fuzzy impression that the idea you are after, requires more powerfull control structures such as delimited continuations that are beyond ths scope of Pythons simple coroutines. Kay From pete.forman at westerngeco.com Tue Apr 24 07:43:16 2007 From: pete.forman at westerngeco.com (Pete Forman) Date: Tue, 24 Apr 2007 12:43:16 +0100 Subject: Python's handling of unicode surrogates References: <1177051493.468698.176740@b75g2000hsg.googlegroups.com> <4629591a$0$13629$9b622d9e@news.freenet.de> <1177122874.524447.85130@p77g2000hsh.googlegroups.com> Message-ID: <4pn6576z.fsf@wgmail2.gatwick.eur.slb.com> Ross Ridge writes: > The Unicode standard doesn't require that you support surrogates, > or any other kind of character, so no you wouldn't be lying. +1 on Ross Ridge's contributions to this thread. If Unicode is processed using UTF-8 or UTF-32 encoding forms then there are no surrogates. They would only be present in UTF-16. CESU-8 is strongly discouraged. A Unicode 16-bit string is allowed to be ill-formed as UTF-16. The example they give is one string that ends with a high surrogate code point and another that starts with a low surrogate code point. The result of concatenation is a valid UTF-16 string. The above refers to the Unicode standard. In Python with narrow Py_UNICODE a unicode string is a sequence of 16-bit Unicode code points. It is up to the programmer whether they want to specially handle code points for surrogates. Operations based on concatenation will conform to Unicode, whether or not there are surrogates in the strings. -- Pete Forman -./\.- Disclaimer: This post is originated WesternGeco -./\.- by myself and does not represent pete.forman at westerngeco.com -./\.- the opinion of Schlumberger or http://petef.port5.com -./\.- WesternGeco. From amaccormack at gmail.com Mon Apr 2 06:29:13 2007 From: amaccormack at gmail.com (amaccormack at gmail.com) Date: 2 Apr 2007 03:29:13 -0700 Subject: Parallel ping problems python puzzler Message-ID: <1175509753.092714.281990@n76g2000hsh.googlegroups.com> I wrote a quick script to check the "up-ness" of a list of machines, and timeout after 1 second. However, with a lot of timeouts, the script takes a logn time, so I thought to parallelise it. However, as soon as I do, the pings that do not get a response never return, so their threads block forever and the program hangs. Environment is: Python 2.3.3 (#1, Jan 5 2005, 15:24:27) [GCC 3.3.3 (SuSE Linux)] on linux2 (running on SLES9) pinglist=[] class testit(Thread): def __init__ (self,ip): Thread.__init__(self) self.ip = ip self.status = -1 def run(self): # -w 1 option to ping makes it timeout after 1 second pingcmd="/bin/ping -c 2 -q -i 0.3 -w 1 %s >/dev/null" % ip self.status = os.system(pingcmd) def serping(ip): pingcmd="/bin/ping -c 2 -q -i 0.3 -w 1 %s >/dev/null" % ip os.system(pingcmd) for machname in machlist: #serping(machname) # this works in serial, and works current = testit(machname) # this works in parallel, and doesn't work pinglist.append(current) current.start() # Wait for all pings to pong for pingle in pinglist: pingle.join() Anyone got an idea what's going on? Is it the way that the ping timeout works in SuSE is not thread-safe? From S.Mientki-nospam at mailbox.kun.nl Wed Apr 18 16:16:52 2007 From: S.Mientki-nospam at mailbox.kun.nl (Stef Mientki) Date: Wed, 18 Apr 2007 22:16:52 +0200 Subject: Future Python Gui? In-Reply-To: References: <1176859699.906386.326720@b75g2000hsg.googlegroups.com> <1176863948.526051.186210@n76g2000hsh.googlegroups.com> <1176909848.455264.174730@e65g2000hsc.googlegroups.com> Message-ID: > The rumours on "problems installing GUI toolkits" are greatly exagerated Not at all !! As an experienced computer user, I yesterday installed a well known Python package on a clean winXP machine, and it costed me be about 1.5 .. 2 hours !! There are always unexpected situations, I think software developers call them "new features" ;-) cheers, Stef Mientki From shane at hathawaymix.org Thu Apr 26 14:38:59 2007 From: shane at hathawaymix.org (Shane Hathaway) Date: Thu, 26 Apr 2007 12:38:59 -0600 Subject: wtf In-Reply-To: <9d7816d30704261135ta3cf99n854519e843bdd6e7@mail.gmail.com> References: <9d7816d30704261135ta3cf99n854519e843bdd6e7@mail.gmail.com> Message-ID: <4630F1C3.1030602@hathawaymix.org> Sergiy wrote: > print 1 / 2 > print -1 / 2 > > 0 > -1 > > correct? Yes. It works like the floor() function. >>> import math >>> math.floor(1.0 / 2) 0.0 >>> math.floor(-1.0 / 2) -1.0 Shane From attn.steven.kuo at gmail.com Thu Apr 12 01:15:23 2007 From: attn.steven.kuo at gmail.com (attn.steven.kuo at gmail.com) Date: 11 Apr 2007 22:15:23 -0700 Subject: python regular expression help In-Reply-To: References: <138221.90891.qm@web58906.mail.re1.yahoo.com> Message-ID: <1176354923.264709.291150@b75g2000hsg.googlegroups.com> On Apr 11, 9:50 pm, "Gabriel Genellina" wrote: > En Wed, 11 Apr 2007 23:14:01 -0300, Qilong Ren > escribi?: > > > Thanks for reply. That actually is not what I want. Strings I am dealing > > with may look like this: > > s = 'a = 4.5 b = 'h' 'd' c = 4.5 3.5' > > What I want is > > a = 4.5 > > b = 'h' 'd' > > c = 4.5 3.5 > > That's a bit tricky. You have LHS = RHS where RHS includes all the > following text *except* the very next word before the following = (which > is the LHS of the next expression). Or something like that :) > > py> import re > py> s = "a = 4.5 b = 'h' 'd' c = 4.5 3.5" > py> r = re.compile(r"\w+\s*=\s*.*?(?=\w+\s*=|$)") > py> for item in r.findall(s): > ... print item > ... > a = 4.5 > b = 'h' 'd' > c = 4.5 3.5 > Another way is to use split: import re lhs = re.compile(r'\s*(\b\w+\s*=)') for s in [ "a = 4 b =3.4 5.4 c = 4.5", "a = 4.5 b = 'h' 'd' c = 4.5 3.5"]: tokens = lhs.split(s) results = [tokens[_] + tokens[_+1] for _ in range(1,len(tokens), 2)] print s print results -- Regards, Steven From rNOSPAMon at flownet.com Mon Apr 23 12:51:24 2007 From: rNOSPAMon at flownet.com (Ron Garret) Date: Mon, 23 Apr 2007 09:51:24 -0700 Subject: Select weirdness References: Message-ID: In article , Jean-Paul Calderone wrote: > Twisted does this out of the box, for what it's worth. Thanks. I will look at that. rg From gagsl-py2 at yahoo.com.ar Mon Apr 9 13:12:22 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 09 Apr 2007 14:12:22 -0300 Subject: Using/finding ODBC and DBI References: <09042D621CD4AA479C678463F3A646D0F7466B@sottemail1.ent.ad.cognos.com> Message-ID: En Mon, 09 Apr 2007 10:12:20 -0300, Boudreau, Emile escribi?: > Hello all, I'm trying to use ODBC and DBI but I don't seem to have the > right files on my system. I have looked around and I can't find what I'm > looking for. From the information I have been able to find these are not odbc is included in the pywin32 package, available from SourceForge -- Gabriel Genellina From steve at holdenweb.com Fri Apr 6 15:48:05 2007 From: steve at holdenweb.com (Steve Holden) Date: Fri, 06 Apr 2007 15:48:05 -0400 Subject: Newbie Question about sequence multiplication In-Reply-To: References: <6cOdnVFCLMXxuYnbnZ2dnUVZ_rCsnZ2d@comcast.com> <1175726885.373889.23850@y80g2000hsf.googlegroups.com> <1175739226.176472.96280@p77g2000hsh.googlegroups.com> Message-ID: <4616A3F5.4050908@holdenweb.com> Scott wrote: [...] > > Now when suggesting books, keep in mind that, that while I'm new to Python > (and programming in general) I'm able to grasp difficult concepts as long > as I have enough detail as to why it is the way it is. For instance I'm, by > experience and nature, a computer technician and communications specialist. > I've studied, everything from childrens walkie talkie to deep space > satalittes back to how computers talk (which is why I'm here now trying to > learn the language of computers). And all that just because I have a > unquenchable desire to know. SO, with that all said, the more details the > better. If you have a book with 4 chapters on functions......I want to read > it. > > Any help would be greatly appreciated. As I've said, this is something that > I feel I have to know. > "Dive into Python" is probably the best free read about Python for programmers. It takes you in deep much more quickly that the tutorial, but if you can understand it you develop quite a sophisticated understanding of the language in a fairly short time. 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 andrew.jefferies at gmail.com Thu Apr 26 08:14:00 2007 From: andrew.jefferies at gmail.com (andrew.jefferies at gmail.com) Date: 26 Apr 2007 05:14:00 -0700 Subject: File not read to end In-Reply-To: References: <1177522730.327454.121120@s33g2000prh.googlegroups.com> Message-ID: <1177589640.804485.149390@c18g2000prb.googlegroups.com> On Apr 25, 3:03 pm, Facundo Batista wrote: > andrew.jeffer... at gmail.com wrote: > > My log is around 200,000 lines but it is stopping at line 26,428. I > > checked that line and there aren't any special characters. > > Are you in Windows? Just in case, put "rb" as the mode of the open. > > Regards, > > -- > . Facundo > . > Blog:http://www.taniquetil.com.ar/plog/ > PyAr:http://www.python.org/ar/ I am running Windows (Vista). I tried the "rb" as you suggested but it didn't solve the problem. Thanks for the suggestion. --Andrew From m.yanowitz at kearfott.com Tue Apr 10 07:12:53 2007 From: m.yanowitz at kearfott.com (Michael Yanowitz) Date: Tue, 10 Apr 2007 07:12:53 -0400 Subject: Breaking up Strings correctly: In-Reply-To: <1176175701.971632.164360@l77g2000hsb.googlegroups.com> Message-ID: <000d01c77b61$2ee32230$0d7d12ac@kearfott.com> -----Original Message----- From: python-list-bounces+m.yanowitz=kearfott.com at python.org [mailto:python-list-bounces+m.yanowitz=kearfott.com at python.org]On Behalf Of Adam Atlas Sent: Monday, April 09, 2007 11:28 PM To: python-list at python.org Subject: Re: Breaking up Strings correctly: On Apr 9, 8:19 am, "Michael Yanowitz" wrote: > Hello: > > I have been searching for an easy solution, and hopefully one > has already been written, so I don't want to reinvent the wheel: Pyparsing is indeed a fine package, but if Paul gets to plug his module, then so do I! :) I have a package called ZestyParser... a lot of it is inspired by Pyparsing, actually, but I'm going in a different direction in many areas. (One major goal is to be crazily dynamic and flexible on the inside. And it hasn't failed me thus far; I've used it to easily parse grammars that would make lex and yacc scream in horror.) Here's how I'd do it... from ZestyParser import * from ZestyParser.Helpers import * varName = Token(r'\$(\w+)', group=1) varVal = QuoteHelper() | Int sp = Skip(Token(r'\s*')) comparison = sp.pad(varName + CompositeToken([RawToken(sym) for sym in ('=','<','>','>=','<=','!=')]) + varVal) #Maybe I should "borrow" PyParsing's OneOf idea :) expr = ExpressionHelper(( comparison, (RawToken('(') + Only(_top_) + RawToken(')')), oper('NOT', ops=UNARY), oper('AND'), oper('OR'), )) Now you can scan for `expr` and get a return value like [[['IP', '=', '127.1.2.3'], ['AX', '<', 15]], [['IP', '=', '127.1.2.4'], ['AY', '! =', 0]]] (for the example you gave). Note that this example uses several features that won't be available until the next release, but it's coming soon. So Michael, though you'd still be able to parse this with the current version, the code wouldn't look as nice as this or the Pyparsing version. Maybe just add it to your watchlist. :) - Adam -- Thanks for your and Gerard's and Gabriel's responses. I guess what I was looking for was something simpler than parsing. I may actually use some of what you posted. But I am hoping that if given a string such as: '((($IP = "127.1.2.3") AND ($AX < 15)) OR (($IP = "127.1.2.4") AND ($AY != 0)))' something like split(), where I can pass it something like [' AND ', ' OR ', ' XOR '] will split the string by AND, OR, or XOR. BUT split it up in such a way to preserve the parentheses order, so that it will split on the outermost parenthesis. So that the above string becomes: ['OR', '(($IP = "127.1.2.3") AND ($AX < 15))', '(($IP = "127.1.2.4") AND ($AY != 0))'] No need to do this recursively, I can repeat the process, however if I wish on each string in the list and get: ['OR', ['AND', '($IP = "127.1.2.3")', '($AX < 15)'], ['AND', '($IP = "127.1.2.4")', '($AY != 0)']] Can this be done without parsers? Perhaps with some variation of re or split. Has something like this already been written? Thanks in advance: From steve at REMOVEME.cybersource.com.au Wed Apr 4 05:08:04 2007 From: steve at REMOVEME.cybersource.com.au (Steven D'Aprano) Date: Wed, 04 Apr 2007 19:08:04 +1000 Subject: how to remove multiple occurrences of a string within a list? References: <1175624433.206953.214290@n59g2000hsh.googlegroups.com> <1175626905.957243.301870@w1g2000hsg.googlegroups.com> <1175637235.783612.45980@o5g2000hsb.googlegroups.com> <1175673563.212459.322290@y66g2000hsf.googlegroups.com> Message-ID: On Wed, 04 Apr 2007 00:59:23 -0700, 7stud wrote: > On Apr 3, 3:53 pm, "bahoo" wrote: >> > target = "0024" >> > l = ["0024", "haha", "0024"] >> >> >> > for index, val in enumerate(l): >> > if val==target: >> > del l[index] >> >> > print l >> >> This latter suggestion (with the for loop) seems to be buggy: if there >> are multiple items in the list "l" equal to "target", then only the >> first one will be removed! >> >> Thanks anyways. > > Prove it. Try replacing l = ["0024", "haha", "0024"] with l = ["0024", "0024", "haha"] and re-running the code. Actually, the description of the bug isn't quite right. The behaviour of the for loop isn't defined -- sometimes it will work, sometimes it won't, depending on how many items there are, and which of them are equal to the target. The reason it is buggy is that it is deleting items from the same list it is trying to enumerate over. The only safe way to do that is to iterate over the list backwards, only deleting items you've already seen and won't go over again: for i in range(len(my_list), -1, -1)): if condition: del my_list[i] I don't think reversed() will help you here, but I can't check for sure because I've only got Python 2.3 on this system. -- Steven D'Aprano From DustanGroups at gmail.com Sun Apr 8 16:32:46 2007 From: DustanGroups at gmail.com (Dustan) Date: 8 Apr 2007 13:32:46 -0700 Subject: RFC: Assignment as expression (pre-PEP) In-Reply-To: <1hw8tyt.o3fd3h1fbcjfpN%aleax@mac.com> References: <1175802680.021987.39220@p77g2000hsh.googlegroups.com> <1176035258.355141.221290@d57g2000hsg.googlegroups.com> <1hw8tyt.o3fd3h1fbcjfpN%aleax@mac.com> Message-ID: <1176064366.868136.90300@b75g2000hsg.googlegroups.com> On Apr 8, 10:56 am, a... at mac.com (Alex Martelli) wrote: > Dustan wrote: > > >>> class Wrapper(object): > > def __init__(self, obj): > > self.obj = obj > > def getit(self): > > return self.obj > > def setit(self, obj): > > self.obj = obj > > return obj > > Yeah, that's substantialy the same approach I posted as a Python > Cookbook recipe almost six years ago, see > . Indeed, I did discover that in my copy of the Python Cookbook some time ago. Perhaps I should have noted that. > My specific use case for that recipe was when using Python to code a > "reference algorithm" found in a book, so that deep restructuring was > unwanted -- a similar but opposite case is using Python to explore > prototype algorithms that would later be recoded e.g. in C (here, too, > you don't really want to refactor the Python code to use dictionaries > "properly", so assign-and-test is handy). > > Alex From laurent.pointal at wanadoo.fr Sun Apr 1 13:43:04 2007 From: laurent.pointal at wanadoo.fr (Laurent Pointal) Date: Sun, 01 Apr 2007 19:43:04 +0200 Subject: reverse engineering Excel spreadsheet References: <460fd6d0.0@entanet> Message-ID: <460fedfd$0$25945$ba4acef3@news.orange.fr> Duncan Smith wrote: > Hello, > I am currently implementing (mainly in Python) 'models' that come > to me as Excel spreadsheets, with little additional information. I am > expected to use these models in a web application. Some contain many > worksheets and various macros. > > What I'd like to do is extract the data and business logic so that I can > figure out exactly what these models actually do and code it up. An > obvious (I think) idea is to generate an acyclic graph of the cell > dependencies so that I can identify which cells contain only data (no > parents) and those that depend on other cells. If I could also extract > the relationships (functions), then I could feasibly produce something > in pure Python that would mirror the functionality of the original > spreadsheet (using e.g. Matplotlib for plots and more reliable RNGs / > statistical functions). > > The final application will be running on a Linux server, but I can use a > Windows box (i.e. win32all) for processing the spreadsheets (hopefully > not manually). Any advice on the feasibility of this, and how I might > achieve it would be appreciated. > > I assume there are plenty of people who have a better knowledge of e.g. > COM than I do. I suppose an alternative would be to convert to Open > Office and use PyUNO, but I have no experience with PyUNO and am not > sure how much more reliable the statistical functions of Open Office > are. At the end of the day, the business logic will not generally be > complex, it's extracting it from the spreadsheet that's awkward. Any > advice appreciated. TIA. Cheers. > > Duncan As I remember, there is a documentation about Excel documents in xlrd package. And with that, you dont need to use Excel via COM to find data in the document. http://www.lexicon.net/sjmachin/xlrd.htm May also look at pyExcelerator http://sourceforge.net/projects/pyexcelerator/ From apardon at forel.vub.ac.be Wed Apr 18 06:07:12 2007 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 18 Apr 2007 10:07:12 GMT Subject: Python Feature Request: Allow changing base of member indices to 1 References: <1176546465.632410.52630@w1g2000hsg.googlegroups.com> <1176579205.948684.171640@q75g2000hsh.googlegroups.com> Message-ID: On 2007-04-14, Paddy wrote: > On Apr 14, 11:27 am, samj... at gmail.com wrote: >> This is like the previous one. Please check for sanity and approve for >> posting at python-dev. >> >> I would like to have something like "option base" in Visual Basic. >> IIRC it used to allow me to choose whether 0 or 1 should be used as >> the base of member indices of arrays. In Python, the same can be used >> with strings, lists, tuples etc. >> >> This would mean: >> foo = "foo" >> => foo[1] == 'f' >> >> foo = ['foo', 'bar', 'spam' ] >> => foo[1] == 'foo' >> >> foo = ('spam', 'eggs') >> => foo[1] == 'spam' >> >> For convenience it should also affect the range function so that: >> >> range(3) = [1, 2, 3] >> >> because this is often used where arrays would be used in VB. >> >> Finally, when the programmer does not specify his choice of base at >> the beginning of the program, the current behaviour of using 0 as base >> should continue so that there is no problem with backward >> compatibility. > > Here is a document giving good reasons for indexing to start at > zero, as in Python. I find he just picks the reasons he agrees with. If you pick your values as a <= i <= b it has the advantage that the bounds are explicit. No need to add or substract 1 from one of the values to get the exact boundis. Now how much weight you want to give this characteristic is open for debate but the fact that it isn't even mentioned doesn't give me much confidence in the author's ability to weight all the pro's and con's. > http://www.cs.utexas.edu/users/EWD/transcriptions/EWD08xx/EWD831.html > The author has done a bit: > http://en.wikipedia.org/wiki/Dijkstra > > Having more than one index start point would be a maintenance > nightmare best avoided. (It can be done in Perl). It was never a problem when I still programmed in Pascal. -- Antoon Pardon From larry.bates at websafe.com Mon Apr 2 13:12:25 2007 From: larry.bates at websafe.com (Larry Bates) Date: Mon, 02 Apr 2007 12:12:25 -0500 Subject: Is any way to split zip archive to sections? In-Reply-To: References: Message-ID: <46113979.6000906@websafe.com> Tim Williams wrote: > On 30/03/07, Durumdara wrote: >> 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)? >> > > If you are iterating through a list of files to be backed up, and > adding them to a ZIP one-by-one then you could use something like this > which adds each file until the zip is over 15mb - then it closes the > ZIP and creates the next one. > > Not tested or optimised :) > --------------------------------------------------------------------------------------------------- > > import zipfile > > archive_num = 1 > outfile = zipfile.ZipFile('/zips/archive%s.zip' % archive_num, "w") > zsize = 0 > > for full_name in filelist: > full_name_path = os.path.join(full_name, full_path) > > if zsize > 15728640 : # 15mb > outfile.close() > archive_num += 1 > outfile = zipfile.ZipFile('/zips/archive%s.zip' % archive_num, "w") > zsize= 0 > > outfile.write( full_name_path , full_name_path , > zipfile.ZIP_DEFLATED) # add the file > zsize += outfile.getinfo(full_name_path).compress_size # get > compressed size of file > > outfile.close() You can do slightly better as following: change to (not tested): import os import stat import zipfile archive_num = 1 outfile = zipfile.ZipFile('/zips/archive%s.zip' % archive_num, "w") zsize = 0 for full_name in filelist: full_name_path = os.path.join(full_name, full_path) if outfile.fp.tell() > 15728640: # 15mb outfile.close() archive_num += 1 outfile = zipfile.ZipFile('/zips/archive%s.zip' % archive_num, "w") outfile.write(full_name_path,full_name_path,zipfile.ZIP_DEFLATED) There is still a couple of "issues": 1) Files larger than 15Mb may not be able to be compressed to fall below the limit. 2) If you are near the 15Mb limit and the next file is very large you have the same problem. -Larry From maxime.p at gmail.com Sun Apr 1 18:37:09 2007 From: maxime.p at gmail.com (Ulysse) Date: 1 Apr 2007 15:37:09 -0700 Subject: Launch script on Linux using Putty Message-ID: <1175467029.572354.138930@y66g2000hsf.googlegroups.com> Hello, I have a python script which runs all the time (using of library threading). I would like this scipt to run on a remote linux Os using Putty. The problem is, when I close Putty command line window running on my Win PC, the python script stops to run too. I tried to use cron tables instead. By setting the time and restart cron process, but it's not practical. Do you know the right way to do this ? Regards From michele.simionato at gmail.com Thu Apr 26 11:55:14 2007 From: michele.simionato at gmail.com (Michele Simionato) Date: 26 Apr 2007 08:55:14 -0700 Subject: Scheduler Module Help In-Reply-To: References: <25547.4246260293$1177577452@news.gmane.org> Message-ID: <1177602914.339195.163920@u32g2000prd.googlegroups.com> Robert Rawlins - Think Blue wrote:> Hello Guys, > > > I'm using the sched module to create a set of functions that run every > > 10 or 20 minutes whilst the application is running, however it would > > seem that the moment I run scheduler.run() it prevents any other > > operations in my application from running, its sits dormant until it > > runs the scheduled functions. sched is meant to be used with threads. A probably better alternative is to use an asynchronous framework (i.e. Twisted or a GUI) and use the native techniques to schedule function calls. Michele Simionato From m.yanowitz at kearfott.com Mon Apr 9 08:19:00 2007 From: m.yanowitz at kearfott.com (Michael Yanowitz) Date: Mon, 9 Apr 2007 08:19:00 -0400 Subject: Breaking up Strings correctly: Message-ID: <003901c77aa1$414765f0$0d7d12ac@kearfott.com> Hello: I have been searching for an easy solution, and hopefully one has already been written, so I don't want to reinvent the wheel: Suppose I have a string of expressions such as: "((($IP = "127.1.2.3") AND ($AX < 15)) OR (($IP = "127.1.2.4") AND ($AY != 0))) I would like to split up into something like: [ "OR", "(($IP = "127.1.2.3") AND ($AX < 15))", "(($IP = "127.1.2.4") AND ($AY != 0))" ] which I may then decide to or not to further split into: [ "OR", ["AND", "($IP = "127.1.2.3")", "($AX < 15)"], ["AND", "(($IP = "127.1.2.4")", ($AY != 0))"] ] Is there an easy way to do this? I tried using regular expressions, re, but I don't think it is recursive enough. I really want to break it up from: (E1 AND_or_OR E2) and make that int [AND_or_OR, E1, E2] and apply the same to E1 and E2 recursively until E1[0] != '(' But the main problem I am running to is, how do I split this up by outer parentheseis. So that I get the proper '(' and ')' to split this upper correctly? Thanks in advance: Michael Yanowitz From soarnil at gmail.com Sat Apr 7 21:53:13 2007 From: soarnil at gmail.com (soarnil) Date: 7 Apr 2007 18:53:13 -0700 Subject: How to control files such as windows update program? Message-ID: <1175997193.271155.144030@d57g2000hsg.googlegroups.com> I hope i could write a program to execute a range of ".exe" files. When there is a "Licensing Agreement", the program can choose "Accept",then click "Next" until "Finish".Or maybe it could use some function to finish this rather then really "click" the buttons. From jmg3000 at gmail.com Sun Apr 29 22:08:03 2007 From: jmg3000 at gmail.com (jmg3000 at gmail.com) Date: 29 Apr 2007 19:08:03 -0700 Subject: Chart drawing tool in python In-Reply-To: <1177897942.532255.317000@y80g2000hsf.googlegroups.com> References: <1177897942.532255.317000@y80g2000hsf.googlegroups.com> Message-ID: <1177898883.069300.129570@h2g2000hsg.googlegroups.com> On Apr 29, 9:52 pm, "ying... at gmail.com" wrote: > Hi, > > In Perl, there is a GD module to draw custom chart. > > http://www-128.ibm.com/developerworks/opensource/library/os-perlgdcha... > > Can you please tell me if there is an equivalent library in python? > > Thank you. I've used PyChart in the past. Check out the Python wiki page on it to get started quickly. ---John From grante at visi.com Tue Apr 10 12:15:44 2007 From: grante at visi.com (Grant Edwards) Date: Tue, 10 Apr 2007 16:15:44 -0000 Subject: Check for keypress on Linux xterm ? References: <131m56dsgr7or38@corp.supernews.com> Message-ID: <131ne1g8eq7d060@corp.supernews.com> On 2007-04-10, hlubenow wrote: >>> My problem is, I don't want my program to wait for the >>> keypress. I just want to check, if a key is currently pressed >>> and if not, I'd like to continue with my program (like >>> "INKEY$" in some BASIC-dialects). >> >> The answer to this frequently asked question is actually in the FAQ: > > http://www.python.org/doc/faq/library.html#how-do-i-get-a-single-keypress-at-a-time > > You're answer is only less than half correct: > > Most of the given examples use something like > > c = sys.stdin.read(1) > > like my example does. This blocks input. read() will not block if the file has been set to non-blocking mode. That's what these two lines in the FAQ answer do: oldflags = fcntl.fcntl(fd, fcntl.F_GETFL) fcntl.fcntl(fd, fcntl.F_SETFL, oldflags | os.O_NONBLOCK) I do make mistakes, but before telling somebody he's wrong, it might be a good idea to actually try what he's suggested. ;) -- Grant Edwards grante Yow! Edwin Meese made me at wear CORDOVANS!! visi.com From mail at microcorp.co.za Sun Apr 1 11:07:45 2007 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Sun, 1 Apr 2007 17:07:45 +0200 Subject: Mastering Python (OT) References: <1174045298.826137.262890@o5g2000hsb.googlegroups.com><1174052358.486071.163280@e65g2000hsc.googlegroups.com><46018fd8$0$18018$426a74cc@news.free.fr><46091cdf$0$19664$426a74cc@news.free.fr> <000f01c771d2$2fc41940$03000080@hendrik> Message-ID: <003301c7746f$859d0300$03000080@hendrik> "Steve Holden" wrote: > Hendrik van Rooyen wrote: > > It comes out something like "Chum-lee", with the ch like chicken... > > > > (that's what I have heard - but who knows - It may have been > > a regional dialect, a case of the blind leading the blind, or > > someone pulling the piss..) > > > You have been correctly informed. It's one of the least intuitive names > in the English language. Oh No! - don't tell me there is worse - this is already enough to drive a saint to drink! I will have to move to "Hants"... : - ) - Hendrik From bearophileHUGS at lycos.com Sat Apr 14 06:45:01 2007 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 14 Apr 2007 03:45:01 -0700 Subject: list comparison help? In-Reply-To: <1176546175.099596.44140@w1g2000hsg.googlegroups.com> References: <1176546175.099596.44140@w1g2000hsg.googlegroups.com> Message-ID: <1176547501.333204.84300@w1g2000hsg.googlegroups.com> 7stud: > prefixes = [ "the", "this", "that", "da", "d", "is", "are", "r", > "you", "u"] > sentence = "what the blazes is the da this da this the" > sentence = sentence.split() > result = [word for word in sentence if word not in prefixes] > print result If prefixes becomes long enough (let's say > 20) then it's faster to use a set: nowords = [ "the", "this", "that", "da", "d", "is", "are", "r", "you", "u"] prefixes = set(nowords) Bye, bearophile From anton.vredegoor at gmail.com Wed Apr 25 07:50:08 2007 From: anton.vredegoor at gmail.com (Anton Vredegoor) Date: Wed, 25 Apr 2007 13:50:08 +0200 Subject: Would You Write Python Articles or Screencasts for Money? In-Reply-To: References: <462DCCE6.9060908@taupro.com> <1hx2dvj.10ek1v51noh1otN%aleax@mac.com> Message-ID: Antoon Pardon wrote: > On 2007-04-25, Anton Vredegoor wrote: >> Antoon Pardon wrote: >> >>>>> That's a good point, and also a valid reason for restricting the >>>>> voting community to PSF members. Thanks, Alex. >>>> So in order to avoid a suspicion of a conflict of interest you want to >>>> turn the whole thing into private property of the PSF? >>>> >>>> That is the most ridiculous suggestion I have ever >>> I kind of understand why they would want to do this. If you have >>> no limitations on who may vote, such a contest can easily turn >>> into a contest of who can mobilize the biggest clan of supporters. >> Sure, any democratic process can be derailed by a coordinated effort of >> people with a different mentality. To prevent such things by killing the >> democratic process oneself right at the beginning of a project is a >> peculiar way of avoiding this risk. > > As far as I understood the idea was to reward excellence. The process > to achieve this can be democratic, but in that case it is just a means > to an end. The democratic process was not an end itself. Yes, but this sub thread was about avoiding a suspicion of a conflict of interests. If this suspicion is to be avoided by just openly promoting the interests of the members of the PSF that is one hell of a way of solving the problem. A. From bdesth.quelquechose at free.quelquepart.fr Wed Apr 4 19:33:12 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Thu, 05 Apr 2007 01:33:12 +0200 Subject: calling super() In-Reply-To: References: <1175714555.413502.77390@o5g2000hsb.googlegroups.com> Message-ID: <46142cc9$0$14488$426a34cc@news.free.fr> John Clark a ?crit : > Yeah!!! One I can actually answer!!! > +1 QOTW From carsten at uniqsys.com Sat Apr 7 23:59:48 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Sat, 7 Apr 2007 22:59:48 -0500 Subject: tuples, index method, Python's design In-Reply-To: References: <1175867771.114540.61810@n76g2000hsh.googlegroups.com><1175884427.779950.267220@y80g2000hsf.googlegroups.com><1175953520.316208.241490@o5g2000hsb.googlegroups.com> Message-ID: <20070408035010.M46997@uniqsys.com> On Sun, 08 Apr 2007 02:40:52 GMT, Alan Isaac wrote > "Carsten Haese" wrote in message > news:mailman.6146.1175956040.32031.python-list at python.org... > > Adding useless features always makes a product worse. What's your use > > case for tuple.index? > [...] consider a game, > where the fixed set p of players have a fixed order. > A tuple is natural. Now for a player you want to > construct the opponents. If I had the index i it wd > be p[:i]+p[i+1:], but how to get the index? opponents = tuple(x for x in p if x is not current_player) -Carsten From bj_666 at gmx.net Mon Apr 16 12:01:40 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Mon, 16 Apr 2007 18:01:40 +0200 Subject: file resume References: <1176739022.736716.245950@y80g2000hsf.googlegroups.com> Message-ID: In <1176739022.736716.245950 at y80g2000hsf.googlegroups.com>, luca72 wrote: > if i have one file written in binary mode, how can i append others > binary data to this file after the its closure. > ex > my_file = open('blabal', 'wb') > then i write something and then > my_file.close() > now if i need to open it again and append other binary data how can i > proceed? Just open it in append mode: ``open('blablal', 'ab')`` Ciao, Marc 'BlackJack' Rintsch From martin at v.loewis.de Mon Apr 9 09:33:22 2007 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Mon, 09 Apr 2007 15:33:22 +0200 Subject: Unicode problem In-Reply-To: References: <1175975209.261304.183220@p77g2000hsh.googlegroups.com> <4619B124.6040707@v.loewis.de> Message-ID: <461A40A2.2010507@v.loewis.de> > BTW, any reason why an EncodedFile can't act like a Unicode > writer/reader object > if one of its encodings is explicitly set to None? AFAIU, that's not the intention of EncodedFile: instead, it is meant to do recoding. I find it a pretty useless API, and rather see it go away than being enhanced. Regards, Martin From aleax at mac.com Mon Apr 30 23:14:35 2007 From: aleax at mac.com (Alex Martelli) Date: Mon, 30 Apr 2007 20:14:35 -0700 Subject: relative import broken? References: <1hxa9x3.c0unyd1jw7vu9N%aleax@mac.com> <1hxcdkq.47p2r6beuctcN%aleax@mac.com> Message-ID: <1hxeg2v.1ct59rv3oyq87N%aleax@mac.com> Alan Isaac wrote: > "Alex Martelli" wrote in message > news:1hxcdkq.47p2r6beuctcN%aleax at mac.com... > > To me, it makes sense: if a module is top-level, and thus not part of a > > package (and __main__ in particular is always in that state), then > > saying "import from the current package" has no well defined meaning, > > because there IS no "current package". > > Thanks for the explanations. > I do not have an opinion because I have not really thought this through. > > One of the things I was hoping for, however, was for a less hackish way > for scripts bundled with a package to access the package modules. > > That is, suppose I have directory ``mypackage`` with subdirectory > ``scripts``. > What is the pretty way for the scripts to access ``mypackage`` without > assuming ``mypackage`` is in ``sys.path``? I don't know of any "pretty" way -- I'd do it by path manipulation (finding mypackage from os.path.abspath(__file__) and inserting its _parent_ directory in sys.path). Alex From sergei.minayev at gmail.com Fri Apr 6 06:12:51 2007 From: sergei.minayev at gmail.com (Sergei Minayev) Date: 6 Apr 2007 03:12:51 -0700 Subject: Storing of folder structure in SQL DB In-Reply-To: References: <1175774302.652656.285260@d57g2000hsg.googlegroups.com> Message-ID: <1175854371.476464.125540@d57g2000hsg.googlegroups.com> Amit Khemka: > On 5 Apr 2007 04:58:22 -0700, Sergei Minayev wrote: > > Hi All! > > Can you please help me with the following problem: > > I need to store a copy of local folders structure in MySQL database. > > I have chosen the following table structure for that: > > ------------------------------------------------ > > | id | id_uplink | folder_name | > > ------------------------------------------------ > > id - unique property of each folder. > > id_uplink - id of upper level folder is stored here (for example: if > > id of c:\test is 1, than id_uplink of c:\test\python equals 1). > > folder_name - name of folder. > > You see, i dont want to store the path list, but the structure. > > > > The question is how to implement that in Python. I easily made it in C+ > > + using recursion. But, unfortunately, I can't figure it out how to > > make it in python using os.walk function (or can you recommend smth. > > else???). :( Though it looks quite simple, but anyway. > > > > Best Regards, > > os.walk should be more than sufficient in your case. You can navigate > the directory structure and at each 'new' directory find its parents > id and assign a new-id to this 'new' directory. > > An Example: > > import os > root='/my/root/directory' > id =0 > tree={root:(-1, id)} > id+=1 > for path, dirs, files in os.walk(root): > for dir in dirs: > if not tree.has_key(path+'/'+dir): > tree[path+'/'+dir]=(tree[path][1], id) > id+=1 > > It stores ids as a tuple (parent_id, id) in a dictionary(tree). Should > be straight forward to modify to your requirements. Also you can make > the following code more efficient by saving/caching some lookups ! > > 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. Thanks! Your code example was really helpful! From bjourne at gmail.com Sat Apr 14 09:58:44 2007 From: bjourne at gmail.com (=?ISO-8859-1?Q?BJ=F6rn_Lindqvist?=) Date: Sat, 14 Apr 2007 15:58:44 +0200 Subject: Python Feature Request: Add the "using" keyword which works like "with" in Visual Basic In-Reply-To: <1176547372.584539.89170@q75g2000hsh.googlegroups.com> References: <1176547372.584539.89170@q75g2000hsh.googlegroups.com> Message-ID: <740c3aec0704140658l46de15bhb7562844c581925b@mail.gmail.com> Your idea isn't new and has already been discussed lots of time before. It was once planned to be implemented in py3k, but no longer is. One of the problems is that with a "using" statement, you always have to decide whether your code repeats some prefix enough times to use a "using" statement. Should you write: self.quit.action = self.bar self.quit.name = "End it" or should it be: using self.quit: .action = self.bar .name = "End it" ? Not having to bother with petty things like that is an advantage. Javascript has with-statements that are equivalent to your using-statements but from what I've seen most programmers avoid them. They don't increase readability one bit. You already can emulate the using statement like this: def using(obj, **kw): for key, val in kw.items(): setattr(obj, key, val) using(self.quit, action = self.bar, name = "End it") But I have never seen anyone do that, which I think, is a sign that nobody wants the feature. -- mvh Bj?rn From wojciech_mula at poczta.null.onet.pl.invalid Fri Apr 20 15:30:42 2007 From: wojciech_mula at poczta.null.onet.pl.invalid (=?ISO-8859-2?Q?Wojciech_Mu=B3a?=) Date: Fri, 20 Apr 2007 21:30:42 +0200 Subject: regular expression for parsing an html element In-Reply-To: <1177097164.906533.252830@d57g2000hsg.googlegroups.com> References: <1177097164.906533.252830@d57g2000hsg.googlegroups.com> Message-ID: abcd wrote: > My regex so far is: src=\"(.*)\" ....however the group in this case > would end up being, image/blah/a.jpg" id="ddddd">blah blah blah a>..... > > how can I tell the regex group (.*) to end when it gets to the first > " ? Use non-greedy matching, i.e. src=\"(.*?)\" (question mark after *.) See: http://docs.python.org/lib/re-syntax.html w. From jpiitula at ling.helsinki.fi Sun Apr 15 08:37:09 2007 From: jpiitula at ling.helsinki.fi (Jussi Piitulainen) Date: 15 Apr 2007 15:37:09 +0300 Subject: combination function in python References: <1176615838.830315.160210@b75g2000hsg.googlegroups.com> <1176629911.409257.149780@l77g2000hsb.googlegroups.com> Message-ID: Steven D'Aprano writes: > bearophileHUGS wrote: ... >> return factorial(n) // (factorial(k) * factorial(n-k)) > > That's a naive and slow implementation. For even quite small values > of n and k, you end up generating some seriously big long ints, and > then have to (slowly!) divide them. A better _definition_ of the binomial coefficient with upper index r and lower index k is (r * (r - 1) * ...) / (k * (k - 1) * ...) with k factors in both products. These are called falling factorial powers by Graham, Knuth and Patashnik. Their notation is to write n^k and k^k but with the exponent underlined; the latter is just k!, when k > 0. A straightforward implementation below. > A better implementation would be something like this: > > def binomial(n, k): > if not 0 <= k <= n: > return 0 > if k == 0 or k == n: > return 1 > # calculate n!/k! as one product, avoiding factors that > # just get canceled > P = k+1 > for i in xrange(k+2, n+1): > P *= i > # if you are paranoid: > # C, rem = divmod(P, factorial(n-k)) > # assert rem == 0 > # return C > return P//factorial(n-k) > > There's probably even a really clever way to avoid that final > division, but I suspect that would cost more in time and memory than > it would save. Here's one non-clever one for integers n, k that uses n^k / k^k (falling powers) with the smaller of k and n - k as lower index: def choose(n, k): if 0 <= k <= n: ntok = 1 ktok = 1 for t in xrange(1, min(k, n - k) + 1): ntok *= n ktok *= t n -= 1 return ntok // ktok else: return 0 From stewart.midwinter at gmail.com Thu Apr 12 00:38:57 2007 From: stewart.midwinter at gmail.com (midtoad) Date: 11 Apr 2007 21:38:57 -0700 Subject: What happened to http://www.pythonware.com/daily and http://mechanicalcat.net/pyblagg.html? In-Reply-To: <1176063723.883976.145570@d57g2000hsg.googlegroups.com> References: <1175957075.056246.15120@l77g2000hsb.googlegroups.com> <1176063723.883976.145570@d57g2000hsg.googlegroups.com> Message-ID: <1176352737.116063.67570@d57g2000hsg.googlegroups.com> > > I assume the pythonware folk are busy. I notice that Fredrik Lundh > hasn't blogged for some time either. yeah, but Fredrik isn't the maintainer of that list, it's Hamish Lawson. Anyone needing a daily Python fix can get similar info from a couple of other sources: Cheeseshop: http://cheeseshop.python.org Planet Python: http://planet.python.org comp.lang.python-announce: http://groups.google.com/group/comp.lang.python.announce/ That should keep you going for a while! cheers S From andy.rockford at gmail.com Sun Apr 29 14:31:23 2007 From: andy.rockford at gmail.com (Andy) Date: 29 Apr 2007 11:31:23 -0700 Subject: List objects are un-hashable In-Reply-To: References: <1177660237.470851.170200@s33g2000prh.googlegroups.com> Message-ID: <1177871483.452642.16080@n76g2000hsh.googlegroups.com> Thanks Michael and Ant. From cjw at sympatico.ca Fri Apr 20 10:16:30 2007 From: cjw at sympatico.ca (Colin J. Williams) Date: Fri, 20 Apr 2007 10:16:30 -0400 Subject: matplotlib basic question In-Reply-To: <1177016327.543985.34500@o5g2000hsb.googlegroups.com> References: <1177016327.543985.34500@o5g2000hsb.googlegroups.com> Message-ID: orangeDinosaur wrote: > Hi, > > I am exploring the possibility of using python as a replacement of > MATLAB when I leave school. So, I've been playing with matplotlib and > have run into some weird behavior after recently installing python > 2.5.1 and matplotlib 0.90 on my Windows XP machine. Here's an example > of what I see: > >>> >from matplotlib.pylab import * >>>> x=arange(-2*pi,2*pi,pi/24) >>>> y=sin(x) >>>> plot(x,y) > [] >>>> show() > > > So, first off, what's up with the [ at 0x017C38C8>] line that shows up after my plot command? And second, > when I call show(), a new figure pops up with my sin wave -- seems all > right, yes? But I'm not given another >>> prompt in IDLE until or > unless I close the figure that popped up with the show() call. > > So, after closing the figure I type this: > >>>> show() >>>> plot(x,y) >>>> > > and this time another figure pops up with my sine wave again and I get > a prompt as well. But now, the figure window is completely > unresponsive -- I can't even close it without getting the "your > program is not repsonding" business. What am I missing? This > behavior so far seems pretty unintuitive. > > Any clarification is appreciated! > > trevis > Trevis, You might look at Numpy, which deals with multi-dimensional arrays. It has a small matrix component and some progress has been made with MATLAB amenable problems. Colin W. From pdpinheiro at gmail.com Fri Apr 20 15:48:02 2007 From: pdpinheiro at gmail.com (pdpi) Date: 20 Apr 2007 12:48:02 -0700 Subject: When are immutable tuples *essential*? Why can't you just use lists *everywhere* instead? In-Reply-To: <58sacjF2i0sviU1@mid.individual.net> References: <1177088796.622928.224890@d57g2000hsg.googlegroups.com> <58sacjF2i0sviU1@mid.individual.net> Message-ID: <1177098482.814681.30980@n76g2000hsh.googlegroups.com> Iou need only consider having cartesian coordinate sets as the keys for an example. A 2 dimensional list might be overly expensive if your coordinates span a large area but are relatively sparse. From michael at jedimindworks.com Fri Apr 6 16:33:30 2007 From: michael at jedimindworks.com (Michael Bentley) Date: Fri, 6 Apr 2007 15:33:30 -0500 Subject: Debugging multithreaded program using Eclipse/Pydev In-Reply-To: <1175887942.192837.187600@n76g2000hsh.googlegroups.com> References: <1175887942.192837.187600@n76g2000hsh.googlegroups.com> Message-ID: <8155FF06-E2BB-47F7-A16B-D06C861D0AD0@jedimindworks.com> On Apr 6, 2007, at 2:32 PM, John Henry wrote: > I am back against the wall trying to migrate my multithreaded > application from Python 2.3 to 2.5. The part of the code that's > failing has to do with queues (2.3 queues and 2.5 queues are not the > same). Since WingIDE doesn't support multithread debugging (they've > been saying that one day they might support that - and that was 2003), > I am starting to look for alternatives. The alpha release of Wing IDE (3.0.0-a1) does in fact, support multithread debugging. It is an alpha release but so far, I'm quite satisfied with it. hth, Michael From sbassi at clubdelarazon.org Sat Apr 14 17:56:02 2007 From: sbassi at clubdelarazon.org (Sebastian Bassi) Date: Sat, 14 Apr 2007 18:56:02 -0300 Subject: Making a tree out of a 2 column list In-Reply-To: <1176568327.669229.22910@b75g2000hsg.googlegroups.com> References: <1176568327.669229.22910@b75g2000hsg.googlegroups.com> Message-ID: <9e2f512b0704141456u7030b66alf13f8426052d48d7@mail.gmail.com> On 14 Apr 2007 09:32:07 -0700, mensanator at aol.com wrote: > def tree_path(key,tree,indent): > print '\t'*indent,key > if tree.has_key(key): > for m in tree[key]: > tree_path(m,tree,indent+1) > return Thank you. It worked!. I changed it a bit to return a list with the results: def tree_path(key,tree,hijos): hijos.append(key) if tree.has_key(key): for m in tree[key]: tree_path(m,tree,hijos) return hijos Then I call it like this: MyList=tree_path(9608,tree,[]) Best, SB. From bbxx789_05ss at yahoo.com Mon Apr 16 04:06:35 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: 16 Apr 2007 01:06:35 -0700 Subject: pyparsing Catch-22 In-Reply-To: <1176696704.924584.75720@e65g2000hsc.googlegroups.com> References: <1176686782.270354.164630@l77g2000hsb.googlegroups.com> <1176696704.924584.75720@e65g2000hsc.googlegroups.com> Message-ID: <1176710795.136757.26570@b75g2000hsg.googlegroups.com> Paul McGuire wrote: > Me? Push? Boy, a guy posts a couple of examples, tries to help some > people that are stuck with a problem, and what does he get? Called > "pushy"? Sheesh! Hey, I never called you pushy! Ok, maybe I sounded a little harsh--I was pretty frustrated after all. I guess I should have said something along the lines of, "If you are going to promote pyparsing, it would be nice to be able see what it is all about it." > Fortunately, I get enough positive feedback from > these posts that my feelings are pretty resilient these days. > > Anyway, thanks and point taken for the alert on this subject from the > newbie's perspective. When I first wrote these installations and > started the pyparsing project on SF, I was fairly newb myself - I had > to ask Dave Kuhlman to write setup.py for me! So I assumed the target > audience already knew the stuff I was having to learn. I assumed that > setup.py was just common knowledge among the Python world. > > I think your suggestion of a Wiki page on this subject should fill > this gap neatly, especially since pyparsing is somewhat targetted at > the newb and near-newb user, one that is struggling with regexp's or > some other parsing technology, and just wants to get some basic code > working. The other posts in this thread contain plenty of material to > start from. Also, thanks for the Mac OS X point of view, most of my > work is on Windows, and a little bit on Linux, but absolutely none on > Mac. And I see that I should not assume knowledge of tar, either, so > I'll be sure to mention its destructive streak, in overwriting > existing files with the same name as those in the archive. Once > untar'ed, there *is* a file named README, with an introduction and > instructions to invoke setup.py properly. Iol. I read it: --------------------- Installation ============ Do the usual: python setup.py install (pyparsing requires Python 2.3.2 or later.) ------------------------ Not much to go on--not even a mention of what directory you should be in when you run that command. Plus, you need to extract the files from the .tar file first. > > I'm glad to see you perservered and got pyparsing installed. You can > also run pyparsing.py itself, which will run a simple SQL parser > test. If you have not yet found the docs or examples, *please* look > over the sample code in the examples directory, and the class-level > documentation in the htmldocs directory. The docs directory should > also include the materials from my PyCon'06 presentations. > > Please post back, either here or on the Pyparsing wiki discussion > pages, and let me know how your pyparsing work is progressing. > > -- Paul (the developer, but you can call me "Paul") > I'm pretty facile with regex's, and after looking at some pyparsing threads over the last week or so, I was interested in trying it. However, all of the beginning examples use a Word() in the parse expression, but I couldn't find an adequate explanation of what the arguments to Word() are and what they mean. I finally found the information buried in one of the many documents--the one called "Using the Pyparsing Module". If that seems like an obvious place to look, I did start there, but I didn't find it at first. I also scoured the the wiki, and I looked in the file pycon06- IntroToPyparsing-notes.pdf, which has this: Basic Pyparsing Words and Literals From jstroud at mbi.ucla.edu Sat Apr 14 07:02:53 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Sat, 14 Apr 2007 11:02:53 GMT Subject: Python Feature Request: Add the "using" keyword which works like "with" in Visual Basic In-Reply-To: <1176547372.584539.89170@q75g2000hsh.googlegroups.com> References: <1176547372.584539.89170@q75g2000hsh.googlegroups.com> Message-ID: samjnaa at gmail.com wrote: > Please check for sanity and approve for posting at python-dev. > > In Visual Basic there is the keyword "with" which allows an object- > name to be declared as governing the following statements. For > example: > > with quitCommandButton > .enabled = true > .default = true > end with > > This is syntactic sugar for: > > quitCommandButton.enabled=true > quitCommandButton.default=true > > This can be very useful especially in GUI programming when we have to > type the same object name in line-after-line. I personally found > having to type the word "self" umpteen times inside classes very > irritating. Such a beautiful language is Python, she should have this > good feature from VB too. > > Now I hear that the word "with" is being discussed for a different > purpose in Py 3 as a result of a PEP and I don't want to conflict with > that. So I propose the word "using" as a replacement. This also is > similar to the C++ "using" keyword which exposes the members of a > namespace to access without specifying the namespace scope for each > reference. For example after giving "using namespace std;" I can > change all references to "std::cout" to "cout", which is similar to > what I am proposing for Python now. > > Some thoughts about how this "using" statement should behave. The word > using should be followed by an object name and a colon indicating the > start of a block. The object named after "using" must determine the > context (or whatever the technical word is) of the of the statements > in that block. > > self.setFixedSize(200, 120) > self.quit = QtGui.QPushButton("Quit", self) > self.quit.setGeometry(62, 40, 75, 30) > self.quit.setFont(QtGui.QFont("Times", 18, QtGui.QFont.Bold)) > self.connect(self.quit, QtCore.SIGNAL("clicked()"), QtGui.qApp, > QtCore.SLOT("quit()")) > > to be rewritten as: > > using self: > __setFixedSize(200,120) > __quit = QtGui.QPushButton("Quit", self) > __using quit: > ____setGeometry(62, 40, 75, 30) > ____setFont(QtGui.QFont("Times", 18, QtGui.QFont.Bold)) > __connect(self.quit, QtCore.SIGNAL("clicked()"), QtGui.qApp, > QtCore.SLOT("quit()")) > > [I don't know whether usenet will retain my indenting, so I changed > the tabs to underscores.] > > This context governing may need to be limited to the first applicable > member - so that in the above example "self" governs setFixedSize, > quit, quit and connect only in each sentence and quit (self.quit) > governs setGeometry and setFont only. (Point is that the parser should > not search for self.QtGui, self.self or self.QtCore in sentences 3 and > 7, and self.quit.QtGui in sentence 6.) > > Due to my absence of professional experience, my request may be > somewhat unpolished technical-wise, but I believe that this is a very > useful feature for Python and hence request the technically- > knowledgeable to reformat it as necessary. Thank you. > I like this one for some reason. Just the "using self" would save hella typing in a lot of classes. I would favor a convention with leading dots to disambiguate from other variables. This wouldn't conflict with, say, floats, because variable names can't begin with a number. James From smithj at rpath.com Wed Apr 11 12:47:11 2007 From: smithj at rpath.com (Jonathan Smith) Date: Wed, 11 Apr 2007 12:47:11 -0400 Subject: bittorent In-Reply-To: <1eb3a0e10704110922v17f83f79se5972dce07415a5@mail.gmail.com> References: <1eb3a0e10704110922v17f83f79se5972dce07415a5@mail.gmail.com> Message-ID: <461D110F.8080908@rpath.com> Linus Nordstr?m wrote: > Hello > Im planing playing a bit whit bittorrent, but I'm having some trouble > about where to start. So if anyone could point me in the right > direction it would be much appreciated. > The best would be if there are some already written modules that > handle downloading and seeding torrents, but if that cant be found a > good source on how one dose to build some sort of bitorrent client > would be nice. > > thanks in advance you might start with bittorrent itself [1] - it is written in python. [1]: http://www.bittorrent.com/download -smithj From duncan.booth at invalid.invalid Thu Apr 12 16:19:45 2007 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 12 Apr 2007 20:19:45 GMT Subject: tuples, index method, Python's design References: Message-ID: "Alan Isaac" wrote: > I doubt that *anyone* who programs in Python > has not encountered the situation where they change > a tuple to a list *solely* for the purpose of getting > access to the index method. This suggests a missing > method, does it not? Who has not done this? > Name yourself! My name is Duncan and I claim my ?5. I've checked through quite a lot of code and I can't find any situation where I've converted a tuple to a list before calling the index method (I did find one case, but it wasn't my code). My suspicicion is that any case where you find yourself calling index on a tuple indicates a code smell. Antoon came up with a use case which appeared plausible at first glance, but at least to me felt fundamentally wrong. (Without Carsten's useful post pointing out that he should have used array rather than struct I wouldn't instantly have know exactly why it was wrong.) My thoughts at the moment are that Python *should* have an index method on tuple: I wrote earlier that the benefit should outweight the costs, but I think by now the cost of implementing and maintaining it is probably outweighed by the pain of reading this thread. From bruno.42.desthuilliers at wtf.websiteburo.oops.com Tue Apr 17 03:14:24 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Tue, 17 Apr 2007 09:14:24 +0200 Subject: strange behaviour with keyword arguments and inheritance In-Reply-To: <1176771364.964642.209300@b75g2000hsg.googlegroups.com> References: <1176771364.964642.209300@b75g2000hsg.googlegroups.com> Message-ID: <462473c8$0$18520$426a74cc@news.free.fr> matthewperpick a ?crit : > Check out this toy example that demonstrates some "strange" behaviour > with keyword arguments and inheritance. Nope. It demonstrates that default arguments are eval'd only once (when the def statement is eval'd), which is documented and a FAQ. > I have a > very rudimentary understading of python's guts, but I would still call > the behaviour unexpected. Or perhaps I should rtfm? Well, since you mention it... !-) From newsgroups at nospam.nowire.org Mon Apr 2 05:31:39 2007 From: newsgroups at nospam.nowire.org (=?ISO-8859-1?Q?Thomas_Kr=FCger?=) Date: Mon, 02 Apr 2007 11:31:39 +0200 Subject: Web App Framework with PostgreSQL + fast + easy In-Reply-To: References: Message-ID: Ben schrieb: > I'm looking for a web application framework with a good interface to > PostgreSQL. You may check out Django: http://www.djangoproject.com/ Thomas From g.brandl at gmx.net Tue Apr 10 04:49:37 2007 From: g.brandl at gmx.net (Georg Brandl) Date: Tue, 10 Apr 2007 10:49:37 +0200 Subject: exec statement Syntax Error on string pulled from MySQL In-Reply-To: <1176191064.840339.247160@d57g2000hsg.googlegroups.com> References: <1176191064.840339.247160@d57g2000hsg.googlegroups.com> Message-ID: gregpinero at gmail.com schrieb: > It's the strangest thing, I'm pulling some text out of a MySQL table > and trying to run exec on it, and it keeps giving me a syntax error, > always at the end of the first line. > > Thanks in advance for any help. I'm really stuck on this one! > > -Greg > > I'm not sure what information would be most useful but here's a start: > > The last code I stored in the table and pulled out was simply: > print 'greg' > print 'greg2' > > To which my error log says: > Traceback (most recent call last): > File "/home/public/web/webapi.py", line 303, in wsgifunc > result = func() > File "/home/public/web/request.py", line 125, in > func = lambda: handle(inp, fvars) > File "/home/public/web/request.py", line 61, in handle > return tocall(*([urllib.unquote(x) for x in args] + fna)) > File "/home/public/EZsession.py", line 119, in proxyfunc > return func(self, *args, **kw) > File "/home/htdocs/code.py", line 94, in POST > print utility.run(name,revision,inp) > File "/home/public/utility.py", line 177, in run > exec code+'\n' in context > File "", line 1 > print 'greg' > ^ > SyntaxError: invalid syntax > (Note the ^ actually appears under after the ' ) You have Windows line endings (\r\n) in the string, which Python doesn't like. Don't store it like that, or if you must, do a .replace('\r', '') before exec'ing it. Georg -- Thus spake the Lord: Thou shalt indent with four spaces. No more, no less. Four shall be the number of spaces thou shalt indent, and the number of thy indenting shall be four. Eight shalt thou not indent, nor either indent thou two, excepting that thou then proceed to four. Tabs are right out. From ziga.seilnacht at gmail.com Tue Apr 17 02:50:27 2007 From: ziga.seilnacht at gmail.com (Ziga Seilnacht) Date: 16 Apr 2007 23:50:27 -0700 Subject: How to better pickle an extension type In-Reply-To: <1176736722.383507.37810@n59g2000hsh.googlegroups.com> References: <1176736722.383507.37810@n59g2000hsh.googlegroups.com> Message-ID: <1176792627.930045.60410@p77g2000hsh.googlegroups.com> dgdev wrote: > I would like to pickle an extension type (written in pyrex). I have > it working thus far by defining three methods: > > class C: > # for pickling > __getstate__(self): > ... # make 'state_obj' > return state_obj > > __reduce__(self): > return C,(args,to,__init__),me.__getstate__() > > # for unpickling > __setstate__(self,state_obj): > self.x=state_obj.x > ... > > This gets the class pickling and unpickling. > > However, I'd like to not specify arguments for __init__ (as I do now > in __reduce__), and so not have __init__ invoked during unpickling. > > I would like to have the pickling machinery somehow create an > uninitialized object, and then call its __setstate__, where I can re- > create it from 'state_obj'. > > Is there a kosher way to do so, that is without me having to have a > special mode in the constructor for when the object is being created > by the unpickler? Why are you overwriting the __reduce__() method? The default object.__reduce__() method, inherited by all new style classes, already does what you want. If you really must overwrite it, and you don't want __init__() to get called, then you should return a reconstructor named __newobj__() as the first item of reduce tuple. Something like this: >>> def __newobj__(cls, *args): ... return cls.__new__(cls, *args) ... >>> class C(object): ... def __init__(self): ... print "I shouldn't be called at reconstruction" ... def __reduce__(self): ... try: ... getnewargs = self.__getnewargs__ ... except AttributeError: ... newargs = (self.__class__,) ... else: ... newargs = (self.__class__,) + getnewargs() ... try: ... getstate = self.__getstate__ ... except AttributeError: ... # this ignores __slots__ complications ... state = self.__dict__ ... else: ... state = getstate() ... # this ignores list and dict subclasses ... return __newobj__, newargs, state ... >>> c = C() I shouldn't be called at reconstruction >>> import pickle >>> for proto in range(3): ... assert isinstance(pickle.loads(pickle.dumps(c, proto)), C) ... >>> Ziga From DustanGroups at gmail.com Sat Apr 21 08:58:00 2007 From: DustanGroups at gmail.com (Dustan) Date: 21 Apr 2007 05:58:00 -0700 Subject: Suggestion: str.itersplit() Message-ID: <1177160280.784224.53460@b58g2000hsg.googlegroups.com> >From my searches here, there is no equivalent to java's StringTokenizer in python, which seems like a real shame to me. However, str.split() works just as well, except for the fact that it creates it all at one go. I suggest an itersplit be introduced for lazy evaluation, if you don't want to take up recourses, and it could be used just like java's StringTokenizer. Comments? From elguavas at users.sourceforge.net Sat Apr 21 00:03:03 2007 From: elguavas at users.sourceforge.net (Stephen M. Gava) Date: Sat, 21 Apr 2007 04:03:03 -0000 Subject: using tkinter to display html References: <1176988173.015892.273660@e65g2000hsc.googlegroups.com> <1177064902.230394.133830@d57g2000hsg.googlegroups.com> Message-ID: On Fri, 20 Apr 2007 03:28:22 -0700, Rob Wolfe wrote: >> > The following thread has various ideas in it: >> > http://mail.python.org/pipermail/python-list/2001-October/107989.html >> >> thanks mike, i found that thread before i posted here, it doesn'rt >> answer my question though. > > Why not? Did you try to use tkhtml [1]_ with python wrapper [2]_. IMHO > it works pretty nice. i found the tkhtml page but it hasn't been updated since 2002 and the mailing list doesn't even exist anymore. so unsure of the future on that. > > .. [1] http://www.hwaci.com/sw/tkhtml/ .. [2] didn't find these bindings though, so thanks, i'll have a play. stephen. > http://tix.sourceforge.net/Tixapps/src/Python/TkHtml.py > From gdamjan at gmail.com Mon Apr 2 11:50:26 2007 From: gdamjan at gmail.com (Damjan) Date: Mon, 02 Apr 2007 17:50:26 +0200 Subject: frame of Qt program References: <5c62a320704020145q246e94cq4f3084fda6af8813@mail.gmail.com> Message-ID: <461125ff$0$90268$14726298@news.sunsite.dk> > Look at the network examples included with PyQt4. Particularly > fortuneclient.py and fortuneserver.py. > > PyQt4 has its own network classes that are fully integrated with the event > loop making it easy to write GUI/network applications. As threads also > have an event loop its also easy to push the network handling out to > separate threads. The next version of Qt will add support for SSL. I've always wondered how PyQT4 compares to Twisted for writing network apps. Qts signal/slot mechanisam is much easier to understand/work with than deferreds. On the other hand Twisted probably supports more protocols right now. -- damjan From pyalbert at gmail.com Tue Apr 17 06:14:50 2007 From: pyalbert at gmail.com (Ros) Date: 17 Apr 2007 03:14:50 -0700 Subject: sql to xml Message-ID: <1176804890.007875.286920@e65g2000hsc.googlegroups.com> Hi, I wish to write xml file after validating data from mssql database. I am using xml data mapping list and would use it for validating data. Here is the program : Map_list.xml : Program : from cElementTree import iterparse import pymssql # Database connection details host = '192.168.1.1' db = 'Books' usr = 'ros_albert' pwd = 'ros_albert' conn = pymssql.connect(host=host, user=usr, password=pwd, database=db) table = "books_details" cursor = conn.cursor() cursor.execute( 'select * from books_details') for row in cursor.fetchall(): fname = row[0] # Here is the code to validate the minimum length & maximum length of data, if its ok then I would write the data into xml file context = iterparse('Map_list.xml', events=("start", "end")) root = None for event, child in context: if event == "start": if child.tag == 'loop': w.push_loop(child.attrib['id']) if child.tag == 'ele': w.push_ele(child.attrib['id']) # Here I am validating the data using "Map_list.xml" file, validation part is working fine. if event == "end": if child.tag == 'ele': writer.pop_ele() if child.tag == 'loop': writer.pop_loop() I am able to write a data from 1 xml file to another but not getting how to write & validate data from sql to xml. May be I am not sure what mapping is. I wish to map the data columns in sql database with the xml data. any help would be highly appreciated. Regards, Ros From skip at pobox.com Mon Apr 23 21:04:25 2007 From: skip at pobox.com (skip at pobox.com) Date: Mon, 23 Apr 2007 20:04:25 -0500 Subject: script for seconds in given month? In-Reply-To: <1177360091.516469.77830@l77g2000hsb.googlegroups.com> References: <1176740556.859125.221980@l77g2000hsb.googlegroups.com> <1hwokmz.1ropcwj17pg55dN%aleax@mac.com> <1176796031.889407.323950@b75g2000hsg.googlegroups.com> <1177360091.516469.77830@l77g2000hsb.googlegroups.com> Message-ID: <17965.22425.57167.749222@montanaro.dyndns.org> ed> I, unfortunately, failed to realize the actual platform the script ed> is for is IronPython. When trying to import calendar in IronPython, ed> I get: ed> SyntaxError: future feature is not defined: with_statement ed> (c:\Python25\Lib\calendar.py, line 8) So try the 2.4 version of calendar.py... Skip From sreetlatha at gmail.com Thu Apr 5 02:08:46 2007 From: sreetlatha at gmail.com (Sreelatha G) Date: Thu, 5 Apr 2007 11:38:46 +0530 Subject: Python and Java Message-ID: Hi I am new to python .I need your help in solving my problem. Is there any way to call python files in a java file .How is it possible? Thanks Sreelatha -------------- next part -------------- An HTML attachment was scrubbed... URL: From gagsl-py2 at yahoo.com.ar Sat Apr 21 07:36:51 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sat, 21 Apr 2007 08:36:51 -0300 Subject: how to find the OS name..?? References: <1177153990.286509.274350@y80g2000hsf.googlegroups.com> Message-ID: En Sat, 21 Apr 2007 08:13:10 -0300, pradeep nair escribi?: > How do i determine the type of OS i'm working on using python??(i.e > whether CentOS,Fedora,SLES,.......along with the version) os.uname() If you need more detailed information try the platform module -- Gabriel Genellina From bik.mido at tiscalinet.it Tue Apr 17 07:02:05 2007 From: bik.mido at tiscalinet.it (Michele Dondi) Date: Tue, 17 Apr 2007 13:02:05 +0200 Subject: [OT] Re: is laziness a programer's virtue? References: <1176757271.282365.319740@n76g2000hsh.googlegroups.com> <96adnb0sJ8PubL7bnZ2dnUVZ_gednZ2d@comcast.com> Message-ID: <86a923hn1t66tc6i0bfromoufr4jkcarm0@4ax.com> On Mon, 16 Apr 2007 17:58:52 -0400, D Herring wrote: >- Please topquote snippets from the threads about which you are commenting. > >- Please set your newsreader to prepend "Re: " or somesuch when replying >to a toplevel post. > >- Please don't preach about "meta-talk and policing" in a post which is >mostly meta-talk and preaching. FYI "Please" is probably a word that XL ignores completely. Thus do what most humans in their sane state of mind would do. Killfile it. If for some reason you can't, then ignore it. Certainly, do not feed it. Michele -- {$_=pack'B8'x25,unpack'A8'x32,$a^=sub{pop^pop}->(map substr (($a||=join'',map--$|x$_,(unpack'w',unpack'u','G^ <1177962288.575008.48490@q75g2000hsh.googlegroups.com> <1177967919.968338.3300@l77g2000hsb.googlegroups.com> Message-ID: En Mon, 30 Apr 2007 21:32:20 -0300, John Nagle escribi?: > kyosohma at gmail.com wrote: > >>> In addition to the warning that reload() does not recursively reload >>> modules that the reloaded module depends on, be warned that reloading a >>> module does not magically affect any functions or objects from the old >>> version that you may be holding on to. > > Maybe reloading modules should be deprecated. The semantics > are awful, and it interferes with higher-performance implementations. Maybe all the drawbacks should be clearly stated instead, telling that it's not a magic wand as someone could think. -- Gabriel Genellina From kyosohma at gmail.com Fri Apr 20 10:08:41 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: 20 Apr 2007 07:08:41 -0700 Subject: wxPython and how to return text entry to main program? In-Reply-To: References: <1177011490.435609.155870@o5g2000hsb.googlegroups.com> <1177030290.529322.56210@p77g2000hsh.googlegroups.com> Message-ID: <1177078121.901267.88340@n76g2000hsh.googlegroups.com> On Apr 19, 9:05 pm, Steve Holden wrote: > 7stud wrote: > > On Apr 19, 1:38 pm, Tyler wrote: > > [after quoting umpteen lines of code] > > > > > > > You can do this: > > > --- > > class MyFrame(wx.Frame): > > > .. > > .. > > .. > > def OnSubmit(self, event): > > globals()["userInput"] = self.txtCtrlName.GetValue() > > self.Close() > > > app = MyApp() > > app.MainLoop() > > > print userInput > > ----- > > Please try to limit your quoting to what's relevant. > > 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 Steve, I think Tyler is opening a custom dialog from his main GUI application. He should have used "ShowModal" if he was using one of wxPython's standard dialog boxes, but since he was creating his own custom one he didn't need to, which is why I told him to use the self.Close(True) method to destroy the dialog. Then again, maybe I am being "wrong-headed" about the whole thing. I was trying to come up with the "instance variable" way of storing the variables, but I could not think of how to implement it last night. Here are some other threads on the topic that I thought were interesting: http://mail.python.org/pipermail/tutor/2005-May/038648.html http://lists.wxwidgets.org/archive/wxPython-users/msg06482.html http://www.daniweb.com/techtalkforums/thread60439.html Mike From danfan1981 at yahoo.com Fri Apr 20 16:28:56 2007 From: danfan1981 at yahoo.com (danfan1981 at yahoo.com) Date: 20 Apr 2007 13:28:56 -0700 Subject: how to get a wrap aound slice of numpy array Message-ID: <1177100936.803752.54890@y5g2000hsa.googlegroups.com> Hi, I am learning Numpy and using it for a course project. Suppose x = [0, 1, 2, 3, 4], I know that x[0:2] would give [0,1], and x[-1] give [4], is there a way that I can get [4,0,1]. I try x[-1:2], but it returns an empty array. I am doing convolution (e.g. convolve [0, 1, 2, 3, 4] with [1,-2,1]) with wrap-around boundary condition, so sometimes the indices would wrap around the boundaries, and sometimes not. I would like to find a generic expression for both cases. From eugene.vandenbulke at gmail.com Thu Apr 26 19:00:59 2007 From: eugene.vandenbulke at gmail.com (EuGeNe Van den Bulke) Date: Fri, 27 Apr 2007 01:00:59 +0200 Subject: EuroPython vs PyconUK References: <4630D480.7050308@gmail.com> Message-ID: Steve Holden wrote: > So by this reasoning there should have been no "Python UK" conference > for the last four years (in case you didn't know it ran as a track of > the C/C++ conference, but ths track has now broadened to include all > scripting languages). And what about the people who can't get the time > and/or money to attend EuroPython? I am afraid there is a misunderstanding. I have no problem with PyCon UK but would like to have elements to help me choose (the official language of PyCon Uno Italy is Italian so that fixes it :P). > Diversity is good, so it isn't one vs. the other. And the UK really *is* > part of Europe (no matter how its politicians behave) :P I agree that diversity is good (you won't hear me say that there are too many web frameworks in Python :D) but isn't dilution a danger? If Guido was a rock star and I was a groupie, I would want to know which festival to attend to see him on stage. I guess there is always Google Video ;) More seriously in Geneva there were people from all over the place, speakers and attendees, which is one of the reason why such conferences are interesting (or am I deluded?). It is harder for someone from Australia to come twice to Europe in the space of 2 months than for a pythoneer lambda to spend a couple of days studying another web framework to see if it fits how his brain works and the problem he's got to solve. Looking at the reactions to my post, I must be wrong. I didn't mean to offend anyone if I did. I'll go to Vilnius because I have never seen the city and try to go to Birmingham if the program looks interesting (not very rational or is it?). Cheers, EuGeNe -- http://www.3kwa.com From deets at nospam.web.de Sat Apr 7 17:17:50 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sat, 07 Apr 2007 23:17:50 +0200 Subject: 1 Thread = 3 interpreter launched ??? In-Reply-To: <1175957690.323531.50820@o5g2000hsb.googlegroups.com> References: <1175957690.323531.50820@o5g2000hsb.googlegroups.com> Message-ID: <57qg3uF2dug0uU1@mid.uni-berlin.de> nono240 at gmail.com schrieb: > Hi all, and thanks for reading ! > > I'm using Python 2.4.2 with an embedded platform (16MB RAM) running > Linux 2.6.20. > My main script use a thread for some reasons (more precisely a > periodic timer within a separate module). > While looking at the memory consumption, here's what i found : > > PID USER STATUS RSS PPID %CPU %MEM COMMAND > 171 root R 384 164 1.5 2.6 top > 218 root R 4172 217 0.1 29.1 main_script.py > 216 root S 4172 180 0.0 29.1 main_script.py > 217 root S 4172 216 0.0 29.1 main_script.py > > When creating the thread, Python forks 2 times and thus consume me > around 60% of RAM ! > > Is it a normal behaviour while using threads ??? > > It's very critical, am i missed something ? Yes. That some linuxes list each thread as one process. No need to worry... Diez From fuzzyman at gmail.com Tue Apr 24 10:59:23 2007 From: fuzzyman at gmail.com (Fuzzyman) Date: 24 Apr 2007 07:59:23 -0700 Subject: No speedup on multi-processor machine? In-Reply-To: <1177361572.800543.263330@n59g2000hsh.googlegroups.com> References: <1177189332.916296.205280@d57g2000hsg.googlegroups.com> <1177197495.821701.140390@b58g2000hsg.googlegroups.com> <1177200844.134908.192110@q75g2000hsh.googlegroups.com> <1177361572.800543.263330@n59g2000hsh.googlegroups.com> Message-ID: <1177426763.184463.48740@u32g2000prd.googlegroups.com> On Apr 23, 9:52 pm, Klaas wrote: > On Apr 21, 5:14 pm, Fuzzyman wrote: > > > Additionally, extending IronPython from C# is orders of magnitude > > easier than extending CPython from C. > > Given the existence of Pyrex, that statement is pretty difficult to > substantiate. > With Pyrex you still need to do memory management for non-Python types. Additionally compiling C# from within IronPython is *very*easy. C# is a much easier language to use than C - even with the help of Pyrex. You use types defined in C# *natively* within IronPython. All the best, Fuzzyman http://www.voidspace.org.uk/python/articles.shtml > -Mike From kyosohma at gmail.com Wed Apr 18 09:06:46 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: 18 Apr 2007 06:06:46 -0700 Subject: Win32com, and Excel issues. In-Reply-To: <1176881939.612038.278770@y5g2000hsa.googlegroups.com> References: <1176881939.612038.278770@y5g2000hsa.googlegroups.com> Message-ID: <1176901606.433286.225770@q75g2000hsh.googlegroups.com> On Apr 18, 2:38 am, Ant wrote: > Hi all, > > I'm doing some Excel automation work for a friend, and am developing > on a machine running Office 2000. My friends machine is running Excel > 2003. The code I've written works like a charm on my machine (in fact > all three of my machines), but falls over early on on Excel 2003. > > The code snippet it falls over on is code to copy one worksheet after > another: > > app = wincl.Dispatch("Excel.Application") > app.Visible = True > app.Workbooks.Open(self.filename) > sheet = app.Worksheets(1) > sheet.Copy(None, sheet) > > and this last line throws the following exception: > > pywintypes.com_error: (-2147417851, 'the server threw an exception.' > , None, None) > > which isn't too helpful. > > I'm wondering if something has changed in the Excel API that doesn't > allow a null parameter to Copy or some similar issue. I tried using > the keyword argument format, but that simply refused to work. > > Other relevant information: > > * The program is packaged using py2exe, so I know that the same > version of Python, and the same libraries are on each machine. > * One of the test machines running Excel 2000 does not have Python > installed. > * The machines are all of a similar spec. > > Any ideas are welcome! I can't find anything about copying a worksheet, but I found a some fairly detailed information about COM objects and getting more information about Python's bindings to them here: http://www.oreilly.com/catalog/pythonwin32/chapter/ch12.html or here: http://mathieu.fenniak.net/plotting-in-excel-through-pythoncom/ Hopefully this will give you some pointers. Mike From Jun.Jin.act at gmail.com Mon Apr 16 02:08:29 2007 From: Jun.Jin.act at gmail.com (Jun.Jin.act+group.python@gmail.com) Date: 15 Apr 2007 23:08:29 -0700 Subject: How to initialize a table of months. In-Reply-To: <1176700472.052332.226350@d57g2000hsg.googlegroups.com> References: <1176694257.338172.217660@y80g2000hsf.googlegroups.com> <1176694407.102613.37460@w1g2000hsg.googlegroups.com> <1176700472.052332.226350@d57g2000hsg.googlegroups.com> Message-ID: <1176703709.549428.5310@w1g2000hsg.googlegroups.com> On Apr 16, 1:14 pm, "Paul McGuire" wrote: > On Apr 15, 10:33 pm, "7stud" wrote: > > > > > On Apr 15, 9:30 pm, "7stud" wrote: > > > > On Apr 15, 7:30 pm, "Steven W. Orr" wrote: > > > Arrgh. > > > import calendar > > > months = calendar.month_abbr > > #returns an array with the 0 element empty > > #so the month names line up with the indexes 1-12 > > > d = {} > > for i in range(1, 13): > > d[months[i]] = i > > > print d > > This dict construction idiom is worth learning: > d = dict( (a,b) for a,b in ... some kind of list comprehension or > generator expr... ) > > In this case: > d = dict( (mon,i) for i,mon in enumerate(calendar.month_abbr) ) > > Or to avoid including that pesky 0'th blank element: > d = dict( [(mon,i) for i,mon in enumerate(calendar.month_abbr)][1:] ) > > -- Paul Great! From deets at nospam.web.de Wed Apr 25 19:23:01 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 26 Apr 2007 01:23:01 +0200 Subject: Python not giving free memory back to the os get's me in real problems ... In-Reply-To: <599nhgF2jlkssU1@mid.dfncis.de> References: <1177510121.882503.145560@n15g2000prd.googlegroups.com> <599nhgF2jlkssU1@mid.dfncis.de> Message-ID: <59a66qF2j472uU1@mid.uni-berlin.de> TimC schrieb: > Donald 'Paddy' McCarthy wrote > >> Could you split the program into one handling the outer loop and >> calling another program, with data transfer, to handle the inner >> loops? >> >> - Paddy. > > I'm afraid this isn't possible, because the python macro is called > and started from within our commercial tool which leads to the > cirumstance that this tool eats up more and more memory. > > Due to the fact that there is no way we can start the tool via > commandline giving an argument that tells the tool it has to > start macroXY.py after startup I don't see a way to lower the > memory usage by splitting it up in two loops. Is the python macro crippled in any way - e.g. threading? Maybe delegating the actual processing to an external python process you feed through the macro might work. Diez From www.ieshoes.com118 at gmail.com Fri Apr 13 20:18:05 2007 From: www.ieshoes.com118 at gmail.com (www_ieshoes_com) Date: 13 Apr 2007 17:18:05 -0700 Subject: ieShoes.com Shop nike air jordan air force 1 dunk sb bape sta shoes Message-ID: <1176509885.739197.241490@e65g2000hsc.googlegroups.com> Main Menu Search Basket Content Checkout Customer Service Order Tracking AddFavorite Member Login Login Name: Password: Register Forget your password? Categories Nike Shoes Air Force I Air Jordan 1-10 Air Jordan 11-22 Air Max TN Air Max 95 Air Max 97 Air Max 2003 Air Max 360 Nike Dunk Nike Dunk For Women Nike Shox R4 Nike Signature Series Other Brand Shoes BAPE STA Adidas Adidas For Women Timberland Ice Cream Puma Gucci Prada Shoes For Women Shoes For Kids Shoes For Football Jeans Red Monkey Bathing Ape True Religion Evisu Jeans Clothing Bathing Ape Hoodies Bathing Ape Jackets Bathing Ape-Bady Milo Bathing Ape T-shirts Red Monkey T-shirts New Arrivals Live Help Email: ieshoes at yahoo.com MSN: ieshoes at hotmail.com AIM: ieshoes Customer Service How To Order Payment Shipment Sizing Info If you want to shop smart, shop at IEShoes.com. IEShoes.com guarantees reliable service, and we would like to maintain our reputation for having excellence in customer service and fast shipping! If you have been searching around for Air Jordan Kicks, Custom sneakers, Air Force Ones, Nike Dunk SB,A Bathing,Ape,Adidas,adicolor and more, you have come to the perfect spot! We carry a wide variety of hard to find Jordans, Air Force 1's, and more exclusive sneakers. Latest News 2/28/07 please note:the biggest us size 14 we can supply,and only the air jordan XI (11) retro have the size 14.thank you. www.ieshoes.com Customer support team 2/5/07 Dear the customers who ordered the shoes at 6th,21th,22th,23th DEC 2006 ,becuase the ieshoes.com system update, we have nothing info of the order id:3113,3108,3107,3105,3104, 3100,3094,3093,3070,3032,3026, 3022,3019.2502,2500,2492,1442,1445 please E-mail us tell your order including the shoes photo, the size ,the shipping address ,so we can ship the shoes .thank you for your patience. IEShoes.com Customer support team 2/3/07 Please note:the wholesale orders are always welcomed,and considered 10 pairs or more,and if you want to know the wholesale more ,please email to :ieshoes at yahoo.com. thank you ! ieshoes.com admin 2/2/07 When you pay the item,the system will bring you to the ctopay.com/EN/ (show:abank) online payment ,the online payment company is our partner.and that is 100% Safe Purchase Guarantee,They use Secure Sockets Layer (SSL), an encryption technology that works with ALL browsers, so that no one can read a buyer's personal information. www.ieshoes.com admin 2/2/07 Please note:When you pay by credit card,your name and billing address must be entered exactly as they appear on your credit card statement to avoid any delay or deny in the authorization process.And your billing address phone number must match telephone number on your credit card account for the payment te be accepted! www.ieshoes.com admin 1/18/07 Hello,if you pay by credit card,the bank 's Description show you the letter: MOP/NETEL INFORMATION & SE,MACAU .so when you get the monthy statement,that is your order.thank you! 12/20/06 NOTE:All the list price include the shipping charge.thank you! 12/1/06 If you use the Moliza explorer, you maybe can not put the shoes in your basket. So please use the IE6.0,or IE7.0 explorer. thank you! 12/1/06 Merry Christmas! Welcome to our shop,Enjoy your shopping here! 9/11/06 Dear Valued Customers: There are mass email sent to our financial address jerme2008 at hotmail.com.These makes our work trouble and you didn't got reply intime. Email to ieshoes at yahoo.com to GET support ASAP plz.Thanks. Customer Support Team 8/24/06 Website are updating,If you have problem to login to your account email us your account ID details plz: ieshoes at yahoo.com Customer Service Team 6/11/06 Due to the enormous amount of orders , a lot of our packages have been shipped but may not input your tracking number to your order status. We wish to inform those who haven't received tracking numbers to email us: ieshoes at yahoo.com.we will provide you the details ASAP. Thank you for your patience and kind understanding. Customers Service Team 6/5/06 Please note : If you need to change your address or ANY of your account information in your account, you may easily login using the login details you have created during your first purchase. You DO NOT need to contact customer service for this. Thank you -Admin 5/26/06 Please note : Your tracking numbers will not appear at the USPS website until your item has reached US grounds. So when you received your tracking numbers give it three days before checking at the USPS website. If you cannot find your record there, try to check after a day or two. - Admin 5/24/06 Please note: When sending us emails about your orders, please include the Ieshoes' account name you used when you made your purchase. This is so we would be able to pull your account. Please note: Please use a legitimate email account when emailing us. Also please clean up your Inbox so you will be able to receive our emails. There has been a lot of emails that we have sent out that were returned to us. Thank you. - Customer Support Team 5/23/06 If you have checked your tracking number on usps.com and nothing came up, then check it on http://www.ems.com.cn/english-main.jsp and type in your tracking number where it says " Item Number" and hit GO! - Admin We guarantee that any purchase you make on the IEShoes.com website will be 100% safe.IEShoes's servers use Secure Sockets Layer (SSL), an encryption technology that works with ALL browsers, so that no one can read a buyer's personal information. Attention please: All prices listed are for retail prices including the shipping charge( FREE SHIPPING ), Don't hesitate to contact us for wholesale details. Bestsellers: >>more Item NO.: Dunk-53 Color : view photo Price : US$ 79.99 Detail Item NO.: Jordan V-27 Color : black/silver Price : US$ 75 Detail Item NO.: bape 006 Color : grey/black Price : US$ 75.99 Detail Item NO.: Jordan IV-2 Color : Mars Blackmon Edition Price : US$ 79.99 Detail Item NO.: jordan VII-8b Color : black/orange Price : US$ 79.99 Detail Item NO.: Jordan XI-8 Color : black/red Price : US$ 78.99 Detail New Arrivals: >>more Item NO.: Adicolor Y6-W Updated : 4/13/2007 Color : black/yellow Price : US$ 86.99 Detail Item NO.: Adicolor Y5-W Updated : 4/13/2007 Color : view photo Price : US$ 83.99 Detail Item NO.: Adicolor Y4-W Updated : 4/13/2007 Color : view photo Price : US$ 83.99 Detail Item NO.: Adicolor Y3-W Updated : 4/13/2007 Color : view photo Price : US$ 86.99 Detail Item NO.: Adicolor W6-W Updated : 4/13/2007 Color : white Price : US$ 83.99 Detail Item NO.: Adicolor W5-W Updated : 4/13/2007 Color : white Price : US$ 83.99 Detail Item NO.: Adicolor W4-W Updated : 4/13/2007 Color : white/black Price : US$ 83.99 Detail Item NO.: Adicolor R5-W Updated : 4/13/2007 Color : red Price : US$ 86.99 Detail Item NO.: Adicolor R4-W Updated : 4/13/2007 Color : view photo Price : US$ 86.99 Detail We Accept: ?Copyright 2006 ieshoes.com From tjreedy at udel.edu Wed Apr 25 17:27:03 2007 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 25 Apr 2007 17:27:03 -0400 Subject: conditional print statement ? References: <2c923$462fb3e0$d443bb3a$18429@news.speedlinq.nl> Message-ID: "Stef Mientki" wrote in message news:2c923$462fb3e0$d443bb3a$18429 at news.speedlinq.nl... | if Print_Info: print Datafile.readline() | else: Datafile.readline() Since both branches discard the data read, I presume Martin's fix is what you really want. | Is there a more compressed way to write such a statement, | especially I dislike the redundancy "Datafile.readline()". But for future reference, if you really do need to call a method in multiple places (or even just multiple times in a loop) you can condense like so: dread = Datafile.readline # followed by ... dread() # as needed Terry Jan Reedy From martin at v.loewis.de Wed Apr 4 17:04:09 2007 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Wed, 04 Apr 2007 23:04:09 +0200 Subject: troubles building python 2.5 on Windows XP x64 Windows Server 2003 sp1 Platform SDK In-Reply-To: <1175622506.730227.37060@p77g2000hsh.googlegroups.com> References: <1175622506.730227.37060@p77g2000hsh.googlegroups.com> Message-ID: <461412C9.8090609@v.loewis.de> bhochstetler at gmail.com schrieb: > I am needing to build python 2.5 on Windows XP x64 Windows Server 2003 > sp1 Platform SDK and am not finding anything documented on the process > to use. Has anyone had any success with this? I did - I built the official binaries with it. > If so has anyone > documented it? The documentation that resides in pcbuild/readme.txt is > not helpful at all. Did you try to follow it? If so, what precisely did you fail at? [in another message] > This doc has not been updated since the 64 bit compilers came out > officially. That is not true. The documentation was last updated on 2006-07-14, which is after an AMD-64 SDK was released. > It doesn't make a whole lot of sense of what steps you > should follow to build python. I saw a link on the comp.lang.python > that had the steps, but that link doesn't go anywhere now. I had to > jump through some hoops to get it to build on VC 2005 64 bit, but that > at least had an IDE to use If you use vsextcomp, you also have an IDE to do the build. This is indeed how the official AMD-64 binaries for Python 2.5 were produced. Regards, Martin From goodTweetieBird at hotmail.com Thu Apr 26 18:08:08 2007 From: goodTweetieBird at hotmail.com (gtb) Date: 26 Apr 2007 15:08:08 -0700 Subject: Python keywords In-Reply-To: References: <1177613379.115009.23430@r3g2000prh.googlegroups.com> Message-ID: <1177625288.496090.267930@s33g2000prh.googlegroups.com> On Apr 26, 1:59 pm, "Hamilton, William " wrote: > > -----Original Message----- > > From: python-list-bounces+whamil1=entergy.... at python.org > [mailto:python- > > list-bounces+whamil1=entergy.... at python.org] On Behalf Of gtb > > Sent: Thursday, April 26, 2007 1:50 PM > > To: python-l... at python.org > > Subject: Re: Python keywords > > > On Apr 26, 10:16 am, Larry Bates wrote: > > >http://docs.python.org/ref/keywords.html > > > > in keyword is a general one and can be used for many objects. > > > > x in 'xyz' > > > > y in ['a','b','c','y','z''] > > > > z in ('a','b','c','y','z'] > > > > key in {'key1':1, 'key2': 2} > > > > The in you see with a for isn't associated with the for loop > > > but rather the sequence you are iterating over > > > > for i in range(10): > > > > -Larry > > > Thanks Larry. I saw that page you referenced above and that is how I > > knew it was a keyword. But I still have found nodocumentation that > > supports the examples you provided. > > http://docs.python.org/ref/comparisons.html#l2h-438 > > This information is 2 clicks away from any page in the reference: click > the index link, then scroll down to the link to "in operator". > > --- > -Bill Hamilton Thanks, Bill. I clicked there before and decided I must be experiencing an indexing error or such due to using firefox instead of IE when I didn't see "in operator" at the top of the page. Best Regards, john From mjones at 21cenlogic.com Sun Apr 29 18:19:18 2007 From: mjones at 21cenlogic.com (Mitchell Jones) Date: Sun, 29 Apr 2007 17:19:18 -0500 Subject: Video: Professor of Physics Phd at Cal Tech says: 911 Inside Job References: <1177467203.719625.93920@u32g2000prd.googlegroups.com> <1177780530.539758.275660@c35g2000hsg.googlegroups.com> <1177788032.971421.65550@c35g2000hsg.googlegroups.com> Message-ID: In article <1177788032.971421.65550 at c35g2000hsg.googlegroups.com>, War Office <911falseflag at gmail.com> wrote: > On 28 abr, 14:15, Eric Gisse wrote: > > On Apr 24, 6:13 pm, stj... at rock.com wrote: [snip] > > I love how folks like you ask for intellectual honesty when every > > effort is made to ignore evidence that doesn't agree with your > > presupposed findings. > > Which evidence would that be? ***{I'm not a fan of the Bush administration, and would not put it past them to carry out an event such as 911, to create an excuse to jettison the Constitution and Bill of Rights. What is certain in any case is that, in fact, the Bush administration has used the events of 911 as an excuse to toss out the Constitution and Bill of Rights. There are, however, at least three possible scenarios regarding 911 itself: (1) The plane crashes were planned and executed by terrorists. The towers fell because of the impacts. Building 7 fell because of the impact of debris from the north tower. (2) The plane crashes were planned and executed by the Bush administration. The towers fell because of the impacts. Building 7 fell because of the impact of debris from the north tower. (3) The plane crashes were planned and executed by the Bush administration. The towers fell because of the impacts, plus the effects of pre-planted demolition charges. Building 7 fell because of the impact of debris from the north tower, plus the effects of pre-planted explosive charges. I analyzed (3), above, in great detail a month or so back, in a sci.physics thread entitled "The amazing denial of what "conspiracy kooks" really means...." If you are really interested in a reasoned response to those arguments, you can probably still find that thread on Google. My conclusion at the time was that possibility (3), above, fails because pre-planted explosives are not needed to explain why the towers fell, or why building 7 fell. Possibilities (1) and (2), therefore, are all that remains. This post is for informational purposes only, and is not to be taken as an indication that I am interesting in slogging my way through all this stuff again. Once is more than enough, and so I am killfiling this thread after making this post. --Mitchell Jones}*** ***************************************************************** If I seem to be ignoring you, consider the possibility that you are in my killfile. --MJ From kw at codebykevin.com Wed Apr 18 20:25:24 2007 From: kw at codebykevin.com (Kevin Walzer) Date: Wed, 18 Apr 2007 20:25:24 -0400 Subject: Future Python Gui? In-Reply-To: <1176941169.750013.216660@e65g2000hsc.googlegroups.com> References: <1176859699.906386.326720@b75g2000hsg.googlegroups.com> <1176923448.998078.170760@e65g2000hsc.googlegroups.com> <46267C84.8040505@codebykevin.com> <1176941169.750013.216660@e65g2000hsc.googlegroups.com> Message-ID: <4caef$4626b6f4$4275d90a$19707@FUSE.NET> bcwhite at pobox.com wrote: >> On Windows, the easiest way to install Tile is to grab it from >> ActiveState's Tcl distribution >> (http://www.activestate.com/products/activetcl/) and then place it with >> the Tcl/Tk bits that come with Python. The Tcl/Tk build for Windows that >> python.org provides doesn't ship with Tile. You'll also have to install >> the Tile wrapper at the site I referenced earlier in your site-packages >> directory. > > For posterity's sake, here's what I did... > > - install python http://www.python.org/download/ > (use the Windows MSI install package) > - go to http://bruno.thoorens.free.fr/ and do the download > - instructions say to copy "tty.py" to "Tkinter" folder, but that > doesn't exist > - copy instead to C:\Python25\Lib > - copy folders as directed (to C:\Python25\Tcl) > > This should also work with the ActivePython download at > http://www.activestate.com/products/activepython/ . > > Within your program, you need: > > # Import "Tile" theming engine > tkroot.tk.call('package', 'require', 'tile') > tkroot.tk.call('namespace', 'import', '-force', 'ttk::*') > tkroot.tk.call('tile::setTheme', 'xpnative') > > after your call to "tkroot = Tk()" (or "tkroot = Tkinter.Tk()" if you > just "import Tkinter"). > > The frustrating part is that the main reason I wanted this is because > it says it wraps a "Notebook" widget. If it does, I can't find it! > > > -- Brian > The wrapper I maintain works differently, and includes the notebook widget. -- Kevin Walzer Code by Kevin http://www.codebykevin.com From 12cc104 at gmail.com Sun Apr 22 17:48:19 2007 From: 12cc104 at gmail.com (proctor) Date: 22 Apr 2007 14:48:19 -0700 Subject: recursion depth problem In-Reply-To: References: <1177267774.416169.276780@e65g2000hsc.googlegroups.com> <1177271382.859369.104790@q75g2000hsh.googlegroups.com> Message-ID: <1177278499.378120.246560@o5g2000hsb.googlegroups.com> On Apr 22, 2:06 pm, Steven Bethard wrote: > proctor wrote: > > On Apr 22, 1:24 pm, Michael Bentley wrote: > >> On Apr 22, 2007, at 1:49 PM, proctor wrote: > > >>> i have a small function which mimics binary counting. it runs fine as > >>> long as the input is not too long, but if i give it input longer than > >>> 8 characters it gives > >>> RuntimeError: maximum recursion depth exceeded in cmp > >>> i'm not too sure what i am doing improperly. is there really a lot of > >>> recursion in this code? > >>> ================== > >>> import sys > >>> def ch4(item, n=0): > >>> if n < len(item): > >>> if item[n] == '0': > >>> item[n] = '1' > >>> print ''.join(item) > >>> ch4(item) > >>> elif item[n] == '1': > >>> item[n] = '0' > >>> ch4(item, n+1) > >>> ch4(list(sys.argv[1])) > >>> ================== > >> Yes. There really is *that* much recursion in that code. 502 levels > >> with input length of 8 characters, 1013 with 9 characters, 2035 with > >> 10 characters... There's a pattern there ;-) > > > ok, thanks michael! > > > is there a way to avoid it here? how could i write this better, (if > > at all)? > > Google for permutation-like recipies: > > http://www.google.com/search?q=Python+permutations > > Use the code from the first hit:: > > >>> for x in xselections('01', 8): > ... print ''.join(x) > ... > 00000000 > 00000001 > 00000010 > ... > 11111101 > 11111110 > 11111111 > > Explaining to your teacher why your code uses generators when you > haven't been taught them yet is left as an exercise to the reader. ;-) > > STeVe this is really nice, thanks steve. much slicker than my code. for interest sake: is my method unredeemable? thanks very much! sincerely, proctor From grahn+nntp at snipabacken.dyndns.org Tue Apr 24 09:37:46 2007 From: grahn+nntp at snipabacken.dyndns.org (Jorgen Grahn) Date: 24 Apr 2007 13:37:46 GMT Subject: Python un-plugging the Interpreter References: <1hwu415.1yyvbo61efn1uqN%aleax@mac.com> Message-ID: On Thu, 19 Apr 2007 20:39:57 -0700, Alex Martelli wrote: > Steve Holden wrote: > >> A long time ago Greg Stein produced a patch that removed the need for >> the GIL, but nobody seemed to want to pay the penalty it extracted in >> speed reduction, so it languished unadopted. > > Perhaps the current wave of dual-core and quad-core CPUs in cheap > consumer products would change people's perceptions -- I wonder... Maybe it would change /perceptions/, but would normal users suddenly start running things that are (a) performance-critical, (b) written in Python and (c) use algorithms that are possible to parallellize? I doubt it. (But I admit that I am a bit negative towards thread programming in general, and I have whined about this before.) /Jorgen -- // Jorgen Grahn R'lyeh wgah'nagl fhtagn! From thorsten at thorstenkampe.de Mon Apr 2 11:10:49 2007 From: thorsten at thorstenkampe.de (Thorsten Kampe) Date: Mon, 2 Apr 2007 16:10:49 +0100 Subject: I18n issue with optik References: Message-ID: * Jarek Zgoda (Mon, 02 Apr 2007 17:52:34 +0200) > Thorsten Kampe napisa?(a): > > > I can't see the "solution" here. Is the optparse "print_help" function > > wrong? Why should there even be errors if I use "unicode = True" with > > gettext.install? > > > > I have ISO-8859-15 gettext translations and I want optparse to display > > them correctly. What do I have to do? > > Please, see gettext module documentation on this topic. > > The solution is: always install your translation with unicode=True > setting. This assures usage of ugettext() instead of gettext() and works > properly with character sets other than ASCII. Your messages are > internally decoded to unicode objects and passed to output. Then the > displayed output will be limited only by the encoding of your terminal, You are right. My problem is that all the terminals I use are set to US-ASCII (rxvt under Cygwin, Console[1] running bash, Poderosa[2] running bash). Even those who actually support non-ASCII characters. I got the tip to set a different encoding by sys.stdout = codecs.EncodedFile(sys.stdout, 'utf-8') but unfortunately this does not change the encoding. So my question is: how can I set a different encoding to sys.stdout (or why can I set it without any error but nothing changes?) Thorsten [1] http://sourceforge.net/project/screenshots.php?group_id=43764 [2] http://en.poderosa.org/present/about_poderosa.html From mailmaverick666 at gmail.com Fri Apr 13 08:24:56 2007 From: mailmaverick666 at gmail.com (rishi pathak) Date: Fri, 13 Apr 2007 17:54:56 +0530 Subject: Arrays, Got Me Confused In-Reply-To: <-3019760016345041986@unknownmsgid> References: <-3019760016345041986@unknownmsgid> Message-ID: <180b672e0704130524k876df57qccb2613a4c8acd1@mail.gmail.com> HI, You will have to import Numeric module Add from Numeric import * to the script For the second question: Suppose you wrote the code for your class in firewall.py and your main script is main.py Put the file firewall.py in the directory where you have main.py Then in main.py do : import firewall.py To create an object of class Firewall firewallDemo=firewall.Firewall() May be this will help On 4/13/07, Robert Rawlins - Think Blue wrote: > > Hello Guys, > > > > I'm struggling to get my head into arrays in python, I've used them plenty > in other languages but I'm struggling to find any decent documentation for > them in python. I'm looking to build a list of network MAC address's into an > array, which will probably be used for logging and firewalling and things. > > > > I've build the basic class, the idea is that the class represents the > firewall, and I have functions for the firewall like addDevice() and > isFirewalled() where I pass in the address and it returns a value or updates > the array. However I'm getting an error when trying to create an empty array > on the init. > > > > #!/usr/bin/python > > # Filename: Firewall.py > > > > class Firewall: > > > > def __init__(self): > > Self.FireArray = array(c) > > > > p = Firewall() > > print p > > > > > > Throws: > > > > Traceback (most recent call last): > > File "./firewall.py", line 9, in ? > > p = Firewall() > > File "./firewall.py", line 7, in __init__ > > Self.FireArray = array(c) > > NameError: global name 'array' is not defined > > > > How can I solve this problem? From what I've seen writing I can't see > anything wrong with my syntax, perhaps you can shed some light on the > situation. Whilst I'm writing there is also another question I would like to > pose briefly. How do a create an object from an external file? Obviously in > my one above all I need do is call Firewall() and it creates an instance, > but I'm used to creating my class's as separate files, how do I create them > as an object in my main application? > > > > Thanks, > > > > Rob > > -- > 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 michele.simionato at gmail.com Fri Apr 27 00:36:28 2007 From: michele.simionato at gmail.com (Michele Simionato) Date: 26 Apr 2007 21:36:28 -0700 Subject: EuroPython vs PyconUK In-Reply-To: <4630D480.7050308@gmail.com> References: <4630D480.7050308@gmail.com> Message-ID: <1177648588.208173.117060@t38g2000prd.googlegroups.com> On Apr 26, 6:34 pm, EuGeNe Van den Bulke wrote: > I do realize that the UK is not really part of Europe (no polemic :P) > but I am nevertheless curious about the logic behind creating another > major Python event in Europe. Wasn't EuroPython enough? > > Like many I am sure, I probably won't be able to attend both (and I > really enjoyed the Geneva experience so definitely want to renew "it"). > How would you go about selecting which conference to attend? > > They are only 2 months apart, 6 would have been easier for the > attendees! Could the organizers liaise one way or another to make > Pythoneers life as easy and fun as the language and give as much > information out as possible as early as possible (early bird early) for > people to make the best decision? > > I know marketing matters but ... > > EuGeNe --http://www.3kwa.com I don't see the problem. In my view EuroPython is the big event in Europe. If you can go to only one conference and you have the possibility to travel to Vilnius, then go to EuroPython. The national conferences are of interest primarily for people of that national (of course, not exclusively). I would be happy with a conference for any nationality. Each nation will have its national speakers. EuroPython will have all Europe to chose speakers from. BTW, this year I will go both to PyCon It and EuroPython, last year I went both to PyUK and EuroPython. The more, the better ;) Michele Simionato From spamtrap at dot-app.org Sun Apr 8 05:40:25 2007 From: spamtrap at dot-app.org (Sherm Pendley) Date: Sun, 08 Apr 2007 05:40:25 -0400 Subject: Hide the python-script from user References: <8ktie4-0i9.ln1@athlon.my> <1175898877.869321.112310@w1g2000hsg.googlegroups.com> <7ovie4-nfa.ln1@athlon.my> Message-ID: jmcbray-usenet at carcosa.net (Jason F. McBrayer) writes: > A determined and technically savvy user will surely find > the key (not least by debugging the start-script). ... and then write a patch that disables the key, and distribute that to a few million of his not so determined or savvy friends. > Basically, this doesn't work for the same reason that DRM doesn't > work. That reason being, it only needs to be cracked once. The odds are heavily stacked in the crackers' favor. sherm-- -- Web Hosting by West Virginians, for West Virginians: http://wv-www.net Cocoa programming in Perl: http://camelbones.sourceforge.net From steve at holdenweb.com Fri Apr 13 12:31:39 2007 From: steve at holdenweb.com (Steve Holden) Date: Fri, 13 Apr 2007 12:31:39 -0400 Subject: Class Dependancy Injection In-Reply-To: <15088.0762412728$1176479941@news.gmane.org> References: <15088.0762412728$1176479941@news.gmane.org> Message-ID: Robert Rawlins - Think Blue wrote: > Hey again guys, > > > > I?m looking to get an answer about dependency injection in python > classes, what is the best way to deal with this? > > > > For instance, in my application I have a configuration bean which > contains all the applications configuration information. Now in one of > other classes I need access to those configuration settings. What I > would have done in my ColdFusion/JAVA type applications is create an > instance of the configuration bean, and then pass that in as an argument > to the constructor for my other class, then have the other class set > that as a ?self? variable. Then from within my class I can access the > configuration details like self.config.getName() and it would return the > name of the application. > > How is this best handled in python, can I still inject dependencies as a > constructor argument like that? If so then is there anything in > particular I need to watch out for that may cause me trouble? > That indeed sounds like the best way to proceed. You should find that, modulo the language differences, the technique works in just the same way. You shouldn't anticipate trouble. 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 kyosohma at gmail.com Tue Apr 10 14:23:37 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: 10 Apr 2007 11:23:37 -0700 Subject: Can I get the exit code "n" passed to sys.exit(n) ? In-Reply-To: <1176228956.865875.295980@p77g2000hsh.googlegroups.com> References: <1176228956.865875.295980@p77g2000hsh.googlegroups.com> Message-ID: <1176229417.465182.152280@d57g2000hsg.googlegroups.com> On Apr 10, 1:15 pm, "Yujo" wrote: > Hello everybody, > > In the following code of the finish() function, is there any way to > get the exit code passed to sys.exit() ? > > def finish() : > RETURN_CODE_FROM_SYS_EXIT = ???? # how can I get it ? > if RETURN_CODE_FROM_SYS_EXIT = 0 : > # process ended OK > else : > # process ended with some error > # execute something > > atexit.register(finish) > > # this is my main program.... > > ERR_CODE=3 > sys.exit(ERR_CODE) > > Regards, > > Yujo I'm not sure if this will help or not, but this article is pretty enlightening and is written by a well-known Pythonista: http://www.artima.com/weblogs/viewpost.jsp?thread=4829 Here is another older post with helpful information: http://www.daniweb.com/techtalkforums/thread31226.html And here's a hack that might work: http://www.daniweb.com/techtalkforums/thread31166.html Mike From anton.vredegoor at gmail.com Sun Apr 15 12:14:04 2007 From: anton.vredegoor at gmail.com (Anton Vredegoor) Date: Sun, 15 Apr 2007 18:14:04 +0200 Subject: proposed PEP: iterator splicing In-Reply-To: <1176645742.313412.3120@o5g2000hsb.googlegroups.com> References: <7xirbyi5d7.fsf_-_@ruckus.brouhaha.com> <1176645742.313412.3120@o5g2000hsb.googlegroups.com> Message-ID: Kay Schluehr wrote: > Maybe you should start by developing a design pattern first and > publish it in the Cookbook. I have the fuzzy impression that the idea > you are after, requires more powerfull control structures such as > delimited continuations that are beyond ths scope of Pythons simple > coroutines. I was reacting to a request for thoughts. I firmly believe that there should be a relatively unrestricted brainstorming phase before one tries to implement things. I have often noticed a lot of counterproductive bickering about use cases and implementations on the developers list, but luckily not so much here. There is something like premature optimizations with respect to creative processes too! A. From mcPas.De.Spam at mclaveauPas.De.Spam.com Mon Apr 16 02:27:10 2007 From: mcPas.De.Spam at mclaveauPas.De.Spam.com (Michel Claveau) Date: Mon, 16 Apr 2007 08:27:10 +0200 Subject: How to initialize a table of months. References: Message-ID: Hi (bis) A class way : class cmon(object): Jan=1 Feb=2 Fev=2 Mar=3 Apr=4 Avr=4 May=5 Mai=5 Jun=6 Jui=6 Juin=6 Jul=7 Juil=7 Aug=8 Aou=8 Sep=9 Oct=10 Nov=11 Dec=12 print cmon.Mar print cmon.Sep print cmon.Dec -- @-salutations Michel Claveau From kay.schluehr at gmx.net Mon Apr 23 12:30:10 2007 From: kay.schluehr at gmx.net (Kay Schluehr) Date: 23 Apr 2007 09:30:10 -0700 Subject: Can __init__ not return an object? In-Reply-To: References: Message-ID: <1177345810.135528.192570@o5g2000hsb.googlegroups.com> On Apr 22, 4:36 am, "Steven W. Orr" wrote: > When I go to create an object I want to be able to decide whether the > object is valid or not in __init__, and if not, I want the constructor to > return something other than an object, (like maybe None). I seem to be > having problems. At the end of __init__ I say (something like) > > if self.something < minvalue: > del self > return None > > and it doesn't work. I first tried just the return None, then I got crafty > and tried the del self. Is what I'm trying to do possible in the > constructor or do I have to check after I return? Or would raising an > exception in the constructor be appropriate? You can raise an exception of course but it would just create a side effect. Another way to achieve what you request for is manipulating the class creation mechanism. class A(object): def __new__(cls, x): if x == 0: return None obj = object.__new__(cls) obj.__init__(x) return obj class B(A): def __init__(self, x): self.x = x The condition can always be checked within the static __new__ method. Kay From sjmachin at lexicon.net Sun Apr 29 08:34:08 2007 From: sjmachin at lexicon.net (John Machin) Date: 29 Apr 2007 05:34:08 -0700 Subject: Could zipfile module process the zip data in memory? In-Reply-To: References: <1177845313.798239.71580@o5g2000hsb.googlegroups.com> <1177847479.803195.12820@c35g2000hsg.googlegroups.com> Message-ID: <1177850048.310363.76510@l77g2000hsb.googlegroups.com> On Apr 29, 10:14 pm, "Daniel Nogradi" wrote: > > > > I made a C/S network program, the client receive the zip file from the > > > > server, and read the data into a variable. how could I process the > > > > zipfile directly without saving it into file. > > > > In the document of the zipfile module, I note that it mentions the > > > > file-like object? what does it mean? > > > > > class ZipFile( file[, mode[, compression[, allowZip64]]]) > > > > Open a ZIP file, where file can be either a path to a file (a > > > > string) or a file-like object. > > > > Yes it is possible to process the content of the zipfile without > > > saving every file: > > > > [untested] > > > > from zipfile import ZipFile > > > from StringIO import StringIO > > > > zipp = ZipFile( this_is_the_zip_file_from_your_server, 'r' ) > > > for name in zipp.namelist( ): > > > content = zipp.read( name ) > > > s = StringIO( ) > > > s.write( content ) > > > # now the file 'name' is in 's' (in memory) > > > # you can process it further > > > # ............ > > > s.close( ) > > > zipp.close( ) > > > > HTH, > > > Daniel > > Thanks! > > Maybe my poor english makes you confusion:-). The client receive the > > zip file data from the server, and keep these data as a variable, not > > as a file in harddisk. such as "zipFileData", but the first argument > > of the "ZipFile" is filename. I would like to let the ZipFile() open > > the file from "zipFileData" directly but not file in harddisk > > > zipp = ZipFile( this_is_the_zip_file_from_your_server, 'r' ) > > ^ I don't have this file, all its data > > is in a variable. > > Well, as you correctly pointed out in your original post ZipFile can > receive a filename or a file-like object. If the zip archive data is > in zipFileData then you might do: > > from StringIO import StringIO > from zipfile import ZipFile > > data = StringIO( ) > data.write( zipFileData ) > data.close( ) Even if that worked, it would be a long-winded way to do it. Please contemplate the docs: """getvalue( ) Retrieve the entire contents of the ``file'' at any time before the StringIO object's close() method is called.[snip note re mixing str & unicode] close( ) Free the memory buffer. """ The short working way is: """class StringIO( [buffer]) When a StringIO object is created, it can be initialized to an existing string by passing the string to the constructor.""" From gregtech at wp.pl Wed Apr 18 16:04:30 2007 From: gregtech at wp.pl (Grzegorz =?iso-8859-2?Q?=A6lusarek?=) Date: Wed, 18 Apr 2007 22:04:30 +0200 Subject: converting currency using locals References: <1a6pqx9mwzy6n$.1up65mccv8fm.dlg@40tude.net> Message-ID: <1avqlonvuyvtc$.101dks6tk0lxc$.dlg@40tude.net> Dnia Wed, 18 Apr 2007 19:38:26 +0100, Michael Hoffman napisa?(a): > Grzegorz ?lusarek wrote: >> Hi all. I have situation that I have value that holds price and I must show >> this price using national specification(e.g. thousands_sep). Any idea how >> this can be done under python 2.4.4? I saw that function format from module >> locals can format value with national specification, but this could be done >> only in python 2.5. Any solution for 2.4? > > I think you mean locale, for anyone else who was puzzled by this. Upss, I'm sorry ofcourse I was thinking about locale. Grzegorz ?lusarek From larry.bates at websafe.com Wed Apr 18 09:14:57 2007 From: larry.bates at websafe.com (Larry Bates) Date: Wed, 18 Apr 2007 08:14:57 -0500 Subject: How to Passs NULL as a IDispatch Pointer to method? In-Reply-To: <1176862267.482764.73530@b58g2000hsg.googlegroups.com> References: <1176783870.081696.278100@l77g2000hsb.googlegroups.com> <462529A4.40507@websafe.com> <1176862267.482764.73530@b58g2000hsg.googlegroups.com> Message-ID: Yingpu Zhao wrote: > Thanks to Larry. > I want to pass the IDispatch pointer of other COM object to > AddShapeInfo or pass null to tell x do nothing. > for example. > > Rect= Dispatch("Rect.Document") > ShapeSet = Dispatch("xxx.Document") > ShapeSet.AddShapeInfo("Rect", 0, Shape) > > or > > ShapeSet.AddShapeInfo("EmptyShape", 0, None) > I think you will need to pass a basically empty class that is wrapped in an IDispatch object. See my earlier example. -Larry From bbxx789_05ss at yahoo.com Wed Apr 4 23:38:04 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: 4 Apr 2007 20:38:04 -0700 Subject: Getting word frequencies from files which are in folder. In-Reply-To: <1175717246.781352.178090@e65g2000hsc.googlegroups.com> References: <1175710660.753453.205000@n76g2000hsh.googlegroups.com> <4613f24f$0$327$e4fe514c@news.xs4all.nl> <1175717246.781352.178090@e65g2000hsc.googlegroups.com> Message-ID: <1175744284.893290.319960@y66g2000hsf.googlegroups.com> On Apr 4, 2:07 pm, krisbee1... at gmail.com wrote: > My question is how to get word frequencies from this files? > I will be glad to get any help. > --files have a read(), readline(), and readlines() method --strings have a split() method, which splits the string on whitespace(e.g. spaces) --lists have a count() method From dd55 at cornell.edu Mon Apr 23 10:53:05 2007 From: dd55 at cornell.edu (Darren Dale) Date: Mon, 23 Apr 2007 10:53:05 -0400 Subject: python style guide inconsistencies References: <5922mkF2i88dhU1@mid.individual.net> Message-ID: Bjoern Schliessmann wrote: > Darren Dale wrote: > >> I was just searching for some guidance on how to name packages and >> modules, and discovered some inconsistencies on the >> www.python.org. http://www.python.org/doc/essays/styleguide.html >> says "Module names can be either MixedCase or lowercase." That >> page also refers to PEP 8 at >> http://www.python.org/dev/peps/pep-0008/, which says "Modules >> should have short, all-lowercase names. ... Python packages should >> also have short, all-lowercase names ...". >> >> Which is most up to date? > > The priority is, IMHO, clear. The old style guide essay says, at the > beginning: > > | This style guide has been converted to several PEPs (Python > | Enhancement Proposals): PEP 8 for the main text, PEP 257 for > | docstring conventions. See the PEP index. > > So PEP 8 is the most recent. Then perhaps http://www.python.org/doc/essays/styleguide.html should either be updated to either agree with or simply link to PEPs 8 and 257. What is the point of keeping old, out-of-date essays up on python.org? That beginning comment does not indicate that the essay is any different from the PEPs. From bbxx789_05ss at yahoo.com Sat Apr 14 14:57:58 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: 14 Apr 2007 11:57:58 -0700 Subject: Python Feature Request: Add the "using" keyword which works like "with" in Visual Basic In-Reply-To: <1176547372.584539.89170@q75g2000hsh.googlegroups.com> References: <1176547372.584539.89170@q75g2000hsh.googlegroups.com> Message-ID: <1176577078.549674.293390@y80g2000hsf.googlegroups.com> On Apr 14, 4:42 am, samj... at gmail.com wrote: > This also is > similar to the C++ "using" keyword which exposes the members of a > namespace to access without specifying the namespace scope for each > reference. For example after giving "using namespace std;" I can > change all references to "std::cout" to "cout", which is similar to > what I am proposing for Python now. > ...which is a bad practice in C++. When you expose the members of a namespace, you create the potential for name clashes with the names in your program. Why would you want to infect Python with that problem? From nick at craig-wood.com Sun Apr 15 05:30:06 2007 From: nick at craig-wood.com (Nick Craig-Wood) Date: Sun, 15 Apr 2007 04:30:06 -0500 Subject: Python Feature Request: Allow changing base of member indices to 1 References: <1176546465.632410.52630@w1g2000hsg.googlegroups.com> <1176579205.948684.171640@q75g2000hsh.googlegroups.com> Message-ID: Sherm Pendley wrote: > "Paddy" writes: > > > Having more than one index start point would be a maintenance > > nightmare best avoided. > > Quite right. > > > (It can be done in Perl). > > When was the last time you used Perl? It was allowed in Perl 4 and earlier, > because many Perl users were moving from Awk, which uses an array base of 1. > Even then, having multiple index start points within a single program wasn't > the idea; the idea was to allow programs originally written in Awk to be > ported to Perl with minimal updating. > > It was deprecated as of 5.0 though - which was released in '94. It still > works, for the sake of backwards compatibility, but its use in new code is > highly discouraged. I seem to remember from "Programming Perl" that Larry Wall said it was a serious mistake to add this feature to perl. If it is a feature too far for perl then it is *definitely* a feature too far for python ;-) -- Nick Craig-Wood -- http://www.craig-wood.com/nick From steven.klass at gmail.com Tue Apr 24 10:59:20 2007 From: steven.klass at gmail.com (rh0dium) Date: 24 Apr 2007 07:59:20 -0700 Subject: Convert a string to a list Message-ID: <1177426760.164877.104990@t38g2000prd.googlegroups.com> Hi all, I am using pexpect to drive another tool. Some of the data I get back would be better suited as a list and I want to know a simple way to parse the data to push it into a list. For example I get the following string back. I want to convert this to a list: '("." ".." "cdslib_cleanup.py" "cadence.py" "cdsinit_cdsenv_cleanup.py")' should be: ["." ".." "cdslib_cleanup.py" "cadence.py" "cdsinit_cdsenv_cleanup.py"] It should be able to handle embeded lists like this: '("." ("cadence.py" "foo_cleanup.py") "cdslib_cleanup.py" "cadence.py" "cdsinit_cdsenv_cleanup.py")' should become ["." ["cadence.py" "foo_cleanup.py"] "cdslib_cleanup.py" "cadence.py" "cdsinit_cdsenv_cleanup.py"] Is there some exisitng code which will handle this task? From attn.steven.kuo at gmail.com Thu Apr 5 13:52:44 2007 From: attn.steven.kuo at gmail.com (attn.steven.kuo at gmail.com) Date: 5 Apr 2007 10:52:44 -0700 Subject: how to remove multiple occurrences of a string within a list? In-Reply-To: <1hw28y7.1t2kviz1x7guagN%aleax@mac.com> References: <1175624433.206953.214290@n59g2000hsh.googlegroups.com> <1hw28y7.1t2kviz1x7guagN%aleax@mac.com> Message-ID: <1175795564.907524.143560@y66g2000hsf.googlegroups.com> On Apr 4, 7:43 pm, a... at mac.com (Alex Martelli) wrote: (snipped) > A "we-don't-need-no-stinkin'-one-liners" more relaxed approach: > > import collections > d = collections.defaultdict(int) > for x in myList: d[x] += 1 > list(x for x in myList if d[x]==1) > > yields O(N) performance (give that dict-indexing is about O(1)...). > > Collapsing this kind of approach back into a "one-liner" while keeping > the O(N) performance is not easy -- whether this is a fortunate or > unfortunate ocurrence is of course debatable. If we had a "turn > sequence into bag" function somewhere (and it might be worth having it > for other reasons): > > def bagit(seq): > import collections > d = collections.defaultdict(int) > for x in seq: d[x] += 1 > return d > > then one-linerness might be achieved in the "gimme nonduplicated items" > task via a dirty, rotten trick...: > > list(x for bag in [bagit(myList)] for x in myList if bag[x] == 1) > > ...which I would of course never mention in polite company... > > Alex With a "context managed" set one could have, as a one-liner: with cset() as s: retval = [ (x, s.add(x))[0] for x in myList if x not in s ] I've not looked at the underlying implementation of set(), but I presume that checking set membership is also about O(1). -- Cheers, Steven From grahn+nntp at snipabacken.dyndns.org Thu Apr 19 12:46:09 2007 From: grahn+nntp at snipabacken.dyndns.org (Jorgen Grahn) Date: 19 Apr 2007 16:46:09 GMT Subject: Shebang or Hashbang for modules or not? References: <1176308951.932721.197630@y80g2000hsf.googlegroups.com> <461d56e9$0$27586$426a74cc@news.free.fr> <461fe2d8$0$11935$426a74cc@news.free.fr> Message-ID: On Fri, 13 Apr 2007 22:46:03 +0200, Bruno Desthuilliers wrote: > Jorgen Grahn a ?crit : ... >> If you distribute a >> Python program to Unix users in that form, they may not want to know >> or care which language it's written in. Especially if you decide, a >> few releases later, that you want to switch to Perl or something. > > > No one in it's own mind would decide to switch from Python to Perl !-) > I was trolling a bit, too ;-) Actually, it made sense in my case. It was a typical Perl task -- a filter regex-parsing a huge (a few hundred megabytes) text file. Rewriting it in Perl for speed was faster and more readable than rewriting it in Python for speed. > More seriously, and as far as I'm concerned, when I want to make a > python script (by opposition to a python 'module') available as a unix > command, I either use a symlink or a shell script calling the python > script. A symlink yes, but a shell script? Wouldn't it be easier to write a one-liner (well, two-liner) Python script in that case? >>>>I'm used to having a >>>>shebang in every .py file >>> >>>An encoding declaration might be more useful IMHO !-) ... >> I always use both. > > Even in modules ????? Yes, for a few reasons: - file(1) can tell it's Python source - I tend to leave unit tests in my modules - I just started doing that when I first tried Python; it's part of my mental boilerplate I don't claim they are good reasons. And since I strongly dislike setting the execute bit on things that aren't executable, I should probably stop using the shebang everywhere, too ... /Jorgen -- // Jorgen Grahn R'lyeh wgah'nagl fhtagn! From steve at holdenweb.com Wed Apr 4 12:34:47 2007 From: steve at holdenweb.com (Steve Holden) Date: Wed, 04 Apr 2007 12:34:47 -0400 Subject: How to process the nested String for sybase sql statement? In-Reply-To: References: Message-ID: boyeestudio wrote: > now,I want to insert some data to the sybase database, > some variable such as i,j,k,name,k,j I have defined before. > I write the sql statement here But I meet some errors,How to write this > nested String for sql query? > For example: > > >>>import Sybase > >>> db = Sybase.connect('boyee','sa','',"test'') > >>> c = db.cursor() > ...... > > >>> values = "%d,%d,%d,%s,%d,%d" % (i,j,k,name,k,j) > >>> c.execute("'insert into > productinfo(productid,spid,corpid,productname,type1, > type2) value(@value)',{'@value':values}") > > Traceback (most recent call last): > File "", line 1, in ? > File "C:\Python24\lib\site-packages\Sybase.py", line 774, in execute > self.description = fetcher.start(self.arraysize) > File "C:\Python24\lib\site-packages\Sybase.py", line 517, in start > return self._start_results() > File "C:\Python24\lib\site-packages\Sybase.py", line 645, in > _start_results > self._raise_error(Error, 'ct_results') > File "C:\Python24\lib\site-packages\Sybase.py", line 506, in _raise_error > raise exc(text) > Sybase.Error: ct_results > > Any reply is enjoyable,Thank a lot! > Try instead: values = (i,j,k,name,k,j) c.execute("""insert into productinfo (productid, spid, corpid, productname, type1, type2) values (%d,%d,%d,%s,%d,%d)""", values) I haven't used the Sybase module - you may find you need to use %s,%s,%s,%s,%s,%s to represent the parameterized values in the query rather than %d,%d,%d,%s,%d,%d Don't forget to call db.commit() to make the changes permanent. 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 xah at xahlee.org Mon Apr 23 06:53:11 2007 From: xah at xahlee.org (Xah Lee) Date: 23 Apr 2007 03:53:11 -0700 Subject: The Hack of bitmask used as Predicate Parameters Message-ID: <1177325591.380907.262730@n76g2000hsh.googlegroups.com> In this article, i explain how the use of bit masks is a hack in many imperative languages. Often, a function will need to take many True/False parameters. For example, suppose i have a function that can draw a rainbow, and each color of the rainbow can be turned on or off individually. My function specification can be of this form: ?rainbow(red, orange, yellow, green, blue, violet, purple)?. Each parameter is a true or false value. So, to draw a rainbow with only red and yellow stripes on, one would code, for example ?rainbow(t,f,t,f,f,f,f)?, where ?t? stands for true and ?f? stands for false. (or, similar values for the true/false of the language's boolean system) The problem with this simple approach is that when a function has too many parameters, ?which position means what? becomes difficult to remember and manage. Alternatively, a high-level language may provide a system for named parameters. So, for example, the function may be called like this with 2 arguments ?rainbow(red:t, yellow:t)?, meaning, give the true values to the parameters named ?red? and ?yellow?. Parameters not given may automatically assumed to have false values by default. Similarly, the language can simply have the function call look like this: ?rainbow(red, yellow)?, where omitted parameter names simply means false. LSL deals with this issue by using a concept of bit-mask that came from low-level languages. From the programer's point of view, the way to call this rainbow function would look like this: ?rainbow(red| yellow)?. On the surface, it seems just a syntax variation. But actually, the ?red? and ?yellow? here are global constants of type integer, defined by the language, and the ?|? is actually a bit-wise binary operator. To explain this to a educated person (e.g. a mathematician) but who are not a professional programer, it gets a bit complex as one has to drag in binary notation, boolean operation on binary notation realized as a sequence of slots, and the compiler ease in processing numbers as binary digits, and the compiler writer and language designer's laziness in resorting to these instead of a high- level interface of named parameters. The hack of using the so-called bit-mask as a interface for functions that need named parameters, is similar to languages using ?1? and ?0? as the true/false symbols in its boolean system, and languages using the ?or? operator ?||? as a method of nested ?if else? program flow constructs. The problem with these hacks, is that they jam logically disparate semantics into the same construct. Their effects is making the source code more difficult to read, and thus increased programer error. ---- It may seem like nickpicking to say that it is a hack. However, when many such seemingly trivially improper designs appear in a language, adds up to the language's illness, and overall making the language difficult to learn, difficult to read, difficult to extend, increase programing errors, and most importantly, reduce a clear understanding of key concepts. Unix and C, are the primary perpetrator of this sin. Due to their ?$free$? and ?speedy? and ?simplistic? nature as cigarettes given to children, have passed these designs to many imperative languages and left programers not understanding the basic issues of a function's parameters and named parameters. Examples of using bitmask as a hack: ? Many functions in C. (e.g. fcntl) ? Unix's function/?command line tool?'s error values. (as bits) ? Perl's ?sysopen?, ?select?, and others. (if you know a perl example that isn't related to unix, pls let me known) ? Second Life's Linden Scripting Language. (see http://xahlee.org/sl/ls-prob.html ) A example of confusion about function's parameters is exhibited in unix's bewildering, inconsist syntaxes in its command line tools's ways of taking arguments. (some parameter influence other parameters. Argument order sometimes matter, sometimes doesn't, sometimes causing unintented output and sometimes causing syntax error. Named parameters sometimes have the names optional(!). Named parameters that are predicates sometimes act by their presence along, sometimes by their value, sometimes accept both, sometimes causes syntax error. Some defaults are supplied to unnamed parameters, and some are to named parameters. Some parameters has synonyms. ...) For another example in a more modern language, is Python's ?re.search()? function for text pattern matching. Its optional third parameter is a bitmask. ( see ?Regular Expressions in Python? http://xahlee.org/perl-python/python_re-write/lib/node111.html ) As a example of not clearly understanding a function's parameters and the need and role of named parameters in computing languages, Python's ?sorted? function as well as its ?lambda? construct are both victims. (Further reading: ? ?Sorting in Python and Perl? http://xahlee.org/perl-python/python_doc_sort.html ? ?Python Doc Problem Example: sort()? http://xahlee.org/perl-python/sort_list.html ? ?Lambda in Python 3000? http://xahlee.org//perl-python/python_3000.html ) Bitmask used as a function's parameter but not considered as a hack, would be if it actually deals with bits necessarily (e.g. in protocols that employ bits. (e.g. in networking), byte processing, binary digit computation, ...) I would appreciate other examples you know in the above languages, and or in particular if Java, Lisp, Haskell. ---- This article is a modified excerpt from ?Linden Scripting Language Problems? at http://xahlee.org/sl/ls-prob.html Xah xah at xahlee.org ? http://xahlee.org/ From gjcarneiro at gmail.com Sun Apr 1 08:47:39 2007 From: gjcarneiro at gmail.com (Gustavo Carneiro) Date: Sun, 1 Apr 2007 13:47:39 +0100 Subject: [Python-Dev] Python 3000 PEP: Postfix type declarations In-Reply-To: References: Message-ID: On 4/1/07, Gustavo Carneiro wrote: > > On 4/1/07, Georg Brandl wrote: > [...] > > > Example > > ======= > > > > This is the standard ``os.path.normpath`` function, converted to type > > declaration > > syntax:: > > > > def normpath?(path?)?: > > """Normalize path, eliminating double slashes, etc.""" > > if path? == '': > > return '.' > > initial_slashes? = path?.startswith?('/')? > > # POSIX allows one or two initial slashes, but treats three or > > more > > # as single slash. > > if (initial_slashes? and > > path?.startswith?('//')? and not > > path?.startswith?('///')?)?: > > initial_slashes? = 2 > > comps? = path?.split?('/')? > > new_comps? = []? > > for comp? in comps?: > > if comp? in ('', '.')?: > > continue > > if (comp? != '..' or (not initial_slashes? and not > > new_comps?)? or > > (new_comps? and new_comps?[-1]? == '..')?)?: > > new_comps?.append?(comp?) > > elif new_comps?: > > new_comps?.pop?()? > > comps? = new_comps? > > path? = '/'.join(comps?)? > > if initial_slashes?: > > path? = '/'*initial_slashes? + path? > > return path? or '.' > > > > As you can clearly see, the type declarations add expressiveness, while > > at the > > same time they make the code look much more professional. > > > Is this supposed to be a joke? /me ashamed for not having noticed the date of this PEP... :P -- Gustavo J. A. M. Carneiro "The universe is always one step beyond logic." -------------- next part -------------- An HTML attachment was scrubbed... URL: From surekap at gmail.com Sun Apr 29 17:48:48 2007 From: surekap at gmail.com (Prateek) Date: 29 Apr 2007 14:48:48 -0700 Subject: fastest way to find the intersection of n lists of sets Message-ID: <1177883328.835058.138990@p77g2000hsh.googlegroups.com> I have 3 variable length lists of sets. I need to find the common elements in each list (across sets) really really quickly. Here is some sample code: # Doesn't make sense to union the sets - we're going to do intersections later anyway l1 = reduce(operator.add, list(x) for x in l1) l2 = reduce(operator.add, list(x) for x in l2) l3 = reduce(operator.add, list(x) for x in l3) # Should I do this in two steps? Maybe by intersecting the two shortest lists first? s = frozenset(l1) & frozenset(l2) & frozenset(l3) I'm assuming frozensets are (somehow) quicker than sets because they're immutable. Any code suggestions? Maybe using something in the new fancy-schmancy itertools module? Thanks, Prateek From mwilson at the-wire.com Sat Apr 14 11:35:57 2007 From: mwilson at the-wire.com (Mel Wilson) Date: Sat, 14 Apr 2007 11:35:57 -0400 Subject: Python Feature Request: Allow changing base of member indices to 1 In-Reply-To: <1176559643.450533.296850@n59g2000hsh.googlegroups.com> References: <1176546465.632410.52630@w1g2000hsg.googlegroups.com> <4620b47b$0$14410$9b622d9e@news.freenet.de> <1176557999.665663.299740@y80g2000hsf.googlegroups.com> <1176559643.450533.296850@n59g2000hsh.googlegroups.com> Message-ID: jamadagni wrote: > OK fine. It is clear that this feature must be implemented if at all > only on a per-module basis. So can we have votes for per-module > implementation of this feature? The only way that can work is if the API to the module doesn't expose ANY sequence indices. It would be a great pain to have to remember which of the modules you've imported expect base 0 and which expect base 1. (There's a Monty Python sketch: a station full of police officers who only understand you if you speak slowly/quickly/high-pitched/low-pitched/etc. depending on the individual officer.) The scheme could work if the module was carefully programmed to show and accept only application-relevant values that nobody would expect to have an alternative base -- quantities of things, arbitrary code numbers, and the like. Mel. From http Sat Apr 14 13:59:42 2007 From: http (Paul Rubin) Date: 14 Apr 2007 10:59:42 -0700 Subject: tuples, index method, Python's design References: <7xzm5igbrb.fsf@ruckus.brouhaha.com> <1176200361.260546.280510@n76g2000hsh.googlegroups.com> <740c3aec0704100824m132c45fbi5c4c3ec0c0fa3a67@mail.gmail.com> <1176489534.568939.249910@q75g2000hsh.googlegroups.com> <7x3b33k0l9.fsf@ruckus.brouhaha.com> <1176572775.382873.282850@q75g2000hsh.googlegroups.com> Message-ID: <7xr6qmrg4x.fsf@ruckus.brouhaha.com> "Rhamphoryncus" writes: > > > > i = s.index(e) => s[i] = e > > > > Then this algorithm is no longer guaranteed to work with strings. > > > It never worked correctly on unicode strings anyway (which becomes the > > > canonical string in python 3.0). > > > > What?! Are you sure? That sounds broken to me. > > Nope, it's pretty fundamental to working with text, unicode only being > an extreme example: there's a wide number of ways to break down a > chunk of text, making the odds of "e" being any particular one fairly > low. Python's unicode type only makes this slightly worse, not > promising any particular one is available. I don't understand this. I thought that unicode was a character coding system like ascii, except with an enormous character set combined with a bunch of different algorithms for encoding unicode strings as byte sequences. But I've thought of those algorithms (UTF-8 and so forth) as basically being kludgy data compression schemes, and unicode strings are still just sequences of code points. From p.edelman at gmail.com Fri Apr 27 11:29:25 2007 From: p.edelman at gmail.com (Pieter Edelman) Date: 27 Apr 2007 08:29:25 -0700 Subject: Access to raw command line? In-Reply-To: <1331kmvfdi9ck12@corp.supernews.com> References: <1177571070.229968.155710@t39g2000prd.googlegroups.com> <1177603801.337600.5150@r30g2000prh.googlegroups.com> <1331kmvfdi9ck12@corp.supernews.com> Message-ID: <1177687765.829887.10910@n35g2000prd.googlegroups.com> Yes, but I want to make it less difficult for my end users, not more difficult. I think the best is to require an extra switch for the photo files, as some of the people here suggested. On Apr 26, 6:27 pm, Grant Edwards wrote: > On 2007-04-26, Pieter Edelman wrote: > > > All your posts pretty much confirmed my own thoughts on this subject. > > Every option requires a specific action from the user, and as Bjoern > > points out, it would differ from what everybody is used to. I think > > there's no trivial and reliable way to do this, so I can better leave > > it the way it is (at least for now). > > Quoting things on the command line that you don't want the > shell to expand is trivial and reliable. It's also something > than any shell user should know. > > -- > Grant Edwards grante Yow! I wonder if there's > at anything GOOD on tonight? > visi.com From whamil1 at entergy.com Mon Apr 30 11:16:15 2007 From: whamil1 at entergy.com (Hamilton, William ) Date: Mon, 30 Apr 2007 10:16:15 -0500 Subject: import structures In-Reply-To: <1177945378.731721.137080@o5g2000hsb.googlegroups.com> Message-ID: <588D53831C701746A2DF46E365C018CE01D2CA80@LITEXETSP001.etrsouth.corp.entergy.com> > -----Original Message----- > From: python-list-bounces+whamil1=entergy.com at python.org [mailto:python- > list-bounces+whamil1=entergy.com at python.org] On Behalf Of spohle > Sent: Monday, April 30, 2007 10:03 AM > To: python-list at python.org > Subject: Re: import structures > > On Apr 30, 8:00 am, Paul McGuire wrote: > > On Apr 30, 9:56 am, spohle wrote: > > > > > > > > > hi, > > > > > i have written a small project for myself all in seperate classes and > > > each of the classes lives in a seperate file. now i am looking for an > > > import structure something like import wx, and then have access to all > > > my classes just like wx.Button or wx.BoxSizer etc. > > > > > as of now i have a __init__.py file in the directory with: > > > from pkgutil import extend_path > > > __path__ = extend_path(__path__, __name__) > > > > > but i still have to import each class by it's own. im really looking > > > for something like import wx > > > and then get all my access right away under this new namespace. > > > > > thank you in advance > > > > If it really is a small project, consider just putting all the classes > > into a single module, say spohlePkg.py. Then your users would import > > this module using "import spohlePkg", and would access the classes as > > "spohlePkg.ClassA", "spohlePkg.ClassB", etc. > > > > -- Paul > > yeah i had that, but my classes grew really fast and i decided to > split them up. but you're right that in one file that would solve my > problem. still hoping to find a way for the seperate files. > If you've got modules a, b, and c, you can create a wrapper module d that imports from each of those. from a import * from b import * from c import * Then, import d and use it as the module name. So if a had a SomeThing class, you could do this: import d x = d.SomeThing() --- -Bill Hamilton From wangday at gmail.com Wed Apr 4 09:15:30 2007 From: wangday at gmail.com (lancered) Date: 4 Apr 2007 06:15:30 -0700 Subject: An error of matrix inversion using NumPy Message-ID: <1175692530.364381.77110@n59g2000hsh.googlegroups.com> Hi dear all, I am using Python2.4.2+NumPy1.0.1 to deal with a parameter estimation problem with the least square methods. During the calculations, I use NumPy package to deal with matrix operations, mostly matrix inversion and trasposition. The dimentions of the matrices used are about 29x19,19x19 and 29x29. During the calculation, I noticed an apparent error of inverion of a 19x19 matrix. Denote this matrix as KK, U=KK^ -1, I found the product of U and KK is not equivalent to unit matrix! This apparently violate the definition of inversion. The inversion is through the function linalg.inv(). I have checked that det(KK)=-1.2E+40. At first, I thought the error may be caused by such a large determinant, so I scaled it as LL=KK/100, then invert LL. Since det(LL)=11.5 and all its elements are within -180.0 to 850.0, this seems easier. But the result is still not correct, the product of LL^-1 thus obtained and LL still not unit matrix ... At the same time, the inversion results of some 29x19 matrices are correct. So, can you tell me what goes wrong? Is this a bug in Numpy.linalg? How to deal with this situation? If you need, I can post the matrix I used below, but it is so long,so not at the moment. Thanks in advance! From tdelaney at avaya.com Wed Apr 4 19:35:45 2007 From: tdelaney at avaya.com (Delaney, Timothy (Tim)) Date: Thu, 5 Apr 2007 09:35:45 +1000 Subject: how can I clear a dictionary in python Message-ID: <2773CAC687FD5F4689F526998C7E4E5FF1ED52@au3010avexu1.global.avaya.com> Antoon Pardon wrote: > People are often enough not very exact in their communication and > that goes double for people who are new in a particular subject. > So I think it is entirely appropiate to think about the real question > the person is strugling with that hides between the question > actually asked. > > Yes sometimes those who try to guess the intentions of the OP > are going totally off in the wrong direction. But I have also > seen those people providing very helpfull information, while > those that would stick to the "actual" question didn'y provide > very usefull information. And yet it's giving the *wrong* information if the person was asking exactly the question they intended to ask. If you think there is some ambiguity, you should *clarify* the question before answering. Answering a different question to the one that is asked just causes problems, and the kind of thread this has degenerated into. Tim Delaney From mail at microcorp.co.za Fri Apr 20 01:51:28 2007 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Fri, 20 Apr 2007 07:51:28 +0200 Subject: comparison with None References: <_JAVh.1700$jR5.897@trnddc08> <462709FB.9020607@gmail.com> <462792BE.906@gmail.com> Message-ID: <00ee01c78318$68c76420$03000080@hendrik> "Steve Holden" wrote: > PS: Revision question: How many objects of type NoneType are there? You ask the damnesd Questions. There must be millions of the little buggers out there, with the population shifting incessantly as instances of the interpreter are started, and die.. I think this is a question that can never be answered with an unqualified number... Unless of course, the answer is 42. - Hendrik From ashokagk at gmail.com Thu Apr 26 13:18:18 2007 From: ashokagk at gmail.com (Ashok) Date: 26 Apr 2007 10:18:18 -0700 Subject: problem in running python on winnt Message-ID: <1177607898.610768.48320@r3g2000prh.googlegroups.com> hello, I have built a standalone gui application using py2exe which works fine in my WinXp SP2 machine and another WinXp machine. When i try to run it in a Win NT SP6 machine, I get the following error. Traceback (most recent call last): File "auto.py", line 4, in ? File "zipextimporter.pyo", line 82, in load_module File "wx\_init_.pyo", line 45, in? File "zipextimporter.pyo", line 82, in load_module File "wx\_init_.pyo", line 4, in? File "zipextimporter.pyo", line 98, in load_module ImportError : MemoryLoadLibrary failed loading wx\_core_.pyd I use python 2.4.2, wxpython 2.8, py2exe 0.6.6 for development can anybody come up with a solution? thanks in advance ____ AGK From octomancer at blueyonder.co.uk Mon Apr 2 07:48:10 2007 From: octomancer at blueyonder.co.uk (Octo) Date: 2 Apr 2007 04:48:10 -0700 Subject: Any "consumer review generators" available? In-Reply-To: References: Message-ID: <1175514490.263622.138320@y80g2000hsf.googlegroups.com> On 29 Mar, 20:00, Uri Guttman wrote: > >>>>> "a" == aralsky writes: > > a> I am looking for a fake consumer review generator that could > a> generate realistic looking reviews for any products, kind of like > a> on amazon.com but generated by Artificial Intelligence. Is there a > a> package available in your favorite programing language... thx alan > > it's called a human being. and hope you find some with ethics which you > don't seem to have. People don't have ethics, they have morals. Ethics are characteristics of collectives, not individuals. R From bearophileHUGS at lycos.com Sat Apr 14 06:50:52 2007 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 14 Apr 2007 03:50:52 -0700 Subject: Python Feature Request: (?) Group all file-directory-related stdlib functions in one place In-Reply-To: <1176546615.450418.268090@y5g2000hsa.googlegroups.com> References: <1176546615.450418.268090@y5g2000hsa.googlegroups.com> Message-ID: <1176547852.844011.105250@q75g2000hsh.googlegroups.com> > Currently file-directory-related functionality in the Python standard > library is scattered among various modules such as shutil, os, > dircache etc. So I request that the functions be gathered and > consolidated at one place. Some may need renaming to avoid conflicts > or for clarification. I think similar consolidations of the STD lib are positive, they are scheduled for Python V.3.0-3.1: http://www.python.org/dev/peps/pep-3001/ http://www.python.org/dev/peps/pep-3108/ If you submit this to python-dev I suggest you to work as much as possible: finding a good organization, writing justifications all for all the changes etc. You can also remember that lot of people are using some nonstandard modules, like the path one, that may be fit for the STD library, once cleaned up a bit, so you have to take into accout that too. Bye, bearophile From silverburgh.meryl at gmail.com Sun Apr 1 14:15:39 2007 From: silverburgh.meryl at gmail.com (silverburgh.meryl at gmail.com) Date: 1 Apr 2007 11:15:39 -0700 Subject: re.findall() hangs in python In-Reply-To: <1175423039.310796.50200@n76g2000hsh.googlegroups.com> References: <1175397176.567214.194810@n59g2000hsh.googlegroups.com> <1175423039.310796.50200@n76g2000hsh.googlegroups.com> Message-ID: <1175451339.781866.47380@n76g2000hsh.googlegroups.com> On Apr 1, 5:23 am, irs... at gmail.com wrote: > On Apr 1, 6:12 am, "silverburgh.me... at gmail.com" > > wrote: > > But when 'data' does not contain pattern, it just hangs at > > 're.findall' > > > pattern = re.compile("(.*) > re.S) > > That pattern is just really slow to evaluate. What you want is > probably something more like this: > > re.compile(r']*src\s*=\s*"([^"]*img[^"]*)"') > > "dot" is usually not so great. Prefer "NOT end-character", like [^>] > or [^"]. Thank you. Your suggestion solves my problem! From fd0man at gmail.com Sun Apr 1 13:52:30 2007 From: fd0man at gmail.com (Michael B. Trausch) Date: Sun, 01 Apr 2007 13:52:30 -0400 Subject: Character set woes with binary data In-Reply-To: References: <1175415685.21349.79.camel@pepper.trausch.us> Message-ID: <1175449950.10317.22.camel@pepper.trausch.us> On Sun, 2007-04-01 at 06:09 -0300, Gabriel Genellina wrote: > > When putting the MIME segments (listed line-by-line in a Python list) > > together to transmit them. The files are typically JPG or some other > > binary format, and as best as I understand the protocol, the binary data > > needs to be transmitted directly (this is evidenced by looking at the > > tcp-stream of an existing client for uploading files). > > But I think your problem has nothing to do with MIME: you are mixing > unicode and string objects; from your traceback, either the "L" list or > "eol" contain unicode objects that can't be represented as ASCII strings. > I never said it did. It just happens to be the context with which I am working. I said I wanted to concatenate materials without regard for the character set. I am mixing binary data with ASCII and Unicode, for sure, but I should be able to do this. The current source can be found at http://fd0man.theunixplace.com/scrapbook.py which is the version that I am having the problem with. > > It seems that Python thinks it knows better than I do, though. I want > > to send this binary data straightaway to the server. :-) > > You don't appear to be using the standard email package (which includes > MIME support) so don't blame Python... > I am not saying anything about Python's standard library. Furthermore, I am not using MIME e-mail. The MIME component that I am using, which should be ideal for me, builds the message just fine?when not using a binary component. I am looking for how to tell Python to combine these objects as nothing more than a stream of bytes, without regard for what is inside the bytes. That is what I was asking. You did not tell me how to do that, or if that is even possible, so why flame me? I am not saying "Python is bad, evil!" and blaming it for my ignorance, but what I am asking for is how to accomplish what I am attempting to accomplish. The MIME component is a (slightly modified) version of the recipe provided from the ASPN Python Cookbook. In short: How do I create a string that contains raw binary content without Python caring? Is that possible? Thanks, Mike > -- > Gabriel Genellina > -- 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 bbxx789_05ss at yahoo.com Tue Apr 10 20:20:51 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: 10 Apr 2007 17:20:51 -0700 Subject: __file__ Message-ID: <1176250851.946892.273550@l77g2000hsb.googlegroups.com> Hi, I'm having trouble understanding what the definition of __file__ is. With this program: ------ #data.py: def show(): print __file__ if __name__ == "__main__": show() ------- if I run data.py with the prompt pointing to the directory that contains data.py, then __file__ produces a filename: data.py If I run data.py with the prompt pointing to a different directory, then file produces what I entered on the command line, e.g.: ./2testing/dir1/data.py If I import the data module into another python program, e.g.: ------- #test1.py: from data import show show() ------ and test1.py is in the same directory as data.py, __file__ produces an absolute path to the data module: /Users/me/2testing/dir1/data.pyc If test1.py is in a different directory than data.py, __file__ produces the path used in sys.path.append(), e.g.: ---- import sys sys.path.append("./2testing/dir1") import data data.show() ---output:------ ./2testing/dir1/data.pyc ====or====== import sys sys.path.append("/Users/me/2testing/dir1") import data data.show() ---output:------- /Users/me/2testing/dir1/data.pyc And some modules have __file__ in their __dict__ and some don't: ------- import sys, pprint, data pprint.pprint(data.__dict__) print print "*******" print pprint.pprint(sys.__dict__) From aisaac at american.edu Fri Apr 13 15:06:50 2007 From: aisaac at american.edu (Alan G Isaac) Date: Fri, 13 Apr 2007 14:06:50 -0500 Subject: vocab question Message-ID: Pardon the vocab question; I'm not a computer science type. According to the Reference Manual, a class defintion has the structure:: classdef ::= "class" classname [inheritance] ":" suite What is the entire part before the suite called? (Just pointing to a reference is fine & helpful, as long as its not an entire course on BNF.) Thanks, Alan Isaac From cam.ac.uk at mh391.invalid Sun Apr 15 19:04:12 2007 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Mon, 16 Apr 2007 00:04:12 +0100 Subject: Portably generating infinity and NaN In-Reply-To: References: <462008d1$0$11763$9b622d9e@news.freenet.de> Message-ID: skip at pobox.com wrote: > Michael> If you're going to change CPython to do this, I think adopting > Michael> PEP 754, and using the fpconst module would be better than > Michael> changing how float() works when called on string literals. > > But PEP 754 will only work for architectures supporting IEEE 754. I realize > that's the vast majority of systems, but aren't there still a few Crays and > VMS machines out there? (Do those architectures support NaN and Inf?) Will float("NaN") work on these systems? (I don't know.) I guess it probably works on some system that isn't IEEE 754. -- Michael Hoffman From gagsl-py2 at yahoo.com.ar Tue Apr 10 07:48:36 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 10 Apr 2007 08:48:36 -0300 Subject: setup() and C extensions References: <1176184942.119878.230850@p77g2000hsh.googlegroups.com> Message-ID: En Tue, 10 Apr 2007 03:02:22 -0300, 7stud escribi?: > I can't find any documentation on the setup() function in the > distutils.core module; specifically I want to know what the 'name' > argument does. In some examples in the python docs, they use the name > argument like this: http://docs.python.org/dist/module-distutils.core.html > So it looks like the 'name' argument should be a package name. Exactly. > However, when I compile an extension module using that format, I can > import the module using the syntax: > > import module1 > > I don't have to use PackageName.module1. "name" should be the full dotted name - but I've never tried it actually. -- Gabriel Genellina From bcwhite at pobox.com Wed Apr 18 20:16:03 2007 From: bcwhite at pobox.com (bcwhite at pobox.com) Date: 18 Apr 2007 17:16:03 -0700 Subject: Future Python Gui? In-Reply-To: <1176935956.875561.67080@o5g2000hsb.googlegroups.com> References: <1176859699.906386.326720@b75g2000hsg.googlegroups.com> <1176863948.526051.186210@n76g2000hsh.googlegroups.com> <1176909848.455264.174730@e65g2000hsc.googlegroups.com> <1176935956.875561.67080@o5g2000hsb.googlegroups.com> Message-ID: <1176941763.039168.4880@n59g2000hsh.googlegroups.com> > As I've said often enough on the topic of Web frameworks, picking > winners gives only a temporary victory to those who want to avoid > making decisions. It's better to provide people with a means of making > an informed choice, and it should be realised that people will > approach this choice from rather different angles. It isn't always > going to be, "I want to write a Python application - what GUI should I > use?" Instead, it may be, "I want to write a KDE application - can I > do so in Python and what are my options?" Pretending that the answer > is always the same will frequently drive people to other technologies, > not attract them to a technology selling a vision that turns out to be > a mirage. This is getting off-topic, I guess, so I'll only comment once because I don't want to get wrapped up in a flame war. This is the argument used by people who think that having both KDE and GNOME is a good thing because it promotes competition, etc. Personally, I believe it's a bad thing because it duplicates effort and delivers an inconsistent look & feel. Developers are forced to choose a framework, not knowing if it will go away in favor of another choice and rendering their own hard work obsolete. I don't want my work dependent upon the framework. I'd rather have less good if it meant longer-term stability and greater consistency. But that's just me. -- Brian From i3dmaster at gmail.com Wed Apr 11 12:47:48 2007 From: i3dmaster at gmail.com (i3dmaster) Date: 11 Apr 2007 09:47:48 -0700 Subject: Universal Feed Parser issue In-Reply-To: References: <1176227922.910993.36910@y80g2000hsf.googlegroups.com> <1176267073.787216.80170@n76g2000hsh.googlegroups.com> Message-ID: <1176310068.224477.57200@p77g2000hsh.googlegroups.com> On Apr 11, 12:06 am, "Gabriel Genellina" wrote: > En Wed, 11 Apr 2007 01:51:13 -0300, i3dmaster > escribi?: > > > > > On Apr 10, 6:45 pm, "Gabriel Genellina" > > wrote: > >> En Tue, 10 Apr 2007 14:58:42 -0300, i3dmaster > >> escribi?: > > >> > > >> > ... > >> > > >> > > >> > > > >> > After parsed by feedparser, the timezone element does not get the > >> > attribute "America/Mountain". Same thing on status element. This does > >> > not sound an expected result. I am wondering if it should be > >> > considered a bug... > > >> Usually it's a good idea to read the documentation... > >>http://www.feedparser.org/docs/namespace-handling.html > > > I did. Perhaps its because of not 100% atom compatible of my feed > > format? See if I use gnosis xml utility to parse it, it works fine > > though... > > The link above answers *exactly* your question - have you actually read > the page? > > -- > Gabriel Genellina Hmm... well I don't know if I made my question clear then or you might have misread it?... Anyway, the namespace handling wasn't the issue of this question. feedparser handles it as expected but only when there is a text value associated with it. Look at the rdf file you will see the prism:issn element has a text value but in my case, the foo:timezone element DOES NOT have a text value but a Attribute or maybe attributes... What it looks like is feedparser simply ignores all the attributes when parsing it. This behavior wasn't seen from other xml parsers though. From jstroud at mbi.ucla.edu Sat Apr 21 05:34:20 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Sat, 21 Apr 2007 02:34:20 -0700 Subject: lambda generator - curious behavior in 2.5 In-Reply-To: <4629d7a5_3@news.bluewin.ch> References: <4629d7a5_3@news.bluewin.ch> Message-ID: Boris Borcic wrote: > >>> x = (lambda : ((yield 666),(yield 777),(yield 888)))() > >>> x.next() > 666 > >>> x.next() > 777 > >>> x.next() > 888 > >>> x.next() > (None, None, None) > >>> x = (lambda : ((yield 666),(yield 777),(yield 888)) and None)() > >>> x.next() > 666 > >>> x.next() > 777 > >>> x.next() > 888 > >>> x.next() > > Traceback (most recent call last): > File "", line 1, in > x.next() > StopIteration > >>> Seems like a bug: py> def doit(): ((yield 1), (yield 2), (yield 3)) ... py> x = doit() py> x.next() 1 py> x.next() 2 py> x.next() 3 py> x.next() ------------------------------------------------------------ Traceback (most recent call last): File "", line 1, in James From 12cc104 at gmail.com Fri Apr 27 02:33:57 2007 From: 12cc104 at gmail.com (proctor) Date: 26 Apr 2007 23:33:57 -0700 Subject: regex question Message-ID: <1177655637.717863.93920@o40g2000prh.googlegroups.com> hello, i have a regex: rx_test = re.compile('/x([^x])*x/') which is part of this test program: ============ import re rx_test = re.compile('/x([^x])*x/') s = '/xabcx/' if rx_test.findall(s): print rx_test.findall(s) ============ i expect the output to be ['abc'] however it gives me only the last single character in the group: ['c'] C:\test>python retest.py ['c'] can anyone point out why this is occurring? i can capture the entire group by doing this: rx_test = re.compile('/x([^x]+)*x/') but why isn't the 'star' grabbing the whole group? and why isn't each letter 'a', 'b', and 'c' present, either individually, or as a group (group is expected)? any clarification is appreciated! sincerely, proctor From jstroud at mbi.ucla.edu Thu Apr 12 16:51:26 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Thu, 12 Apr 2007 13:51:26 -0700 Subject: Need help with the get() method of a Text entry In-Reply-To: <1176409717.585710.184960@y80g2000hsf.googlegroups.com> References: <1176409717.585710.184960@y80g2000hsf.googlegroups.com> Message-ID: Chad wrote: > I have a simple little program that brings up asks the user to enter a > note, then is supposed to place that note into a text file when the > user hits the submit button. However, when the user hits the submit > button, absolutely nothing happens. IDLE doesn't give an error > message and the note is not entered into the text file. For > troubleshooting puposes, I wanted to see if IDLE would at least print > the user's input; it doesn't do that either. Can someone please help > me? > > Here is the code: > > from Tkinter import * > > class Application(Frame): > """ GUI application that creates a story based on user input. """ > def __init__(self, master): > """ Initialize Frame. """ > Frame.__init__(self, master) > self.grid() > self.create_widgets() > > def create_widgets(self): > """ Create widgets to get note information. """ > # create instruction label and text entry for notes > Label(self, > text = "Notes" > ).grid(row = 0, column = 0, columnspan = 2 ) > > > self.notes_ent = Text(self, width = 75, height = 10, wrap = > WORD) > self.notes_ent.grid(row = 2, column = 0 ,columnspan = 7, > rowspan = 3, sticky = W) > create submit button > text1 = StringVar(self) > text1 = self.notes_ent.get(1.0, END) > self.notes_ent.config(state=NORMAL) > Button(self, > text = "Add Note", > command = self.add_note(text1) > ).grid(row = 1, column = 0, sticky = W) > > def add_note(self, text1): > print text1 > text_file = open("write_it.txt", "a+") > text_file.write(text1) > > root = Tk() > root.title("Mad Lib") > app = Application(root) > root.mainloop() > Your main problem is that you are calling add_note when you bind it. You don't want to do that. It will get called when the event (button press) happens. Most (or hopefully) all of the remedy is: 1. rename text1 to self.text1 2. change "command = self.add_note(text1)" to "command = self.add_note" 3. change "def add_note(self, text1):" to "def add_note(self):" 4. delete "print text1" 5. chane "text_file.write(text1)" to "text_file.write(text1.get())" I think I got everything. James From anton.vredegoor at gmail.com Wed Apr 18 15:23:10 2007 From: anton.vredegoor at gmail.com (Anton Vredegoor) Date: Wed, 18 Apr 2007 21:23:10 +0200 Subject: multirember&co In-Reply-To: <1176921030.330467.76860@o5g2000hsb.googlegroups.com> References: <1176768854.720234.23320@w1g2000hsg.googlegroups.com> <1176790588.024371.119360@n76g2000hsh.googlegroups.com> <1176850352.999231.79260@n59g2000hsh.googlegroups.com> <1176921030.330467.76860@o5g2000hsb.googlegroups.com> Message-ID: attn.steven.kuo at gmail.com wrote: > > If you don't wish to use objects, you can replace them with > a closure: > > import collections > > def xsplitter(iseq, pred): > queue = [ collections.deque(), collections.deque() ] > def it(parity): > while True: > if queue[parity]: > yield queue[parity].popleft() > else: > try: > el = iseq.next() > if pred(el) == parity: > yield el > else: > queue[not parity].append(el) > except StopIteration: > raise > its = [ it(False), it(True) ] > return its[True], its[False] > > > idata = iter([1, 'a', 3, 'a', 4, 5, 6, 'a']) > it1, it2 = xsplitter(idata, lambda x: x == 'a') > > from itertools import izip > for el1, el2 in izip(it1, it2): > print el1, el2 > > > Oh, I and do like your rewrite; it's much less > repetitive and cleaner than my original version. But still, the 'while True:' loop and the 'try-except' clause and the explicit StopIteration are not necessary ... from collections import deque def xsplitter(seq, pred): Q = deque(),deque() it = iter(seq) def gen(p): while Q[p]: yield Q[p].popleft() for x in it: if pred(x) == p: yield x else: Q[~p].append(x) for x in gen(p): yield x return gen(1),gen(0) def test(): L = 1, 'a', 3, 'a', 4, 5, 6, 'a' it1, it2 = xsplitter(L, lambda x: x == 'a') print it1.next() print it2.next() print it1.next() if __name__=='__main__': test() A. From rdh at new.rr.com Mon Apr 16 15:25:39 2007 From: rdh at new.rr.com (DataSmash) Date: 16 Apr 2007 12:25:39 -0700 Subject: moving multiple directories In-Reply-To: <4623C22B.2000304@websafe.com> References: <1176740512.975411.158380@p77g2000hsh.googlegroups.com> <4623C22B.2000304@websafe.com> Message-ID: <1176751539.615630.235510@q75g2000hsh.googlegroups.com> Thanks Larry, I'll give that a try... R.D. > > Use win32.moveFile method instead. This links directly to the Windows > MoveFile method that just moves the directory entries around. > > From Win32 Documentation: > > win32api.MoveFile > MoveFile(srcName, destName) > > Renames a file, or a directory (including its children). > > Parameters > > srcName : string > > The name of the source file. > > destName : string > > The name of the destination file. > > Comments > This method can not move files across volumes. > > -Larry From jjl at pobox.com Wed Apr 11 16:31:04 2007 From: jjl at pobox.com (John J. Lee) Date: Wed, 11 Apr 2007 20:31:04 GMT Subject: Calling Python from Javascript? References: Message-ID: <87k5wi7iwi.fsf@pobox.com> Kenneth McDonald writes: > I know that there's some work out there to let Python make use of > Javascript (Spidermonkey) via (I assume) some sort of bridging C/C++ > code. Anyone know of efforts to allow the reverse? I'd really like to > make use of Python when doing Mozilla DOM programming, and I can never > get a clear idea of when PyXPCOM might be available to those of us who > don't know the ins and outs of compiling Mozilla, and its XPCOM > structures. So if there was an easy way to simply and quickly pass > even just strings back and forth between Python and Moz Javascript, > that would make certain things a heck of a lot easier. I too wonder what happened to Mark Hammond's work on the DOM_AGNOSTIC_2 branch a year or so back. Might be nice to be able to write Firefox extensions in Python. Practically, I know that e.g. the firefox htmltidy extension (I forget the name) contains binaries built from C code, not just JS, so I guess you could write a Firefox extension that embeds CPython in a similar way. John From syedamjad_a at yahoo.com Mon Apr 16 14:32:52 2007 From: syedamjad_a at yahoo.com (CSUIDL PROGRAMMEr) Date: 16 Apr 2007 11:32:52 -0700 Subject: getting from command line options to file Message-ID: <1176748372.685762.169820@w1g2000hsg.googlegroups.com> hi folks I am new to python. I have a module does call a os.command(cmd) where cmd is a rpm command. Instead of using os.command and getting the results on command line , i would like to dump the output in a file. Is os.command(cmd > filename) the most efficient command?? thanks From jzgoda at o2.usun.pl Sun Apr 29 09:57:46 2007 From: jzgoda at o2.usun.pl (Jarek Zgoda) Date: Sun, 29 Apr 2007 15:57:46 +0200 Subject: Asynchronous XML-RPC client library? In-Reply-To: <1177854769.627406.214270@n59g2000hsh.googlegroups.com> References: <1177854769.627406.214270@n59g2000hsh.googlegroups.com> Message-ID: Stefano Canepa napisa?(a): >> Is there anything like that? Googling yields many articles on async >> servers, but virtually nothing on clients. I have to talk to remote in >> an environment that does not allow threads... > > Why don't you try twisted (http://www.twistedmatrix.com) Because this is a small plugin to a larger application written in C and I don't want to make such dependency. Twisted is just too large to be a dependency for a ~500 LOC (including GUI code) plugin. -- Jarek Zgoda http://jpa.berlios.de/ From jjl at pobox.com Mon Apr 16 14:52:39 2007 From: jjl at pobox.com (John J. Lee) Date: Mon, 16 Apr 2007 18:52:39 GMT Subject: how to check the 'content/type' using urlopen References: <1176679523.382142.309220@b75g2000hsg.googlegroups.com> Message-ID: <87vefwb18h.fsf@pobox.com> Michael Bentley writes: > On Apr 15, 2007, at 6:25 PM, John wrote: > > > > > i have the following code to open a URL address, but can you please > > tell me how can I check the content type of the url response? > > > > Thank you. > > > > try: > > req = Request(url, txdata, txheaders) > > handle = urlopen(req) > > except IOError, e: > > print e > > print 'Failed to open %s' % url > > return 0; > > > > else: > > data = handle.read() > > Not absolutely sure about this, but try handle.headers.get('Content- > Type') before the read. handle.get_header("Content-type") John From jgodoy at gmail.com Sat Apr 21 17:55:53 2007 From: jgodoy at gmail.com (Jorge Godoy) Date: Sat, 21 Apr 2007 18:55:53 -0300 Subject: Suggestion: str.itersplit() References: <1177160280.784224.53460@b58g2000hsg.googlegroups.com> <1177190327.236981.153770@o5g2000hsb.googlegroups.com> Message-ID: <87bqhhxuhi.fsf@gmail.com> Dustan writes: > If anybody could inform me on how to get my hands on the python source > code, I might even be able to come up with an example of how it could > be implemented. I have no idea how to unzip that tgz or tar.bz2 file > on a windows machine, though (and that's not from lack of trying). You can try WinZip. Last time I had to use a Windows machine it was able to untar + gunzip some files perfectly fine (as we are able to unzip and unrar on *nix...). -- Jorge Godoy From grante at visi.com Tue Apr 3 17:19:34 2007 From: grante at visi.com (Grant Edwards) Date: Tue, 03 Apr 2007 21:19:34 -0000 Subject: Need help on reading line from file into list References: <1175630106.220186.107900@y66g2000hsf.googlegroups.com> <4612b8f2$0$28546$426a74cc@news.free.fr> <1175633434.823351.69800@q75g2000hsh.googlegroups.com> Message-ID: <1315h76e02send9@corp.supernews.com> On 2007-04-03, bahoo wrote: > Thanks, this helped a lot. > I am now using the suggested > map(str.strip, open('source.txt').readlines()) > > However, I am a C programmer, and I have a bit difficulty > understanding the syntax. That bit of syntax is completely, utterly, 100%, identical to C: 1) open('source.txt') is called which returns a file object (think of it sort of like a struct). 2) the readlines() method of that file object is then called. 3) str.strip and the return value from readlines() are then passed as parameters to the map() function. > I don't see where the "str" came from, You really ought to go through one or more of the tutorials. "str" is a built-in type: $ python Python 2.4.3 (#1, Dec 10 2006, 22:09:09) [GCC 3.4.6 (Gentoo 3.4.6-r1, ssp-3.4.5-1.0, pie-8.7.9)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> print str >>> dir(str) ['__add__', '__class__', '__contains__', '__delattr__', '__doc__', '__eq__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__getslice__', '__gt__', '__hash__', '__init__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__str__', 'capitalize', 'center', 'count', 'decode', 'encode', 'endswith', 'expandtabs', 'find', 'index', 'isalnum', 'isalpha', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'replace', 'rfind', 'rindex', 'rjust', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill'] > so perhaps the output of "open('source.txt').readlines()" is > defaulted to "str? Sorry, I don't know that that means. The return value from open('sources.txt').readlines() is being passed as the second parameter to the map() function. str.strip is being passed as the first parameter to map. -- Grant Edwards grante Yow! Is there something at I should be DOING with a visi.com GLAZED DONUT?? From arnodel at googlemail.com Sun Apr 29 03:36:30 2007 From: arnodel at googlemail.com (Arnaud Delobelle) Date: 29 Apr 2007 00:36:30 -0700 Subject: editing scripts on a mac In-Reply-To: References: Message-ID: <1177832190.802879.255210@e65g2000hsc.googlegroups.com> On Apr 27, 5:37 pm, Tommy Grav wrote: [...] > I think emacs is bundled with OS X and can be started in a terminal > window with emacs. If you want a non-terminal editor Aquaemacs > (http://aquamacs.org/) is available and easily installed on mac. Personally I prefer Carbon Emacs: http://homepage.mac.com/zenitani/emacs-e.html -- Arnaud From mail at timgolden.me.uk Mon Apr 30 05:14:54 2007 From: mail at timgolden.me.uk (Tim Golden) Date: Mon, 30 Apr 2007 10:14:54 +0100 Subject: Dict Copy & Compare In-Reply-To: <000601c78b06$b9fb0950$2df11bf0$@rawlins@thinkbluemedia.co.uk> References: <00da01c78b01$3e80b900$bb822b00$@rawlins@thinkbluemedia.co.uk> <4635AB95.4010309@timgolden.me.uk> <000601c78b06$b9fb0950$2df11bf0$@rawlins@thinkbluemedia.co.uk> Message-ID: <4635B38E.5020606@timgolden.me.uk> Robert Rawlins - Think Blue wrote: > I have two dicts, one named 'this' and the other named 'that'. > > I want to get all the unique keys from 'this' and log them into a file, I > then want to take all the unique values from 'that' and log them into a > separate file. Couple of points which are confusing me: 1) Any dict can *only* have unique keys, ie you can't have a key appearing more than once in a dictionary by definition. 2) You speak of unique keys in "this" but unique values in "that". Is that deliberate on your part? Might be, but I'm not quite clear. > I have functions set up for the logging, so I can call it like > logThis(uniquekey) and logThat(uniquekey). Here you refer to "uniquekey" in both cases, so maybe a mistake above? > So it's just a case of firstly returning a list of all keys that are in > 'this' but NOT in 'that' and then visa versa, then loop over them performing > the function. OK, well following by example earlier: d1 = dict (a=1, b=2, c=3) d2 = dict (b=4, c=5, d=6) s1 = set (d1) # => set of 'a', 'b', 'c' s2 = set (d2) # => set of 'b', 'c', 'd' s1_not_in_s2 = s1 - s2 # => set of 'a' s2_not_in_s1 = s2 - s1 # => set of 'd' for key in s1_not_in_s2: print key, "=>", d1[key] for key in s2_not_in_s1: print key, "=>", d2[key] Obviously there are more concise ways of representing this; I'm just spelling the whole thing out to make it clearer (I hope). If this approach seems fruitful, have a look at the set typeit's a recentish addition to Python but very useful for this kind of thing: http://docs.python.org/lib/types-set.html TJG From grflanagan at yahoo.co.uk Fri Apr 27 09:33:51 2007 From: grflanagan at yahoo.co.uk (Gerard Flanagan) Date: 27 Apr 2007 06:33:51 -0700 Subject: what python technology for my app? In-Reply-To: References: Message-ID: <1177680831.854138.47520@t39g2000prd.googlegroups.com> On Apr 27, 12:18 pm, Chris wrote: > I have an database containing lots of numerical data. I want to write a > browser based interface that will allow selection of various key > parameters and yield tables, plots and/or printouts of the data > according to the selections. Ultimately I want this to run on an > intranet so that others can get access via their browsers. > > The application is for in-house use only and not likely to have more > than a few users at any one time. > Any advice on what technologies I should be looking at for this? Python > based naturally, and hopefully simple and lightweight. > If I can throw something moderately > functional together in a week or two (along with all the learning that > entails) I'll be happy. > > btw - Platform needs to be windows because that's what on my desk. > 1) for small intranet, 2) in Python, 3) dead simple, 4) runs on Windows - consider Karrigell: http://karrigell.sourceforge.net/en/front.htm Gerard From bdesth.quelquechose at free.quelquepart.fr Thu Apr 5 19:53:22 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Fri, 06 Apr 2007 01:53:22 +0200 Subject: RFC: Assignment as expression (pre-PEP) In-Reply-To: References: <1175802680.021987.39220@p77g2000hsh.googlegroups.com> Message-ID: <461582fc$0$7529$426a74cc@news.free.fr> Duncan Booth a ?crit : > TimeHorse at gmail.com wrote: > > >>Performing a list of mutually exclusive checks that require data >>processing can cause excessive tabification. For example, consider >>the following python snipet... >> >>temp = my_re1.match(exp) >>if temp: >> # do something with temp >>else: >> temp = my_re2.match(exp) >> if temp: >> # do something with temp >> else: >> temp = my_re3.match(exp) >> if temp: >> # do something with temp >> else: >> temp = my_re4.match(exp) >> > > > Can you come up with a real example where this happens and which cannot be > easily rewritten to provide better, clearer code without the indentation? > > I'll admit to having occasionally had code not entirely dissimilar to this > when first written, but I don't believe it has ever survived more than a > few minutes before being refactored into a cleaner form. I would claim that > it is a good thing that Python makes it obvious that code like this should > be refactored. +2 QOTW From aleax at mac.com Mon Apr 30 10:51:10 2007 From: aleax at mac.com (Alex Martelli) Date: Mon, 30 Apr 2007 07:51:10 -0700 Subject: While we're talking about annoyances References: <1177837565.317999.244420@c35g2000hsg.googlegroups.com> <1177857049.938363.166170@p77g2000hsh.googlegroups.com> <1hxchgp.7sw7efb72rh2N%aleax@mac.com> <1hxcm3o.19dhbys1wllx20N%aleax@mac.com> Message-ID: <1hxdhcd.v9sfz54elovkN%aleax@mac.com> Michael Hoffman wrote: ... > >> Well, counting the index() function that is called in both cases, the > >> original rank() had one sort, but my version has two sorts. > > > > That doesn't affet the big-O behavior -- O(N log N) holds whether you > > have one sort, or three, or twentyseven. > > I've taught programming classes before, and I would have had to fail > anybody who misunderstood speed badly enough to claim that something > repeating an O(N log N) algorithm 27 times was no faster than doing it > once. ;-) As for me, I would fail somebody who thought they could compare speed this way -- if the O(N log N) executed 27 times took (on a given machine) 1 millisecond times N times log N, and the other one (on the same machine) 1 second times N times log N (and in the big-O notation you can NEVER infer what the multiplicative constant is), for example, such a comparison would be totally of base. > As Arnaud points out, asymptotic behavior is not the same as speed. His > original statement that the more recently proposed definitions of rank() > are slower than the OP's may be correct. And if it's not, it's not > because they're all O(N log N). And if it is, it's not because of the "one sort" versus "two sorts": by that sole criterion you just cannot guess (sensibly) at speed (measuring is much better, though it has its own pitfalls). Alex From bdesth.quelquechose at free.quelquepart.fr Sat Apr 21 15:17:19 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sat, 21 Apr 2007 21:17:19 +0200 Subject: When are immutable tuples *essential*? Why can't you just use lists *everywhere* instead? In-Reply-To: <1177109625.619171.121610@d57g2000hsg.googlegroups.com> References: <1177088796.622928.224890@d57g2000hsg.googlegroups.com> <1177089206.550423.288670@q75g2000hsh.googlegroups.com> <58sf33F2b1q8tU1@mid.individual.net> <1177103370.022138.110320@n59g2000hsh.googlegroups.com> <1177108656.291537.182560@o5g2000hsb.googlegroups.com> <1177109625.619171.121610@d57g2000hsg.googlegroups.com> Message-ID: <462a59cd$0$18198$426a74cc@news.free.fr> garrickp at gmail.com a ?crit : > On Apr 20, 4:37 pm, John Machin wrote: > >>One inessential but very useful thing about tuples when you have a lot >>of them is that they are allocated the minimum possible amount of >>memory. OTOH lists are created with some slack so that appending etc >>can avoid taking quadratic time. > > > Speaking of inessential but very useful things, I'm also a big fan of > the tuple swap... Which relies on unpacking, which also works with lists.... From steve at holdenweb.com Fri Apr 13 09:11:14 2007 From: steve at holdenweb.com (Steve Holden) Date: Fri, 13 Apr 2007 09:11:14 -0400 Subject: Question About Creating Lists In-Reply-To: References: <1176414392.977660.16610@o5g2000hsb.googlegroups.com> Message-ID: Scott wrote: > >> Please forgo the psychological self analysis from your future posts. > > Unfortunately I can't, that's how I am, love it or leave it. But if your > going to be condescending about it, please leave your future replies in your > outbox. Now don't take that as I don't appreciate your reply. I just don't > appreciate the tone of that statement. I wouldn't say something about your > pseudonym possibly making up for some personal deficiency only because it > wouldn't be right. Email etiquette is a beautiful thing. > And that's a really sideways way to take a swipe at someone while pretending to be too high-minded to do it (plus see James's comments about other possible explanations). If you kiddies would take this fight out into the playground perhaps the rest of the class can continue. It *would* be helpful if you "just asked the question". You said in your original post that "... I need to know the petty just because I need to know", but that's an abuse of the word need unless you suffer from a quite unusual psychological compulsion. Another psychological compulsion, of course, is the inability to ignore the irrelevant in other people's posts. The two apparently don't combine well. > And I'm sorry if you didn't mean it that way, but that's the way it read. > To you. Get over it, this is Usenet. You will experience worse if you stick at it long enough. >> I don't think your question has anything to do with lists. Maybe this >> will help: there is a distinction between what are called "literals" >> and "variables". > > My question was in fact about lists and their proper "syntax" (I'm guessing > that's the right word). Basically all I was asking was if I had the idea > down or not, which was meant to be implied when I wrote: Am I safe in > assuming.... > > Maybe I didn't write it the exact way to get the response I needed, and if > it read differently I'm sorry. But that's all I was asking. > > You can't really separate the syntax of lists from the syntax of the rest of Python. Maybe you didn't mean syntax, it's hard to know. There are, as has been pointed out, names and values. Names are references to values. So after you say five = 5 the following conditions are true: [1, 2, 3, 4, 5] == [1, 2, 3, 4, five] [1, 2, 3, 4, 'five'] != [1, 2, 3, 4, five] Then execute five = 'five' and the truth value of both conditions flips, so the first is false and the second is true. The value referenced by the name five changes as new values are assigned (in Python we tend to prefer to say "bound", to remind us that names are really references) to it. The values represented by the literals 5 and 'five' will never change. 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 inq1ltd at verizon.net Fri Apr 20 11:34:01 2007 From: inq1ltd at verizon.net (jim-on-linux) Date: Fri, 20 Apr 2007 11:34:01 -0400 Subject: PY shutil on win xp home version In-Reply-To: <46286A1E.5010700@timgolden.me.uk> References: <1176898887.530470.222830@p77g2000hsh.googlegroups.com> <200704192004.22604.inq1ltd@verizon.net> <46286A1E.5010700@timgolden.me.uk> Message-ID: <200704201134.01554.inq1ltd@verizon.net> Thanks Tim for resopnding, I appreciate the help. I convinced the client to install Linux on 4 machines rather than upgrade from xp home to XP Pro, and more machines to come if the like it. jim-on-linux On Friday 20 April 2007 03:22, you wrote: > jim-on-linux wrote: > > On Wednesday 18 April 2007 17:02, Tim Golden > > > > wrote: > >> jim-on-linux wrote: > >>> python help, > >>> > >>> A client is using win xp home. > >>> > >>> my program contains; > >>> shutil.copyfile(n, 'prn') > >>> > >>> This runs fine on win xp pro but they are > >>> getting the following traceback. > >>> > >>> File "LOP_PRT_10.pyc", line 170, in > >>> __init__ File "LOP_PRT_10.pyc", line 188, > >>> in Fprint1 File "shutil.pyc", line 47, in > >>> copyfile IOError: [Errno 2] No such file or > >>> directory: 'prn' > >>> > >>> Since this runs ok on win xp pro, does this > >>> have something to do with the home version > >>> of xp. > >>> > >>> I'm thinking of changeing 'prn' to 'lpt1' > >>> and trying again but I don't want to use > >>> the client as a testor. Or is there some > >>> other explaination for the problem. > >> > >> Not that this is your question, but if > >> you're trying to print under Windows have > >> you looked at: > >> > >> > >> http://tgolden.sc.sabren.com/python/win32_ho > >>w_d o_i/print.html > >> > >> for alternatives? > >> > >> TJG > > > > Thanks for the response, > > > > I got the following to work on windows. > > > > win32api.ShellExecute ( > > 0, 'print', > > filename, None, ".", 0 > > ) > > > > However it prints the name of the file at the > > top and adds a page number on the bottom. Is > > there some way of eliminating the filename > > and page number. > > Unfortunately, this approach is quick-and-dirty > and you're at the mercy of whatever the "print" > verb does to "filename" on your box. (Although > you can configure that if you try hard enough). > > I'm afraid if you want control, you'll have to > go the PDF route or to automate Word / > OpenOffice etc. > > TJG From gagsl-py2 at yahoo.com.ar Thu Apr 12 21:19:32 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 12 Apr 2007 22:19:32 -0300 Subject: Using python to delta-load files into a central DB References: Message-ID: En Thu, 12 Apr 2007 14:05:15 -0300, Chris Nethery escribi?: > At present, users of the separate application can run recalculation > functions that modify all 700 files at once, causing my code to take the > whole ball of wax, rather than just the data that has changed. Are they text files, or what? What kind of modifications? some lines changed/deleted/added? a column recalculated along the whole file? > What I would like to do is spawn separate processes and load only the > delta > data. The data must be 100% reliable, so I'm leary of using something > like > difflib. I also want to make sure that my code scales since the number > of > files is ever-increasing. Why don't you like difflib? AFAIK it has no known bugs. -- Gabriel Genellina From nagle at animats.com Fri Apr 13 14:16:58 2007 From: nagle at animats.com (John Nagle) Date: Fri, 13 Apr 2007 18:16:58 GMT Subject: "HTTP error -1" from urllib2 Message-ID: I'm getting a wierd error from urllib2 when opening certain URLs. The code works for most sites, but not all of them. Here's the traceback: [Thread-2] InfoSitePage EXCEPTION while processing page "http://www.fourmilab.ch": Problem with page "http://www.fourmilab.ch": HTTP error -1 - .. Traceback (most recent call last): File "D:\projects\sitetruth\InfoSitePage.py", line 318, in httpfetch fd = url_opener.open(self.requestedurl) # open file by url File "D:\projects\sitetruth\miscutils.py", line 149, in open result = urllib.FancyURLopener.open(self, url, *args) File "D:\python24\lib\urllib.py", line 190, in open return getattr(self, name)(url) File "D:\python24\lib\urllib.py", line 322, in open_http return self.http_error(url, fp, errcode, errmsg, headers) File "D:\python24\lib\urllib.py", line 339, in http_error return self.http_error_default(url, fp, errcode, errmsg, headers) File "D:\projects\sitetruth\miscutils.py", line 144, in http_error_default raise InfoException.InfoException(self.url, 'HTTP error %s - %s.' % (errcode, errmsg)) InfoException: Problem with page "http://www.fourmilab.ch": HTTP error -1 - .. This fails identically using Python 2.4 on a Windows desktop and on Python 2.5 on a Linux server. The site being accessed reads fine in a browser. It's not a redirect, and it doesn't insist on cookies. See "http://mail.python.org/pipermail/python-list/2005-March/314301.html" for another problem involving "HTTP error -1". John Nagle From gagsl-py2 at yahoo.com.ar Mon Apr 9 08:52:06 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 09 Apr 2007 09:52:06 -0300 Subject: [offtopic?] problem with UDP broadcast on Windows XP References: <461a271c$0$323$e4fe514c@news.xs4all.nl> Message-ID: En Mon, 09 Apr 2007 08:43:23 -0300, Irmen de Jong escribi?: > I have this UDP socket server that binds on ('',9090) and is used > to be a broadcast responder. It works fine when I start the server > from the cmd prompt. UDP broadcast packets sent to ('',9090) > arrive in the server. > > However now I'm running the same server as a Windows NT Service. > The same code is executed, the UDP server socket is bound to the > same address. But this time, the UDP broadcast packets do NOT arrive.... Try running the service impersonating another user (not LOCAL_SERVICE, the default). You can change that from the service control panel. -- Gabriel Genellina From R.Brodie at rl.ac.uk Fri Apr 20 10:37:42 2007 From: R.Brodie at rl.ac.uk (Richard Brodie) Date: Fri, 20 Apr 2007 15:37:42 +0100 Subject: setDaemon problem. References: <1177057029.688992.160020@o5g2000hsb.googlegroups.com> <58rk68F2hof6mU1@mid.uni-berlin.de> <1177076608.110673.305970@d57g2000hsg.googlegroups.com> Message-ID: "Michael Hoffman" wrote in message news:f0aij2$j59$1 at gemini.csx.cam.ac.uk... >> Neither is particularly intuitive; it just depends whether you are more >> familiar with the Posix terminology or the Java one. I personally prefer >> detached but there is little chance of a name change now. > > Why not? That's what Python 3.0 is for. I think you need a better reason than: "it's mildly confusing to people, if they don't read the manual" for an API change; but that's just my opinion. From DustanGroups at gmail.com Tue Apr 17 06:24:45 2007 From: DustanGroups at gmail.com (Dustan) Date: 17 Apr 2007 03:24:45 -0700 Subject: Python Feature Request: Allow changing base of member indices to 1 In-Reply-To: <58cu2bF2gtuo3U2@mid.individual.net> References: <1176546465.632410.52630@w1g2000hsg.googlegroups.com> <4620b47b$0$14410$9b622d9e@news.freenet.de> <1176557999.665663.299740@y80g2000hsf.googlegroups.com> <1176559643.450533.296850@n59g2000hsh.googlegroups.com> <58cu2bF2gtuo3U2@mid.individual.net> Message-ID: <1176805485.948822.39540@l77g2000hsb.googlegroups.com> On Apr 14, 4:06 pm, Bjoern Schliessmann wrote: > jamadagni wrote: > > OK fine. It is clear that this feature must be implemented if at > > all only on a per-module basis. So can we have votes for > > per-module implementation of this feature? > > I don't think it's worth the hassle. BTW, what's, IYHO, the distinct > advantage of starting array indices at 1? For newbies, it's easier to count starting with 1. It's rather unintuitive to start at 0. That's not to say that I support this feature request; I got used to counting from 0. It just took me some time. > Regards, > > Bj?rn > > -- > BOFH excuse #90: > > Budget cuts From steven.bethard at gmail.com Tue Apr 3 17:28:51 2007 From: steven.bethard at gmail.com (Steven Bethard) Date: Tue, 03 Apr 2007 15:28:51 -0600 Subject: troubles building python 2.5 on Windows XP x64 Windows Server 2003 sp1 Platform SDK In-Reply-To: <1175631751.721474.236190@n59g2000hsh.googlegroups.com> References: <1175622506.730227.37060@p77g2000hsh.googlegroups.com> <1175624672.570370.248710@y80g2000hsf.googlegroups.com> <1175631751.721474.236190@n59g2000hsh.googlegroups.com> Message-ID: bhochstetler at gmail.com wrote: > This doc has not been updated since the 64 bit compilers came out > officially. It doesn't make a whole lot of sense of what steps you > should follow to build python. I saw a link on the comp.lang.python > that had the steps, but that link doesn't go anywhere now. I had to > jump through some hoops to get it to build on VC 2005 64 bit, but that > at least had an IDE to use. Well, if you figure it out, and you'd like to let others know, please post a documentation bug report: http://sourceforge.net/tracker/?group_id=5470&atid=105470 Sorry I wasn't more help. STeVe From kyosohma at gmail.com Fri Apr 13 09:14:04 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: 13 Apr 2007 06:14:04 -0700 Subject: where to report bug/get help for wxpython In-Reply-To: References: Message-ID: <1176470044.286666.174510@n59g2000hsh.googlegroups.com> On Apr 12, 9:35 pm, alf wrote: > Hi, > > I have another problem with wxpython - that is the best place to report > bug - evident memory leak on Linux and win32. > > -- > alf You'll need to go to the official wxPython website, here: http://wxpython.org/ There's a link to the mailing list (for help) and a link on how to report a bug. I would recommend reporting your problem to the users group mailing list first to find out if your problem is a known bug or not. Mike From ptmcg at austin.rr.com Wed Apr 18 05:22:24 2007 From: ptmcg at austin.rr.com (Paul McGuire) Date: 18 Apr 2007 02:22:24 -0700 Subject: How to communicate via USB "port" In-Reply-To: <1176875664.555559.259840@y80g2000hsf.googlegroups.com> References: <1176875664.555559.259840@y80g2000hsf.googlegroups.com> Message-ID: <1176888144.285219.101530@l77g2000hsb.googlegroups.com> On Apr 18, 12:54 am, "robinp... at gmail.com" wrote: > Can someone explain how I would read the data from the USB "port"? I > don't know if it matters, but I am trying to read the data from a GPS > plugged in to the USB port. > > Thank you, > Robin Just a guess, but can you use pyserial to talk to USB001? -- Paul From jstroud at mbi.ucla.edu Fri Apr 27 00:17:42 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Thu, 26 Apr 2007 21:17:42 -0700 Subject: How to find complementary colour for pixel In-Reply-To: <1177578583.205643.65200@r35g2000prh.googlegroups.com> References: <1177578583.205643.65200@r35g2000prh.googlegroups.com> Message-ID: Johny wrote: > I use PIL to write some text to a picture.The text must be seen wery > clearly. > I write the text to different pictures but to the same position. As > pictures maybe different, colour, in the position where I write the > text, is also different. > Is there a way how to set the font colour so that it will be seen very > clearly in the picture? > For example, if the picture is bright ( for example yellow), the font > colour should be dark( e.g. black) and vice versa. > Is there a routine in PIL available that calculates complementary > colour for RGB pixel format? > Can anyone help? > Thanks > L. > Don't you just xor with black? From mail at timgolden.me.uk Fri Apr 13 08:26:58 2007 From: mail at timgolden.me.uk (Tim Golden) Date: Fri, 13 Apr 2007 13:26:58 +0100 Subject: Arrays, Got Me Confused In-Reply-To: References: <000101c77dc3$d4152a00$7c3f7e00$@rawlins@thinkbluemedia.co.uk> Message-ID: <461F7712.2040201@timgolden.me.uk> Michael Bentley wrote: > > On Apr 13, 2007, at 7:04 AM, Robert Rawlins - Think Blue wrote: >> #!/usr/bin/python >> >> # Filename: Firewall.py >> class Firewall: >> def __init__(self): >> >> Self.FireArray = array(c) >> >> p = Firewall() >> >> print p >> Throws: >> >> >> >> Traceback (most recent call last): >> >> File "./firewall.py", line 9, in ? >> >> p = Firewall() >> >> File "./firewall.py", line 7, in __init__ >> >> Self.FireArray = array(c) >> >> NameError: global name 'array' is not defined >> >> >> >> How can I solve this problem? > from array import array Well, also the line referencing "Self.FireArray" is not going to work, unless there's some global "Self" knocking around. Python is case-sensitive. More importantly, I suspect, is that the OP's almost certainly looking for a Python *list*, not an array in this case. It's hard to tell, since we've no idea what's in the "c" which is being passed to the array. Robert - can you explain what you're trying to do and/or post a wider fragment of code? TJG From http Sun Apr 15 14:07:08 2007 From: http (Paul Rubin) Date: 15 Apr 2007 11:07:08 -0700 Subject: yield, curry, mix-in, new.function, global, closure, .... what will work? References: <1176657848.944538.169780@p77g2000hsh.googlegroups.com> Message-ID: <7xy7ktmrzn.fsf@ruckus.brouhaha.com> ecir.hana at gmail.com writes: > Let me explain: First, changer() is kind of templating language so it > should be written down in this form - however, it can change during > run-time as you like. Basically, it is just ordinary python code which > changes (should change) the local variables of another function, > run(). Oh, and it has to be *thread-safe*. That is total madness. Just use a normal object or dictionary with a lock. From bdesth.quelquechose at free.quelquepart.fr Tue Apr 10 19:13:43 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Wed, 11 Apr 2007 01:13:43 +0200 Subject: Why NOT only one class per file? In-Reply-To: References: <1175721799.714907.52770@o5g2000hsb.googlegroups.com> <46142acc$0$7532$426a34cc@news.free.fr> <4614b40e$0$26843$426a74cc@news.free.fr> <46154952$0$23907$426a74cc@news.free.fr> <46158702$0$18849$426a74cc@news.free.fr> Message-ID: <461c110b$0$24661$426a74cc@news.free.fr> Sherm Pendley a ?crit : > Bruno Desthuilliers writes: > > >>Sherm Pendley a ?crit : >> >>>Bruno Desthuilliers writes: >>> >>> >>> >>>>Sherm Pendley a ?crit : >>>> >>>>In my book, it's huge classes and methods that are usually a smell of >>>>a design problem. >>> >>> >>>Obviously we're reading different books. >> >>Obviously. But I didn't gain this knowledge from books. > > > Obviously, you have no sense of humor. Obviously, we don't have the same sense of humor. >>FWIW, I'd be interested if you'd let us know about any book pretending >>that monster classes are good design !-) > > You've already decided that "monster classes" are bad design, I came to this conclusion from my own experience, and it seems that quite a few other programmers (most of them either better and/or more experimented than me) came to the same conclusion. But feel free to believe it's an a priori if that makes you feel better. > and that > anything conflicting with your belief is mere pretense. Why should I waste > my time debating when you've already made up your mind? Then don't. But I'd still be interested if you could let us know about any book advocating monster classes as good design. >>>But that's OK - I'm not on a crusade to convince everyone to work my way. >>>If "one class per file" doesn't work well for you, don't write that way. >>>All I'm saying is, what works well for you isn't necessarily what works >>>well for everyone. >> >>It seems that it works well for almost anyone having some real-world >>experience with languages like Python. > > I didn't say otherwise. So let's rephrase your previous assertion : "what works well for almost anyone having some real world experience with languages like Python isn't necessarily what works well for everyone" (implied : "... when using a Python-like language" - this seemed obvious but it may be better to state it more explicitly, just in case...). > You're arguing a false dichotomy; Nope, just stating a fact - from which you may or not derive some conclusions. > the fact that one > approach works well does not prove that others won't work equally well. The fact that a in a given context a significant majority of experimented users usually favors one approach over the other might be taken as an indication that there might be some reason for this. About "proofs", I'm afraid that "proving" things learned from experience can be sometimes difficult - or at least above my own skills, specially in a language I'm not very fluent with. But I think I did tried (perhaps unsuccessfully, but that's another problem) to back my POV, instead of just resorting to rethoric like you're doing here. > I'm > not saying that your preferred style is wrong; I'm just saying that it's a > matter of preference, not a universal truth. If it was only *my* "preferred style", I wouldn't even argue. Now I'm not presenting it as a "universal truth", but as the result of experience (and not only my own) with a given class of languages. Asserting that one should *always* only put one class per file is just as non-sensical as asserting that one should *always* put several classes in a same file. Not only because Python doesn't requires you to use classes, but mostly because it's arbitrary and dogmatic. You seem to have (dis)missed the point where I said that I *almost* never had a single class in a file - which implies that I *sometimes* do this - when it makes sens from either a practical or logical POV. FWIW, I would certainly not try to apply this "preferred style" when writing GUIs in C++. You see, the fact that some idiom (style, whatever) works well with a given (class of) language(s) doesn't mean it's the more effective in some other context. Here again, it seems that you (dis)missed the point where I asked you if your thousands-lines-long classes were written in Python. From http Sat Apr 7 22:33:05 2007 From: http (Paul Rubin) Date: 07 Apr 2007 19:33:05 -0700 Subject: block scope? References: <7xr6qwal50.fsf@ruckus.brouhaha.com> <7xtzvseqzo.fsf@ruckus.brouhaha.com> <1hw72cg.115yokgarr9enN%aleax@mac.com> <1hw7kzo.1hepj3c1who5zhN%aleax@mac.com> <1hw7lxn.18itayl1fua6w0N%aleax@mac.com> <7xodlzofw2.fsf@ruckus.brouhaha.com> <1hw7rf0.1p2nwloex6vupN%aleax@mac.com> Message-ID: <7xmz1jsihq.fsf@ruckus.brouhaha.com> aleax at mac.com (Alex Martelli) writes: > >>> locals['x']=5 > Traceback (most recent call last): > File "", line 1, in > TypeError: 'builtin_function_or_method' object does not support item > assignment Whoops, yeah, meant "locals()['x'] = 5". > I think that ideally there should be a runtime error when assigning an > item of locals() with a key that's not a local variable name (possibly > excepting functions containing exec, which are kind of screwy anyway). I have no opinion of this, locals() has always seemed like a crazy part of the language to me and I never use it. I'd be happy to see it gone since it makes compiling a lot easier. From f98dawa at dd.chalmers.se Wed Apr 11 12:40:02 2007 From: f98dawa at dd.chalmers.se (Dag) Date: Wed, 11 Apr 2007 16:40:02 +0000 (UTC) Subject: text file vs. cPickle vs sqlite a design question Message-ID: I have an application which works with lists of tuples of the form (id_nr,'text','more text',1 or 0). I'll have maybe 20-50 or so of these lists containing anywhere from 3 to over 30000 tuples. The actions I need to do is either append a new tuple to the end of the list, display all the tuples or display all the tuples where the last element is a 1 Basically what I'm wondering is the best way to store these data stuctures to disc. As the subject mentioned I've basically got three approaches. Store each list as a text file, pickle each list to file or shove the whole thing into a bunch of database tables. I can see pros and cons with each approach. Does anybody have any advice as to whether any of these approaches is obviously better than any other? On one hand I like the text file approach since it lets me append without loading everything into memory, on the other hand the sqlite approach makes it easy to select stuff with SELECT * FROM foo WHERE... which could be handy if ever need to add more advanced filtering. Dag From notrealaddress at all.com Wed Apr 11 10:15:48 2007 From: notrealaddress at all.com (Dropkick Punt) Date: Wed, 11 Apr 2007 23:15:48 +0900 Subject: Connection problems with irclib References: <1176299174.112447.57440@e65g2000hsc.googlegroups.com> Message-ID: On Wed, 11 Apr 2007 06:46:14 +0000, Paul Boddie wrote: > On 11 Apr, 15:31, "Dropkick Punt" wrote: >> Hi. I've written a bot in python, using the irclib by Joel Rosdahl. >> >> Works fine from my linux box at home, but when I upload it to my shell at >> veritynet.net, can't seem to get it to connect to an irc server. > > It may well be the case that your hosting provider has blocked various > IRC ports and/or traffic. Thanks but no. The shell is generally used for eggdrops, and port 6667 is open. They even installed python specifically so I could run this bot. > >> It doesn't report any errors. >> >> Anyone have any idea how I might go about at least diagnosing the problem? >> Any suggestions might help. > > Check your provider's usage policy and documentation. From gagsl-py2 at yahoo.com.ar Sat Apr 21 06:49:03 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sat, 21 Apr 2007 07:49:03 -0300 Subject: lambda generator - curious behavior in 2.5 References: <4629d7a5_3@news.bluewin.ch> Message-ID: En Sat, 21 Apr 2007 06:21:00 -0300, Boris Borcic escribi?: > >>> x = (lambda : ((yield 666),(yield 777),(yield 888)))() > >>> x.next() > 666 > >>> x.next() > 777 > >>> x.next() > 888 > >>> x.next() > (None, None, None) I think nobody thought in advance this case (a lambda expression with yield?), else it would have been forbidden. The lambda is roughly equivalent to: def anonymous(): return ((yield 666),(yield 777),(yield 888)) x = anonymous() but *that* function is forbidden: a generator cannot contain a "return something" statement. Writing it as a lambda expression, you are bypassing the compiler check. Those three None are the 3 yield values, combined into one tuple. You can verify using send instead of next; the Nones are replaced by the received values: py> x = (lambda : ((yield 666),(yield 777),(yield 888)))() py> x.send(None) 666 py> x.send(1) 777 py> x.send(2) 888 py> x.send(3) (1, 2, 3) That was the return in effect. As the function (or lambda) is exited, the next try should raise StopIteration: py> x.send(4) Traceback (most recent call last): File "", line 1, in StopIteration Let's check with dis: py> dis.dis(x.gi_frame.f_code) 1 0 LOAD_CONST 0 (666) 3 YIELD_VALUE 4 LOAD_CONST 1 (777) 7 YIELD_VALUE 8 LOAD_CONST 2 (888) 11 YIELD_VALUE 12 BUILD_TUPLE 3 15 RETURN_VALUE > >>> x = (lambda : ((yield 666),(yield 777),(yield 888)) and None)() > >>> x.next() > 666 > >>> x.next() > 777 > >>> x.next() > 888 > >>> x.next() > > Traceback (most recent call last): > File "", line 1, in > x.next() > StopIteration > >>> This time, the ((tuple) and None) is like saying "discard the tuple and return None instead", and that fires the usual StopIteration. -- Gabriel Genellina From robert.rawlins at thinkbluemedia.co.uk Fri Apr 27 03:55:23 2007 From: robert.rawlins at thinkbluemedia.co.uk (Robert Rawlins - Think Blue) Date: Fri, 27 Apr 2007 08:55:23 +0100 Subject: : Re-ocurring Events In-Reply-To: <003101c7889c$ffabe6c0$ff03b440$@rawlins@thinkbluemedia.co.uk> References: <003101c7889c$ffabe6c0$ff03b440$@rawlins@thinkbluemedia.co.uk> Message-ID: <003b01c788a1$69fbcb90$3df362b0$@rawlins@thinkbluemedia.co.uk> Just as another quick update, I've found this module for python that may be able to help me, its designed to spot date patterns for things like recurring events I guess, http://www.biostat.wisc.edu/~annis/creations/period.py.html Quite how I can integrate it into my project I'm not sure but if I can loop through each of the events in my XML and see if they are meant to be recurring today then that's fantastic. If anyone has any rough ideas on how this might work for me I'd love to hear some rough concepts. Thanks, Rob -----Original Message----- From: python-list-bounces+robert.rawlins=thinkbluemedia.co.uk at python.org [mailto:python-list-bounces+robert.rawlins=thinkbluemedia.co.uk at python.org] On Behalf Of Robert Rawlins - Think Blue Sent: 27 April 2007 08:24 To: python-list at python.org Subject: RE:: Re-ocurring Events Thank you guys for your suggestions. I've been having a look at that launchd stuff from apple but couldn?t really see how that applies to my requirements. I've been putting some serious thought into how this should work as its essentially the final part of the puzzle for my application, I'll have a fully working model for my application. I've been thinking about the possibility of using a combination of xpath to search the XML with some loops which change the date. As events won't ever be set to start before 01-01-2007 I can set that as the ceiling for my loop. So when I'm searching for weekly events, I 'simply' take today's date and time and loop from now until 01-01-2007 decrementing the date by a week each iteration of the loop and then search the XML for events in that date, make sense? I know that's a fairly intensive way of doing it, but if it works it works. Now, the loop is where I'm really struggling, I've not done any looping with dates, can anyone give me a hand with this? How can I loop back in time from now to beginning of 07 a week at a time? Do we have some form of dateAdd() I can use with a while loop? Perhaps. Date = (now) While date > 2007-01-01: Date = dateAdd(date, -1, w) Something to that effect? Then I can quickly xpath for every iteration of the loop. Thanks guys for any help. Rob -----Original Message----- From: python-list-bounces+robert.rawlins=thinkbluemedia.co.uk at python.org [mailto:python-list-bounces+robert.rawlins=thinkbluemedia.co.uk at python.org] On Behalf Of Laurent Pointal Sent: 26 April 2007 15:33 To: python-list at python.org Subject: Re: Re-ocurring Events Daniel Nogradi a ?crit : >> A bit more of a complex one this time, and I thought I'd get your >> opinions >> on the best way to achieve this. Basically I'm looking for a way to >> describe >> a re-occurring event, like a calendar event or appointment I guess. I'm >> likely to use an XML file for the definition of the events, but >> imagine I've >> got an event that looks something like this. >> >> > repeat="daily" >> /> May take a look at launchd (Apple) XML dialect, it may have at least the semantic for your need. For other parts... elementtree, yes. >> Now what I want to do is be able to build a class which has a function >> like >> 'getCurrentEvent()' which will return any events that should be >> occurring at >> that time. So if the current system time and date is 2007-01-03 13:00:00 >> then it will return THAT event to me, but if it was say 2007-01-03 >> 16:00:00 >> then it would not, as the event isn't 'due' to occur at that time. Make >> sense? >> >> What's the best way of handling this? I'm really a little lost as to >> how I >> might get started, checking a static date time isn't a problem, it's >> when it >> comes to these re-occurring events that I struggle a little. The idea is >> that I would have 5 core repetitions, none, daily, weekly, monthly and >> annually. > > This will not solve all your problems, but a very convenient way of > handling XML is the element tree module (that comes with python 2.5): > http://docs.python.org/lib/module-xml.etree.ElementTree.html > > HTH, > Daniel -- http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list From ironfroggy at gmail.com Tue Apr 24 20:56:20 2007 From: ironfroggy at gmail.com (Calvin Spealman) Date: Tue, 24 Apr 2007 20:56:20 -0400 Subject: Charlotte Python Group Message-ID: <76fd5acf0704241756v4892a590wfea0f9ce780b04f0@mail.gmail.com> Attending my first meetup tomorrow for the Agile Charlotte group from meetup.com. My old area, surrounded by cows and corn, had no chance of getting any meetups, so I'm excited to be back at the city and able to partake in some community. If anyone by chance is attending, or near enough to make it, check out the information and drop a note. -- Read my blog! I depend on your acceptance of my opinion! I am interesting! http://ironfroggy-code.blogspot.com/ From wojciech_mula at poczta.null.onet.pl.invalid Mon Apr 2 09:32:23 2007 From: wojciech_mula at poczta.null.onet.pl.invalid (=?ISO-8859-2?Q?Wojciech_Mu=B3a?=) Date: Mon, 02 Apr 2007 15:32:23 +0200 Subject: Cascading ifs In-Reply-To: References: Message-ID: Ernesto Garc?a Garc?a wrote: > Hi experts, > > How would you do this without the more and more indenting cascade of ifs?: > > match = my_regex.search(line) > if match: > doSomething(line) > else: > match = my_regex2.search(line) > if match: > doSomething2(line) > else: > match = my_regex3.search(line) > if match: > doSomething3(line) > > etc. tbl = [(my_regex, doSomething), (my_regex2, doSomething2), (my_regex3, doSomething3)] for regex, fun in tbl: match = regexp.match(line) if match: fun(line) break w. From voxiac at gmail.com Sat Apr 21 19:56:36 2007 From: voxiac at gmail.com (voxiac at gmail.com) Date: 21 Apr 2007 16:56:36 -0700 Subject: '\\' in regex affects the following parenthesis? Message-ID: <1177199796.111430.300790@l77g2000hsb.googlegroups.com> Could someone tell me why: >>> import re >>> p = re.compile('\\.*\\(.*)') Fails with message: Traceback (most recent call last): File "", line 1, in re.compile('\\dir\\(file)') File "C:\Python25\lib\re.py", line 180, in compile return _compile(pattern, flags) File "C:\Python25\lib\re.py", line 233, in _compile raise error, v # invalid expression error: unbalanced parenthesis I thought '\\' should just be interpreted as a single '\' and not affect anything afterwards... The script 'redemo.py' shipped with Python by default is just fine about this regex however. From bruno.42.desthuilliers at wtf.websiteburo.oops.com Thu Apr 5 04:32:37 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Thu, 05 Apr 2007 10:32:37 +0200 Subject: Why NOT only one class per file? In-Reply-To: References: <1175721799.714907.52770@o5g2000hsb.googlegroups.com> <46142acc$0$7532$426a34cc@news.free.fr> Message-ID: <4614b40e$0$26843$426a74cc@news.free.fr> Sherm Pendley a ?crit : > Bruno Desthuilliers writes: > >> Chris Lasher a ?crit : >> >>> so I thought I'd ask here to >>> see why the Python idiom is the way it is: why should we NOT be >>> placing classes in their own separate files? >> Because it just sucks. > > ... > >> Just ask him why Java insists on 'one-(public)-class-per-file', and >> why it's considered good form in C++. I mean, the real *technical* >> reasons... > > Yeah, as if "because it just sucks" is a technical reason. :-) It doesn't pretend to be one !-) > It's a stylistic thing, nothing more. A bit more than just 'stylistic' IMHO. It's a matter of convenience. Having to manage hundreds of files each with a dozen lines of code is a PITA. Having to retype the same import statements in hundreds of files is a PITA - and a good way to waste time and forget something when one has to fix these import statements (yes, even with the appropriate tediting tools). I wouldn't call such considerations "nothing more than stylistic". > There's no technical basis for it, No, but there's no technical reason for putting each class in a separate file. > just personal preference. True, I prefer to avoid boilerplate proliferation, switching-file-dance, and maintenance nightmares. From b.r.willems at gmail.com Wed Apr 18 11:29:22 2007 From: b.r.willems at gmail.com (Bart Willems) Date: Wed, 18 Apr 2007 11:29:22 -0400 Subject: Combinate 2 lists to a dict ? In-Reply-To: <1176908596.222474.33440@n76g2000hsh.googlegroups.com> References: <1176908596.222474.33440@n76g2000hsh.googlegroups.com> Message-ID: Jia Lu wrote: > I have 2 lists, > a = [1,2,3] > b = ["ooo","aaa","ppp"] reading the documentation might help. If that doesn't work, try d = dict(zip(a, b)) From bdesth.quelquechose at free.quelquepart.fr Tue Apr 3 15:50:34 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Tue, 03 Apr 2007 21:50:34 +0200 Subject: How can i compare a string which is non null and empty In-Reply-To: References: Message-ID: <4612a725$0$28554$426a74cc@news.free.fr> Steven Howe a ?crit : (nb : original post reinserted) > Plissken.s at gmail.com a ?crit : >> how can i compare a string which is non null and empty? >> (snip) >> In java,I do this: >> if (str != null) && (!str.equals("")) .... >> >> how can i do that in python? > > how about just testing it's length? > >>> from types import StringType > > def stringTest(x): > ... if type(x) == StringType: > ... if len(x) == 0: > ... print 'Empty String' > ... else: > ... print 'Not Empty String' > ... else: > ... print 'value not String Type' > ... (snip) I'm sorry to say this is a excellent candidate for the DailyWTF. It's a perfect exemple of uselessly overcomplificated non-idiomatic code. And it doesn't even answers the OP's question. The pythonic translation of the OP's java snippet is : if some_str: # code here This will test that some_str is neither the None object (closer Python equivalent to Java's null) nor an empty string. Whic is what the OP asked for. HTH From zombiefreakx at gmail.com Tue Apr 24 13:11:15 2007 From: zombiefreakx at gmail.com (P-Cubed) Date: Tue, 24 Apr 2007 12:11:15 -0500 Subject: Trees, Lists and Check Boxes Message-ID: <7badbbac0704241011y7a9809e0s44b44b90c366735e@mail.gmail.com> I'm looking for some assistance extending the TreeListCtrl class to include the check box ability of the CustomTreeCtrl as well as 3-state check boxes. Main Column Column1 ----------------------------------------- ------------- [o] Child1 |-----[ ]Child1.1 |-----[ ]Child1.2 |-----[o]Child1.3 |-----[ ]Child1.3.1 Value1 |-----[ ]Child1.3.2 Value2 |-----[ ]Child1.3.3 Value3 |-----[X]Child1.3.4 Value4 [o] Child2 |-----[ ]Child2.1 |-----[ ]Child2.2 |-----[ ]Child2.3 |-----[o]Child2.4 |-----[ ]Child2.4.1 Value1 |-----[X]Child2.4.2 Value2 |-----[ ]Child2.4.3 Value3 |-----[ ]Child2.4.4 Value4 [o] Child3 |-----[ ]Child3.1 |-----[ ]Child3.2 |-----[ ]Child3.3 |-----[ ]Child3.4 |-----[ ]Child3.4.1 Value1 |-----[ ]Child3.4.2 Value2 |-----[ ]Child3.4.3 Value3 |-----[ ]Child3.4.4 Value4 Any ideas on the easiest and most effective way to do this? From slm_guzel at hotmail.com Sun Apr 8 16:42:34 2007 From: slm_guzel at hotmail.com (gslm) Date: 8 Apr 2007 13:42:34 -0700 Subject: getting button's coordinations Message-ID: <1176064954.941880.296920@o5g2000hsb.googlegroups.com> Hi, I want to use a button's coordinations for my application.It's necessary for determinig an area for ImageGrab function.Because all widgets are on a button.And I want to have this screenshot and save it as image file. Or is there any command which print all of the view of button(all the components on the button)? regards... From bj_666 at gmx.net Thu Apr 26 13:45:38 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Thu, 26 Apr 2007 19:45:38 +0200 Subject: My python annoyances so far References: <1177541453.471959.120830@c18g2000prb.googlegroups.com> <59bf34F2k27v5U1@mid.individual.net> <1177603623.774892.230390@t38g2000prd.googlegroups.com> Message-ID: In <1177603623.774892.230390 at t38g2000prd.googlegroups.com>, flifus wrote: > Well, why do some things in the library have to be functions, and > other things have to be class methods? > > Why aren't they all just either functions or class methods? like > perhaps ruby. To which class should `sorted()` belong to then? Or the functions in the `math` module? What about `itertools`? In languages without functions, like Java, you'll have to write static methods where you really want functions, just because Java forces you to stuff everything into classes. And instead of a simple ``lambda`` function one needs to write an anonymous class with a method. Quite convoluted. Ciao, Marc 'BlackJack' Rintsch From Eric_Dexter at msn.com Mon Apr 30 12:22:50 2007 From: Eric_Dexter at msn.com (Eric_Dexter at msn.com) Date: 30 Apr 2007 09:22:50 -0700 Subject: Reading Data From an Excel Sheet In-Reply-To: <1177922130.251948.107740@p77g2000hsh.googlegroups.com> References: <1177922130.251948.107740@p77g2000hsh.googlegroups.com> Message-ID: <1177950170.022726.113610@n76g2000hsh.googlegroups.com> On Apr 30, 3:35 am, sagar wrote: > Hi all, > I want a python script which takes in input an EXCEL sheet > and then reads the data in it. > Any code snippets will be fine and this i want this in windows > XP . > > Thanks in Advance > Sagar Meesala have you tried to output to csv (the comma output stuff) and then load it.. (I don't know if that is an option for excel but I use the reverse concept for dex tracker as many excel compatable sites allow csv.) https://sourceforge.net/projects/dex-tracker From peterbe at gmail.com Sun Apr 1 12:38:41 2007 From: peterbe at gmail.com (Peter Bengtsson) Date: 1 Apr 2007 09:38:41 -0700 Subject: Pickling a class with a __getattr__ Message-ID: <1175445521.216223.130470@y80g2000hsf.googlegroups.com> Hi, I'm trying to pickle an object instance of a class that is like a dict but with a __getattr__ and I'm getting pickling errors. This works but is not good enough. $ python2.4 >>> import cPickle as pickle >>> class Dict(dict): ... pass ... >>> >>> >>> friend = Dict(name='Zahid', age=40) >>> friend {'age': 40, 'name': 'Zahid'} >>> v=pickle.dumps(friend) >>> p=pickle.loads(v) >>> p {'age': 40, 'name': 'Zahid'} This is what happens when I'm trying to be clever: >>> import cPickle as pickle >>> class Dict(dict): ... def __getattr__(self, key): ... return self.__getitem__(key) ... >>> friend = Dict(name='Zahid', age=40) >>> friend {'age': 40, 'name': 'Zahid'} >>> friend.name 'Zahid' >>> v=pickle.dumps(friend) Traceback (most recent call last): File "", line 1, in ? File "/usr/lib/python2.4/copy_reg.py", line 73, in _reduce_ex getstate = self.__getstate__ File "", line 3, in __getattr__ KeyError: '__getstate__' Why can't I pickle the slightly more featurefull class there called 'Dict'? I've got my reasons for not going for a simple type dict but feel that that is irrelevant right now. From irmen.NOSPAM at xs4all.nl Mon Apr 9 17:33:56 2007 From: irmen.NOSPAM at xs4all.nl (Irmen de Jong) Date: Mon, 09 Apr 2007 23:33:56 +0200 Subject: [offtopic?] problem with UDP broadcast on Windows XP In-Reply-To: References: <461a271c$0$323$e4fe514c@news.xs4all.nl> <461a6523$0$327$e4fe514c@news.xs4all.nl> Message-ID: <461ab146$0$321$e4fe514c@news.xs4all.nl> Gabriel Genellina wrote: > Ouch, no more ideas from me. You'll surely get more answers from a > Windows networking group - this appears not to be related to Python anyway. Yeah I know that... That's what I mentioned in my original post... But I'm a noob on that type of thing, no idea where to get reliable help. So I hoped the good folks in this group could help me out a little. :) Thanks for your idea anyway! -Irmen From christian at dowski.com Mon Apr 9 09:18:28 2007 From: christian at dowski.com (Christian) Date: 9 Apr 2007 06:18:28 -0700 Subject: Kill thread In-Reply-To: <1176110066.940676.173020@e65g2000hsc.googlegroups.com> References: <1176110066.940676.173020@e65g2000hsc.googlegroups.com> Message-ID: <1176124708.672830.244710@q75g2000hsh.googlegroups.com> On Apr 9, 5:14 am, "Teja" wrote: > Hi all, > > Can any on help me out in killing a thread (i.e deleteing the reources > like, stack ,memory etc) which is started with > win32process.beginthreadex()??? > > Rite now, I am suspending the thread. But any pointers as to how to > delete the thread permanently? > > Its pretty urgent... Please... > > Teja.P Well, the answer with Python threads is that you don't kill them - you ask them to go away. But since you are using something in the pywin32 package, that rule might not apply. Perhaps you would have better luck asking on the python-win32 list: http://mail.python.org/mailman/listinfo/python-win32 Christian http://www.dowski.com From bjourne at gmail.com Mon Apr 30 17:00:15 2007 From: bjourne at gmail.com (=?ISO-8859-1?Q?BJ=F6rn_Lindqvist?=) Date: Mon, 30 Apr 2007 21:00:15 +0000 Subject: Is it possible to merge xrange and slice? In-Reply-To: <1177956139.320184.50590@n76g2000hsh.googlegroups.com> References: <1177956139.320184.50590@n76g2000hsh.googlegroups.com> Message-ID: <740c3aec0704301400p2d47a9abw1d79c0878a1a92e6@mail.gmail.com> On 30 Apr 2007 11:02:19 -0700, Bas wrote: > stupid question, but would it be possible to somehow merge xrange > (which is supposed to replace range in py3k) and slice? Both have very > similar start, stop and step arguments and both are lightweight > objects to indicate a range. But you can't do a[xrange(10,20)] and > 'for i in slice(10,20)'. The only difference is see is some behavior > with infinities (e.g. object[3:] gives a slice(3,maxint) inside > _getitem_ , but I think this should not be a large problem > (xrange(0,infinity) could just yield a generator that never stops). > > Which problems am I overlooking that prevent this? Novel idea but how would slice(3,-1) work? -- mvh Bj?rn From steven.bethard at gmail.com Tue Apr 3 16:16:59 2007 From: steven.bethard at gmail.com (Steven Bethard) Date: Tue, 03 Apr 2007 14:16:59 -0600 Subject: troubles building python 2.5 on Windows XP x64 Windows Server 2003 sp1 Platform SDK In-Reply-To: <1175624672.570370.248710@y80g2000hsf.googlegroups.com> References: <1175622506.730227.37060@p77g2000hsh.googlegroups.com> <1175624672.570370.248710@y80g2000hsf.googlegroups.com> Message-ID: bhochstetler at gmail.com wrote: > On Apr 3, 2:04 pm, Steven Bethard wrote: >> bhochstet... at gmail.com wrote: >>> I am needing to build python 2.5 on Windows XP x64 Windows Server 2003 >>> sp1 Platform SDK and am not finding anything documented on the process >>> to use. Has anyone had any success with this? If so has anyone >>> documented it? The documentation that resides in pcbuild/readme.txt is >>> not helpful at all. >>> >> What have you tried already? From the readme: >> >> All you need to do is open the workspace "pcbuild.sln" in MSVC++, >> select the Debug or Release setting (using "Solution Configuration" >> from the "Standard" toolbar"), and build the projects. > > There is no IDE available with the 64 bit compiler on Windows Server > 2003 Platform SDK, so that is not an option. Ahh, I see. Did you try this:: Building for Itanium -------------------- The project files support a ReleaseItanium configuration which creates Win64/Itanium binaries. For this to work, you need to install the Platform SDK, in particular the 64-bit support. This includes an Itanium compiler (future releases of the SDK likely include an AMD64 compiler as well). In addition, you need the Visual Studio plugin for external C compilers, from http://sf.net/projects/vsextcomp. The plugin will wrap cl.exe, to locate the proper target compiler, and convert compiler options accordingly. The project files require atleast version 0.9. I can't tell whether vsextcomp handles your compiler or not though... STeVe From rNOSPAMon at flownet.com Fri Apr 13 19:44:45 2007 From: rNOSPAMon at flownet.com (Ron Garret) Date: Fri, 13 Apr 2007 16:44:45 -0700 Subject: BaseHTTPServer and Apache References: Message-ID: In article , Ron Garret wrote: > Does > anyone know of a straightforward way to get Apache to "forward" requests > to a given path to another HTTP server running on a different port? Never mind, I think I figured it out. Apparently what I need is the ProxyPassReverse directive. I'd still be interested in hearing about people's experience using BaseHTTPServer for real applications. Thanks, rg From steve at REMOVE.THIS.cybersource.com.au Fri Apr 6 09:49:53 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Fri, 06 Apr 2007 23:49:53 +1000 Subject: how to remove multiple occurrences of a string within a list? References: <1175624433.206953.214290@n59g2000hsh.googlegroups.com> <1175626905.957243.301870@w1g2000hsg.googlegroups.com> <1175637235.783612.45980@o5g2000hsb.googlegroups.com> <1175673563.212459.322290@y66g2000hsf.googlegroups.com> Message-ID: On Wed, 04 Apr 2007 15:56:34 +0200, Hendrik van Rooyen wrote: > Now how would one do it and preserve the original order? > This apparently simple problem is surprisingly FOS... > But list comprehension to the rescue : > >>>>[x for x in duplist if duplist.count(x) == 1] > ['haha', 5, 6] >>>> > > *shakes head* duh... why does it take so long? Because you are using Shlemiel the painter's algorithm: http://www.joelonsoftware.com/articles/fog0000000319.html Each time you call duplist.count(), you go back to the beginning of the list and walk the entire list. You end up walking the list over and over and over again. -- Steven. From chris.lasher at gmail.com Sun Apr 8 22:41:54 2007 From: chris.lasher at gmail.com (Chris Lasher) Date: 8 Apr 2007 19:41:54 -0700 Subject: Why NOT only one class per file? In-Reply-To: <1175721799.714907.52770@o5g2000hsb.googlegroups.com> References: <1175721799.714907.52770@o5g2000hsb.googlegroups.com> Message-ID: <1176086514.440339.231980@d57g2000hsg.googlegroups.com> On Apr 4, 5:23 pm, "Chris Lasher" wrote: > A friend of mine with a programming background in Java and Perl places > each class in its own separate file in . I informed him that keeping > all related classes together in a single file is more in the Python > idiom than one file per class. He asked why, and frankly, his valid > question has me flummoxed. > > [snip] > > Thoughts, comments, and insight much appreciated, > Chris Thanks to all who replied and made this a very interesting and informative discussion! It gave my friend, and myself, plenty to think about. Much appreciated, Chris From qilong_ren at yahoo.com Wed Apr 11 22:14:01 2007 From: qilong_ren at yahoo.com (Qilong Ren) Date: Wed, 11 Apr 2007 19:14:01 -0700 (PDT) Subject: python regular expression help Message-ID: <138221.90891.qm@web58906.mail.re1.yahoo.com> Hi, Thanks for reply. That actually is not what I want. Strings I am dealing with may look like this: s = 'a = 4.5 b = 'h' 'd' c = 4.5 3.5' What I want is a = 4.5 b = 'h' 'd' c = 4.5 3.5 ----- Original Message ---- From: liupeng To: python-list at python.org Sent: Wednesday, April 11, 2007 6:41:30 PM Subject: Re: python regular expression help pattern = re.compile(r'\w+\s*=\s*[0-9]*.[0-9]*\s*') lists = pattern.findall(s) print lists ['a=4 ', 'b=3.4 ', 'c=4.5'] On Wed, Apr 11, 2007 at 06:10:07PM -0700, Qilong Ren wrote: > Hi, everyone, > > I am extracting some information from a given string using python RE. The > string is ,for example, > s = 'a = 4 b =3.4 5.4 c = 4.5' > What I want is : > a = 4 > b = 3.4 5.4 > c = 4.5 > Right now I use : > pattern = re.compile(r'\w+\s*=\s*.*?\s+') > lists = pattern.findall(s) > It works for the string like 'a = 4 b = 3.4 c = 4.5', but does not work with > strings like 'a=4 b=3.4 5.4 c = 4.5' > > Any suggestion? > > Thanks,Qilong > > ??????????????????????????????????????????????????????????????????????????????? > Don't get soaked. Take a quick peak at the forecast > with theYahoo! Search weather shortcut. > -- > http://mail.python.org/mailman/listinfo/python-list -- http://mail.python.org/mailman/listinfo/python-list ____________________________________________________________________________________ Need Mail bonding? Go to the Yahoo! Mail Q&A for great tips from Yahoo! Answers users. http://answers.yahoo.com/dir/?link=list&sid=396546091 -------------- next part -------------- An HTML attachment was scrubbed... URL: From therealandy at nospam.com Mon Apr 23 05:00:24 2007 From: therealandy at nospam.com (The Real Andy) Date: Mon, 23 Apr 2007 19:00:24 +1000 Subject: *** Dr G Polya BRILLIANTLY analyses the Virgina Shooting Incident *** References: <1177266754.126153.202760@b58g2000hsg.googlegroups.com> <1177287460.376404.323520@b58g2000hsg.googlegroups.com> Message-ID: On 22 Apr 2007 17:17:40 -0700, bill.sloman at ieee.org wrote: >On Apr 22, 8:49 pm, Jim Thompson Web-Site.com> wrote: >> Ignorant Bastard Poster >> >> On 22 Apr 2007 11:32:34 -0700, therm... at india.com wrote: >> >> >Dr Gideon Polya published some 130 works in a 4 decade scientific >> >career, most recently a huge pharmacological reference text >> >"Biochemical Targets of Plant Bioactive Compounds" (Taylor & Francis, >> >New York & London, 2003), and is currently editing a completed book on >> >global avoidable mortality (numerous articles on this matter can be >> >found by a simple Google search for "Gideon Polya" and on his >> >websites: >> >> >Here is the BRILLIANT AND INCISIVE ANALYSIS: >> >> >http://countercurrents.org/polya230407.htm<------ >> >> >Dr Polya, we are incredibly proud of you. God Bless you for your >> >courage. > >Note that Dr. Polya comes from Tasmania - the Australian state where I >was born. > >Meanwhile, Jim's decline continues - he has now committed top posting. >Institutionalisation can't be far away. A few home truths, but when i read this kind of diatribe: "The past and present US mass murder and genocide is largely un-reported by lying, racist, genocide-ignoring Mainstream media and Racist Bush-ite (RB) America (and its lackey Racist White Australia) are ruled by r?gimes locked into denial over the seriousness of global warming" Makes me wonder about the credibility of any statement Dr Gideon Polya makes. From bellman at lysator.liu.se Thu Apr 12 03:21:51 2007 From: bellman at lysator.liu.se (Thomas Bellman) Date: Thu, 12 Apr 2007 07:21:51 +0000 (UTC) Subject: Get Shift + TAB in ncurses. References: Message-ID: andmarti at gmail.com wrote: > Anyone can help me getting the shift + tab key combination ? > I tried with getch () but with no success. > May be using the sys.stdin ?? It's generally not possible. Most terminals I have used send the same character (ASCII code 9) when you press Shift-Tab as when you press Tab. You can't differentiate between Ctrl-X and Shift-Ctrl-X either, or between Tab and Ctrl-I. Your specific terminal may be sending some other character sequence when you press Shift-Tab (my Xterm sends ESC [ Z by default), or you may be able to program it to do so, but that will only apply to your terminal, not to anyone else's. -- Thomas Bellman, Lysator Computer Club, Link?ping University, Sweden "Don't tell me I'm burning the candle at both ! bellman @ lysator.liu.se ends -- tell me where to get more wax!!" ! Make Love -- Nicht Wahr! From azi.stdout at gmail.com Mon Apr 9 10:09:46 2007 From: azi.stdout at gmail.com (azi.stdout at gmail.com) Date: 9 Apr 2007 07:09:46 -0700 Subject: Nice "bug" to loose a contest In-Reply-To: References: <1176029528.528010.210230@n59g2000hsh.googlegroups.com> <1176032438.921825.42730@b75g2000hsg.googlegroups.com> <1176121156.470714.256010@y80g2000hsf.googlegroups.com> Message-ID: <1176127786.687835.209200@l77g2000hsb.googlegroups.com> On Apr 9, 2:47 pm, "Gabriel Genellina" wrote: > En Mon, 09 Apr 2007 09:19:16 -0300, escribi?: > > > Yeah, I've noticed that too, altough I'm clueless on how stdio handles > > that differently. Now I'm wondering, what's the behaviour of the > > Python snippet that reads from stdout in Windows.. Can someone on > > Windows try it and report please? > > It does the right thing: > > py> print sys.stdout.readlines() > Traceback (most recent call last): > File "", line 1, in > IOError: [Errno 9] Bad file descriptor > > -- > Gabriel Genellina I'm wondering if this could be treated as a bug of some kind? I always thought that the purpose of "higher" interpreted languages is to hide the implementation details as much as possible, offering a unique,equal and transparent environment on all systems (as much as this is possible). From marcus at schnupfnase.com Mon Apr 16 23:48:19 2007 From: marcus at schnupfnase.com (schnupfy) Date: 16 Apr 2007 20:48:19 -0700 Subject: strange behaviour sys.argv In-Reply-To: <46243841$0$75690$c30e37c6@lon-reader.news.telstra.net> References: <1176772070.349541.80890@y5g2000hsa.googlegroups.com> <46243841$0$75690$c30e37c6@lon-reader.news.telstra.net> Message-ID: <1176781699.486440.213770@l77g2000hsb.googlegroups.com> On Apr 17, 3:00 pm, Charles Sanders wrote: > Michael Hoffman wrote: > > schnupfy wrote: > > >> I am not used to python and I am wondering about this thing: > > > This is not a Python question. It is a question about how to use bash. > > [snip] > > Michael is correct, it is a bash thing, nothing to do with python. > bash (and other *nix like shells) generally break arguments on > white space. Quoting (both single and double) overrides this with > (slightly) different rules for different shells. > > > /root/mk/services.py 192.168.1.101 critical "192.168.1.101 > > 192.168.1.101 SNMPv2-MIB::sysUpTime.0 14:13:02:57.06 SNMPv2- > > MIB::snmpTrapOID.0 SNMPv2-SMI::enterprises.789.0.13 SNMPv2- > > SMI::enterprises.789.0.2"cfCannotTakeover == 1 priority == critical" > > SNMP-COMMUNITY-MIB::snmpTrapAddress.0 192.168.1.101 SNMP-COMMUNITY- > > MIB::snmpTrapCommunity.0 "public"" > > Assuming this has been folded and actually is one long > line (which the output confirms), you have passed the python > script seven arguments > > '192.168.1.101' (blank seperated) > 'critical' (also blank seperated) > a string extending from just after the first double quote to > just before the second, ie starting with '192.168.1.101' and > ending with '789.0.2', with the immediately following (no > white space) unquoted text 'fCannotTakeover' appended > '==' (blank seperated) > 'priority" > '==' > a string starting with critical, with the quoted string from > 'SNMP-COMMUNITY' to 'Community.0 ' (including the blank), the > unquoted string 'public', and the null quoted string "" all > appended. > > > TRAP='192.168.1.101 192.168.1.101 SNMPv2-MIB::sysUpTime.0 > > 14:13:02:57.06 SNMPv2-MIB::snmpTrapOID.0 SNMPv2-SMI::enterprises. > > 789.0.13 SNMPv2-SMI::enterprises.789.0.2"cfCannotTakeover == 1 > > priority == critical" SNMP-COMMUNITY-MIB::snmpTrapAddress.0 > > 192.168.1.101 SNMP-COMMUNITY-MIB::snmpTrapCommunity.0 "public"' > > HOST=$(echo "$TRAP" | awk '{print $1}') > > SEVERITY='critical' > > /root/mk/services.py $HOST $SEVERITY \"$TRAP\" > > Here, the variables are expanded, and then split into > arguments on white space unless quoted. The backslashes protect > the double quotes so they are treated as normal characters, so > the $TRAP variable is also split into arguments on white space. > Quotes resulting from the substitution of $TRAP are also protected > (ie are treated as ordinary characters). > > The result is > > '192.168.1.101" (From $HOST) > 'critical' (From $SEVERITY) > '"192.168.1.101' (Leading '"' from \", rest from > $TRAP, blank seperated) > '192.168.1.101' (from $TRAP, blank seperated) > 'SNMPv2-MIB::sysUpTime.0' > and so on for the rest of the $TARP string, splitting it at > white space. The last part of $TRAP, '"public"', has a double > quote appended from the \". > > Python is giving exactly what the shell has given it in both cases. > > Charles ok, thanks for the answers. I try to hand over the 3rd part (the long trap) as one cmd argument. I will ask in a shell ng. Thanks again. Cheers Marcus From "enquiring mind" at braindead.com Sun Apr 1 19:51:08 2007 From: "enquiring mind" at braindead.com (enquiring mind) Date: Sun, 01 Apr 2007 23:51:08 GMT Subject: Pygame Q (linux) beginner References: <460F28F2.D91DB67A@braindead.com> Message-ID: <46105382.58F3B2DE@braindead.com> hlubenow wrote: > > enquiring mind wrote: > > > Running 2.4.1 Python (learning) > > Running SUSE Linux 10 > > > > At Chapter 5 is where the Pygame module is > > introduced so I have a little time before I have to figure out what I > > have to download and install. > > Are you asking for advice how to install pygame on SuSE 10 ? > Well, that's easy: > > python-pygame....rpm comes with SuSE. > Just install it with YaST2; the additional packages it > needs (like libSDL) are installed automatically then. > So you don't have to download any packages from www.pygame.org. > > Another hint: If sound in pygame doesn't work, try > > export SDL_AUDIODRIVER=alsa > > right before starting your script. > > H. Thank you very much. A buddy installed SUSE 10 in Dec. for me so I shall ask him to look for rpm which I understand from your post includes pygame. You have no idea how much I appreciate your information. From sickcodemonkey at gmail.com Thu Apr 5 16:22:14 2007 From: sickcodemonkey at gmail.com (Sick Monkey) Date: Thu, 5 Apr 2007 16:22:14 -0400 Subject: Cascading ifs In-Reply-To: References: Message-ID: <2adc542f0704051322u6bfb03b9m4b1d7dec3127bb2@mail.gmail.com> If it is just the indentation that is bothering you, you could do this: match = "test" if match == "1": print "1" elif match == "2": print "2" elif match == "test": print "test" On 4/2/07, Ernesto Garc?a Garc?a wrote: > > Hi experts, > > How would you do this without the more and more indenting cascade of ifs?: > > match = my_regex.search(line) > if match: > doSomething(line) > else: > match = my_regex2.search(line) > if match: > doSomething2(line) > else: > match = my_regex3.search(line) > if match: > doSomething3(line) > > etc. > > Thanks in advance and regards, > Ernesto > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From kyosohma at gmail.com Mon Apr 9 09:55:20 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: 9 Apr 2007 06:55:20 -0700 Subject: focus trap in tkinter In-Reply-To: <1176125246.044107.4240@p77g2000hsh.googlegroups.com> References: <1176125246.044107.4240@p77g2000hsh.googlegroups.com> Message-ID: <1176126920.803344.171800@l77g2000hsb.googlegroups.com> On Apr 9, 8:27 am, "vigac... at gmail.com" wrote: > Hi all, > > I'm trying to write a simple tkinter program, then this problem popped > up. The followin code will describe the problem. > > ------------------------------------------ > > import Tkinter > > class countdown(Tkinter.Frame): > def __init__(self, master = None): > Tkinter.Frame.__init__(self, master) > self.ticker = Tkinter.Label(self) > self.pack() > self.ticker.pack() > self.ticker["text"] = "foo" > self.master.bind("", self.__focus_in) > self.master.bind("", self.__focus_out) > self.master.wm_attributes("-topmost", 1) > > def __focus_in(self, detail): > self.master.wm_attributes("-alpha", 1) > > def __focus_out(self, detail): > self.master.wm_attributes("-alpha", 0.8) > > if ("__main__" == __name__): > root = Tkinter.Tk() > app = countdown(master = root) > app.mainloop() > > ------------------------------------------ > > My aim is to set the alpha property of the toplevel window to 0.8 when > it lose focus, and set it back to 1 when it regain focus, pretty > simple. But the problem is, whenever wm_attributes() is called, a new > focus event is generated, and then wm_attributes() will be called > again, then the program runs into endless loop of receiving focus > events. Simply run above code will see what's going on. > > I tried to disable FocusIn event in the event handlers, by calling > self.master.unbind(), but it doesn't work. > > I also tried to bind FocusIn and FocusOut event to the frame, the > label widgets, instead of the toplevel window, but both frame and > label widgets doesn't receive focus event, even after I set their > takefocus properties to 1. > > There should be a way to make it work, just I didn't find it. Any > input? > > Best regards! I found some info on focus events in a previous post: http://mail.python.org/pipermail/python-list/2000-January/021226.html Maybe it will give you an idea. Lundh's site has a lot of event information on it: http://effbot.org/tkinterbook/tkinter-events-and-bindings.htm If you were using wxPython, you'd do an event.Skip(), but I can't seem to find that functionality in Tkinter. Maybe you'll have better luck. Hopefully a Tkinter guru will come to the rescue. Sorry I wasn't more help. Mike From quentel.pierre at wanadoo.fr Sat Apr 14 02:39:30 2007 From: quentel.pierre at wanadoo.fr (Pierre Quentel) Date: 13 Apr 2007 23:39:30 -0700 Subject: File DB instead of real database? In-Reply-To: <1176524076.446204.70730@w1g2000hsg.googlegroups.com> References: <1176524076.446204.70730@w1g2000hsg.googlegroups.com> Message-ID: <1176532770.829780.31460@d57g2000hsg.googlegroups.com> On 14 avr, 06:14, "Jia Lu" wrote: > Hello all > > I donot want to use a real DB like MySQL ... But I need something to > save about more than 1000 articles. > Is there any good ways? > Hi, For small sets of data PyDbLite is a good alternative to full-blown db engines >>> import PyDbLite >>> db = PyDbLite.Base("records").create('title','artist') >>> db.insert('Ok Computer','Radiohead') 0 >>> db.insert('Night On Earth','Rialto') 1 >>> db.insert('Employment','Kaiser Chiefs') 2 >>> print [ r['title'] for r in db ] ['Ok Computer', 'Night On Earth', 'Employment'] >>> print [ r['artist'] for r in db if r['artist'].startswith('R') ] ['Radiohead', 'Rialto'] >>> The syntax is intuitive for Python programmers (list comprehensions) ; it's a single, small Python module downloable at http://quentel.pierre.free.fr/PyDbLite/index.html Regards, Pierre From sergei.minayev at gmail.com Thu Apr 5 07:58:22 2007 From: sergei.minayev at gmail.com (Sergei Minayev) Date: 5 Apr 2007 04:58:22 -0700 Subject: Storing of folder structure in SQL DB Message-ID: <1175774302.652656.285260@d57g2000hsg.googlegroups.com> Hi All! Can you please help me with the following problem: I need to store a copy of local folders structure in MySQL database. I have chosen the following table structure for that: ------------------------------------------------ | id | id_uplink | folder_name | ------------------------------------------------ id - unique property of each folder. id_uplink - id of upper level folder is stored here (for example: if id of c:\test is 1, than id_uplink of c:\test\python equals 1). folder_name - name of folder. You see, i dont want to store the path list, but the structure. The question is how to implement that in Python. I easily made it in C+ + using recursion. But, unfortunately, I can't figure it out how to make it in python using os.walk function (or can you recommend smth. else???). :( Though it looks quite simple, but anyway. Best Regards, Segei From b83503104 at yahoo.com Tue Apr 3 15:55:06 2007 From: b83503104 at yahoo.com (bahoo) Date: 3 Apr 2007 12:55:06 -0700 Subject: Need help on reading line from file into list Message-ID: <1175630106.220186.107900@y66g2000hsf.googlegroups.com> Hi, I have a text file containing a single line of text, such as 0024 How should I read it into a "list"? I tried this, but the "join" did not work as expected. Any suggestions? infile = open('my_file.txt','r') for line in infile: line.join(line) my_list.extend( line ) From ZeeGeek at gmail.com Sun Apr 15 04:29:53 2007 From: ZeeGeek at gmail.com (ZeeGeek) Date: 15 Apr 2007 01:29:53 -0700 Subject: Standardizing XML Message-ID: <1176625793.392269.24060@n59g2000hsh.googlegroups.com> Is there a module for python to standardize XML? Since MSN Live Space doesn't use standard XML in the posts, I want to standardize them so that I can use them elsewhere. From bbxx789_05ss at yahoo.com Mon Apr 23 18:47:46 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: 23 Apr 2007 15:47:46 -0700 Subject: wx.TextCtrl.SetDefaultStyle not working? In-Reply-To: <1177347923.815387.205690@q75g2000hsh.googlegroups.com> References: <1177123135.263882.238100@y5g2000hsa.googlegroups.com> <1177159392.124932.218960@n76g2000hsh.googlegroups.com> <1177347923.815387.205690@q75g2000hsh.googlegroups.com> Message-ID: <1177368466.352760.50610@o5g2000hsb.googlegroups.com> On Apr 23, 11:05 am, "bcwh... at pobox.com" wrote: > > On my platform, styling the text doesn't work for single line > > TextCtrl's(which seems kind of stupid), and on Windows I think you are > > required to specify wx.TE_RICH2 to style the text. This following > > code colors the entered text red for me: > > That's it! I didn't have the TE_RICH2 option set. It works now. > > The docs say it's Windows only. Does the GTK version work without > this flag? > > -- Brian I'm not sure what GTK is, but on a Mac that style is ignored if it is set. Naturally, you can also style the text without that style being set. So, if you want your program to work cross platform, I assume you should set that style. From puopolo at gmail.com Mon Apr 16 18:13:42 2007 From: puopolo at gmail.com (john) Date: 16 Apr 2007 15:13:42 -0700 Subject: unittest assertRaises Problem Message-ID: <1176761622.220741.261420@y80g2000hsf.googlegroups.com> All: Hi. I am an experienced developer (15 yrs), but new to Python and have a question re unittest and assertRaises. No matter what I raise, assertRaises is never successful. Here is the test code: class Foo: def testException(self): raise ValueError class FooTestCase(unittest.TestCase): testTryThis(self): f = Foo() self.assertRaises(ValueError, f.testException()) This fails --- unittest reports the following: FAILED (errors=1) This seems like the most basic thing in the world. I am running Python 2.5 on Windows XP using Eclipse and PyDev Any help appreciated. Thanks, John From newsgroups at nospam.nowire.org Fri Apr 6 07:59:37 2007 From: newsgroups at nospam.nowire.org (=?ISO-8859-1?Q?Thomas_Kr=FCger?=) Date: Fri, 06 Apr 2007 13:59:37 +0200 Subject: Using os.popen3() to get binary data In-Reply-To: <1175857372.585042.239310@y80g2000hsf.googlegroups.com> References: <1175857372.585042.239310@y80g2000hsf.googlegroups.com> Message-ID: Christoph Krammer schrieb: > for image in images: > if (image[0:3] == 'GIF'): > (si, so, se) = os.popen3('giftopnm -image=all', 'b') > si.write(image) > frame = so.readlines() > > But with this code the script just hangs. When I interrupt the script, > I get the following error message: > Traceback (most recent call last): > File "/home/tiger/stock-spam/scripts/all_in_one.py", line 46, in ? > frames = so.readlines() > KeyboardInterrupt > close failed: [Errno 32] Broken pipe Just a try: use read() instead of readlines()! Thomas From bj_666 at gmx.net Sat Apr 28 02:14:47 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Sat, 28 Apr 2007 08:14:47 +0200 Subject: Beginner Ping program References: <1177739647.737759.32610@u30g2000hsc.googlegroups.com> Message-ID: In <1177739647.737759.32610 at u30g2000hsc.googlegroups.com>, Linus Cohen wrote: > I'm a newbie to python and programming in general, so I wanted a > simple project to start off. What I'm trying to do here is write a > python command-line ping program, much like the Unix and Windows ping > programs. I've got this much worked out already: > > class ping > def PING(IP, pings, size): Why is it a class? I would have expected a `ping()` function. And you might have a look at `PEP 8 -- Style Guide for Python Code`_ for spelling conventions for class and function names. .. _PEP 8 -- Style Guide for Python Code: http://www.python.org/dev/peps/pep-0008/ Ciao, Marc 'BlackJack' Rintsch From tubby at bandaheart.com Thu Apr 12 13:56:44 2007 From: tubby at bandaheart.com (tubby) Date: Thu, 12 Apr 2007 13:56:44 -0400 Subject: odd unicode error Message-ID: This: for root, dirs, files in os.walk(search_path): for f in files: print f ############### Produces this: Traceback (most recent call last): File "/home/brad/Desktop/my_script.pyw", line 340, in -toplevel- hunt(target_files(search_path, skip_file_extensions(), skip_files()), path_to_results) File "/home/brad/Desktop/my_script.pyw", line 161, in target_files for root, dirs, files in os.walk(search_path): File "os.py", line 291, in walk for x in walk(path, topdown, onerror): File "os.py", line 291, in walk for x in walk(path, topdown, onerror): File "os.py", line 281, in walk if isdir(join(top, name)): File "posixpath.py", line 65, in join path += '/' + b UnicodeDecodeError: 'ascii' codec can't decode byte 0xd0 in position 1: ordinal not in range(128) ################## I'm running Python 2.4.4c1 (#2, Oct 11 2006, 21:51:02) [GCC 4.1.2 20060928 (prerelease) (Ubuntu 4.1.1-13ubuntu5)] on linux2 Any ideas? I can't catch this with try/except and using unicode(f) doesn't help either. From skip at pobox.com Sat Apr 7 21:54:09 2007 From: skip at pobox.com (skip at pobox.com) Date: Sat, 7 Apr 2007 20:54:09 -0500 Subject: Is http://cheeseshop.python.org/pypi/ having issues In-Reply-To: References: <1175967418.642658.46930@l77g2000hsb.googlegroups.com> Message-ID: <17944.19265.249117.382711@montanaro.dyndns.org> >> Has any one noticed any issues with http://cheeseshop.python.org/pypi/? >> I have been trying for hours to install packages (using easy_install) >> but the connection keeps timing out. cyb> I'm having issues still. Wiki too Please try again. Skip From deets at nospam.web.de Fri Apr 13 06:35:06 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Fri, 13 Apr 2007 12:35:06 +0200 Subject: Try problem In-Reply-To: <1176458373.765057.164010@y80g2000hsf.googlegroups.com> References: <1176455642.199343.136720@l77g2000hsb.googlegroups.com> <1176456312.752519.198130@e65g2000hsc.googlegroups.com> <1176458373.765057.164010@y80g2000hsf.googlegroups.com> Message-ID: <5894mtF2g7geqU1@mid.uni-berlin.de> SamG schrieb: > On Apr 13, 2:25 pm, mik3l3... at gmail.com wrote: >> On Apr 13, 5:14 pm, "SamG" wrote: >> >>> import sys >>> try: >>> s=1 >>> if s==1: >>> sys.exit(0) >>> else: >>> sys.exit(1) >>> except SystemExit,s: >>> if (s==0): >>> print s >>> else: >>> print "Hello" >>> How come i always end up getting the "Hello" printed on the screen as >>> logically i should a '0' printed? >> if you put a debug print statement, eg >> >> ... >> except SystemExit,s: >> print "s in exception " , s, type(s) >> if (s==0): >> .... >> >> you will notice 's' is an "instance". so when it reaches the if >> (s==0), which you are comparing with a number, it will fail and then >> hello is printed. > > Then how do we check the value of the s's instance? By not naming the caught exception like a variable you used beforehand? The character 'e' comes to my mind... Diez From pavlovevidence at gmail.com Wed Apr 11 20:21:28 2007 From: pavlovevidence at gmail.com (Carl Banks) Date: 11 Apr 2007 17:21:28 -0700 Subject: MRO theory In-Reply-To: <1176319581.754293.151420@p77g2000hsh.googlegroups.com> References: <1176317929.068559.263330@o5g2000hsb.googlegroups.com> <1176319581.754293.151420@p77g2000hsh.googlegroups.com> Message-ID: <1176337288.148350.156350@n76g2000hsh.googlegroups.com> On Apr 11, 3:26 pm, "Clarence" wrote: > No, there is no circularity. The problem is coming about in the JPype > application. It creates a Python class to proxy any Java class or Java > interface that the program uses (directly or indirectly). As far as > the > Java proxies go, when it creates a class it can have at most one > superclass > that is a proxy of a Java class, and arbitrarily many superclasses > which > are proxies of Java interfaces. > > The problem basically comes about because interfaces are not classes, > but a class is being created to stand in for each one. Yes. In Java, because there's no possibility of conflicting methods, interfaces can be listed in any order. But when proxying Java classes with Python, the order of interfaces becomes important. > There is real Java code that is causing a class construction failure > because of an inability to construct a consistent mro. I've tried > several > approaches to make it work, and by accident, sorting the list of > interface > proxy classes, using the default comparison, make it work. It *might* not be an accident. Because Java interfaces can be listed in any order, it's quite possible that some interface hierarchies in Java violate Python's MRO restrictions right out of the box. I would guess that JPype deals with this situation by applying a consistent ordering to of bases when it creates a proxy class. And it just might turn out that "order of creation" is the sort key. Or something else could be the key (alphabetical by name?). Regardless, sorted order just *might* be the proper order to list bases to ensure MRO consistency. Or I could be way off base. I'd suggest that this is probably a question better answered on the JPype mailing list, since they would have answers and not just speculations. > That made > me > wonder if the theory had something to say. Obviously, if class A is > created > before class B, then B cannot be a base class of A, hence the > chronological > order of class creation _might_ have something to do with creating > acceptable > or unacceptable mro's. I doubt it "happens" to work that way. If sorting the bases works in general, it's probably deliberate. Carl Banks From jsavard at ecn.ab.ca Sat Apr 28 10:46:10 2007 From: jsavard at ecn.ab.ca (Quadibloc) Date: 28 Apr 2007 07:46:10 -0700 Subject: *** Dr G Polya BRILLIANTLY analyses the Virgina Shooting Incident *** In-Reply-To: <1177430456.620057.190820@n15g2000prd.googlegroups.com> References: <1177266754.126153.202760@b58g2000hsg.googlegroups.com> <1177287460.376404.323520@b58g2000hsg.googlegroups.com> <1177416547.394200.314950@r3g2000prh.googlegroups.com> <1177430456.620057.190820@n15g2000prd.googlegroups.com> Message-ID: <1177771570.535837.199190@p77g2000hsh.googlegroups.com> bill.slo... at ieee.org wrote: > On Apr 24, 2:09 pm, Quadibloc wrote: > > I never thought that I would feel the urge to call someone an > > edelweiss-eating Tanzanian devil, but Dr. Polya proved that I lacked > > imagination. . > The effect is - in fact - more severely damaged by your confusion > between Tasmania - where Dr. Polya actually lives - and Tanzania which > is a country in Africa with a name similar enough to confuse semi- > literate Americans. . Had you read his essay, as I did, you would have known that even if I had had the two countries confused previously, Dr. Polya would have disabused me of any such confusion before I finished his essay. Rather, the point of my remark, as ought to be clear, was that such an epithet - by displaying conspicuous disregard for the distinction between Tasmania and Tanzania, and the distinction between Australia and Austria, *both at the same time* - is intended to be insulting, and the author's vituperative attack on the United States makes him deserving of insult. Australia - Tasmania included - would today be under the iron heel of Imperial Japan had it not been for the armed might of the United States of America! John Savard From sjmachin at lexicon.net Tue Apr 24 20:28:53 2007 From: sjmachin at lexicon.net (John Machin) Date: Wed, 25 Apr 2007 10:28:53 +1000 Subject: Blank rows resulting from simple csv script In-Reply-To: <5976vbF2j160eU1@mid.uni-berlin.de> References: <1177444717.188536.20340@r3g2000prh.googlegroups.com> <5976vbF2j160eU1@mid.uni-berlin.de> Message-ID: <462EA0C5.9090103@lexicon.net> On 25/04/2007 6:17 AM, Diez B. Roggisch wrote: > Drew schrieb: >> Hi all - >> >> I've written a simple script to read a .csv file and then write out >> rows to a new file only if the value in the 4th column is a 0. Here's >> the code: >> >> import csv >> >> reader = csv.reader(open('table_export.csv','rb')) >> >> writer = csv.writer(open('new_jazz.csv','w')) >> >> for row in reader: >> if row[3] == '0': >> writer.writerow(row) >> >> This is writing out the correct rows, however it is writing a blank >> row between each of the rows written out. Any ideas? > > The modes aren't compatible - either use rb, wb or r,w > Bzzzzt! *ALWAYS* use binary mode for both reading and writing. From bdesth.quelquechose at free.quelquepart.fr Fri Apr 13 17:17:19 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Fri, 13 Apr 2007 23:17:19 +0200 Subject: help In-Reply-To: References: Message-ID: <461fea2b$0$17973$426a74cc@news.free.fr> pierre-yves guido a ?crit : > hello (I hope my english is not so bad), De ce point de vue l?, ?a peut aller... > I'm doing a training course and I'm a newbie in Python. My problem : > I have a form, HTML form ? GUI form ? In both cases, using which environment/libs/framework ? > and when I click, Where ? > I make an update. But all the > parameters are all required to make the update. So I'd like to put in my > code something like [optional]... > > My code (simplyfied) : > > prg.ev_ind_update(wf_pk_ev_ind=wf_pk_ev_ind,wf_fonction=wf_fonction,wf_nom=wf_nom) May I suggest the use of humanly readable meaningfull names ? > > and so, when I put nothing in wf_nom, it put me that error :"the > parameter wf_nom...was omitted from the request...". Looks like some Zope stuff. > But sometimes, > wf_nom is not required ! Then make it an optional parameter. How to do so depends on context not given here, so we can't help much unless you post enough informations. From steve at holdenweb.com Fri Apr 20 00:58:54 2007 From: steve at holdenweb.com (Steve Holden) Date: Fri, 20 Apr 2007 00:58:54 -0400 Subject: Python un-plugging the Interpreter In-Reply-To: <1hwu415.1yyvbo61efn1uqN%aleax@mac.com> References: <1hwu415.1yyvbo61efn1uqN%aleax@mac.com> Message-ID: Alex Martelli wrote: > Steve Holden wrote: > >> A long time ago Greg Stein produced a patch that removed the need for >> the GIL, but nobody seemed to want to pay the penalty it extracted in >> speed reduction, so it languished unadopted. > > Perhaps the current wave of dual-core and quad-core CPUs in cheap > consumer products would change people's perceptions -- I wonder... It would be nice to see the GIL banished, but the impression I get from my (limited) acquaintance with the Python 3.0 world leads me to believe that its banishment is *not* being treated as a priority. I can understand that it would be a major engineering effort, but I should have thought the returns on multi-core architectures would have been worth considering. It's going to be interesting to see whether perceptions in the CPython world change as PyPy and IronPython progress. 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 michael at jedimindworks.com Sun Apr 22 18:37:05 2007 From: michael at jedimindworks.com (Michael Bentley) Date: Sun, 22 Apr 2007 17:37:05 -0500 Subject: recursion depth problem In-Reply-To: <1177276111.720137.315710@b75g2000hsg.googlegroups.com> References: <1177267774.416169.276780@e65g2000hsc.googlegroups.com> <1177275314.846022.249000@e65g2000hsc.googlegroups.com> <1177276111.720137.315710@b75g2000hsg.googlegroups.com> Message-ID: <8BB48821-50C4-46CF-9DBE-BB56B6615138@jedimindworks.com> On Apr 22, 2007, at 4:08 PM, proctor wrote: > On Apr 22, 2:55 pm, half.ital... at gmail.com wrote: >> On Apr 22, 11:49 am, proctor <12cc... at gmail.com> wrote: >> >> >> >>> hello, >> >>> i have a small function which mimics binary counting. it runs >>> fine as >>> long as the input is not too long, but if i give it input longer >>> than >>> 8 characters it gives >> >>> RuntimeError: maximum recursion depth exceeded in cmp >> >>> i'm not too sure what i am doing improperly. is there really a >>> lot of >>> recursion in this code? >> >>> ================== >> >>> import sys >> >>> def ch4(item, n=0): >>> if n < len(item): >>> if item[n] == '0': >>> item[n] = '1' >>> print ''.join(item) >>> ch4(item) >>> elif item[n] == '1': >>> item[n] = '0' >>> ch4(item, n+1) >> >>> ch4(list(sys.argv[1])) >> >>> ================== >> >>> this function expects input in the form of a string of zeros, like >>> this: >> >>> python test-bin.py 00000000 >> >>> and is expected to output a list of permutations like this: >> >>> $ python test-bin.py 0000 >>> 1000 >>> 0100 >>> 1100 >>> 0010 >>> 1010 >>> 0110 >>> 1110 >>> 0001 >>> 1001 >>> 0101 >>> 1101 >>> 0011 >>> 1011 >>> 0111 >>> 1111 >> >>> thanks for all help! >> >>> sincerely, >>> proctor >> >> If you just want to make it work as is....check >> >> sys.setrecursionlimit() >> >> ~Sean > > very nice. thanks sean. so is the structure of my original code > unrescuable? i cannot rearrange it to bypass the recursion? > Anything that can be done with recursion can be done without recursion. If you really wanted to mimic a binary counter, why not write a function that converts a number to binary? Then you could just count up from 0, printing the return from your binary conversion function... And the binary converter would be pretty easy too: just think of it as making change -- for a given number you just divide the number by each of [2 ** x for x in range(len(sys.argv[1]), 0, -1)] and append the string representations of the answers to a list and if the answer is 1, subtract that much from the number... From mail at timgolden.me.uk Mon Apr 2 10:23:53 2007 From: mail at timgolden.me.uk (Tim Golden) Date: Mon, 02 Apr 2007 15:23:53 +0100 Subject: Mastering Python (OT) In-Reply-To: References: <1174045298.826137.262890@o5g2000hsb.googlegroups.com><1174052358.486071.163280@e65g2000hsc.googlegroups.com><46018fd8$0$18018$426a74cc@news.free.fr><46091cdf$0$19664$426a74cc@news.free.fr> <000f01c771d2$2fc41940$03000080@hendrik> <003301c7746f$859d0300$03000080@hendrik> Message-ID: <461111F9.9040600@timgolden.me.uk> Steve Holden wrote: > Speaking of which, here's a limerick To read it you need to know not > only that Hampshire is colloquially know as Hants, but also that > Salisbury's ancient Roman name is Sarum. > > There once was a young man of Salisbury > Whose manners were most halisbury-scalisbury > He visited Hampshire > Without any pampshire > Till somebody told him to walisbury. Not to mention the meaning (or at least existence) of the phrase harum-scarum and the pronounciation of Sarum and the possible wordplay inherent in... ... oh well, you know what I mean! I had a laugh, anyway. Thanks, Steve. TJG From see_signature at nospam.nowire.org Sun Apr 15 14:19:07 2007 From: see_signature at nospam.nowire.org (=?ISO-8859-1?Q?Thomas_Kr=FCger?=) Date: Sun, 15 Apr 2007 20:19:07 +0200 Subject: Authenticating clients and servers In-Reply-To: References: Message-ID: Thomas Kr?ger schrieb: > Many protocols support an additional SSL/TLS-Layers (e.g. HTTP -> > HTTPS). There you can use SSL certificate authentication. It may > berequired to set up a small CA, but done right it is pretty secure. I missed the best: The Twisted framework has SSL authentication already implemented: http://twistedmatrix.com/ But there also more lightweigt implementations like httplib.HTTPSConnection (for clients) or pyopenssl Thomas -- sinature: http://nospam.nowire.org/signature_usenet.png From jzgoda at o2.usun.pl Mon Apr 30 13:28:22 2007 From: jzgoda at o2.usun.pl (Jarek Zgoda) Date: Mon, 30 Apr 2007 19:28:22 +0200 Subject: Cgi File Upload without Form In-Reply-To: <1177943490.669714.176360@y5g2000hsa.googlegroups.com> References: <1177708242.553577.226530@n15g2000prd.googlegroups.com> <1177943490.669714.176360@y5g2000hsa.googlegroups.com> Message-ID: Karsten.G.Weinert at googlemail.com napisa?(a): >> Could you explain this statement? When I want to move data to a >> server in a CGI environment, a form post is the easiest way I can >> think of. What are the specific restrictions making forms a problem? > what I was thinking was: a form post is meant to be used manually. But > maybe I am wrong here and I can teach my VBA program to fill in forms > automatically. If I were using python as client, I could fill in forms > with urllib. However, I using python only server-side. "Form" usually means an action accessible for HTTP POST request with content-type multipart/form-data. Uploading files is usually done in this way, if you don't want/cann't use more sophisticated means like WebDAV (which is HTTP extension, btw). -- Jarek Zgoda http://jpa.berlios.de/ From python at rcn.com Sat Apr 21 16:32:48 2007 From: python at rcn.com (Raymond Hettinger) Date: 21 Apr 2007 13:32:48 -0700 Subject: lambda generator - curious behavior in 2.5 In-Reply-To: References: <4629d7a5_3@news.bluewin.ch> Message-ID: <1177187568.117750.304910@n76g2000hsh.googlegroups.com> [Gabriel Genellina] > This time, the ((tuple) and None) is like saying "discard the tuple and > return None instead", and that fires the usual StopIteration. It looks like the offending code is in the gen_send_ex() function in Objects/genobject.c: if (result == Py_None && f->f_stacktop == NULL) { Py_DECREF(result); result = NULL; /* Set exception if not called by gen_iternext() */ if (arg) PyErr_SetNone(PyExc_StopIteration); } The conditional should probably be: if (result 1= NULL && f->f_stacktop == NULL) Please open a bug report on SF and assign to me. Raymond Hettinger From Marko.Cain.23 at gmail.com Sun Apr 15 12:31:09 2007 From: Marko.Cain.23 at gmail.com (Marko.Cain.23 at gmail.com) Date: 15 Apr 2007 09:31:09 -0700 Subject: how to strip the domain name in python? In-Reply-To: <1176564977.498635.171600@n59g2000hsh.googlegroups.com> References: <1176526155.679721.159870@l77g2000hsb.googlegroups.com> <1176564977.498635.171600@n59g2000hsh.googlegroups.com> Message-ID: <1176654669.737355.78300@y5g2000hsa.googlegroups.com> On Apr 14, 10:36 am, Marko.Cain... at gmail.com wrote: > On Apr 14, 12:02 am, Michael Bentley > wrote: > > > > > On Apr 13, 2007, at 11:49 PM, Marko.Cain... at gmail.com wrote: > > > > Hi, > > > > I have a list of url names like this, and I am trying to strip out the > > > domain name using the following code: > > > >http://www.cnn.com > > >www.yahoo.com > > >http://www.ebay.co.uk > > > > pattern = re.compile("http:\\\\(.*)\.(.*)", re.S) > > > match = re.findall(pattern, line) > > > > if (match): > > > s1, s2 = match[0] > > > > print s2 > > > > but none of the site matched, can you please tell me what am i > > > missing? > > > change re.compile("http:\\\\(.*)\.(.*)", re.S) to re.compile("http:\/ > > \/(.*)\.(.*)", re.S) > > Thanks. I try this: > > but when the 'line' ishttp://www.cnn.com, I get 's2' com, > but i want 'cnn.com' (everything after the first '.'), how can I do > that? > > pattern = re.compile("http:\/\/(.*)\.(.*)", re.S) > > match = re.findall(pattern, line) > > if (match): > > s1, s2 = match[0] > > print s2 Can anyone please help me with my problem? I still can't solve it. Basically, I want to strip out the text after the first '.' in url address: http://www.cnn.com -> cnn.com From deets at nospam.web.de Sun Apr 15 17:04:52 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sun, 15 Apr 2007 23:04:52 +0200 Subject: reading from sys.stdin In-Reply-To: <1176666672.619314.98640@d57g2000hsg.googlegroups.com> References: <1176366058.261031.111870@p77g2000hsh.googlegroups.com> <1176387908.406115.270630@w1g2000hsg.googlegroups.com> <1176438754.995753.50190@d57g2000hsg.googlegroups.com> <1176454871.538968.176620@n76g2000hsh.googlegroups.com> <1176457007.589050.285400@d57g2000hsg.googlegroups.com> <1176538930.891355.230880@n59g2000hsh.googlegroups.com> <1176577574.338733.325790@n59g2000hsh.googlegroups.com> <1176666672.619314.98640@d57g2000hsg.googlegroups.com> Message-ID: <58fibnF2gibllU1@mid.uni-berlin.de> >> 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 just typed in 700 lines of text, and the iteration hasn't begun > yet. Should I keep going? > Well, I'm not sure how much of a programmer you are if you don't get the idea of writing a _program_ to do the typing.... -------- a.py ----------- import sys counter = 0 try: while True: s = str(counter) + '\n' counter += len(s) sys.stdout.write(s) except IOError: sys.stderr.write(s) ------- b.py ------------ import sys lst = [] for line in sys.stdin: lst.append(line) break print lst ----------------- Besides that, a little bit of logic thinking should make clear that having to wait till EOF won't work too much for piping programs that produce continously output with possibly terabytes of data. Even under modern memory constraints... Diez From b83503104 at yahoo.com Tue Apr 3 17:52:13 2007 From: b83503104 at yahoo.com (bahoo) Date: 3 Apr 2007 14:52:13 -0700 Subject: how to remove multiple occurrences of a string within a list? In-Reply-To: References: <1175624433.206953.214290@n59g2000hsh.googlegroups.com> <1175625098.269660.184790@o5g2000hsb.googlegroups.com> <1175627593.307674.11280@w1g2000hsg.googlegroups.com> Message-ID: <1175637133.938883.224570@q75g2000hsh.googlegroups.com> On Apr 3, 4:21 pm, Steve Holden wrote: > bahoo wrote: > > On Apr 3, 2:31 pm, "Matimus" wrote: > >> It depends on your application, but a 'set' might really be what you > >> want, as opposed to a list. > > >>>>> s = set(["0024","haha","0024"]) > >>>>> s > >> set(["0024","haha"])>>> s.remove("0024") > >>>>> s > >> set(["haha"]) > > > This sounds cool. > > But is there a command I can convert the "set" back to a "list"? > > That would be list(). So what you want is > > s = set(["0024","haha","0024"]) > s.remove("0024") > l = list(s) > > or something like it. It seems, a priori, unlikely that you only want to > remove items with that specific value, Is this part of some larger 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 Thanks for all the suggestions. The larger problem is, I have a list of strings that I want to remove from another list of strings. So I guess what I will do is, use a for loop, and within the for loop, do the "list" to "set" and then back to "list". From paul at boddie.org.uk Tue Apr 10 11:57:16 2007 From: paul at boddie.org.uk (Paul Boddie) Date: 10 Apr 2007 08:57:16 -0700 Subject: tuples, index method, Python's design In-Reply-To: References: <1175867771.114540.61810@n76g2000hsh.googlegroups.com> <1175884427.779950.267220@y80g2000hsf.googlegroups.com> <1175953520.316208.241490@o5g2000hsb.googlegroups.com> <7xzm5igbrb.fsf@ruckus.brouhaha.com> <1176200361.260546.280510@n76g2000hsh.googlegroups.com> <1176215231.002726.148960@y5g2000hsa.googlegroups.com> Message-ID: <1176220636.297496.21440@o5g2000hsb.googlegroups.com> On 10 Apr, 17:29, Steve Holden wrote: > > You can call something non-controversial when it generates a thread like > this? :-) It's really a storm in a teacup. The acid test would be to > generate a patch that added the method and then see if you could get a > committer to commit it. All else (including my own contributions) is > mere hot air. The patch is already submitted: http://sourceforge.net/tracker/index.php?func=detail&aid=1696444&group_id=5470&atid=305470 I won't miss tuple.index very often if it never gets in, but it's always enlightening/entertaining to see the rationales given for the rejection of this and other features, in contrast to things like "y if x else z" which just seem to mysteriously acquire momentum and then power their way in regardless. Paul From bjourne at gmail.com Tue Apr 17 08:14:30 2007 From: bjourne at gmail.com (=?ISO-8859-1?Q?BJ=F6rn_Lindqvist?=) Date: Tue, 17 Apr 2007 14:14:30 +0200 Subject: is laziness a programer's virtue? In-Reply-To: References: <1176757271.282365.319740@n76g2000hsh.googlegroups.com> <1176797558.403629.53140@b75g2000hsg.googlegroups.com> Message-ID: <740c3aec0704170514q619b83b4r614459bb8a006b12@mail.gmail.com> On 4/17/07, Mirco Wahab wrote: > The reason why I answered your posting at all (besides > seeing your x-post going into 5 ng's) is your mentioning > of 'God'. According to christian tradition (which is > somehow on topic in a Perl group) it is exactly the > case of Jesus (imho), who was (in his context) the > "/Do you really want to look like a dolt in public/" > man par excellance. Socrates also comes into the mind ;-) Fits George W. Bush too. -- mvh Bj?rn From kyosohma at gmail.com Mon Apr 23 14:26:15 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: 23 Apr 2007 11:26:15 -0700 Subject: Learning Python - First Project In-Reply-To: <1177339942.371167.93970@b75g2000hsg.googlegroups.com> References: <1177339942.371167.93970@b75g2000hsg.googlegroups.com> Message-ID: <1177352775.828143.9910@y5g2000hsa.googlegroups.com> On Apr 23, 9:52 am, KDawg44 wrote: > Hi, > > I am new to Python and am trying to write a little front end to > another application in Python. > > What I want is to have a gui pop up listing some items with several > buttons. The guts of the program I am not having any trouble with but > the GUI part I am (or more accurately, the transition between GUI > pieces). > > The first GUI that pops up lists some groups in a listbox and gives > the user the choice to create a new group, open a group, rename the > group, or delete the group. The new group and rename group buttons > pop up a dialog gui asking for the name/new name. The Open Group is > to open another GUI listing projects within that group in a list with > similar options (New Project, Open Project, Rename Project, Delete > Project). > > My question is, how should I create all these GUIs? Should each GUI > be its own class with its own __init__? Then is the first GUI the > root (how I have it set up now) and all other GUIs using Toplevel()? > > I hope this makes sense (because it only sort of makes sense in my > head). > > THanks for any suggestions. Hi, You should be able to create one main window as "root" and use standard dialogs for the dialogs you mentioned. As for the "Open Group" button, you might use a tree widget instead of opening another window. You could put the tree in a splitter window or something and it might look nicer. Of course, you can do another window, but it would be a custom, hand-coded window and NOT a standard dialog. That would mean that it would indeed be another class with its own "__init__". You can set both the standard dialogs and your custom one to "ShowModal" and then you shouldn't need to use Toplevel(). I am assuming you are using Tkinter for your front-end GUI. You might also take a gander at wxPython. It has an excellent demo you could download and it might give you some additional ideas for implementation: www.wxpython.org . Mike From howe.steven at gmail.com Tue Apr 24 14:20:28 2007 From: howe.steven at gmail.com (Steven Howe) Date: Tue, 24 Apr 2007 11:20:28 -0700 Subject: RPM error In-Reply-To: <1177431491.757683.138350@r35g2000prh.googlegroups.com> References: <1177431491.757683.138350@r35g2000prh.googlegroups.com> Message-ID: <462E4A6C.8060009@gmail.com> CSUIDL PROGRAMMEr wrote: > Hi folks > I am new to python > I am trying to write a program that will install rpm > using rpm -ivh xxx.rpm > > I want to know if python has in-built exceptions to catch no- > dependencies error. > > If not how can i build them > > thanks > > not really sure where your going with this... but you could use popen3 to redirect the StdError and StdOut of rpm to files. Then read those files (in particular StdError) for dependency output *popen3*( cmd[, mode[, bufsize]]) Executes cmd as a sub-process. Returns the file objects |(child_stdin, child_stdout, child_stderr)|. Availability: Macintosh, Unix, Windows. New in version 2.0. if your app doesn't wnat to wait, you can use os.spawn functions *P_NOWAIT* *P_NOWAITO* Possible values for the mode parameter to the spawn*() family of functions. If either of these values is given, the spawn*() functions will return as soon as the new process has been created, with the process ID as the return value. Availability: Macintosh, Unix, Windows. New in version 1.6. *P_WAIT* Possible value for the mode parameter to the spawn*() family of functions. If this is given as mode, the spawn*() functions will not return until the new process has run to completion and will return the exit code of the process the run is successful, or |-signal| if a signal kills the process. Availability: Macintosh, Unix, Windows. New in version 1.6. sph From larry.bates at websafe.com Tue Apr 10 11:24:17 2007 From: larry.bates at websafe.com (Larry Bates) Date: Tue, 10 Apr 2007 10:24:17 -0500 Subject: Problem with getting an option value In-Reply-To: References: Message-ID: Lucas Malor wrote: > Peter Otten wrote: >> Lucas Malor wrote: >>> The problem is options is an instance, so options."delete", for example, >>> is wrong; I should pass options.delete . How can I do? >> Use getattr(): > > Thank you. Do you know also if I can do a similar operation with functions? I want to select with a string a certain get() function of ConfigParser: > > if type == "int" : > funcname = "getint" > elif type == "bool" : > funcname = "getboolean" > etc. > > How can I invoke the funcion with its name in a string? > > PS: your answers had not arrived to my mail account. Is because I'm using a disposal address? Or simply it's because I'm not registered to the list? > > > > -------------------------------------- > Protect yourself from spam, > use http://sneakemail.com Use a dispatch dictionary: dispatch={'int': getint, 'bool': getboolean} then call it: dispatch(t)(*args) Note: You should NOT use type as a variable name because it will shadow the built-in type function. -Larry From bignose+hates-spam at benfinney.id.au Wed Apr 18 02:58:23 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Wed, 18 Apr 2007 16:58:23 +1000 Subject: What makes an iterator an iterator? References: Message-ID: <87hcrekw34.fsf@benfinney.id.au> Steven D'Aprano writes: > class Parrot(object): > def __iter__(self): > return self > def __init__(self): > self.next = self._next() > def _next(self): > for word in "Norwegian Blue's have beautiful plumage!".split(): > yield word Clearly the problem is you've misused an apostrophe. Python doesn't like the plural getting an apostrophe. -- \ "Speech is conveniently located midway between thought and | `\ action, where it often substitutes for both." -- John Andrew | _o__) Holmes, _Wisdom in Small Doses_ | Ben Finney From cam.ac.uk at mh391.invalid Thu Apr 19 13:26:31 2007 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Thu, 19 Apr 2007 18:26:31 +0100 Subject: Python un-plugging the Interpreter In-Reply-To: References: Message-ID: S.Mohideen wrote: > I was thinking about the feasbility of adjusting Python as a > compiled language. In addition to the Python compilers listed by Steve, there is also Pyrex, which translates a Python-like language to C, and allows one to interact with it from Python with very little difficulty. -- Michael Hoffman From robert.rawlins at thinkbluemedia.co.uk Mon Apr 30 04:26:25 2007 From: robert.rawlins at thinkbluemedia.co.uk (Robert Rawlins - Think Blue) Date: Mon, 30 Apr 2007 09:26:25 +0100 Subject: Dict Copy & Compare Message-ID: <00da01c78b01$3e80b900$bb822b00$@rawlins@thinkbluemedia.co.uk> Hello Guys, I'm looking for a little advice on dicts, firstly I need to learn how to copy a dict, I suppose I could just something like. Self.newdict = self.olddict But I fear that this only creates a reference rather than an actual copy, this means that as soon as I clear out the old one, the new one will effectively be empty. What's the best way to ACTUALY copy a dict into a new variable? Next up I'm looking to compare two different dictionaries, then loop through the unique results that are in each and print them out. Is there a more efficient way of doing this other than a loop with an if/else statement? For a in self.dict1: If a not in self.dict2: Print 'Found %s' % (a) For b in self.dict2: If b not in self.dict1: Print 'Found %s' % (b) That would firstly loop through the first dict and output any of its unique values, it then loops through the second dict and output any of its unique values, is this the best way of doing this? Or is there something more efficient? Thanks, Rob Rawlins -------------- next part -------------- An HTML attachment was scrubbed... URL: From bbxx789_05ss at yahoo.com Wed Apr 11 16:56:14 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: 11 Apr 2007 13:56:14 -0700 Subject: Nested dictionaries trouble In-Reply-To: <1176317876.917874.58040@n59g2000hsh.googlegroups.com> References: <1176317876.917874.58040@n59g2000hsh.googlegroups.com> Message-ID: <1176324974.215624.108300@q75g2000hsh.googlegroups.com> 1) You have this setup: logMonths = {"Jan":"01", "Feb":"02",...} yearTotals = { "2005":{"01":0, "02":0, ....} "2006": "2007": } Then when you get a value such as "Jan", you look up the "Jan" in the logMonths dictionary to get "01". Then you use "01" and the year, say "2005", to look up the value in the yearTotals dictionary. Why do that? What is the point of even having the logMonths dictionary? Why not make "Jan" the key in the the "2005" dictionary and look it up directly: yearTotals = { "2005":{"Jan":0, "Feb":0, ....} "2006": "2007": } That way you could completely eliminate the lookup in the logMonths dict. 2) In this part: logMonth = logMonths[logLine[1]] currentYearMonth = yearTotals[logLine[4]][logMonth] # Update year/month value currentYearMonth += int(logLine[7]) yearTotals[logLine[4]][logMonth] = currentYearMonth I'm not sure why you are using all those intermediate steps. How about: yearTotals[logLine[4]][logLine[1]] += int(logLine[7]) To me that is a lot clearer. Or, you could do this: year, month, val = logLine[4], logLine[1], int(logLine[7]) yearTotals[year][month] += val 3) >I'm thinking there's an error in the way >I set my dictionaries up or reference them Yep. It's right here: for year in years: yearTotals.setdefault(year, monthTotals) Every year refers to the same monthTotals dict. You can use a dicts copy() function to make a copy: monthTotals.copy() Here is a reworking of your code that also eliminates a lot of typing: import calendar, pprint years = ["200%s" % x for x in range(5, 8)] print years months = list(calendar.month_abbr) print months monthTotals = dict.fromkeys(months[1:], 0) print monthTotals yearTotals = {} for year in years: yearTotals.setdefault(year, monthTotals.copy()) pprint.pprint(yearTotals) logs = [ ["", "Feb", "", "", "2007", "", "", "12"], ["", "Jan", "", "", "2005", "", "", "3"], ["", "Jan", "", "", "2005", "", "", "7"], ] for logLine in logs: year, month, val = logLine[4], logLine[1], int(logLine[7]) yearTotals[year][month] += val for x in yearTotals.keys(): print "KEY", "\t", "VALUE" print x, "\t", yearTotals[x] for y in yearTotals[x].keys(): print " ", y, "\t", yearTotals[x][y] From bbxx789_05ss at yahoo.com Fri Apr 20 01:48:15 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: 19 Apr 2007 22:48:15 -0700 Subject: List of Objects In-Reply-To: <1177039105.373843.56420@p77g2000hsh.googlegroups.com> References: <1177037915.042476.153190@n76g2000hsh.googlegroups.com> <1177039105.373843.56420@p77g2000hsh.googlegroups.com> Message-ID: <1177048095.387362.316760@e65g2000hsc.googlegroups.com> On Apr 19, 9:18 pm, Paddy wrote: > > # create a list of instances > gazelles= [ Gazelle() for x in range(5)] > Nice. I knew there had to be a way to use a list comprehension, but I couldn't figure it out. From victor.lebrun at gmail.com Tue Apr 24 16:10:37 2007 From: victor.lebrun at gmail.com (vml) Date: 24 Apr 2007 13:10:37 -0700 Subject: how to serialize a COM object ? Message-ID: <1177445437.543694.49070@r3g2000prh.googlegroups.com> I have a problem : I have a COM object. I would like to pass this com object from a server to a client through a socket. I tried to put the com object into a stringIO with the pickle module but : "can't pickle PyIDispatch objects" Is there other possibilities to pass a COM object through a network ? (pyro) thanks! From attn.steven.kuo at gmail.com Wed Apr 18 15:50:57 2007 From: attn.steven.kuo at gmail.com (attn.steven.kuo at gmail.com) Date: 18 Apr 2007 12:50:57 -0700 Subject: multirember&co In-Reply-To: References: <1176768854.720234.23320@w1g2000hsg.googlegroups.com> <1176790588.024371.119360@n76g2000hsh.googlegroups.com> <1176850352.999231.79260@n59g2000hsh.googlegroups.com> <1176921030.330467.76860@o5g2000hsb.googlegroups.com> Message-ID: <1176925857.535835.130010@b58g2000hsg.googlegroups.com> On Apr 18, 12:23 pm, Anton Vredegoor wrote: (snipped) > But still, the 'while True:' loop and the 'try-except' clause and the > explicit StopIteration are not necessary ... > > from collections import deque > > def xsplitter(seq, pred): > Q = deque(),deque() > it = iter(seq) > def gen(p): > while Q[p]: yield Q[p].popleft() > for x in it: > if pred(x) == p: yield x > else: > Q[~p].append(x) > for x in gen(p): yield x > return gen(1),gen(0) > > def test(): > L = 1, 'a', 3, 'a', 4, 5, 6, 'a' > it1, it2 = xsplitter(L, lambda x: x == 'a') > print it1.next() > print it2.next() > print it1.next() > > if __name__=='__main__': > test() > > A. Try it with def test(): L = 'a', 1, 2, 'a' it1, it2 = xsplitter(L, lambda x: x == 'a') print it1.next() print it2.next() print it1.next() print it2.next() The last print statement raises StopIteration... We, however, expected each iterator to contain two elements (one yielding 'a' then 'a', and the other yielding 1 then 2). -- Regards, Steven From kw at codebykevin.com Wed Apr 18 20:31:55 2007 From: kw at codebykevin.com (Kevin Walzer) Date: Wed, 18 Apr 2007 20:31:55 -0400 Subject: Future Python Gui? In-Reply-To: <4626B828.8070607@codebykevin.com> References: <1176859699.906386.326720@b75g2000hsg.googlegroups.com> <1176923448.998078.170760@e65g2000hsc.googlegroups.com> <46267C84.8040505@codebykevin.com> <1176941169.750013.216660@e65g2000hsc.googlegroups.com> <4626B828.8070607@codebykevin.com> Message-ID: <4626B87B.4000706@codebykevin.com> This should be saved as "Tile.py." Sorry. ####### ####November 2006: Posted by Kevin Walzer, kw at codebykevin.com. Based on Tile wrapper by Martin Franklin. This version updates the wrapper to reflect changes in Tile commands, and adds support for Tile-based frames (ttk::frame). Freely reusable. import Tkinter from Tkconstants import * class Style: def default(self, style, **kw): """Sets the default value of the specified option(s) in style""" pass def map_style(self, **kw): """Sets dynamic values of the specified option(s) in style. See "STATE MAPS", below.""" pass def layout(self, style, layoutSpec): """Define the widget layout for style style. See "LAYOUTS" below for the format of layoutSpec. If layoutSpec is omitted, return the layout specification for style style. """ pass def element_create(self, name, type, *args): """Creates a new element in the current theme of type type. The only built-in element type is image (see image(n)), although themes may define other element types (see Ttk_RegisterElementFactory). """ pass def element_names(self): """Returns a list of all elements defined in the current theme. """ pass def theme_create(self, name, parent=None, basedon=None): """Creates a new theme. It is an error if themeName already exists. If -parent is specified, the new theme will inherit styles, elements, and layouts from the parent theme basedon. If -settings is present, script is evaluated in the context of the new theme as per style theme settings. """ pass def theme_settings(self, name, script): """Temporarily sets the current theme to themeName, evaluate script, then restore the previous theme. Typically script simply defines styles and elements, though arbitrary Tcl code may appear. """ pass def theme_names(self): """Returns a list of the available themes. """ return self.tk.call("style", "theme", "names") def theme_use(self, theme): """Sets the current theme to themeName, and refreshes all widgets.""" return self.tk.call("style", "theme", "use", theme) class Widget(Tkinter.Widget, Style): def __init__(self, master, widgetName=None, cnf={}, kw={}, extra=()): if not widgetName: ## why you would ever want to create a Tile Widget is behond me! widgetName="ttk::widget" Tkinter.Widget.__init__(self, master, widgetName, cnf, kw) def instate(self, spec=None, script=None): """Test the widget's state. If script is not specified, returns 1 if the widget state matches statespec and 0 otherwise. If script is specified, equivalent to if {[pathName instate stateSpec]} script. """ return self.tk.call(self._w, "instate", spec, script) def state(self, spec=None): """Modify or inquire widget state. If stateSpec is present, sets the widget state: for each flag in stateSpec, sets the corresponding flag or clears it if prefixed by an exclamation point. Returns a new state spec indicating which flags were changed: ''set changes [pathName state spec] ; pathName state $changes'' will restore pathName to the original state. If stateSpec is not specified, returns a list of the currently-enabled state flags. """ return self.tk.call(self._w, "state", spec) class Button(Widget, Tkinter.Button): def __init__(self, master=None, cnf={}, **kw): Widget.__init__(self, master, "ttk::button", cnf, kw) ###add frame support here--KWs class Frame(Widget, Tkinter.Frame): def __init__(self, master=None, cnf={}, **kw): Widget.__init__(self, master, "ttk::frame", cnf, kw) class Checkbutton(Widget, Tkinter.Checkbutton): def __init__(self, master=None, cnf={}, **kw): Widget.__init__(self, master, "ttk::checkbutton", cnf, kw) class Combobox(Widget, Tkinter.Entry): def __init__(self, master=None, cnf={}, **kw): Widget.__init__(self, master, "ttk::combobox", cnf, kw) def current(self, index=None): """If index is supplied, sets the combobox value to the element at position newIndex in the list of -values. Otherwise, returns the index of the current value in the list of -values or -1 if the current value does not appear in the list. """ return self.tk.call(self._w, "current", index) class Entry(Widget, Tkinter.Entry): def __init__(self, master=None, cnf={}, **kw): Widget.__init__(self, master, "ttk::entry", cnf, kw) def validate(self): """Force revalidation, independent of the conditions specified by the -validate option. Returns 0 if the -validatecommand returns a false value, or 1 if it returns a true value or is not specified. """ return self.tk.call(self._w, "validate") class Label(Widget, Tkinter.Label): def __init__(self, master=None, cnf={}, **kw): Widget.__init__(self, master, "ttk::label", cnf, kw) ###add LabelFrame class here--KW class LabelFrame(Widget, Tkinter.Label): def __init__(self, master=None, cnf={}, **kw): Widget.__init__(self, master, "ttk::labelframe", cnf, kw) class Menubutton(Widget, Tkinter.Menubutton): def __init__(self, master=None, cnf={}, **kw): Widget.__init__(self, master, "ttk::menubutton", cnf, kw) class Notebook(Widget): def __init__(self, master=None, cnf={}, **kw): Widget.__init__(self, master, "ttk::notebook", cnf, kw) def add(self, child, cnf=(), **kw): """Adds a new tab to the notebook. When the tab is selected, the child window will be displayed. child must be a direct child of the notebook window. See TAB OPTIONS for the list of available options. """ return self.tk.call((self._w, "add", child) + self._options(cnf, kw)) def forget(self, index): """Removes the tab specified by index, unmaps and unmanages the associated child window. """ return self.tk.call(self._w, "forget", index) def index(self, index): """Returns the numeric index of the tab specified by index, or the total number of tabs if index is the string "end". """ return self.tk.call(self._w, "index") def select(self, index): """Selects the specified tab; the associated child pane will be displayed, and the previously-selected pane (if different) is unmapped. """ return self.tk.call(self._w, "select", index) def tab(self, index, **kw): """Query or modify the options of the specific tab. If no -option is specified, returns a dictionary of the tab option values. If one -option is specified, returns the value of tha t option. Otherwise, sets the -options to the corresponding values. See TAB OPTIONS for the available options. """ return self.tk.call((self._w, "tab", index) + self._options(kw)) def tabs(self): """Returns a list of all pane windows managed by the widget.""" return self.tk.call(self._w, "tabs") class Paned(Widget): """ WIDGET OPTIONS Name Database name Database class -orient orient Orient Specifies the orientation of the window. If vertical, subpanes are stacked top-to-bottom; if horizontal, subpanes are stacked left-to-right. PANE OPTIONS The following options may be specified for each pane: Name Database name Database class -weight weight Weight An integer specifying the relative stretchability of the pane. When the paned window is resized, the extra space is added or subracted to each pane proportionally to its -weight """ def __init__(self, master=None, cnf={}, **kw): Widget.__init__(self, master, "ttk::paned", cnf, kw) def add(self, subwindow, **kw): """Adds a new pane to the window. subwindow must be a direct child of the paned window pathname. See PANE OPTIONS for the list of available options. """ return self.tk.call((self._w, "add", subwindow) + self._options(kw)) def forget(self, pane): """Removes the specified subpane from the widget. pane is either an integer index or the name of a managed subwindow. """ self.tk.call(self._w, "forget", pane) def insert(self, pos, subwindow, **kw): """Inserts a pane at the specified position. pos is either the string end, an integer index, or the name of a managed subwindow. If subwindow is already managed by the paned window, moves it to the specified position. See PANE OPTIONS for the list of available options. """ return self.tk.call((self._w, "insert", pos, subwindow) + self._options(kw)) def pane(self, pane, **kw): """Query or modify the options of the specified pane, where pane is either an integer index or the name of a managed subwindow. If no -option is specified, returns a dictionary of the pane option values. If one -option is specified, returns the value of that option. Otherwise, sets the -options to the corresponding values. """ return self.tk.call((self._w, "pane", pane) + self._options(kw)) class Progressbar(Widget): def __init__(self, master=None, cnf={}, **kw): Widget.__init__(self, master, "ttk::progressbar", cnf, kw) def step(self, amount=1.0): """Increments the -value by amount. amount defaults to 1.0 if omitted. """ return self.tk.call(self._w, "step", amount) def start(self): self.tk.call("ttk::progressbar::start", self._w) def stop(self): self.tk.call("ttk::progressbar::stop", self._w) class Radiobutton(Widget, Tkinter.Radiobutton): def __init__(self, master=None, cnf={}, **kw): Widget.__init__(self, master, "ttk::radiobutton", cnf, kw) class Scrollbar(Widget, Tkinter.Scrollbar): def __init__(self, master=None, cnf={}, **kw): Widget.__init__(self, master, "ttk::scrollbar", cnf, kw) class Separator(Widget): def __init__(self, master=None, cnf={}, **kw): Widget.__init__(self, master, "ttk::separator", cnf, kw) class Treeview(Widget, Tkinter.Listbox): def __init__(self, master=None, cnf={}, **kw): Widget.__init__(self, master, 'ttk::treeview', cnf, kw) def children(self, item, newchildren=None): """If newchildren is not specified, returns the list of children belonging to item. If newchildren is specified, replaces item's child list with newchildren. Items in the old child list not present in the new child list are detached from the tree. None of the items in newchildren may be an ancestor of item. """ return self.tk.call(self._w, "children", item, newchildren) def column(self, column, **kw): """Query or modify the options for the specified column. If no options are specified, returns a dictionary of option/value pairs. If a single option is specified, returns the value of that option. Otherwise, the options are updated with the specified values. The following options may be set on each column: -id name The column name. This is a read-only option. For example, [$pathname column #n -id] returns the data column associated with data column #n. -anchor Specifies how the text in this column should be aligned with respect to the cell. One of n, ne, e, se, s, sw, w, nw, or center. -width w The width of the column in pixels. Default is something reasonable, probably 200 or so. """ pass def delete(self, items): """Deletes each of the items and all of their descendants. The root item may not be deleted. See also: detach. """ return self.tk.call(self._w, "delete", items) def detach(self, items): """Unlinks all of the specified items from the tree. The items and all of their descendants are still present and may be reinserted at another point in the tree but will not be displayed. The root item may not be detached. See also: delete. """ return self.tk.call(self._w, "detach", items) def exists(self, item): """Returns 1 if the specified item is present in the tree, 0 otherwise. """ return self.tk.call(self._w, "exists", item) def focus(self, item=None): """If item is specified, sets the focus item to item. Otherwise, returns the current focus item, or {} if there is none. """ return self.tk.call(self._w, "focus", item) def heading(self, column, **kw): """Query or modify the heading options for the specified column. Valid options are: -text text The text to display in the column heading. -image imageName Specifies an image to display to the right of the column heading. -command script A script to evaluate when the heading label is pressed. """ pass def identify(self, x, y): """Returns a description of the widget component under the point given by x and y. The return value is a list with one of the following forms: heading #n The column heading for display column #n. separator #n The border to the right of display column #n. cell itemid #n The data value for item itemid in display column #n. item itemid element The tree label for item itemid; element is one of text, image, or indicator, or another element name depending on the style. row itemid The y position is over the item but x does not identify any element or displayed data value. nothing The coordinates are not over any identifiable object. See COLUMN IDENTIFIERS for a discussion of display columns and data columns. """ pass def index(self, item): """Returns the integer index of item within its parent's list of children. """ pass def insert(self, parent, index, id=None, **kw): """Creates a new item. parent is the item ID of the parent item, or the empty string {} to create a new top-level item. index is an integer, or the value end, specifying where in the list of parent's children to insert the new item. If index is less than or equal to zero, the new node is inserted at the beginning; if index is greater than or equal to the current number of children, it is inserted at the end. If -id is specified, it is used as the item identifier; id must not already exist in the tree. Otherwise, a new unique identifier is generated. returns the item identifier of the newly created item. See ITEM OPTIONS for the list of available options. """ pass def item(item, **kw): """Query or modify the options for the specified item. If no -option is specified, returns a dictionary of option/value pairs. If a single -option is specified, returns the value of that option. Otherwise, the item's options are updated with the specified values. See ITEM OPTIONS for the list of available options. """ pass def move(self, item, parent, index): """Moves item to position index in parent's list of children. It is illegal to move an item under one of its descendants. If index is less than or equal to zero, item is moved to the beginning; if greater than or equal to the number of children, it's moved to the end. """ pass def next(self, item): """Returns the identifier of item's next sibling, or {} if item is the last child of its parent. """ pass def parent(self, item): """Returns the ID of the parent of item, or {} if item is at the top level of the hierarchy. """ pass def prev(self, item): """Returns the identifier of item's previous sibling, or {} if item is the first child of its parent. """ pass def selection(self): """Returns the list of selected items""" pass def selection_set(self, items): """items becomes the new selection. """ pass def selection_add(self, items): """Add items to the selection """ pass def selection_remove(self, items): """Remove items from the selection """ pass def selection_toggle(self, items): """Toggle the selection state of each item in items. """ pass def set(self, item, column, value=None): """If value is specified, sets the value of column column in item item, otherwise returns the current value. See COLUMN IDENTIFIERS. """ pass if __name__=="__main__": def callback(): print "Hello" root = Tkinter.Tk() root.tk.call("package", "require", "tile") f = Frame(root, width=150) f.pack(fill="both", expand="yes") b = Button(root, text="Tile Button", command=callback) b.pack() #~ c = Checkbutton(root) #~ c.pack() #~ print b.theme_names() #~ cb = Combobox(root) #~ cb.pack() #~ e = Entry(root) #~ e.validate() #~ e.pack() #~ l = Label(root, text="Tile Label") #~ l.pack() #~ mb = Menubutton(root) #~ mb.pack() #~ nb = Notebook(root) #~ f1 = Label(nb, text="page1") #~ nb.add(f1, text="Page1") #~ f1.pack() #~ f2 = Label(nb, text="page2") #~ nb.add(f2, text="Page 2") #~ f2.pack() #~ nb.pack() pb = Progressbar(root, mode="indeterminate") pb.pack() pb.start() b = Button(root, text="Start", command=pb.start) b.pack() b = Button(root, text="Stop", command=pb.stop) b.pack() #~ rb = Radiobutton(root) #~ rb.pack() #~ text = Tkinter.Text(root) #~ scrol = Scrollbar(root) #~ text.pack(side="left", fill="both", expand="yes") #~ scrol.pack(side="left", fill="y") #~ text['yscrollcommand'] = scrol.set #~ scrol['command'] = text.yview #~ l = Label(root, text="Label1") #~ l.pack() #~ s = Separator(root) #~ s.pack(fill="x") #~ l = Label(root, text="Label2") #~ l.pack() #b.theme_use("default") #~ b1 = Tkinter.Button(root, text="Tk Button", command=callback) #~ b1.pack() panes = Paned(root) panes.pack(fill="both", expand="yes") label1 = Label(panes, text="pane1") label2 = Label(panes, text="Pane2") panes.add(label1) panes.add(label2) #~ tree = Treeview(root, columns=("One", "Two", "Three")) #~ tree.insert(None, "end", text="Hello") #~ tree.pack() root.mainloop() From michael at jedimindworks.com Wed Apr 18 04:34:48 2007 From: michael at jedimindworks.com (Michael Bentley) Date: Wed, 18 Apr 2007 03:34:48 -0500 Subject: Strange terminal behavior after quitting Tkinter application In-Reply-To: <1176881604.574369.77230@b58g2000hsg.googlegroups.com> References: <1176881604.574369.77230@b58g2000hsg.googlegroups.com> Message-ID: On Apr 18, 2007, at 2:33 AM, Chris wrote: > > I'm puzzled by some strange behavior when my Python/Tkinter > application quits (on linux): the terminal from which I started Python > is messed up. > > If start up python, then import the code below, then start the program > with Application(), then click the Quit button, my terminal never > prints anything again (such as commands I type). > > > > import Tkinter > import sys > > class Application(Tkinter.Tk): > > def __init__(self,**config): > Tkinter.Tk.__init__(self,**config) > > Tkinter.Button(self,text="Quit",command=self.quit_application).pack() > > def quit_application(self): > sys.exit() > > > > > Can anyone tell me what I'm doing wrong? What happens if you type 'stty sane' (and of course, a carriage return) afterwards? From gandalf at designaproduct.biz Thu Apr 5 12:50:16 2007 From: gandalf at designaproduct.biz (Laszlo Nagy) Date: Thu, 05 Apr 2007 18:50:16 +0200 Subject: Windows service and pyc files In-Reply-To: <46151D34.50608@designaproduct.biz> References: <1175709094.352514.64920@y66g2000hsf.googlegroups.com> <46151D34.50608@designaproduct.biz> Message-ID: <461528C8.9020707@designaproduct.biz> > When I call spawn() from a service, this is written into the logfile: > > 2007-04-05 17:52:53,828 INFO .Spawner Spawing > ['C:\\Python25\\lib\\site-packages\\win32\\PythonService.exe', > 'T:\\Python\\Projects\\Test\\Application.py'] > 2007-04-05 17:52:53,828 ERROR .Spawner Traceback (most recent call last): > File "T:\Python\Projects\Test\Processor.py", line 40, in spawn_downloader > p = subprocess.Popen(params, bufsize=1, stdout=fout.fileno(), > stderr=fout.fileno()) > File "C:\Python25\lib\subprocess.py", line 586, in __init__ > errread, errwrite) = self._get_handles(stdin, stdout, stderr) > File "C:\Python25\lib\subprocess.py", line 681, in _get_handles > p2cread = self._make_inheritable(p2cread) > File "C:\Python25\lib\subprocess.py", line 722, in _make_inheritable > DUPLICATE_SAME_ACCESS) > TypeError: an integer is required > > Okay, here is what I learnt: 1. subprocess.Popen cannot redirect stderr and stdout when called from a win32 service. This is not documented, and makes debugging almost impossible. 2. sys.executable becomes "pythonservice.exe" inside a win32 service. If I specify r"C:\Python25\python.exe" instead of sys.executable, and if I do not specify stdout and stderr parameters for subprocess.Popen, then my program starts to work. Here arises the question: how can I find r"C:\Python25\python.exe" from inside a win32 service? Can I use this: interpreter = os.path.join( os.path.split(sys.executable),[0], os.sep,os.sep,os.sep,'Python.exe' ) Is it safe? Please advise. Thanks, Laszlo From To-Email-Use-The-Envelope-Icon at My-Web-Site.com Sun Apr 22 14:49:01 2007 From: To-Email-Use-The-Envelope-Icon at My-Web-Site.com (Jim Thompson) Date: Sun, 22 Apr 2007 11:49:01 -0700 Subject: *** Dr G Polya BRILLIANTLY analyses the Virgina Shooting Incident *** References: <1177266754.126153.202760@b58g2000hsg.googlegroups.com> Message-ID: Ignorant Bastard Poster On 22 Apr 2007 11:32:34 -0700, thermate at india.com wrote: >Dr Gideon Polya published some 130 works in a 4 decade scientific >career, most recently a huge pharmacological reference text >"Biochemical Targets of Plant Bioactive Compounds" (Taylor & Francis, >New York & London, 2003), and is currently editing a completed book on >global avoidable mortality (numerous articles on this matter can be >found by a simple Google search for "Gideon Polya" and on his >websites: > >Here is the BRILLIANT AND INCISIVE ANALYSIS: > >http://countercurrents.org/polya230407.htm <------ > >Dr Polya, we are incredibly proud of you. God Bless you for your >courage. ...Jim Thompson -- | James E.Thompson, P.E. | mens | | Analog Innovations, Inc. | et | | Analog/Mixed-Signal ASIC's and Discrete Systems | manus | | Phoenix, Arizona Voice:(480)460-2350 | | | E-mail Address at Website Fax:(480)460-2142 | Brass Rat | | http://www.analog-innovations.com | 1962 | America: Land of the Free, Because of the Brave From dgdev3141 at yahoo.com Wed Apr 18 10:13:02 2007 From: dgdev3141 at yahoo.com (dgdev) Date: 18 Apr 2007 07:13:02 -0700 Subject: How to better pickle an extension type In-Reply-To: <1176792627.930045.60410@p77g2000hsh.googlegroups.com> References: <1176736722.383507.37810@n59g2000hsh.googlegroups.com> <1176792627.930045.60410@p77g2000hsh.googlegroups.com> Message-ID: <1176905581.990049.39890@d57g2000hsg.googlegroups.com> Thanks for your replies. The code I showed above was pyrex code, not python code. You are correct that python objects do not require .__reduce__() to be picklable, but apparently c extension types do (makes sense, they must be more opaque to the python machinery). I'll try the .__newobj__(), see if I can get it to do what I want... On Apr 17, 2:50 am, Ziga Seilnacht wrote: > dgdev wrote: > > I would like topicklean extension type (written inpyrex). I have > > it working thus far by defining three methods: > > > class C: > > # for pickling > > __getstate__(self): > > ... # make 'state_obj' > > return state_obj > > > __reduce__(self): > > return C,(args,to,__init__),me.__getstate__() > > > # for unpickling > > __setstate__(self,state_obj): > > self.x=state_obj.x > > ... > > > This gets the class pickling and unpickling. > > > However, I'd like to not specify arguments for __init__ (as I do now > > in __reduce__), and so not have __init__ invoked during unpickling. > > > I would like to have the pickling machinery somehow create an > > uninitialized object, and then call its __setstate__, where I can re- > > create it from 'state_obj'. > > > Is there a kosher way to do so, that is without me having to have a > > special mode in the constructor for when the object is being created > > by the unpickler? > > Why are you overwriting the __reduce__() method? The default > object.__reduce__() method, inherited by all new style classes, > already does what you want. If you really must overwrite it, and > you don't want __init__() to get called, then you should return a > reconstructor named __newobj__() as the first item of reduce > tuple. Something like this: > > >>> def __newobj__(cls, *args): > > ... return cls.__new__(cls, *args) > ...>>> class C(object): > > ... def __init__(self): > ... print "I shouldn't be called at reconstruction" > ... def __reduce__(self): > ... try: > ... getnewargs = self.__getnewargs__ > ... except AttributeError: > ... newargs = (self.__class__,) > ... else: > ... newargs = (self.__class__,) + getnewargs() > ... try: > ... getstate = self.__getstate__ > ... except AttributeError: > ... # this ignores __slots__ complications > ... state = self.__dict__ > ... else: > ... state = getstate() > ... # this ignores list and dict subclasses > ... return __newobj__, newargs, state > ...>>> c = C() > > I shouldn't be called at reconstruction>>> importpickle > >>> for proto in range(3): > > ... assert isinstance(pickle.loads(pickle.dumps(c, proto)), C) > ... > > > > Ziga From grante at visi.com Wed Apr 18 15:26:55 2007 From: grante at visi.com (Grant Edwards) Date: Wed, 18 Apr 2007 19:26:55 -0000 Subject: subprocess "handle is invalid" error References: <132cdrpqsmnvpa7@corp.supernews.com> Message-ID: <132cs7v28o49ca2@corp.supernews.com> On 2007-04-18, Thomas Heller wrote: > I think this is a subprocess bug. It is often attributed to > py2exe because usually developers do never run the script in > pythonW.exe instead of python.exe, and later build a *windows* > program with py2exe (the *windows* program has no console, and > that triggers the bug). [...] Ah, excellent analysis. It does indeed to appear to be a subprocess bug. Switching back to os.popen() makes things "work" again. There's a different problem when the program is started by double-clicking an associated file in a networked directory (works fine in a local directory). That was the initial problem I was trying to troubleshoot by switching trying subprocess.Popen(). > The script can be made to work correctly even with pythonW.exe > (and also as py2exe'd windows program, I just checked it out) > when the 4 commented out lines are uncommented. subprocess > cannot inherit the standard handles when the process has no > console, you have to create pipes for all 3 channels, and > close those that are not needed. Perhaps I'll try switching back to subprocess.Popen() and creating all three pipes. > I thought that this bug was fixed in Python2.5.1 (the release candidate), > but it seems it wasn't. The bug is at > http://sourceforge.net/tracker/index.php?func=detail&aid=1124861&group_id=5470&atid=105470 > >> If all this is correct, I hope that someone adds a section to the py2exe wiki; It had been documented at the py2exe wiki -- though it mentions a different exception. I added the bug-tracker link and also that it throws the "invalid handle" exception. http://www.py2exe.org/index.cgi/Py2ExeSubprocessInteractions > and reopens the above bug report. Since I'm still using 2.4.3, I don't think it would be appropriate for me to do so. -- Grant Edwards grante Yow! It don't mean a at THING if you ain't got visi.com that SWING!! From b83503104 at yahoo.com Mon Apr 9 17:38:12 2007 From: b83503104 at yahoo.com (bahoo) Date: 9 Apr 2007 14:38:12 -0700 Subject: recursively archiving files Message-ID: <1176154692.532747.85720@l77g2000hsb.googlegroups.com> Hi, Can I use python to recursively compress files under subdirectories with a certain format such as "ABC_XXX_XXX.dat" into a .gz or .zip file? I used to do it with "tar" on unix, but I don't like to put commands into a single line, as it is often more prone to error. Thanks bahoo From sjmachin at lexicon.net Sat Apr 21 21:04:39 2007 From: sjmachin at lexicon.net (John Machin) Date: 21 Apr 2007 18:04:39 -0700 Subject: '\\' in regex affects the following parenthesis? In-Reply-To: <1177199796.111430.300790@l77g2000hsb.googlegroups.com> References: <1177199796.111430.300790@l77g2000hsb.googlegroups.com> Message-ID: <1177203878.995330.127620@l77g2000hsb.googlegroups.com> On Apr 22, 9:56 am, vox... at gmail.com wrote: > Could someone tell me why: > > >>> import re > >>> p = re.compile('\\.*\\(.*)') Short answer: *ALWAYS* use raw strings for regexes in Python source files. Long answer: '\\.*\\(.*)' is equivalent to r'\.*\(.*)' So what re.compile is seeing is: \. -- a literal dot or period or full stop (not a metacharacter) * -- meaning 0 or more occurrences of the dot \( -- a literal left parenthesis . -- dot metacharacter meaning any character bar a newline * -- meaning 0 or more occurences of almost anything ) -- a right parenthesis grouping metacharacter; a bit lonely hence the exception. What you probably want is: \\ -- literal backslash .* -- any stuff \\ -- literal backslash (.*) -- grouped (any stuff) > > Fails with message: > > Traceback (most recent call last): > File "", line 1, in > re.compile('\\dir\\(file)') > File "C:\Python25\lib\re.py", line 180, in compile > return _compile(pattern, flags) > File "C:\Python25\lib\re.py", line 233, in _compile > raise error, v # invalid expression > error: unbalanced parenthesis > > I thought '\\' should just be interpreted as a single '\' and not > affect anything afterwards... The second and third paragraphs of the re docs (http://docs.python.org/ lib/module-re.html) cover this: """ Regular expressions use the backslash character ("\") to indicate special forms or to allow special characters to be used without invoking their special meaning. This collides with Python's usage of the same character for the same purpose in string literals; for example, to match a literal backslash, one might have to write '\\\\' as the pattern string, because the regular expression must be "\\", and each backslash must be expressed as "\\" inside a regular Python string literal. The solution is to use Python's raw string notation for regular expression patterns; backslashes are not handled in any special way in a string literal prefixed with "r". So r"\n" is a two-character string containing "\" and "n", while "\n" is a one-character string containing a newline. Usually patterns will be expressed in Python code using this raw string notation. """ Recommended reading: http://www.amk.ca/python/howto/regex/regex.html#SECTION000420000000000000000 > > The script 'redemo.py' shipped with Python by default is just fine > about this regex however. That's because you are typing the regex into a Tkinter app. Likewise if you were reading the regex from (say) a config file or were typing it to a raw_input call. The common factor is that you are not passing it through an extra level of backslash processing. HTH, John From cam.ac.uk at mh391.invalid Thu Apr 26 11:08:56 2007 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Thu, 26 Apr 2007 16:08:56 +0100 Subject: My python annoyances so far In-Reply-To: <1177599046.406827.5210@t38g2000prd.googlegroups.com> References: <1177541453.471959.120830@c18g2000prb.googlegroups.com> <1177599046.406827.5210@t38g2000prd.googlegroups.com> Message-ID: 7stud wrote: > flifus at gmail.com wrote: >> Annoyances: >> > > Every language has annoyances. Python is no exception. Post away. > Anyone that is offended can go drink a Guinness. I find Guinness annoying. -- Michael Hoffman From attn.steven.kuo at gmail.com Thu Apr 12 15:38:27 2007 From: attn.steven.kuo at gmail.com (attn.steven.kuo at gmail.com) Date: 12 Apr 2007 12:38:27 -0700 Subject: "Cloning" file attributes and permissions In-Reply-To: <1176394818.428367@jubilee.claranet.pt> References: <1176394818.428367@jubilee.claranet.pt> Message-ID: <1176406707.711609.211110@q75g2000hsh.googlegroups.com> On Apr 12, 9:20 am, Paulo da Silva wrote: > Hi! > > I need to process a file to produce another file that *must* have > *exactly* the same attributes and permissions of the former. What is the > best way to do this? The file must not exist with contents (it may exist > empty) unless it has the same attributes and permissions. > I know how to do this using, let me call it, "C type code" (stat, chmod, > chown, etc). I would like to hear some opinions on if and how it would > be possible in a more elegant/python way. > Are you using a system that supports the creation of a hard link? If so, try os.link. -- Hope this helps, Steven From bearophileHUGS at lycos.com Wed Apr 4 15:39:30 2007 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 4 Apr 2007 12:39:30 -0700 Subject: Indentifying the LAST occurrence of an item in a list In-Reply-To: References: <1175702329.330032.250750@w1g2000hsg.googlegroups.com> Message-ID: <1175715570.413174.217050@n59g2000hsh.googlegroups.com> Terry Reedy: > def rindex(lis, item): > for i in range(len(lis)-1, -1, -1): > if item == lis[i]: > return i > else: > raise ValueError("rindex(lis, item): item not in lis") This is an alternative, I don't know if it's faster: def rindex(seq, item): for pos, el in enumerate(reversed(seq)): if item == el: return len(seq) - 1 - pos else: raise ValueError("rindex(lis, item): item not in lis") t = [0, 1, 2, 3, 0] print rindex(t, 0) print rindex(t, 3) print rindex(t, 1) Bye, bearophile From bbxx789_05ss at yahoo.com Sun Apr 1 23:01:39 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: 1 Apr 2007 20:01:39 -0700 Subject: can a method access/set another's variables? In-Reply-To: <1175478965.803665.15040@o5g2000hsb.googlegroups.com> References: <1175477764.549115.159410@n59g2000hsh.googlegroups.com> <1175478965.803665.15040@o5g2000hsb.googlegroups.com> Message-ID: <1175482899.581186.249840@o5g2000hsb.googlegroups.com> On Apr 1, 7:56 pm, "wswilson" wrote: > On Apr 1, 9:43 pm, Michael Hoffman wrote: > > > > > asdf1234234 wrote: > > > -a.py- > > > import b > > > > class A: > > > def __init__(self): > > > pass > > > def my_method(self): > > > var = 1 > > > self.var = 2 > > > b.set_var(self) > > > print var > > > print self.var > > > > my_a = A() > > > my_a.my_method() > > > > -b.py- > > > def set_var(self): > > > var = 2 > > > self.var = 2 > > > > I want both var and self.var to be 2 at the end. Is there anything I > > > can pass to set_var() that will give it access to the variables in > > > my_method() like I can use self for the variables in the class A? > > > I hope there isn't a way to do this that simply. :) Why do you want to > > do this, or is it idle curiosity? There is almost surely a better way to > > solve your underlying problem. > > > You can *read* your caller's local variables (either pass locals() as an > > argument or use inspect to get the frame locals), but writing to this > > dictionary has undefined behavior. > > -- > > Michael Hoffman > > I am parsing a document which contains some lines with code I want to > eval or exec. However, due to the complexity of the parsing, I am > splitting it among different methods. So, if I eval something in one > method, it won't be there if I try to access its value a few lines > later since I happen to be in a different method in the parser. Thanks > for the help! class A(object): def early_parse(self): self.result1 = eval("10 + 5") class MyParser(object): def later_parse(self): MyParser.a.result2 = MyParser.a.result1 + eval("20 * 2") a = A() p = MyParser() p.a.early_parse() p.later_parse() print p.a.result1 print p.a.result2 From soren.skou.nielsen at gmail.com Mon Apr 16 08:56:35 2007 From: soren.skou.nielsen at gmail.com (Soren) Date: 16 Apr 2007 05:56:35 -0700 Subject: Boost Problem! Boost.Build not found In-Reply-To: <1176726516.333233.4890@y80g2000hsf.googlegroups.com> References: <1176719740.525832.132610@e65g2000hsc.googlegroups.com> <1176720813.976821.237610@w1g2000hsg.googlegroups.com> <1176722688.351441.303410@w1g2000hsg.googlegroups.com> <1176726516.333233.4890@y80g2000hsf.googlegroups.com> Message-ID: <1176728195.092014.131720@q75g2000hsh.googlegroups.com> On 16 Apr., 14:28, "Rob Wolfe" wrote: > Soren wrote: > > > Try to create boost-build.jam file like this: > > > > # boost-build.jam > > > boost-build C:\boost\boost_1_33_1\tools\build\v1 ; > > > Hi Rob, Thanks for the answer! > > > It did solve the error.. but produced a new one: > > > C:\boost\boost_1_33_1\libs\python\example\tutorial>bjam -sTOOLS=vc-8_0 > > Unable to load Boost.Build: could not find build system. > > --------------------------------------------------------- > > C:\boost\boost_1_33_1\libs\python\example\boost-build.jam attempted to > > load the > > build system by invoking > > > 'boost-build C:/boost/boost_1_33_1/tools/build/v1 ;' > > > but we were unable to find "bootstrap.jam" in the specified directory > > or in BOOST_BUILD_PATH (searching C:\boost\boost_1_33_1, C:/boost/ > > boost_1_33_1/t > > ools/build/v1). > > There is something wrong with your boost installation. > Do you have subdirectory tools/build/v1 in your installation? > > > > > What is bootstrap.jam? .. Haven't seen that one in the short > > tutorial... > > It is essential for boost build system that the file bootstrap.jam > could be found. > > -- > HTH, > Rob Hmm, I see I forgot to install boost-build .. all i did was install boost_1_33_1.exe.. thought it had it all. Now I have unzipped boost- build-2.0-m11.zip inside my boost_1_33_1 directory. It contains a bootstrap.jam file and a new error appear: C:\boost_1_33_1\libs\python\example\tutorial>bjam sTOOLS=vc-8_0 error: Could not find parent for project at '../../../..' error: Did not find Jamfile or project-root.jam in any parent directory. In case you didn't guess... I am totally lost by now! :) If I ever get this thing up and running.. I will write a new tutorial and send it to boost. Thanks! Soren From alainpoint at yahoo.fr Fri Apr 6 01:31:08 2007 From: alainpoint at yahoo.fr (alain) Date: 5 Apr 2007 22:31:08 -0700 Subject: SNMP agent In-Reply-To: <2vlfe4-6n.ln1@lairds.us> References: <1175680387.575097.4590@e65g2000hsc.googlegroups.com> <1175686451.614022.171650@b75g2000hsg.googlegroups.com> <2vlfe4-6n.ln1@lairds.us> Message-ID: <1175837468.058463.154230@p77g2000hsh.googlegroups.com> On Apr 5, 6:50 pm, cla... at lairds.us (Cameron Laird) wrote: > In article <1175686451.614022.171... at b75g2000hsg.googlegroups.com>, > > alain wrote: > >On Apr 4, 1:30 pm, alf wrote: > > >> twistedmatrix.org? > > >I already took a look at it but the agent functionality is somewhat > >primitive. I need something production-ready. > > >Alain > > 'Doesn't exist. > > I understand the sentiment; in principle, it shouldn't be hard > to write a library which supports construction of SNMP agents > in Python. I'm aware of no one who has done so publicly, though. > > Myself, I like using the Tcl-based Scotty. For severely-constrained > performance, though, you'll likely have to go to C, in some form. Hi Cameron, Thanks for the information. I still find it strange that, in all these years of existence, no one felt the need for a SNMP agent in Python. Do Pythoneers only write test tools and not real apps? Alain From dherring at at.tentpost.dot.com Sun Apr 15 21:37:04 2007 From: dherring at at.tentpost.dot.com (D Herring) Date: Sun, 15 Apr 2007 21:37:04 -0400 Subject: is laziness a programer's virtue? In-Reply-To: <1176654319.273907.167280@q75g2000hsh.googlegroups.com> References: <1176654319.273907.167280@q75g2000hsh.googlegroups.com> Message-ID: Blatherskite! http://innovators.vassar.edu/innovator.html?id=8 http://www.itweek.co.uk/itweek/comment/2160655/laziness-mother-invention From grahn+nntp at snipabacken.dyndns.org Tue Apr 24 11:39:23 2007 From: grahn+nntp at snipabacken.dyndns.org (Jorgen Grahn) Date: 24 Apr 2007 15:39:23 GMT Subject: No speedup on multi-processor machine? References: <1177189332.916296.205280@d57g2000hsg.googlegroups.com> <1177197495.821701.140390@b58g2000hsg.googlegroups.com> <1177200844.134908.192110@q75g2000hsh.googlegroups.com> <1177361572.800543.263330@n59g2000hsh.googlegroups.com> Message-ID: On 23 Apr 2007 13:52:52 -0700, Klaas wrote: > On Apr 21, 5:14 pm, Fuzzyman wrote: > >> Additionally, extending IronPython from C# is orders of magnitude >> easier than extending CPython from C. > > Given the existence of Pyrex, that statement is pretty difficult to > substantiate. IMHO, you don't even need Pyrex. When you've done it manually once, you have the blueprint for your other extension modules. Most of the work should be normal "fake OOP in C" programming. Doing it for the first time is another matter, however. /Jorgen -- // Jorgen Grahn R'lyeh wgah'nagl fhtagn! From nogradi at gmail.com Mon Apr 16 08:31:08 2007 From: nogradi at gmail.com (Daniel Nogradi) Date: Mon, 16 Apr 2007 14:31:08 +0200 Subject: string methods of a str subclass In-Reply-To: References: Message-ID: <5f56302b0704160531y7f800b2ax83674d8a30b16524@mail.gmail.com> > > Why is the strip( ) method returning something that is not a mystr > > instance? I would expect all methods operating on a string instance > > and returning another string instance to correctly operate on a mystr > > instance and return a mystr instance. > > Why would you expect that? > Would you expect the __str__ and__repr__ methods also to return a mystr > instance? If not those, then which other ones might also be excluded? > Is x.encode('zip') still a mystr instance or an encoded byte-string? Okay, good point, thanks. > > How would I achieve something > > like this without manually copying all string returning methods from > > str and stuffing the result to mystr( ) before returning? > > You don't without wrapping all the affected methods. It doesn't need to > involve manual copying though: you have a programming language available so > just write a list of method names and then some code to wrap them > automatically. Yes, this is in fact what I am doing, using __getattr__ and such. Thanks again. From mike.klaas at gmail.com Mon Apr 16 19:17:37 2007 From: mike.klaas at gmail.com (Klaas) Date: 16 Apr 2007 16:17:37 -0700 Subject: Really badly structured Python Books. In-Reply-To: <1176575848.526066.254520@y80g2000hsf.googlegroups.com> References: <1176575848.526066.254520@y80g2000hsf.googlegroups.com> Message-ID: <1176765457.784251.68360@y80g2000hsf.googlegroups.com> On Apr 14, 11:37 am, "Andre P.S Duarte" wrote: > I started reading the beginning Python book. It is intended for people > who are starting out in the Python world. But it is really > complicated, because he tries to explain, then after a bad explanation > he puts out a bad example. I really recommend NOT reading the book. > For it will make you want not to continue in Python. This is just me > letting the air out of my lungs. No need to reply this is just a > recommendation. Txs for the opportunity . I went ahead and didn't read the book, and I can feel the improvement already! -Mikw From rw at smsnet.pl Fri Apr 6 15:59:26 2007 From: rw at smsnet.pl (Rob Wolfe) Date: Fri, 06 Apr 2007 21:59:26 +0200 Subject: real time updating of popen, bufsize=0 problems References: <1175885074.694737.261430@e65g2000hsc.googlegroups.com> Message-ID: <87zm5lff4x.fsf@smsnet.pl> "ianar?" writes: > hey all, I'm trying to get real time updates of batch file output. [...] > So I tried subprocess: > proc = subprocess.Popen('"C:/path/to/test.bat"', bufsize=0, > stdout=subprocess.PIPE) Instead of that: > for line in proc.stdout: > self.display.WriteText(line) try that: while True: line = proc.stdout.readline() if not line: break self.display.WriteText(line) When a file is used in a for loop it works like an iterator. You can read details here (description of method ``next``): http://docs.python.org/lib/bltin-file-objects.html -- HTH, Rob From Leisure.201 at gmail.com Sat Apr 28 12:53:05 2007 From: Leisure.201 at gmail.com (Leisure.201 at gmail.com) Date: 28 Apr 2007 09:53:05 -0700 Subject: If you Got Questions? I bet We got Answers Message-ID: <1177779184.963353.314270@e65g2000hsc.googlegroups.com> http://ugotquestions.blogspot.com/ - Find out anything ! From bdesth.quelquechose at free.quelquepart.fr Wed Apr 4 19:30:43 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Thu, 05 Apr 2007 01:30:43 +0200 Subject: Newbie Question about sequence multiplication In-Reply-To: <6cOdnVFCLMXxuYnbnZ2dnUVZ_rCsnZ2d@comcast.com> References: <6cOdnVFCLMXxuYnbnZ2dnUVZ_rCsnZ2d@comcast.com> Message-ID: <46142c35$0$14488$426a34cc@news.free.fr> Scott a ?crit : (snip) > print ' ' * left_margin + '| ' + ' ' sentence + ' |' ^ a '+' is missing here (snip) > Now if i put * before sentence as it is with the rest of the variables, it > actually gets to the point where it asks me for the sentence, but after > inputting my sentence I receive: > Traceback (most recent call last): > File "D:/Programming/Python/sequence string multiplication example", line > 16, in > print ' ' * left_margin + '| ' + ' ' * sentence + ' |' > TypeError: can't multiply sequence by non-int of type 'str' Of course. You can't multiply a string by another string. From sjmachin at lexicon.net Sat Apr 7 22:51:42 2007 From: sjmachin at lexicon.net (John Machin) Date: 7 Apr 2007 19:51:42 -0700 Subject: beginner - py unicode Q error In-Reply-To: <461831CC.251C3EF4@braindead.com> References: <461831CC.251C3EF4@braindead.com> Message-ID: <1176000702.264221.68270@o5g2000hsb.googlegroups.com> On Apr 8, 10:05 am, enquiring mind wrote: > Sorry, I miscopied this line of code: print verbs[0:2] and not > as posted print verbs[:3] verbs[0:2] has 2 elements; the output showed 3 elements. Looks like you "miscopied" the output as well :-) If you think you need to make a correction to a posting: (1) re-read your original post carefully to see if it really does need correcting (yours didn't) (2) reply to your own post i.e. don't start a new thread. Cheers, John From tinaweb at bestemselv.com Thu Apr 19 01:53:55 2007 From: tinaweb at bestemselv.com (Tina I) Date: Thu, 19 Apr 2007 07:53:55 +0200 Subject: Beginner: Formatting text output (PyQt4) In-Reply-To: <2YBVh.4744$2v1.282@newssvr14.news.prodigy.net> References: <2YBVh.4744$2v1.282@newssvr14.news.prodigy.net> Message-ID: Glen wrote: >> Hello again, I don't blame anyone for not answering my last post, > since >> I obviously hadn't spent much time researching, but I've come a little >> ways and have another question. >> >> How can I better format text output to a QTextEdit object? I'm >> inserting 5 columns into each row. When I write the info to a file, it >> looks like the following: >> >> 42: 115 26: 114 35: 112 19: 108 16: 107 45: 107 40: >> 106 5: 105 41: 104 2: 103 >> 9: 102 48: 102 15: 101 22: 101 27: 101 >> 39: 101 43: 101 10: 100 6: 99 34: 99 32: 98 49: >> 98 20: 97 30: 97 8: 96 17: 96 38: 96 12: 95 >> 14: 95 37: 95 >> 4: 94 13: 94 44: 94 36: 93 3: 92 >> 24: 92 28: 92 31: 91 29: 89 7: 88 >> 1: 87 18: 85 46: 85 33: 84 11: 83 >> 23: 83 47: 82 25: 80 21: 79 50: 56 52: 39 51: >> 38 53: 36 54: 25 55: 18 >> >> When I write the contents of the file to my TextEdit object it comes out >> uneven, something like this: >> 42: 115 26: 114 35: 112 19: 108 16: 107 45: 107 40: 106 >> 5: 105 41: 104 2: 103 9: 102 48: 102 15: 101 22: 101 27: >> 101 39: 101 43: 101 10: 100 6: 99 34: 99 32: 98 49: 98 >> 20: 97 30: 97 8: 96 17: 96 38: 96 12: 95 14: 95 >> 37: 95 4: 94 13: 94 44: 94 36: 93 3: 92 24: 92 28: >> 92 31: 91 29: 89 7: 88 >> 1: 87 18: 85 46: 85 33: 84 11: 83 >> 23: 83 47: 82 25: 80 21: 79 50: 56 52: 39 51: 38 >> 53: 36 54: 25 55: 18 >> >> What seems to be happening is that the font that pyqt is using is not >> fixed width, so I did this: >> qTxtFormat = QTextCharFormat() >> qTxtFormat.setFontFixedPitch(True) >> ui.textEdit.setCurrentCharFormat(qTxtFormat) >> >> Also, I tried using the pyqt formatting such as the following: >> >> qStr = QtCore.QString( QtCore.QString( str(tL2[i][0]) >> ).rightJustified(2) + ':' + QtCore.QString( str(tL2[i][1]) >> ).rightJustified(4) ) >> This still gives me uneven columns. >> >> Any suggestions? >> >> Thanks, >> >> Glen > Do you need to use QTextEdit for the output? Sounds like maybe you should look at for example the QTableWidget or maybe the QTreeWidget? Tina From aisaac at american.edu Tue Apr 24 22:14:26 2007 From: aisaac at american.edu (Alan Isaac) Date: Wed, 25 Apr 2007 02:14:26 GMT Subject: gotcha or bug? random state reset on irrelevant import References: <33yXh.5839$Fc1.4387@trnddc05> Message-ID: <6QyXh.3114$1M1.1800@trnddc01> "James Stroud" wrote in message news:f0mb4p$kq0$1 at zinnia.noc.ucla.edu... > if __name__ == "__main__": > seed(314) Thanks for this suggestion. Alan Isaac From lorenzo at excitement.com Sun Apr 8 13:29:06 2007 From: lorenzo at excitement.com (Lorenzo) Date: Sun, 08 Apr 2007 12:29:06 -0500 Subject: How do I get a slice of a string held in a tuple? References: <25ine4-rvt.ln1@Hedley.internal.thethurmans.com> <1176050876.835238.68560@d57g2000hsg.googlegroups.com> Message-ID: In article <1176050876.835238.68560 at d57g2000hsg.googlegroups.com>, "mensanator at aol.com" wrote: > On Apr 8, 11:34?am, Lorenzo Thurman > wrote: > > I have tuple which hold a string in tup[0]. I want to get a slice of > > that string. I thought I would do something like: > > tup[0][start:end] > > But this fails. > > No, it doesn't. > > >>> a = ('abcdefg','hijkl') > >>> a[0] > 'abcdefg' > >>> a[0][1:2] > 'b' > > > > How do I go about it? > > Do it correctly. Post your actual example that fails > and the related error message. Possibnly your indexes > were out of range. > > > I googled this and found a couple > > of references, but no solution. > > Well, there wouldn't be a solution to a non-existent > problem, would there? > > > TIA Here's the code: elapsedTime = mydata[1] index = elapsedTime.find("real") # the index will have a value 0f 110 totaltime = elapsedTime[index:] # instead of this returning a shortened html string, i only # get the left angle bracket '<' -- "My Break-Dancing days are over, but there's always the Funky Chicken" --The Full Monty From ken at theoryyalgebra.com Wed Apr 18 02:43:58 2007 From: ken at theoryyalgebra.com (Ken Tilton) Date: Wed, 18 Apr 2007 02:43:58 -0400 Subject: is laziness a programer's virtue? In-Reply-To: <1176667091.415819.152890@n76g2000hsh.googlegroups.com> References: <1176654319.273907.167280@q75g2000hsh.googlegroups.com> <1176667091.415819.152890@n76g2000hsh.googlegroups.com> Message-ID: Xah Lee wrote: > Dear Ken, > > I want to thank you for your spirit in supporting and leading the lisp > community, in spreading lisp the language both in what you have done > technically as well as evangelization, as well as the love and > knowledge attitude towards newsgroup communities in general, in part > thru your numerous replies to my posts in the past years. Hey, thx, but to me recommending Lisp is like recommending water to a life form. Meanwhile, the last thing anyone can doubt is that you say what you mean and mean what you say, so all we can say about your detractors is... > (as opposed > to, the motherfucking pack of driveling and fuckface ignoramuses that > are predominate personalities in newsgroups, ...OK, but we know this from long Usenet experience. Reaching Enlightenment means smiling on these noisemakers and having compassion for them, for they live in mean, narrow worlds and in attacking you are only reaching for the sunlight you enjoy, in however their ignorant way. The nice thing about this compassionate view is that it leaves you feeling positive and at peace within yourself, whereas the "driveling and fuckface" thing leaves you feeling negative and attacked. less good, for my money. ken From moin at blackhole.labs.rootshell.ws Wed Apr 18 18:27:24 2007 From: moin at blackhole.labs.rootshell.ws (S.Mohideen) Date: Wed, 18 Apr 2007 16:27:24 -0600 Subject: Python Threads - Message-ID: <001801c78208$c21b8080$fa936540@cisco.com> Hi All, Can you please suggest a technique in Python where we can spawn few number of worker threads and later map them to a function/s to execute individual Jobs. Any references would be helpful.. Thanks Moin From eric.mahurin at gmail.com Wed Apr 11 11:18:15 2007 From: eric.mahurin at gmail.com (Eric Mahurin) Date: 11 Apr 2007 08:18:15 -0700 Subject: descriptor object for an attribute? Message-ID: <1176304695.336308.151810@n76g2000hsh.googlegroups.com> Is there a standard way to get a descriptor object for an arbitrary object attribute - independent of whether it uses the descriptor/ property protocol or not. I want some kind of handle/reference/ pointer to an attribute. I know I could make my own class to do this (using the __dict__ of the object and the attribute name), but I would like to use something standard (at least a protocol) if it exists. All that is needed in the protocol is getter and setter methods (like __get__ and __set__ in a descriptor). Of course it would be nice to have a better syntax than those method names of the descriptor (I've seen unary + for the getter and += for the setter somewhere on the web). Now the question I'm going to get is: why? I've used ruby (everything is also already a reference to an object) for several years and been through this discussion. I realize that 90% of the time you want some kind of reference/pointer, there is a better way. But there are those occassions where the most elegant solution is with the concept of a reference. An obvious example in python today is a descriptor object - it looks just like a reference (but is not a pointer) - having getter and setter methods. The times in C/C++ where the elegant solution is with a pointer to a pointer is also another example. That is the situation I'm dealing with now. I'm using a singly linked list (as opposed to a normal list/ array for performance/memory reasons). If you want to insert/delete a node at a certain point in the list, the best thing to have access to would be "link" (attribute or even local variable) where you want to insert/delete. Without a reference, you'd end up with a less than ideal solution: a) do the operation based on the previous node and special case the situation where you want to operate at the head (no previous node), b) do the operation based on the previous node and add a dummy head node, or c) make the list doubly linked, do the operation based on the current node, and either special case the head or add a dummy head node. Really I'm dealing with a directed graph structure, but part of it uses singly linked lists (the children of a parent). Having a handle on any of the links in the graph would be a useful thing. From gagsl-py2 at yahoo.com.ar Mon Apr 9 10:25:29 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 09 Apr 2007 11:25:29 -0300 Subject: Database in memory References: <1176124752.172926.129850@w1g2000hsg.googlegroups.com> Message-ID: En Mon, 09 Apr 2007 10:19:12 -0300, Jim escribi?: > I have an application that will maintain an in-memory database in the > form of a list of lists. Does anyone know of a way to search for and > retreive "records" from such a structure? Why not a true database? SQLite can handle an in-memory database. -- Gabriel Genellina From tjreedy at udel.edu Fri Apr 6 13:39:51 2007 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 6 Apr 2007 13:39:51 -0400 Subject: block scope? References: Message-ID: "Neal Becker" wrote in message news:ev5r7p$pdf$1 at sea.gmane.org... | One thing I sometimes miss, which is common in some other languages (c++), | is idea of block scope. It would be useful to have variables that did not | outlive their block, primarily to avoid name clashes. This also leads to | more readable code. I wonder if this has been discussed? Yes, but Guido (and others) prefer to keep things simple. There is also the question of how to indicate a limited scope. In C++, you put the declaration in the scope. But Python has no such declarations. tjr From nogradi at gmail.com Sun Apr 29 07:37:30 2007 From: nogradi at gmail.com (Daniel Nogradi) Date: Sun, 29 Apr 2007 13:37:30 +0200 Subject: Could zipfile module process the zip data in memory? In-Reply-To: <1177845313.798239.71580@o5g2000hsb.googlegroups.com> References: <1177845313.798239.71580@o5g2000hsb.googlegroups.com> Message-ID: <5f56302b0704290437j377e17f0oca0ab3f3a0a7dd53@mail.gmail.com> > I made a C/S network program, the client receive the zip file from the > server, and read the data into a variable. how could I process the > zipfile directly without saving it into file. > In the document of the zipfile module, I note that it mentions the > file-like object? what does it mean? > > class ZipFile( file[, mode[, compression[, allowZip64]]]) > Open a ZIP file, where file can be either a path to a file (a > string) or a file-like object. Yes it is possible to process the content of the zipfile without saving every file: [untested] from zipfile import ZipFile from StringIO import StringIO zipp = ZipFile( this_is_the_zip_file_from_your_server, 'r' ) for name in zipp.namelist( ): content = zipp.read( name ) s = StringIO( ) s.write( content ) # now the file 'name' is in 's' (in memory) # you can process it further # ............ s.close( ) zipp.close( ) HTH, Daniel From bbxx789_05ss at yahoo.com Mon Apr 9 23:34:10 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: 9 Apr 2007 20:34:10 -0700 Subject: python, wxpython and Mac OS X In-Reply-To: References: <1176086130.330795.268590@n76g2000hsh.googlegroups.com> <1176092755.914088.5040@p77g2000hsh.googlegroups.com> Message-ID: <1176176050.269011.212780@e65g2000hsc.googlegroups.com> On Apr 9, 8:10 am, Robert Kern wrote: > > Should I remove 2.4.4 and install 2.5 instead? > > No, it's okay. > > -- > Robert Kern Ok, thanks. I'll download wxPython and see if I can get it installed properly. From nagle at animats.com Mon Apr 23 02:20:25 2007 From: nagle at animats.com (John Nagle) Date: Sun, 22 Apr 2007 23:20:25 -0700 Subject: Socket exceptions aren't in the standard exception hierarchy Message-ID: Here are three network-related exceptions. These were caught by "except" with no exception type, because none of the more specific exceptions matched. This is what a traceback produced: 1. File "D:\Python24\lib\socket.py", line 295, in read data = self._sock.recv(recv_size) timeout: timed out 2. File "D:\Python24\lib\socket.py", line 295, in read data = self._sock.recv(recv_size) error: (10054, 'Connection reset by peer') 3. File "D:\Python24\lib\socket.py", line 317, in readline data = recv(1) IOError: [Errno socket error] timed out For 1 and 2, those are errors that aren't in the exception hierarchy. Looking at the C code for "socketmodule.c", it's clear that "socket.error" doesn't inherit from any standard exception class. See, in "init_socket()": socket_error = PyErr_NewException("socket.error", NULL, NULL); That first NULL should be some parent exception, maybe "IOError". As it is, "socket.error" is outside the standard exception hierarchy. That's not too good. Case #3, IOError, should have been caught by this: except IOError, message: # I/O error But it wasn't. The "IOError" fell through, was caught by the next outer exception block, and was logged as a generic error. I can't find where in the Python socket module an "IOError" could be raised. I would have expected "socket.timeout". Anyway, I need to know the full set of exceptions that can be raised by sockets. Thanks. John Nagle From AWasilenko at gmail.com Thu Apr 5 20:56:29 2007 From: AWasilenko at gmail.com (Adam W.) Date: 5 Apr 2007 17:56:29 -0700 Subject: Easy question: More items in a For loop? Message-ID: <1175820988.988878.18940@p77g2000hsh.googlegroups.com> I'm trying to write a script that will parse IRC chat logs and color code them if it finds certain characters. I was able to make this work with one character, but to make it even more accurate I would like to use two identifying characters. Here is my code : import urllib2 response = urllib2.urlopen("http://192.168.1.100:81/%23pi.log") tuna = response.readlines()[-10:] for j in tuna: for e,n in j: if e,n == "*"," ": j = "This: " + str.strip(j) + " will be Pink" elif e,n == "<","%": j = "This: " + str.strip(j) + " will be yellow" elif e,n == "<","@": j = "This: " + str.strip(j) + " will be dark pink" print(str.strip(j)) Obviously the "for e,n" business doesnt work, but I think it makes for some decent pseudocode for what I'm trying to accomplish. Here is some sample tuna: ['[7:55pm] My teachings goes back to the last iceage.\r\n', '[7:55pm] <%Zack> ahh now it does\r\n', '[7:55pm] <%Zack> ok\r\n', '[7:55pm] Or it is down just for you.\r\n', '[7:55pm] <@FC3> which one? that -12000 ice age or the one before\r\n', '[7:55pm] the earliest..\r\n', '[7:56pm] so.. 12000 quite long..\r \n', '[7:56pm] <@FC3> the one created by the meteor then\r\n', '[7:57pm] did not know that.. this is just a new teory I am folding.\r\n', '[7:57pm] * P0ke test test test\r\n'] From cam.ac.uk at mh391.invalid Wed Apr 18 10:54:31 2007 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Wed, 18 Apr 2007 15:54:31 +0100 Subject: X root Operator help In-Reply-To: <1176906495.306287.194820@b75g2000hsg.googlegroups.com> References: <1176898887.530470.222830@p77g2000hsh.googlegroups.com> <1176906495.306287.194820@b75g2000hsg.googlegroups.com> Message-ID: [Michael Hoffman] >> In floating point arithmetic, the naive way of calculating both roots >> always using the formula (-b +/- sqrt(b**2 - 4*a*c))/2*a will give you >> inaccurate results sometimes. See >> . [lucidparadox] > Thanks. As of right now I'm just trying to familiarize myself with > the syntax of Python. Actually I should have thought of y**(1/x). math.sqrt(y) might be faster or even more accurate (depending on platform) than y**0.5. > I'm currently a freshman in college so the alternative formula hasn't > been introduced to me yet. It probably won't be unless you take a class in numerical analysis. Many a person has been burned by not thinking about these sorts of things until it is too late (myself included). -- Michael Hoffman From steve at holdenweb.com Fri Apr 13 13:20:01 2007 From: steve at holdenweb.com (Steve Holden) Date: Fri, 13 Apr 2007 13:20:01 -0400 Subject: Problem with algorithm In-Reply-To: <1176482771.267327.247940@e65g2000hsc.googlegroups.com> References: <1176434160.047703.214600@q75g2000hsh.googlegroups.com> <1176434937.258002.162220@p77g2000hsh.googlegroups.com> <1176448576.047996.12930@d57g2000hsg.googlegroups.com> <1176482771.267327.247940@e65g2000hsc.googlegroups.com> Message-ID: Paul McGuire wrote: > On Apr 13, 8:53 am, Steve Holden wrote: >> I'm pretty sure you could give a separate name to each atom ont he known >> universe with a scheme like this. Do you really need 20-byte strings? >> > > Steve, > > Based on the Wikipedia article's estimate of 10**79 atoms in the > observable universe (is that all?), we would need a string of about 57 > characters long to give each one a separate name. > >>> 10 ** 79 > 26 ** 20 True >>> Well, we can't be right all the time, I suppose. Perhaps I need to raise my certainty filters. > (And I'll bet you've typed on an old Royal or two in your time...) > Who are you calling a monkey? look-out-for-my-infinite-number-of-friends-ly y'rs - 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 bdesth.quelquechose at free.quelquepart.fr Fri Apr 13 17:10:24 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Fri, 13 Apr 2007 23:10:24 +0200 Subject: Python editor/IDE on Linux? In-Reply-To: <1176488840.672572.101830@y80g2000hsf.googlegroups.com> References: <1176488840.672572.101830@y80g2000hsf.googlegroups.com> Message-ID: <461fe88c$0$6420$426a74cc@news.free.fr> 7stud a ?crit : > Jack wrote: > >>I wonder what everybody uses for Python editor/IDE on Linux? >>I use PyScripter on Windows, which is very good. Not sure if >>there's something handy like that on Linux. I need to do some >>development work on Linux and the distro I am using is Xubuntu. > > > Everybody uses vim. > Except for real programmers... From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Sat Apr 14 08:12:12 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Sat, 14 Apr 2007 14:12:12 +0200 Subject: Python Feature Request: Add the "using" keyword which works like "with" in Visual Basic References: <1176547372.584539.89170@q75g2000hsh.googlegroups.com> Message-ID: <58buojF2e7nifU1@mid.individual.net> samjnaa at gmail.com wrote: > In Visual Basic there is the keyword "with" which allows an > object- name to be declared as governing the following statements. > For example: > > with quitCommandButton > .enabled = true > .default = true > end with > > This is syntactic sugar for: > > quitCommandButton.enabled=true > quitCommandButton.default=true Personally, I'd never use it. In more complex modules, when you are looking for, e. g., self.myVar and anotherObject.myVar, this "using" statement decreases readability and maintainability (in full text searching). IMHO. Regards, Bj?rn -- BOFH excuse #406: Bad cafeteria food landed all the sysadmins in the hospital. From irstas at gmail.com Mon Apr 2 15:20:26 2007 From: irstas at gmail.com (irstas at gmail.com) Date: 2 Apr 2007 12:20:26 -0700 Subject: Clean "Durty" strings In-Reply-To: References: <1175463083.135907.128480@y80g2000hsf.googlegroups.com> <57bt02F2c9fpuU2@mid.uni-berlin.de> <57cddlF2bsqdbU2@mid.uni-berlin.de> <1175530649.060784.147900@d57g2000hsg.googlegroups.com> Message-ID: <1175541626.024991.22110@y80g2000hsf.googlegroups.com> On Apr 2, 10:08 pm, Michael Hoffman wrote: > irs... at gmail.com wrote: > > But it could be that he just wants all HTML tags to disappear, like in > > his example. A code like this might be sufficient then: re.sub(r'<[^>] > > +>', '', s). > > Won't work for, say, this: > > <text> > -- > Michael Hoffman True, but is that legal? I think the alt attribute needs to use < and >. Although I know what you're going to reply. That BeautifulSoup probably parses it even if it's invalid HTML. And I'd say that I agree, using BeautifulSoup is a better solution than custom regexps. From rschroev_nospam_ml at fastmail.fm Fri Apr 20 17:51:14 2007 From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven) Date: Fri, 20 Apr 2007 21:51:14 GMT Subject: Do other Python GUI toolkits require this? (OT) In-Reply-To: References: <462697A6.6010007@codebykevin.com> <465B30B4-5BA0-459A-BE6F-1038874FA74B@jedimindworks.com> Message-ID: hg schreef: > Roel Schroeven wrote: > >> Hendrik van Rooyen schreef: >>> "Steve Holden" wrote: >>> >>> >>>> Perhaps in Belgium they prefer climbing mountains over walking up and >>>> down gentle hills? >>> Mountains ? Hills ? In Belgium ?? >>> >>> Its not called the battlefield of Europe for nothing... >> I'm not sure if this adds anything of interest (well actually I'm pretty >> sure it doesn't), but our king Albert I was a fanatic mountain climber, >> until he died from a fall in 1934. >> > You never know ... was it a 'steep curve' ? To stay in the general style of this thread, that largely depends on how you interpret that expression :-) I would say yes, but judge for yourself; this is the rock he was climbing when he fell: http://nl.wikipedia.org/wiki/Afbeelding:Roy-m%C3%A5tche.jpg It's completely true that Belgium is a pretty flat country, but there are some regions featuring a somewhat more pronounced differences in height. -- If I have been able to see further, it was only because I stood on the shoulders of giants. -- Isaac Newton Roel Schroeven From robert.rawlins at thinkbluemedia.co.uk Thu Apr 12 09:52:04 2007 From: robert.rawlins at thinkbluemedia.co.uk (Robert Rawlins - Think Blue) Date: Thu, 12 Apr 2007 14:52:04 +0100 Subject: Binary To File Message-ID: <007801c77d09$c1002ba0$430082e0$@rawlins@thinkbluemedia.co.uk> Hello Guys, Is there an easy way to take binary data and build it into a file? Generally this will be BLOB data drawn from a database, the data will be for jpg images, I want to take the blob data and build it into a physical .jpg file. Is there a simple function for doing this in python? Like binary2file() or something along those lines? Thanks, Rob -------------- next part -------------- An HTML attachment was scrubbed... URL: From jstroud at mbi.ucla.edu Mon Apr 9 01:20:45 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Sun, 08 Apr 2007 22:20:45 -0700 Subject: tuples are useless??? In-Reply-To: References: Message-ID: Steven D'Aprano wrote: > On Mon, 09 Apr 2007 02:26:37 +0000, James Stroud wrote: > >> Bart Willems wrote: >>> James Stroud wrote: >>>> ... It boils down to the fact that tuples are useless as a result >>>> unless you know you really need them--and you never really NEED them. >>> Could you clarify that for me? I use tuples *a lot* and I really *NEED* >>> them - I'm building a lot of multi-tier reports where detail-level data >>> is pulled out of a dictionary based on a composed key. It is impossible >>> to build those dictionaries *without* using tuples. >> >> "Impossible" is a strong word, as is "need" (especially when in all caps). >> >> py> import md5 >> py> class HashedList(list): >> ... def __hash__(self): >> ... h = md5.new() >> ... for item in self: >> ... h.update(str(hash(item))) >> ... return int(h.hexdigest(), 16) >> ... >> py> hl = HashedList('bob', 'carol', 'ted') >> py> {hl:3} >> {['bob', 'carol', 'ted']: 3} >> >> Impossible? I wouldn't even say that this was all that difficult. > > Possible, if by possible you mean "broken". > > >>>> D = {hl: 3} >>>> D > {['bob', 'carol', 'ted']: 3} >>>> hl[0] = 'Bob' >>>> D > {['Bob', 'carol', 'ted']: 3} >>>> D.keys()[0] is hl > True >>>> D[hl] > Traceback (most recent call last): > File "", line 1, in > KeyError: ['Bob', 'carol', 'ted'] > > def __setitem__(self, *args): raise TypeError, '%s doesn't support item assignment.' % self.__class__.__name__ Problem fixed. Next? By the way, this would be analagous to the tedious class Something(object): def __init__(self, value): self._value = value value = property(lambda: self._value) just to make sure users don't change the value of value so they don't "break" the instance. I don't think Bart is changing the items in his keys anyway--so the problem which was stated as impossible is still possible. The solution was not to code to your personal expectations but to show how tuples are never essential. Any number of solutions could fix the problem you have invented. James From aleax at mac.com Mon Apr 23 22:20:02 2007 From: aleax at mac.com (Alex Martelli) Date: Mon, 23 Apr 2007 19:20:02 -0700 Subject: Namespaces/introspection: collecting sql strings for validation References: <1921780.hifcbgjtIO@beaureve.gmx.net> <1hwzkoo.118nt2f1htv72tN%aleax@mac.com> Message-ID: <1hx1epp.80dkmd1wjozaaN%aleax@mac.com> Aahz wrote: > >But don't put such black magic in production. The completely different > >way is: just don't. > > Could you expand on that? After all, that's exactly what we do to > implement a super() that works with classic classes -- and it's certainly > production code. Personally, I'd much rather give up super (not a big loss) and classic classes (a substantial net gain:-) than have to maintain such "black magic" in a production environment. Explicit is better than implicit, &c. Alex From http Thu Apr 26 01:17:01 2007 From: http (Paul Rubin) Date: 25 Apr 2007 22:17:01 -0700 Subject: Preferred Random Library References: Message-ID: <7xzm4vu33m.fsf@ruckus.brouhaha.com> Bill Jackson writes: > Is there a preferred random library? Preferred for what? Maybe you want os.urandom(). From rupole at hotmail.com Wed Apr 25 02:41:14 2007 From: rupole at hotmail.com (Roger Upole) Date: Wed, 25 Apr 2007 02:41:14 -0400 Subject: how to serialize a COM object ? References: <1177445437.543694.49070@r3g2000prh.googlegroups.com> Message-ID: <1177483363_3641@sp12lax.superfeed.net> "Carsten Haese" wrote in message news:mailman.6918.1177446594.32031.python-list at python.org... > On Tue, 2007-04-24 at 13:10 -0700, vml wrote: >> I have a problem : >> >> I have a COM object. >> >> I would like to pass this com object from a server to a client through >> a socket. > > That is just as feasible as passing a cruise ship through a phone line. > > A COM object represents a connection to a service or executable that is > running on one computer. Transferring that connection to another > computer is impossible. > > -Carsten > Actually, CoMarshalInterface allows you to do exactly this. Roger ----== 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 skip at pobox.com Tue Apr 3 19:27:30 2007 From: skip at pobox.com (skip at pobox.com) Date: Tue, 3 Apr 2007 18:27:30 -0500 Subject: heap doesn't appear to work as described In-Reply-To: <1175641694.226975.258820@n76g2000hsh.googlegroups.com> References: <1175641694.226975.258820@n76g2000hsh.googlegroups.com> Message-ID: <17938.58082.317522.331513@montanaro.dyndns.org> >> My book says that in a heap, a value at position i will be smaller >> than the values at positions 2*i and 2*i + 1. Check the heapq docs for the constraints the Python heapq module maintains: http://docs.python.org/dev/lib/module-heapq.html They are different than what you stated above: Heaps are arrays for which heap[k] <= heap[2*k+1] and heap[k] <= heap[2*k+2] for all k, counting elements from zero. Skip From msj at infoserv.dk Wed Apr 4 04:10:40 2007 From: msj at infoserv.dk (msj at infoserv.dk) Date: 4 Apr 2007 01:10:40 -0700 Subject: Meetup in Amsterdam Message-ID: <1175674240.460846.20080@y66g2000hsf.googlegroups.com> I'm going to Amsterdam friday the 6. and would like to grab a beer with anyone interested in Python and possible Django development. My company is looking into building a CMS based on Django. Mail me at martinskou [at] gmail [dot] com. From steve at holdenweb.com Thu Apr 5 07:00:35 2007 From: steve at holdenweb.com (Steve Holden) Date: Thu, 05 Apr 2007 07:00:35 -0400 Subject: Why NOT only one class per file? In-Reply-To: <4614cd8a$0$11172$426a74cc@news.free.fr> References: <1175721799.714907.52770@o5g2000hsb.googlegroups.com> <4614cd8a$0$11172$426a74cc@news.free.fr> Message-ID: Christophe wrote: > Chris Lasher a ?crit : >> A friend of mine with a programming background in Java and Perl places >> each class in its own separate file in . I informed him that keeping >> all related classes together in a single file is more in the Python >> idiom than one file per class. He asked why, and frankly, his valid >> question has me flummoxed. > > In Java, you HAVE to place a class in it's own file. That's how the > language works. But in Java, you do not have to place each class in it's > own module/package, in fact, it would be bad. > > It's the same in Python: you do not want to have one class per > module/package. > > Unfortunately, in Python, a module/package is a file, and in Java, it's > a directory. Also, Python doesn't really have the notion of a "root > package/module". > > Translation: "import foo; foo.foo()" sucks so avoid having only one > class per module :) One further thought: http://www.artima.com/weblogs/viewpost.jsp?thread=42242 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 rNOSPAMon at flownet.com Sun Apr 22 16:58:21 2007 From: rNOSPAMon at flownet.com (Ron Garret) Date: Sun, 22 Apr 2007 13:58:21 -0700 Subject: Bug in select (was: Re: Select weirdness) References: Message-ID: In article , Ron Garret wrote: > The answer is obvious: select is looking only at the underlying socket, > and not at the rfile buffers. Here is conclusive proof that there's a bug in select: from socket import * from select import select s=socket(AF_INET, SOCK_STREAM) s.bind(('',8080)) s.listen(5) f = s.accept()[0].makefile() # Now telnet to port 8080 and enter two lines of random text f.readline() select([f],[],[],1) f.readline() Here's the sample input: [ron at mickey:~/devel/sockets]$ telnet localhost 8081 Trying ::1... telnet: connect to address ::1: Connection refused Trying 127.0.0.1... Connected to localhost. Escape character is '^]'. 123 321 And this is the result: >>> f.readline() '123\r\n' >>> select([f],[],[],1) # After one second... ([], [], []) >>> f.readline() '321\r\n' >>> So this is clearly a bug, but surely I'm not the first person to have encountered this? Is there a known workaround? rg From wswilson at gmail.com Mon Apr 2 12:50:46 2007 From: wswilson at gmail.com (wswilson) Date: 2 Apr 2007 09:50:46 -0700 Subject: can a method access/set another's variables? In-Reply-To: <1hvwvwk.jled8buiciriN%aleax@mac.com> References: <1175477764.549115.159410@n59g2000hsh.googlegroups.com> <1hvwvwk.jled8buiciriN%aleax@mac.com> Message-ID: <1175532646.167581.29430@l77g2000hsb.googlegroups.com> On Apr 2, 1:04 am, a... at mac.com (Alex Martelli) wrote: > asdf1234234 wrote: > > My code is: > > -a.py- > > import b > > > class A: > > def __init__(self): > > pass > > Incidentally, these last two lines are totally, utterly useless. Do NOT > define special methods like this -- just omit the whole def statement > and you'll have identical semantics, no wasted boilerplate, even better > performance. > > Alex I know they're useless. I was using the init method before and just replaced what I had with pass instead of deleting it because I expected to use it again later. Thanks for the tip, though. From bruno.42.desthuilliers at wtf.websiteburo.oops.com Tue Apr 10 11:24:10 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Tue, 10 Apr 2007 17:24:10 +0200 Subject: Problem with getting an option value In-Reply-To: References: Message-ID: <461babc3$0$2326$426a34cc@news.free.fr> Lucas Malor a ?crit : > Peter Otten wrote: >> Lucas Malor wrote: >>> The problem is options is an instance, so options."delete", for >>> example, is wrong; I should pass options.delete . How can I do? >> Use getattr(): > > Thank you. Do you know also if I can do a similar operation with > functions? I want to select with a string a certain get() function of > ConfigParser: > > if type == "int" : funcname = "getint" elif type == "bool" : > funcname = "getboolean" etc. You should use a dict to do the dispatch: funcs = {'int':getint, 'bool', getboolean, ...} Then you just have to: result = funcs[type](args...) > How can I invoke the funcion with its name in a string? If you used the full import, ie: import ConfigParser you can use getattr() on the ConfigParser module object (yes, modules are objects). If you directly imported the functions in your own module/script namespace, using either from ConfigParser import some_func or import ConfigParser.some_func as some_func then there's the globals() function that returns a dict of all names=>objects defined in the namespace, so you can use: globals()['some_func'](args) HTH From __peter__ at web.de Sun Apr 1 02:58:51 2007 From: __peter__ at web.de (Peter Otten) Date: Sun, 01 Apr 2007 08:58:51 +0200 Subject: re.findall() hangs in python References: <1175397176.567214.194810@n59g2000hsh.googlegroups.com> Message-ID: silverburgh.meryl at gmail.com wrote: > 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("(.*) re.S) > > print "before find all" > > match = re.findall(pattern, data) > > if (match): > print "match2" > > > > Can you please tell me why it that? Could it be that it is just slow? If not, post a small example of data that provokes findall() to hang. Peter From mzafrullah at usa.net Wed Apr 18 03:39:36 2007 From: mzafrullah at usa.net (Muhammad) Date: 18 Apr 2007 00:39:36 -0700 Subject: ??? POLICE AND CITY/UNIVERSITY OFFICIALS INCOMPETENCE LEADS TO 33 KILLED BY KOREAN-ALQAEDA TERRORIST ??? In-Reply-To: <1176833939.948693.128300@o5g2000hsb.googlegroups.com> References: <1176818165.135834.214220@y80g2000hsf.googlegroups.com> <1176820374.597357.315110@b75g2000hsg.googlegroups.com> <1176833939.948693.128300@o5g2000hsb.googlegroups.com> Message-ID: <1176881976.549438.31190@d57g2000hsg.googlegroups.com> On Apr 17, 12:18 pm, utabintarbo wrote: > On Apr 17, 10:32 am, Muhammad wrote: > > > On Apr 17, 7:56 am, therm... at india.com wrote: > >> - > > You mentioned "Korean Al-Qaeda Terrorist" in the title! Honesty > > demands that you establish it as a fact that the person was connected > > to Al-Qaeda and that he was a terrorist and not some mentally sick > > fellow. > > Muhammad > > Just do it in a more appropriate forum, mmmkay? Sorry about that. But I only post when I feel it necessary. And I thought that if I let this person be, it might get to: But Al-Qaeda is a Muslim terrorist organization, let us go get Muslims. Precisely like Wafa Sultan and Co. who want to eradicate "Radical Islam" for a start, but end up saying "There is no moderate Muslim". In other words, "Get all the Muslims". Not that it frightens me, I have seen much worse, but it is a bother. Muhammad From bbxx789_05ss at yahoo.com Sat Apr 7 17:21:58 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: 7 Apr 2007 14:21:58 -0700 Subject: Objects, lists and assigning values In-Reply-To: References: <1175848886.065401.269260@w1g2000hsg.googlegroups.com> Message-ID: <1175980918.428954.315490@y80g2000hsf.googlegroups.com> On Apr 7, 2:52 pm, Manuel Graune wrote: > "7stud" writes: > > > What book are you reading? > > I worked my way through most of the online-docs. A bit to casual > obviously. > See the online tutorial's section on default function arguments here: http://docs.python.org/tut/node6.html#SECTION006710000000000000000 specifically the "Important Warning". From joshua at eeinternet.com Tue Apr 10 14:48:42 2007 From: joshua at eeinternet.com (Joshua J. Kugler) Date: Tue, 10 Apr 2007 10:48:42 -0800 Subject: installing pyqt4 on ubuntu 6.06 References: <80628d680704100833y197473d2wb421bdec5cd79aae@mail.gmail.com> Message-ID: <461bcf9c$0$21364$88260bb3@free.teranews.com> On Tuesday 10 April 2007 07:35, Pradnyesh Sawant wrote: > Any pointers regarding what packages should i install to get the > system into working condition would be very helpful It's next to impossible, due to conflicts with SIP, and other dependencies. See these two threads (both started by me) for more information: http://ubuntuforums.org/showthread.php?t=243936 http://ubuntuforums.org/showthread.php?t=244612 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 gagsl-py2 at yahoo.com.ar Thu Apr 12 03:42:30 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 12 Apr 2007 04:42:30 -0300 Subject: reaching hidden methods + casting References: <1176362298.986221.280520@n59g2000hsh.googlegroups.com> Message-ID: En Thu, 12 Apr 2007 04:18:19 -0300, per9000 escribi?: > Hi, > can I reach a hidden method when doing ugly inheritance in python? > >>>> class A: > ... def spin(self, n): print "A", n > ... >>>> class B: > ... def spin(self, m): print "B", m > ... >>>> class C(A,B): > ... def spin(self, k): print "C", k > ... >>>> myC = C() >>>> dir(myC) > ['__doc__', '__module__', 'spin'] > > In f.x. the C-family of languages I guess something like this would > call B.spin: > ((B)myC).spin("Lancelot"); // almost forgot the ';' Try this in Python: B.spin(myC, "Lancelot") You can't ask the instance for myC.spin because that would retrieve C.spin; you need B.spin instead. But if you get it this way, it's not associated to a specific instance, so you must pass myC explicitely (becoming 'self'). > Please correct me I am wrong (which I likely am) but as I understand > it this example calls the constructor of int instead of casting it, > right? >>>> leet = int('1337') >>>> leet > 1337 Yes. > So is there another way of digging into the past of a class? Or can/ > should I create constructors for the classes A, B and C that takes > objects of the other classes? No need for that. And usually, that's not what you want either: you're creating a *different* object that way, not calling a (shadowed) method on an existing object. > Or should I have thought about getting unique names before I > implemented the ugly inheritance graph? Perhaps... -- Gabriel Genellina From piyali.de.bis at gmail.com Wed Apr 18 09:08:27 2007 From: piyali.de.bis at gmail.com (piyali biswas) Date: Wed, 18 Apr 2007 18:38:27 +0530 Subject: please sort this out In-Reply-To: <75c5d9400704160139q145a8b0akd9f3b7337397734f@mail.gmail.com> References: <75c5d9400704160139q145a8b0akd9f3b7337397734f@mail.gmail.com> Message-ID: <75c5d9400704180608o9ce253t871a99ea06799ce@mail.gmail.com> hi all, I solved the problem with the help of python cookbook+matplotlib I was getting the main error as * raise RuntimeError("'%s' is not a writable dir; you must set environment variable HOME to be * * a writable dir "%h)* Matplotlib needs the environment variable HOME to point to a writable directory.Thats why i did os.environ[ 'HOME' ] = 'C:/temp' and the cgi-script worked. For further questions about cgi+matplotlib/networkx please see http://www.scipy.org/Cookbook. Its very useful Thanks, Piyali Biswas On 4/16/07, piyali biswas wrote: > > Hi, > I am using networkx and pylab for creating a graph using a python script > abc.py. > I have saved the networkx folder in "C:/Python24/Lib/site-packages". > When I run the script from command prompt, it creates the graph and saves > it to the place I want to but when I write a python-cgi script and run it as > > os.system('python abc.py') > it doesn't gives me any result. > > I have included the path of my system using > os.environ['PATH'] = ".........". > > I also appended the path of networkx directory using > sys.path.append('C:/Python24/Lib/site-packages') as it seems to me that it > is a path related problem and the cgi result page shows error > (1) networkx *undefined* > (2)* *drawing undefined > (3) nx_pylab *undefined* > (4) matplotlib *undefined* > *(5) > raise RuntimeError("'%s' is not a writable dir; you must set environment variable HOME to be > * > * a writable dir "%h)* > Can you please tell me how to enable cgi to run this program on runtime. I > have kept both the cgi script as well as python script in Apache/cgi-bin > folder. > > Thanks, > Piyali > -------------- next part -------------- An HTML attachment was scrubbed... URL: From kyosohma at gmail.com Thu Apr 19 11:18:44 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: 19 Apr 2007 08:18:44 -0700 Subject: tkinter canvas In-Reply-To: References: <1176931838.804999.186070@n59g2000hsh.googlegroups.com> Message-ID: <1176995924.938640.292650@b58g2000hsg.googlegroups.com> On Apr 19, 7:24 am, Gigs_ wrote: > kyoso... at gmail.com wrote: > > On Apr 18, 3:43 pm, Gigs_ wrote: > >> how to write text on canvas. i know that i need to use canvas.create_text, but > >> how to write text than when i create_text? > >> or how to access object ID in canvas and change some options? > > >> thanks in advance! > > > All you need to do is canvas.create_text(x, y, text='Hello World') > > where x and y are coordinates on the canvas. You can also add fg and/ > > or bg to set foreground and background colors, respectively. > > > Mike > > but is there any option to bind event? > when i create text i want to write in text box on canvas so i think that i need > to bind event I'm not sure what you mean. Do you want to type your text into a textbox and as you type, you want it displayed on the canvas itself as well? If that is the case, then yes, you'll need to bind an event. If you just want to type text in a textbox that is on a canvas, the textbox widget takes care of everything and binding an event is unnecessary. Here is some info on events: http://effbot.org/tkinterbook/tkinter-events-and-bindings.htm http://www.builderau.com.au/program/print.htm?TYPE=story&AT=339272995-339024614t-320000000c http://www.bembry.org/technology/python/notes/tkinter_3.php Hope that points you in the right direction. Mike From bdesth.quelquechose at free.quelquepart.fr Fri Apr 13 17:08:57 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Fri, 13 Apr 2007 23:08:57 +0200 Subject: Python editor/IDE on Linux? In-Reply-To: References: Message-ID: <461fe835$0$6420$426a74cc@news.free.fr> Jack a ?crit : > I wonder what everybody uses for Python editor/IDE on Linux? Strange as it might be, not everybody's using the same editor. > I use PyScripter on Windows, which is very good. Not sure if > there's something handy like that on Linux. Oh yes ? Why so ? The best code editor ever is of course emacs,, but you may want to give Eric3 a try. From mail at timgolden.me.uk Fri Apr 20 03:22:06 2007 From: mail at timgolden.me.uk (Tim Golden) Date: Fri, 20 Apr 2007 08:22:06 +0100 Subject: PY shutil on win xp home version In-Reply-To: <200704192004.22604.inq1ltd@verizon.net> References: <1176898887.530470.222830@p77g2000hsh.googlegroups.com> <200704181543.44889.inq1ltd@verizon.net> <46268782.60204@timgolden.me.uk> <200704192004.22604.inq1ltd@verizon.net> Message-ID: <46286A1E.5010700@timgolden.me.uk> jim-on-linux wrote: > On Wednesday 18 April 2007 17:02, Tim Golden > wrote: >> jim-on-linux wrote: >>> python help, >>> >>> A client is using win xp home. >>> >>> my program contains; >>> shutil.copyfile(n, 'prn') >>> >>> This runs fine on win xp pro but they are >>> getting the following traceback. >>> >>> File "LOP_PRT_10.pyc", line 170, in __init__ >>> File "LOP_PRT_10.pyc", line 188, in Fprint1 >>> File "shutil.pyc", line 47, in copyfile >>> IOError: [Errno 2] No such file or directory: >>> 'prn' >>> >>> Since this runs ok on win xp pro, does this >>> have something to do with the home version of >>> xp. >>> >>> I'm thinking of changeing 'prn' to 'lpt1' >>> and trying again but I don't want to use the >>> client as a testor. Or is there some other >>> explaination for the problem. >> Not that this is your question, but if you're >> trying to print under Windows have you looked >> at: >> >> >> http://tgolden.sc.sabren.com/python/win32_how_d >> o_i/print.html >> >> for alternatives? >> >> TJG > > Thanks for the response, > > I got the following to work on windows. > > win32api.ShellExecute ( > 0, 'print', > filename, None, ".", 0 > ) > > However it prints the name of the file at the top > and adds a page number on the bottom. Is there > some way of eliminating the filename and page > number. Unfortunately, this approach is quick-and-dirty and you're at the mercy of whatever the "print" verb does to "filename" on your box. (Although you can configure that if you try hard enough). I'm afraid if you want control, you'll have to go the PDF route or to automate Word / OpenOffice etc. TJG From bdesth.quelquechose at free.quelquepart.fr Wed Apr 11 15:21:32 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Wed, 11 Apr 2007 21:21:32 +0200 Subject: pop() clarification In-Reply-To: References: Message-ID: <461d2c1a$0$7652$426a74cc@news.free.fr> Scott a ?crit : > As said before I'm new to programming, and I need in depth explaination to > understand everything the way I want to know it, call it a personality quirk > ;p. > > With pop() you remove the last element of a list and return its value: > > Now I know list is a bad name, but for the sake of arguement lets assume its > not a built in sequence> > >>>>list = ['this', 'is', 'an', 'example'] >>>>list.pop() > > 'example' > >>>>list > > ['this', 'is', 'an'] > > I understand all that. What I don't understand is why all the documentation > I see says, "When removing a specific element from a list using pop() it > must be in this format: list.pop([i]). There are conventions (not specific to Python) about how to describe languages syntax (including functions signatures). One of these conventions is that things between square brackets are optional. So when you see arguments between square brackets in the *documentation* of a function, that means these arguments are optional. Here, that means that list.pop takes one optional argument which is the index of the element to pop. It defaults to the last element, but nothing prevents you from specifying any other correct index. > I guess simplistically all I'm asking is: Is this just a community agreed > upon rule for readability purposes? It's a (more or less) standard syntax for such things, that you'll find for almost any programming language. For a function taking 2 optionals arguments, you'd see: some_function([opt_arg1 [,opt_arg2]]) Which means that some_function accepts two optional arguments, and that you must pass the first if you also want to pass the second > or Is it a rule that's in place for a > reason I'll learn later on? Please keep in mind my intro sentence to this > post. I would like a very detailed explaination, or at least a link to a > very detailed expression. Languages have a grammar and syntax, and one needs to be able to describe it formally. The usual formalism is some variation of the BNF (Backus-Naur Form) notation. You'll find detailed explanations about BNF here: http://en.wikipedia.org/wiki/Backus-Naur_form And some informations about the variant used in Python's doc here: http://docs.python.org/ref/notation.html HTH From joshua at eeinternet.com Thu Apr 5 15:01:08 2007 From: joshua at eeinternet.com (Joshua J. Kugler) Date: Thu, 05 Apr 2007 11:01:08 -0800 Subject: SUMMON - Rapid prototyping of 2D visualizations References: <1175796722.021072.142110@b75g2000hsg.googlegroups.com> Message-ID: <46153b04$0$16315$88260bb3@free.teranews.com> On Thursday 05 April 2007 10:12, matt.rasmus at gmail.com wrote: > I have been using python for the last two years to create various > visualizations for my research in computational biology. Over the > years, I found that I often needed the same kinds of features for many > of my visualizations (OpenGL graphics with basic scrolling and > zooming). I have implemented these features in an extension module > for python called SUMMON which I have made freely available on my > website for anyone who is interested rasmus/summon/index.shtml>. It does sound interesting. Please add it to the cheese shop to facilitate easier discovery and wider exposure. 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 rokkamraja at gmail.com Thu Apr 26 17:36:46 2007 From: rokkamraja at gmail.com (Raja) Date: 26 Apr 2007 14:36:46 -0700 Subject: override settrace In-Reply-To: References: <1177477557.493519.124620@u32g2000prd.googlegroups.com> Message-ID: <1177623406.044874.167120@b40g2000prd.googlegroups.com> On Apr 25, 8:10 pm, Steve Holden wrote: > Raja wrote: > > Hi, > > I want to override the sys.settrace() call, create a way to trace > > the execution of a python program. Keep track of all objects created > > and destroyed. Keep track of the call pattern throughout the execution > > of the program and output a simplified "call graph" to standard out. > > Please help me in this regard. > > > Thank You, > > How many times do you intend to post this question before waiting > patiently for an answer? > > regards > Steve > -- > Steve Holden +1 571 484 6266 +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, I am sorry for the number of posts but there has been a problem while I submitted and the post didnt appear for almost an hour after my 1st post so I reposted it. From aleax at mac.com Tue Apr 17 21:48:30 2007 From: aleax at mac.com (Alex Martelli) Date: Tue, 17 Apr 2007 18:48:30 -0700 Subject: rewrite for achieving speedup References: <1176821334.217154.36350@y80g2000hsf.googlegroups.com> <4umdnWdZhZNVe7nbnZ2dnUVZ_gGdnZ2d@comcast.com> <1176859022.813949.304600@b75g2000hsg.googlegroups.com> Message-ID: <1hwq963.cfcdai1rjeq9lN%aleax@mac.com> Jun.Jin.act+group.python at gmail.com wrote: > why would binding to a function-local name speeds up performance? Like any other constant-hoisting, pulling the lookup out of the loop speeds things up because otherwise Python must repeat the lookup each time through the loop (Python doesn't _know_ that, for example, zip.zap is always the same bound method object -- without potentially deep analysis, it can't rule out that looking up zap on zip has side effects and the like, so when you tell it to look it up, it looks it up, no ifs, no buts). You can measure the effect with -mtimeit ...: brain:~ alex$ python -mtimeit -s'def f(L): > for x in xrange(1000): L.append' 'f([])' 1000 loops, best of 3: 215 usec per loop brain:~ alex$ python -mtimeit -s'def g(L): > ap = L.append > for x in xrange(1000): ap' 'g([])' 10000 loops, best of 3: 79.1 usec per loop note that in each function f and g I'm doing only the lookup, not the call to the method thus looked up. Of course, this depends on the fact that for a function to use a local variable takes very little time indeed (since the compiler identifies which variables are local, and transforms any use of their names into a rapid indexing of a "local variables array", at the time the def statement executes -- so by the time the function gets called, i.e., that its body executes, that execution takes advantage of this optimization automatically performed by the Python compiler). Alex From superflit at gmail.com Tue Apr 3 15:36:10 2007 From: superflit at gmail.com (flit) Date: 3 Apr 2007 12:36:10 -0700 Subject: way to extract only the message from pop3 Message-ID: <1175628970.874615.127020@y80g2000hsf.googlegroups.com> Hello All, Using poplib in python I can extract only the headers using the .top, there is a way to extract only the message text without the headers? like remove the fields below: " Return-Path: X-Original-To: Received: from [ by (Postfix) with ESMTP id B32382613C for Tue, 3 Apr 2007 09:54:28 -0300 (BRT) Date: Tue, 03 Apr 2007 09:52:15 -0300 From: <@> To: Subject: test Message-Id: MIME-Version: 1.0 Content-Type: text/plain; charset="US-ASCII" Content-Transfer-Encoding: 7bit X-Mailer: Becky! ver. 2.24.02 [en] X-UIDL: !Dn!!HKT!!/k Status: RO " and only get this: this is a text message.. .. Thanks From andy.rockford at gmail.com Sun Apr 29 21:24:49 2007 From: andy.rockford at gmail.com (Andy) Date: 29 Apr 2007 18:24:49 -0700 Subject: Counting In-Reply-To: References: <1177873864.502180.283390@u30g2000hsc.googlegroups.com> <1177877775.780666.222080@p77g2000hsh.googlegroups.com> Message-ID: <1177896289.961612.259690@y5g2000hsa.googlegroups.com> I pretty doubt about this - "c = line.count(k)" I might wanna recheck on that. ------------------------------------- I think it would be obvious how to write this: for i,line in enumerate(linelist): line = line.split() for k in line: if keyword.iskeyword(k): c = line.count(k) total += line.count(k) print "Line #%d has %d keywords." % (i+1, c) break print "Total keyords are: %d" % total From cam.ac.uk at mh391.invalid Mon Apr 23 12:31:33 2007 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Mon, 23 Apr 2007 17:31:33 +0100 Subject: Shebang or Hashbang for modules or not? In-Reply-To: References: <1176308951.932721.197630@y80g2000hsf.googlegroups.com> Message-ID: Steven W. Orr wrote: > On Saturday, Apr 21st 2007 at 19:18 +0100, quoth Michael Hoffman: > > =>Chris Lasher wrote: > =>> Should a Python module not intended to be executed have shebang/ > =>> hashbang (e.g., "#!/usr/bin/env python") or not? I'm used to having a > =>> shebang in every .py file but I recently heard someone argue that > =>> shebangs were only appropriate for Python code intended to be > =>> executable (i.e., run from the command line). > => > =>Personally I include it in all of them, as part of boilerplate in a > =>template. > > I'd recommend againt it. The shebang doesn't do you any good unless it's > also in the presence of a file that has its executable bit set. It doesn't do any bad either, so I don't understand why you would recommend against it. And the bash function I use to create new files from the template also does chmod a+x. Not to mention that I have emacs set such that things with shebangs at the top are automatically chmod a+x, so in my programming environment, having a shebang on files I create and being executable are one and the same. > For example, let's leave python out for a second: I have a shell script. > And I also have lots of files which are not intended to be executed which > are also shell scripts, but which are sucked in by the shell "." or > "source" command (which is *somewhat* analogous to python's import). Lots > of these shell "library" scripts can't execute as standalone. The same > thing is possible with pything scripts. > > Of course, anything that has > if __name__ == "__main__": > in it should always have a shebang and be executable. That's in my template as well. :) I try to write all my modules so that they can easily be adapted to run as scripts, and all my scripts so that they can easily be adapted to use as modules. This has served me well many, many times. I see no reasons to create an artificial barrier to doing this by leaving the shebang out of files where it has no ill effect. -- Michael Hoffman From boyee118 at gmail.com Fri Apr 6 00:20:40 2007 From: boyee118 at gmail.com (boyeestudio) Date: Fri, 6 Apr 2007 12:20:40 +0800 Subject: About python Sybase module and the database manipulation! Message-ID: I write a python program which can insert one record into the Sybase databae at a time using the function "fetchone()",But I find it runs slowly. So I want speed it up,But I don't know how to manipulate the database more efficiently! Thread or any other methods can do it?? -------------- next part -------------- An HTML attachment was scrubbed... URL: From mad.vijay at gmail.com Thu Apr 12 03:14:32 2007 From: mad.vijay at gmail.com (SamG) Date: 12 Apr 2007 00:14:32 -0700 Subject: redirecting stdout to a file as well as screen Message-ID: <1176362072.527678.201150@l77g2000hsb.googlegroups.com> How could i make, from inside the program, to have the stdout and stderr to be printed both to a file as well the terminal(as usual). From vbr at email.cz Wed Apr 18 05:37:56 2007 From: vbr at email.cz (vbr at email.cz) Date: Wed, 18 Apr 2007 11:37:56 +0200 (CEST) Subject: =?us-ascii?Q?unicode=20data=20=2D=20accessing=20codepoints=20=3E=20FFFF=20on=20narrow=20python=20builts?= Message-ID: <1491.3232-2184-285262936-1176889076@email.cz> Hi all, I'd like to ask about the usage of unicode data on a narrow python build. Unicode string literals \N{name} work even without the (explicit) import of unicodedata and it correctly handles also the "wider" unicodes planes - over FFFF >>> u"\N{LATIN SMALL LETTER E}" u'e' >>> u"\N{GOTHIC LETTER AHSA}" u'\U00010330' The unicode data functions works analogous in the basic plane, but behave differently otherwise: >>> unicodedata.lookup("LATIN SMALL LETTER E") u'e' >>> unicodedata.lookup("GOTHIC LETTER AHSA") u'\u0330' (0001 gets trimmed) Is it a bug in unicodedata, or is this the expected behaviour on a narrow build? Another problem I have is to access the "characters" and their properties by the respective codepoints: under FFFF it is possible, to use unichr(), which isn't valid for higher valules on a narrow build It is possible to derive the codepoint from the surrogate pair, which would be usable also for wider codepoints. Currently, I'm using a kind of parallel database for some unicode ranges above FFFF, but I don't think, this is the most effective way. I actually found something similar at http: / / inamidst.com/phenny/modules/codepoint.py using directly the UnicodeData.txt; but I was wondering, If there is a simpler way for doing that; it seems obvious, that the data are present, if it could be used for constucting unicode literals. Any hints are welcome, thanks. vbr From carsten at uniqsys.com Sat Apr 7 10:27:20 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Sat, 07 Apr 2007 10:27:20 -0400 Subject: tuples, index method, Python's design In-Reply-To: <1175953520.316208.241490@o5g2000hsb.googlegroups.com> References: <1175867771.114540.61810@n76g2000hsh.googlegroups.com> <1175884427.779950.267220@y80g2000hsf.googlegroups.com> <1175953520.316208.241490@o5g2000hsb.googlegroups.com> Message-ID: <1175956040.3241.25.camel@localhost.localdomain> On Sat, 2007-04-07 at 06:45 -0700, bearophileHUGS at lycos.com wrote: > Carsten Haese: > > The lack of convincing use cases is still a pertinent reason today. Note > > that the original poster on this thread did not present a use case for > > tuple.index, they were only asking out of curiosity. > > If you have a use case for tuple.index, please show it to me, and I'll > > show you what you should be using instead of a tuple. > > Maybe we can add such methods to the PyPy tuples for some time, to > experimentally see if they make the language worse :-) Adding useless features always makes a product worse. What's your use case for tuple.index? -Carsten From gregtech at wp.pl Wed Apr 18 14:08:24 2007 From: gregtech at wp.pl (Grzegorz =?iso-8859-2?Q?=A6lusarek?=) Date: Wed, 18 Apr 2007 20:08:24 +0200 Subject: converting currency using locals Message-ID: <1a6pqx9mwzy6n$.1up65mccv8fm.dlg@40tude.net> Hi all. I have situation that I have value that holds price and I must show this price using national specification(e.g. thousands_sep). Any idea how this can be done under python 2.4.4? I saw that function format from module locals can format value with national specification, but this could be done only in python 2.5. Any solution for 2.4? example what I want achieve: value 24500.50 Hungarian Price 24 500.50 Romaniam Price 24.500.50 Thanks for any help Gregor From eddie at holyrood.ed.ac.uk Fri Apr 20 11:30:05 2007 From: eddie at holyrood.ed.ac.uk (Eddie Corns) Date: Fri, 20 Apr 2007 15:30:05 +0000 (UTC) Subject: Calculating CIDR blocks References: <1177032744.375099.248380@q75g2000hsh.googlegroups.com> <1177074967.900881.256280@n76g2000hsh.googlegroups.com> Message-ID: =?iso-8859-1?q?Pekka_J=E4rvinen?= writes: >On 20 huhti, 14:34, e... at holyrood.ed.ac.uk (Eddie Corns) wrote: >> Look at:http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/466298 >> it handles most of the logic of combining IP ranges. >> >> Eddie >I'm getting error: >Traceback (most recent call last): > File "ipr.py", line 5, in > x = ipv4.IP4Range(ips) > File "IP4Range.py", line 119, in __init__ > raise TypeError("Invalid argument.") >TypeError: Invalid argument. I haven't used this module for some time but if I recall your requirements properly you need something like: >>> R=IP4.IP4Range() >>> for i in ips: ... R=R|IP4.IP4Range(i) ... >>> for m in R.itermasks(): ... print m ... 192.168.0.0/26 192.168.0.64/27 192.168.0.96/29 192.168.0.104/30 192.168.0.108/31 192.168.0.110/32 192.168.0.128/25 192.168.0.112/28 >>> There may be an easier way my memory is hazy. Eddie From kyosohma at gmail.com Fri Apr 13 15:26:34 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: 13 Apr 2007 12:26:34 -0700 Subject: vocab question In-Reply-To: Message-ID: <1176492394.788553.224810@b75g2000hsg.googlegroups.com> On Apr 13, 2:06 pm, Alan G Isaac wrote: > Pardon the vocab question; > I'm not a computer science type. > According to the Reference Manual, > a class defintion has the structure:: > > classdef ::= "class" classname [inheritance] ":" suite > > What is the entire part before the suite called? > (Just pointing to a reference is fine & helpful, > as long as its not an entire course on BNF.) > > Thanks, > Alan Isaac I don't know if this will help or not, but here goes. Here is a generic class example: class MyNewObject(bases): 'doc string' #class_suite "class" is a keyword of python. MyNewObject is the "class name" of the class you (the programmer) created. And "bases" are what the class inherits from. This is technically known as the new class model. The old one didn't require you to inherit from a parent class, such as "object". Most of my classes still do not sub-class from a parent class yet (except for my wxPython GUI code) as this isn't enforced yet. Mike From steve at holdenweb.com Thu Apr 19 13:10:03 2007 From: steve at holdenweb.com (Steve Holden) Date: Thu, 19 Apr 2007 13:10:03 -0400 Subject: comparison with None In-Reply-To: <462792BE.906@gmail.com> References: <_JAVh.1700$jR5.897@trnddc08> <462709FB.9020607@gmail.com> <462792BE.906@gmail.com> Message-ID: Steven Howe wrote: > Steven D'Aprano wrote: >> On Thu, 19 Apr 2007 08:18:30 -0400, Steve Holden wrote: >> >> >>>> Which is why I suggested using the explicit type(x) == types.NoneType as >>>> opposed to >>>> x is None >>>> >>>> >>>> >>> This seems to go entirely against the spirit of the language. It's about >>> as sensible as writing >>> >>> (3 > 4) == True >>> >> >> >> Please! For extra certainty, you should write that as: >> >> ((int(3) > int(4)) == True) == True >> >> Explicit is better than sensible, yes? >> >> *wink* >> >> >> >> > Your example, even with the *wink*, is stupid. The language requires 3 > to be an integer, 4 to be an integer. > It also requires the reader to have a sense of humor. Where did you misplace yours? Come on, it was clearly meant to be a light-hearted poke, don't take life so seriously. > > The point I was show is with respect to a returned variable (like from a > function or method? *wink* *wink*). > For example, if you expect an open file handle, but get a NoneType > because you didn't really open a file (having given a bad name or maybe > didn't have permission to open a file), then it would be best to test > the type of return object before using it. Then you program could handle > the error gracefully (*wink* *wink* *wink*). > Here you are actually arguing for the "is" test without realizing it. Since "is" actually checks for object identity ("do my two operands occupy the same memory?") it has no need to check the types of its operands. If there's any possibility that you might have a NoneType (of which, as I appear to have to keep reminding you, there is precisely ONE instance, so why not just say "None", since it's the ONLY NoneType object in the known universe) the correct paradigm is to guard the code with if f: ... I am aware that this opens the gates to the hordes who will now pile in pointing out that this will technique will fail if f is zero (integer, real or complex) or one of the many other items that evaluates to false in a Boolean context. I merely point out that none of those things are a file, and that to allow f to be *either* a file *or* one of those other things is inviting trouble in a very big way. However, if the hordes *insist* (as the hordes tend to, especially when partial to salty snails), the very *most* you need is if f is None: ... and anything else is overkill that harms the readability of your program. It's that poor readability that Steven D'Aprano was making fun of in his remarks above, which in truth only echoes what I felt like but refrained from writing when I pointed out the redundancy in the expression (3 > 4) == True. > As much as I love Python, it's ability to morph an object type can be a > pain. Testing before using can prevent a program from Error-ing out. > You still don't convince me that there is there is *any* value in checking the type of an object to determine whether the object is None. If its type is types.NoneType it *must* be None. If it isn't None then no harm can be done by an identity comparison with None, since the type of the operands is irrelevant to "is". regards Steve PS: Revision question: How many objects of type NoneType are there? -- 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 duncan.booth at invalid.invalid Mon Apr 16 06:01:30 2007 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 16 Apr 2007 10:01:30 GMT Subject: string methods of a str subclass References: Message-ID: "Daniel Nogradi" wrote: > Why is the strip( ) method returning something that is not a mystr > instance? I would expect all methods operating on a string instance > and returning another string instance to correctly operate on a mystr > instance and return a mystr instance. Why would you expect that? Would you expect the __str__ and__repr__ methods also to return a mystr instance? If not those, then which other ones might also be excluded? Is x.encode('zip') still a mystr instance or an encoded byte-string? > How would I achieve something > like this without manually copying all string returning methods from > str and stuffing the result to mystr( ) before returning? You don't without wrapping all the affected methods. It doesn't need to involve manual copying though: you have a programming language available so just write a list of method names and then some code to wrap them automatically. From steve at holdenweb.com Tue Apr 3 10:07:44 2007 From: steve at holdenweb.com (Steve Holden) Date: Tue, 03 Apr 2007 10:07:44 -0400 Subject: Finding and copying files with python. In-Reply-To: <1175608048.094777.183660@l77g2000hsb.googlegroups.com> References: <1175606497.896681.119490@l77g2000hsb.googlegroups.com> <1175607107.690245.145130@l77g2000hsb.googlegroups.com> <1175608048.094777.183660@l77g2000hsb.googlegroups.com> Message-ID: gtb wrote: > On Apr 3, 8:31 am, kyoso... at gmail.com wrote: >> On Apr 3, 8:21 am, "gtb" wrote: >> >> >> >> >> >> >> >>> I wish to copy the highest version number of a file from directory \ >>> \ >>> \fileserver\D:\scripts to C:\scripts where the file names are of the >>> form >>> filename_MM.NN.SS.zip, where MM, NN, and SS can be one to three >>> digits. >>> Example directory: >>> other.zip >>> dx_ver_1.1.63.zip >>> dx_ver_1.2.01.zip >>> dx_ver_1.12.7.zip >>> temp.txt >>> Does python have string matching routines that would find the bottom >>> listed zip file and/or file copying routines? >>> A little pointer or two would be much appreciated. >>> Thanks, >>> jh >> You could just use string slicing to cut off the first 7 characters >> and have the numbers available to compare. There's also the os.stat >> module to find the last modified date of the file. You might be able >> to use the glob module to grab a list of the files and then sort the >> list too. >> >> Mike > > Thanks for posting folks. I didn't make my question clear. Before I > sort the files I need to ensure that I am only sorting the files that > match the profile of "filename_MM.NN.SS.zip", where MM, NN, and SS can > be one to three > digits. > > Thanks again, > > jh > OK, well look at the glob module to get a list of the filenames. You are going to have to be careful doing the sort, however, because a simple string comparison won't work for numbers of differing lengths. One way would be to define a function that extracts the numeric components from a filename and produces a three-element tuple or list. Then pass this function to sort() as the "key" argument. 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 manuel.graune at koeln.de Thu Apr 5 13:13:43 2007 From: manuel.graune at koeln.de (Manuel Graune) Date: Thu, 05 Apr 2007 19:13:43 +0200 Subject: Objects, lists and assigning values Message-ID: Hello, while trying to learn how to program using objects in python (up to now simple scripts were sufficient for my needs) I stumbled over the a problem while assigning values to an object. The following piece of code shows what I intend to do: <---snip---> class new_class(object): def __init__( self, internal_list=[]): self.internal_list= internal_list external_list=[[b*a for b in xrange(1,5)] for a in xrange(1,5)] print external_list first_collection=[new_class() for i in xrange(4)] temporary_list=[[] for i in xrange(4)] for i in xrange(4): for j in xrange(4): temporary_list[i].append(external_list[i][j]) first_collection[i].internal_list=temporary_list[i] #Now everything is as I want it to be: for i in xrange(4): print first_collection[i].internal_list #Now I tried to get the same result without the temporary #variable: second_collection=[new_class() for i in xrange(4)] for i in xrange(4): for j in xrange(4): second_collection[i].internal_list.append(external_list[i][j]) #Which obviously leads to a very different result: for i in xrange(4): print second_collection[i].internal_list <---snip---> Can someone explain to me, what's happening here and why the two approaches do not lead to the same results? Thanks in Advance. Regards, Manuel -- A hundred men did the rational thing. The sum of those rational choices was called panic. Neal Stephenson -- System of the world http://www.graune.org/GnuPG_pubkey.asc Key fingerprint = 1E44 9CBD DEE4 9E07 5E0A 5828 5476 7E92 2DB4 3C99 From electronixtar at gmail.com Wed Apr 11 07:14:17 2007 From: electronixtar at gmail.com (est) Date: 11 Apr 2007 04:14:17 -0700 Subject: py script modify it's Modified Time? Message-ID: <1176290057.625687.15150@y80g2000hsf.googlegroups.com> I guess os.stat() could retrieve information about ctime, mtime of a path, but how can I change them? Is it possible to make it work both under Win32 and Linux? P.S. How to get the current running python? (Like WScript.ScriptFullName in vbscript) From kyosohma at gmail.com Tue Apr 3 10:04:30 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: 3 Apr 2007 07:04:30 -0700 Subject: Finding and copying files with python. In-Reply-To: <1175608048.094777.183660@l77g2000hsb.googlegroups.com> References: <1175606497.896681.119490@l77g2000hsb.googlegroups.com> <1175607107.690245.145130@l77g2000hsb.googlegroups.com> <1175608048.094777.183660@l77g2000hsb.googlegroups.com> Message-ID: <1175609070.038315.92510@p77g2000hsh.googlegroups.com> On Apr 3, 8:47 am, "gtb" wrote: > On Apr 3, 8:31 am, kyoso... at gmail.com wrote: > > > > > On Apr 3, 8:21 am, "gtb" wrote: > > > > I wish to copy the highest version number of a file from directory \ > > > \ > > > \fileserver\D:\scripts to C:\scripts where the file names are of the > > > form > > > > filename_MM.NN.SS.zip, where MM, NN, and SS can be one to three > > > digits. > > > > Example directory: > > > other.zip > > > dx_ver_1.1.63.zip > > > dx_ver_1.2.01.zip > > > dx_ver_1.12.7.zip > > > temp.txt > > > > Does python have string matching routines that would find the bottom > > > listed zip file and/or file copying routines? > > > > A little pointer or two would be much appreciated. > > > > Thanks, > > > > jh > > > You could just use string slicing to cut off the first 7 characters > > and have the numbers available to compare. There's also the os.stat > > module to find the last modified date of the file. You might be able > > to use the glob module to grab a list of the files and then sort the > > list too. > > > Mike > > Thanks for posting folks. I didn't make my question clear. Before I > sort the files I need to ensure that I am only sorting the files that > match the profile of "filename_MM.NN.SS.zip", where MM, NN, and SS can > be one to three > digits. > > Thanks again, > > jh Then you probably need to use the glob module and the re module. You may even be able to just use the glob module by doing something like: filenames = glob.glob(r'pathtofiles\*.*.*.*.zip') and then sort that. Mike From mensanator at aol.com Mon Apr 16 21:42:55 2007 From: mensanator at aol.com (mensanator at aol.com) Date: 16 Apr 2007 18:42:55 -0700 Subject: combination function in python In-Reply-To: References: <1176615838.830315.160210@b75g2000hsg.googlegroups.com> <1176629911.409257.149780@l77g2000hsb.googlegroups.com> <1176669548.436118.176300@e65g2000hsc.googlegroups.com> <1176683797.421863.16980@o5g2000hsb.googlegroups.com> Message-ID: <1176774175.555519.257030@y80g2000hsf.googlegroups.com> On Apr 16, 6:40 pm, Anton Vredegoor wrote: > mensana... at aol.com wrote: > > Isn't that what docstrings are for? Can't you leave > > the function name noverk() and add something to the > > effect of "this function calculates combinations"? > > Then it would show up in searches, wouldn't it? > > Yes, a doc string would help finding it in searches, however since this > thread now contains a collection of function names it will suffice. > > There is also the other consideration of being able to easily read code > that others write. Functions that try to do the same thing having the > same name would help. Why not simply the same doc string? You can't expect everyone to use the same function name. > If we had some module in the standard distro that > would contain comb and fac and maybe a few other functions people could > start using the same name to point to the same thing etc. You COULD add those to the standard distro. You COULD read the newsgroups and get various Pythonic solutions. But you don't HAVE to if you're looking just for a solution. > > >>>> def noverk(n,k): > >>>> ? ? ?return reduce(lambda a,b: a*(n-b)/(b+1),xrange(k),1) > >> This is a rather concise function which has the added advantage that it > >> returns 0 when k>n. > > > import gmpy > > print gmpy.comb(4,8) > > > ## 0 > > There is more to it than that. If I see the way the function computes > the values it gives me hints about how I could write a function that > lists all combinations. But you said returning 0 was an advantage, as if that's not typical. I was merely pointing out that it is NOT an advantage over gmpy. Giving you hints about further application is a different advantage than what you listed. > > For example the fact that one can divide the product 'on the fly' -I > mean without computing the totals above and below the division bar- > tells me something about how to tackle the problem of generating the > corresponding combinatorial structure. I *love* combinatorial > structures. Little functions like this have more than once helped me to > understand them better. Fine, and gmpy doesn't give you the actual combinations, so I wrote my own. But if there's a faster, better 3rd party library that can do the same things mine does (permutations with replacement, combinations with replacement, permutations without replacement and combinations without replacement) then I'll drop mine like a live grenade. I wrote this because I needed to use it in a bigger application, the details were not important, just the output. It's the bigger applications details I'm concerned about. > > Math is not so much my way of describing things, I like executable > pseudo code better. Sometimes I had to read math formulas and have > become somewhat used to that notation -it has its uses too- but if > things are written down in code I can rely on the *computer* to execute > the code instead of my brain which unfortunately is not as reliable. > > These advantages are lost when one just imports some optimized code library. And once I looked up the Extended Euclidean Algorithm, made a Python implementaion of it and after I got it all working, I found it was all unnecessary because there was a gmpy function already present (which I had previously ignored because it didn't understand what it meant) that did exactly what I want. Yes, I'm glad I went through the trouble of learning the algorithm, but I simply threw away my version. You talk about losing the advantage of learning how to do this, but is there any difference between your code and gmpy as far as the OP is concerned? Is he going to actually learn anything from your program or is he just going to use it? Is it going to matter to the OP whether he uses a 3rd party module or some code (that he doesn't understand) that he found on Usenet? > > > Perhaps you should use the name > > > comb_works_just_like_the_gmpy_version_only_slower() > > Or maybe 'comb_in_executable_pseudocode', but maybe some other > implementations posted in this thread would be better suited for that. > > Anyway, I have the impression you just don't get the point of people > posting various functions so that one can determine which algorithms > work best or so that one can include each others ideas and create better > functions that combine the best elements of all posted code. Cutting and > pasting Python functions works a lot better in Usenet than importing C > libraries. "Works better" for learning the algorithms, doesn't "work better" performance wise. > > If no one posts code -even if it's not completely working code- how are > we to learn from each other? By focusing on things that aren't available in 3rd party modules. > The fact that someone else somewhere > already saw the light and wrote the perfect function in optimized C or > Fortran code should not stop us from 'reinventing the wheel' -as you > call it- because one can get more proficient in wheel making in the > process and every now and then it even leads to better wheels. But there's no reason why anyone should use your re-invented wheel in place of the old wheel. > > Don't even get me started about this archaic scheme of writing code only > for 'work' instead of for gaining insight that you seem to promote. I didn't mean 'work' in any kind of business sense (all my Python code is strictly amateur mathematics). I meant when you have a task to solve, learning how the tools are made is not important, it's USING the tools. Sure, it's possible to have gained some insight into using the tools by knowing how they're made, but as I said with the EEA, you can keep the insight and throw the program away if there's a better alternative in a 3rd party module. > > > But when there *is* no documentation, that becomes a problem, > > doesn't it? > > This thread is also documentation and I hope it will encourage people to > post more code and share thoughts. > > > Unless you don't know how to write the functions you need > > in which case you're better off relying on external > > modules. Have you ever wondered why Python even *has* > > a standard library? Why doesn't everyone just write > > the functionality they need? > > The main virtue of Pythons standard library should be that it shows one > how to do things and that it introduces a common naming scheme. That was > what got me interested in python in the first place: Now I got to see > how things work! No more dark secrets and proprietary code! I think you would get an argument that that's its MAIN virtue. > > Sometimes it's better to sacrifice clarity for speed and write optimized > lower level code but that doesn't mean there aren't large trade offs > involved. And sometimes it's not. Sometimes high-level clarity is better than low-level clarity. I have no concern about HOW the modular inverse function works, what I care about is how to use it to solve a linear congruence. > > In the future if computers will become faster it would be wise to drop > the optimized code libraries again and reintroduce the Python versions > of the same because by then the Python versions would be fast enough and > it would also result in a smaller code base (but a more functional and > flexible and readable one). You're wrong here. Python and the computers it runs on will NEVER be fast enough, even if Python was compiled and executing native code. When things get faster, the problems get bigger. All the improvement does is push back the threshhold of intractability, it can never make it go away. > > What are you doing on this planet anyway if it's not trying to > understand things? I'm trying to understand what *I* want to understand and ignore what I don't NEED to understand. > > >> Since I'm also interested in the > >> functions themselves -in this case- I'd rather have a > >> few lines of code in my source than importing an > >> optimized code library. > > > Well, some people prefer optimized libraries because > > they have real work to do, not just acedemic excercizes. > > Real work is just an excuse for having a larger slice of the cake than > other people. Other people can be just as or even more essential in the > whole process of developing code than those who get paid. As I said earlier, nothing to do with getting paid. The problems I work on are bigger than algorithms for calculating combination counts, so my focus is on them and if I can employ a 3rd party module, then that's more effort I can devote to the problem. > > A reason against using third party libraries in general is not wanting > to include too many external dependencies that would force the user to > download all kinds of things from different places which could change > their urls or web interfaces. It would also introduce more points where > version conflicts or license conflicts could occur. Strange, you think posting code on Usenet to share with others is good, yet you disparage those who formalize that sharing as a module. > > > So it doesn't matter whether anyone can find noverk(), > > does it? > > It does matter a lot in the long run if people can compare their code to > the code other people write. If still other people profit from these > public exchanges and then adopt a condescending attitude towards the > grass roots processes -either because of misguided adoration for the > best programmers or because they think themselves to be the best or > maybe because of some archaic work related value system- that would > dampen the enthusiasm a bit. I think you're wrong here. I didn't say people shouldn't be posting these solutions, I said anyone who knows better won't be looking for them. Trust me, I was MUCH more enthusiastic about solving my linear congruence problem (which I had been toying with for about a year - calendar time) than I was over knowing how to do an Extended Euclidean Algorithm. > > >> You could take it up with the gmpy author and > >> induce him to get gmpy included in the standard distro if you are so > >> inclined. > > > Alex Martelli knows more about that subject than I and > > it would be pointless for me to bug him about it. > > Perhaps even your kind of misguided criticism would be better than such > a fatalistic attitude. Fatalistic? I knew there were reasons, I just didn't care to make any effort to remember them and saw no reason to look them up. > > A. From anton.vredegoor at gmail.com Fri Apr 20 12:23:17 2007 From: anton.vredegoor at gmail.com (Anton Vredegoor) Date: Fri, 20 Apr 2007 18:23:17 +0200 Subject: multirember&co In-Reply-To: References: <1176768854.720234.23320@w1g2000hsg.googlegroups.com> <1176790588.024371.119360@n76g2000hsh.googlegroups.com> <1176850352.999231.79260@n59g2000hsh.googlegroups.com> <1176921030.330467.76860@o5g2000hsb.googlegroups.com> <1176925857.535835.130010@b58g2000hsg.googlegroups.com> <1177010211.252779.83620@y5g2000hsa.googlegroups.com> <1177025176.943890.252910@b75g2000hsg.googlegroups.com> Message-ID: Anton Vredegoor wrote: > What's up here? Was it a fata morgana? Am I overlooking something? Even more crazy version: def xsplitter(seq, pred): Q = deque(),deque() it = iter(seq) def gen(p): for x in it: Q[pred(x) == p].append(x) while Q[p]: yield Q[p].popleft() while Q[p]: yield Q[p].popleft() return gen(1),gen(0) A. From jstroud at mbi.ucla.edu Sat Apr 7 06:43:09 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Sat, 07 Apr 2007 10:43:09 GMT Subject: Welch essential for learning Tkinter well? In-Reply-To: References: <46151818.6080302@codebykevin.com> Message-ID: <1BKRh.15054$Um6.13418@newssvr12.news.prodigy.net> Dick Moores wrote: > At 10:36 AM 4/6/2007, Russell E. Owen wrote: >> I find Welch's book and the on-line tcl/tk help very helpful for Tkinter >> programming--especially some of the more obscure details. But to use >> either of these resources comfortably you must learn the basics of >> Tkinter first (including understanding the simple mapping between >> Tkinter and Tcl/Tk). > > Where can I get this mapping spelled out? Grayson Appendix A. $25 pdf--well worth it in your time. James From apardon at forel.vub.ac.be Wed Apr 25 07:20:14 2007 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 25 Apr 2007 11:20:14 GMT Subject: Would You Write Python Articles or Screencasts for Money? References: <462DCCE6.9060908@taupro.com> <1hx2dvj.10ek1v51noh1otN%aleax@mac.com> Message-ID: On 2007-04-25, Anton Vredegoor wrote: > Antoon Pardon wrote: > >>>> That's a good point, and also a valid reason for restricting the >>>> voting community to PSF members. Thanks, Alex. >>> So in order to avoid a suspicion of a conflict of interest you want to >>> turn the whole thing into private property of the PSF? >>> >>> That is the most ridiculous suggestion I have ever >> >> I kind of understand why they would want to do this. If you have >> no limitations on who may vote, such a contest can easily turn >> into a contest of who can mobilize the biggest clan of supporters. > > Sure, any democratic process can be derailed by a coordinated effort of > people with a different mentality. To prevent such things by killing the > democratic process oneself right at the beginning of a project is a > peculiar way of avoiding this risk. As far as I understood the idea was to reward excellence. The process to achieve this can be democratic, but in that case it is just a means to an end. The democratic process was not an end itself. So talking about this as if the democratic process itself was somehow the goal seems to miss what it is about. -- Antoon Pardon From kevin.t.ryan at gmail.com Wed Apr 18 22:18:17 2007 From: kevin.t.ryan at gmail.com (Kevin T. Ryan) Date: 18 Apr 2007 19:18:17 -0700 Subject: indexing web pages - in python? In-Reply-To: References: Message-ID: <1176949096.985463.138770@n76g2000hsh.googlegroups.com> On Apr 18, 8:55 pm, Dan Stromberg wrote: > Are there any open source search engines written in python for indexing a > given collection of (internal only) html pages? Right now I'm talking > about dozens, but hopefully it'll be hundreds or thousands at some point. > > I'm thinking some sort of CGI script, with perhaps a cron job that updates > the indexes. > > I'm not particularly looking for something that has a full RDBMS behind > it - just a file that stores indexes. I'll go with an RDBMS-based > solution if I must, but I don't think that's really needed at this point. > > TIA You could try: http://gnosis.cx/download/indexer.py There is an extensive write-up by the author at: http://gnosis.cx/publish/programming/charming_python_15.txt Might be something you'd be interested in ... From nagle at animats.com Fri Apr 27 02:21:49 2007 From: nagle at animats.com (John Nagle) Date: Thu, 26 Apr 2007 23:21:49 -0700 Subject: Socket exceptions aren't in the standard exception hierarchy (M2Crypto issue) In-Reply-To: References: Message-ID: On a related note, M2Crypto's exceptions are direct children of Exception. If we add NetworkError, there will be a better place to put them. Currently, you have to catch, at least, M2Crypto.SSL.Checker.SSLVerificationError M2Crypto.SSL.SSLError both of which can be raised by socket operations if M2Crypto is installed. I'm not sure what errors the stock SSL module raises. (I'm running stress tests on a dedicated machine in a colocation facility. It's examining 11,000 known spam and malware sites right now. This exercises the error handling, forcing many unusual cases and logging the problems. That's why I'm discovering all these library issues.) John Nagle Steve Holden wrote: > John Nagle wrote: > >> Steve Holden wrote: >> >>> John Nagle wrote: >>> >>>> Steve Holden wrote: >>>> >>>>> John Nagle wrote: >>>>> [socket.error bug report] >> >> >>> All these notes should be included in the bug report, as I suspect >>> the module would benefit from additional clarity. >> >> >> Done. See >> >> [ 1706815 ] socket.error exceptions not subclass of StandardError >> >> Also see >> >> [ 805194 ] Inappropriate error received using socket timeout >> [ 1019808 ] wrong socket error returned >> [ 1571878 ] Improvements to socket module exceptions >> [ 708927 ] socket timeouts produce wrong errors in win32 >> >> for related but not identical problems in that area. >> > Thanks. At least this is less likely to be overlooked now. > > regards > Steve From thorsten at thorstenkampe.de Sun Apr 1 14:44:37 2007 From: thorsten at thorstenkampe.de (Thorsten Kampe) Date: Sun, 1 Apr 2007 19:44:37 +0100 Subject: I18n issue with optik References: Message-ID: * Steven Bethard (Sun, 01 Apr 2007 10:21:40 -0600) > Thorsten Kampe wrote: > > * Steven Bethard (Sat, 31 Mar 2007 20:08:45 -0600) > >> Thorsten Kampe wrote: > >>> I've written a script which uses Optik/Optparse to display the > >>> options (which works fine). The text for the help message is localised > >>> (with german umlauts) and when I execute the script with the localised > >>> environment variable set, I get this traceback[1]. The interesting > >>> thing is that the localised optparse messages from displays fine - > >>> it's only my localisation that errors. > >>> > >>> From my understanding, my script doesn't put out anything, it's > >>> optik/optparse who does that. My po file is directly copied from the > >>> optik po file (who displays fine) and modified so the po file should > >>> be fine, too. > >>> > >>> What can I do to troubleshoot whether the culprit is my script, optik > >>> or gettext? > >>> > >>> Would it make sense to post the script and the mo or po files? > >> Yes, probably. Though if you can reduce it to the simplest test case > >> that produces the error, it'll increase your chances of having someone > >> look at it. > > > > The most simple test.py is: > > > > ### > > #! /usr/bin/env python > > > > import gettext, \ > > os, \ > > sys > > > > gettext.textdomain('optparse') > > gettext.install('test') > > > > from optparse import OptionParser, \ > > OptionGroup > > > > cmdlineparser = OptionParser(description = _('THIS SOFTWARE COMES > > WITHOUT WARRANTY, LIABILITY OR SUPPORT!')) > > > > options, args = cmdlineparser.parse_args() > > ### > > > > When I run LANGUAGE=de ./test.py --help I get the error. > > > > ### This is the test.de.po file > > # Copyright (C) 2006 Thorsten Kampe > > # Thorsten Kampe , 2006 > > > > msgid "" > > msgstr "" > > > > "Project-Id-Version: Template 1.0\n" > > "POT-Creation-Date: Tue Sep 7 22:20:34 2004\n" > > "PO-Revision-Date: 2005-07-03 16:47+0200\n" > > "Last-Translator: Thorsten Kampe \n" > > "Language-Team: Thorsten Kampe \n" > > "MIME-Version: 1.0\n" > > "Content-Type: text/plain; charset=ISO-8859-15\n" > > "Content-Transfer-Encoding: 8-bit\n" > > "Generated-By: pygettext.py 1.5\n" > > > > msgid "THIS SOFTWARE COMES WITHOUT WARRANTY, LIABILITY OR SUPPORT!" > > msgstr "DIESES PROGRAMM HAT WEDER GEW?HRLEISTUNG, HAFTUNG NOCH > > UNTERST?TZUNG!" > > ### > > > > The localisation now produces an error in the localised optik files, > > too. > > > > Under Windows I get " File "G:\program files\python\lib\encodings > > \cp1252.py", line 12, in encode > > return codecs.charmap_encode(input,errors,encoding_table)" > > I'm not very experienced with internationalization, but if you change:: > > gettext.install('test') > > to:: > > gettext.install('test', unicode=True) > > what happens? No traceback anymore from optparse but the non-ascii umlauts are displayed as question marks ("?"). Thorsten From duncan.booth at invalid.invalid Wed Apr 25 10:11:11 2007 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 25 Apr 2007 14:11:11 GMT Subject: Tutorial creates confusion about slices References: Message-ID: Steve Holden wrote: >> Wording to that effect makes it more clear that it is a crutch >> that can be usefull now but that it should be discarded later. >> > Most people reading a tutorial are aware that they are being given the > knowledge they need to put the subject matter to immediate use, and that > there may well be refinements that are glossed over or covered in detail > later or elsewhere. The authors of 'The Science of Discworld' coined a term for this 'lies to children' where an explanation to a student is technically wrong but is pitched at the appropriate level for the student. See http://en.wikipedia.org/wiki/Lie-to-children From hayes.tyler at gmail.com Mon Apr 23 19:00:59 2007 From: hayes.tyler at gmail.com (Tyler) Date: 23 Apr 2007 16:00:59 -0700 Subject: vtkStructuredGrid usage question in MayaVi In-Reply-To: <1177369068.590404.3040@b58g2000hsg.googlegroups.com> References: <1177369068.590404.3040@b58g2000hsg.googlegroups.com> Message-ID: <1177369259.298041.143780@l77g2000hsb.googlegroups.com> Just found it!!!! Still not sure what the third entries are, but it's a start! # create a vtk data file sp = pyvtk.StructuredPoints ((nx, ny, 1), (xmin, ymin, 0), (dx, dy, 1)) pd = pyvtk.PointData(pyvtk.Scalars(z, name='Scalars', lookup_table="default")) Tyler From rdm at rcblue.com Sat Apr 7 05:15:49 2007 From: rdm at rcblue.com (Dick Moores) Date: Sat, 07 Apr 2007 02:15:49 -0700 Subject: Welch essential for learning Tkinter well? In-Reply-To: References: <46151818.6080302@codebykevin.com> Message-ID: <20070407091554.F17DF1E400F@bag.python.org> At 10:36 AM 4/6/2007, Russell E. Owen wrote: >In article <46151818.6080302 at codebykevin.com>, > Kevin Walzer wrote: > > > James Stroud wrote: > > >This begs the > > > question, is anyone truly an expert in Tkinter? > > > > Frederick Lundh is, if anyone is. > > > > http://www.pythonware.com/library/tkinter/introduction/index.htm (outdated) > > http://effbot.org/tkinterbook/ (new but incomplete) > >I agree that this is an excellent resource. > >I find Welch's book and the on-line tcl/tk help very helpful for Tkinter >programming--especially some of the more obscure details. But to use >either of these resources comfortably you must learn the basics of >Tkinter first (including understanding the simple mapping between >Tkinter and Tcl/Tk). Where can I get this mapping spelled out? >For learning the basics of Tkinter I suggest the links that Kevin listed >above and/or Alex Martelli's "Python in a Nutshell" (an excellent >reference in any case). Although owning the 2nd ed. of "Python is a Nutshell", I hadn't thought of looking into it for Tkinker. There's a whole chapter, "Tkinter GUIs" (46 pages!). > Grayson's book is another reasonable alternative >(and includes enough reference material to keep you from having to refer >to the tcl/tk documentation very often). One web tutorial that looks good to me is "Thinking in Tkinter", by Stephen Ferg (). My thanks to all who responded. Dick Moores From eugene.vandenbulke at gmail.com Thu Apr 26 19:32:00 2007 From: eugene.vandenbulke at gmail.com (EuGeNe Van den Bulke) Date: Fri, 27 Apr 2007 01:32:00 +0200 Subject: EuroPython vs PyconUK References: <4630D480.7050308@gmail.com> <1177617449.064076.250150@t38g2000prd.googlegroups.com> Message-ID: Fuzzyman wrote: > I assume you have the same problem with the Italian one? Not so much because the official language of Pycon Uno Italy is Italian so I don't feel too concerned (unfortunately my Italian is not quite good enough). > Seriously though, it is *great* to see the UK Python scene flourishing > (and the Italian one). The more events that happen the better, and I > don't think they need be in competition with each other... I *hope* > the Europython guys don't see it like that. I agree it is great to see the Python scene grow (everywhere). The AFPY is organizing "journees python francophones" early June too cf. http://journees.afpy.org/. I have only been to one conference before so I may be under the wrong impressions but I don't see how the three events won't be competing for Ri (as in Shu Ha Ri) speakers for example. Do I sound like a groupie? Alex Martelli, brilliant speaker and Python evangelist (in my Shu Ha eyes anyway), lives in the States and is Italian. Busy as you'd expect from someone working for Google, decides to make the trip to Europe for a Python related conference, henceforth spends 3 1/2 months in Europe so he can do Italy in June (he is listed as an organizer), Lithuania in July and UK in September... I don't know how the EuroPython guys see it. Cheers, EuGeNe -- http://www.3kwa.com From b83503104 at yahoo.com Tue Apr 3 17:53:55 2007 From: b83503104 at yahoo.com (bahoo) Date: 3 Apr 2007 14:53:55 -0700 Subject: how to remove multiple occurrences of a string within a list? In-Reply-To: <1175626905.957243.301870@w1g2000hsg.googlegroups.com> References: <1175624433.206953.214290@n59g2000hsh.googlegroups.com> <1175626905.957243.301870@w1g2000hsg.googlegroups.com> Message-ID: <1175637235.783612.45980@o5g2000hsb.googlegroups.com> On Apr 3, 3:01 pm, "7stud" wrote: > On Apr 3, 12:20 pm, "bahoo" wrote: > > > Hi, > > > I have a list like ['0024', 'haha', '0024'] > > and as output I want ['haha'] > > > If I > > myList.remove('0024') > > > then only the first instance of '0024' is removed. > > > It seems like regular expressions is the rescue, but I couldn't find > > the right tool. > > > Thanks! > > bahoo > > Here are a couple of ways: > > target = "0024" > l = ["0024", "haha", "0024"] > > ------------------------------------ > while(True): > try: > l.remove(target) > except ValueError: > break > > print l > ------------------------------------- > > for index, val in enumerate(l): > if val==target: > del l[index] > > print l This latter suggestion (with the for loop) seems to be buggy: if there are multiple items in the list "l" equal to "target", then only the first one will be removed! Thanks anyways. From steve at REMOVEME.cybersource.com.au Fri Apr 27 00:38:10 2007 From: steve at REMOVEME.cybersource.com.au (Steven D'Aprano) Date: Fri, 27 Apr 2007 14:38:10 +1000 Subject: My python annoyances so far References: <1177541453.471959.120830@c18g2000prb.googlegroups.com> <59bf34F2k27v5U1@mid.individual.net> <1177603623.774892.230390@t38g2000prd.googlegroups.com> <1hx6zi2.1oz684ndspxdgN%aleax@mac.com> Message-ID: On Thu, 26 Apr 2007 19:36:09 -0700, Alex Martelli wrote: > Steven D'Aprano wrote: > ... >> detail you shouldn't care about. Functions that cache the result of long >> time-consuming complications are _good_. > > Not necessarily -- Absolutely -- I didn't mean to imply that functions should _always_ cache their "complications" (I meant to write calculations, but obviously my fingers weren't paying attention to my brain). > > asserts the exactly opposite principle, "Don't save anything you can > recalculate"... of course, the best approach is generally a compromise, > but it's good to be aware of the potentially high costs of caching:-). Yes -- I wouldn't cache anything that was cheap enough to calculate. What cheap enough (in time or memory or other resources) means depends on the circumstances. Nor would I cache things that were likely to change often. -- Steven D'Aprano From fabiofz at gmail.com Tue Apr 17 08:40:02 2007 From: fabiofz at gmail.com (Fabio Zadrozny) Date: Tue, 17 Apr 2007 09:40:02 -0300 Subject: Pydev 1.3.2 Released Message-ID: Hi All, Pydev and Pydev Extensions 1.3.2 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: ----------------------------------------------------------------- * Fix: The vmargs in the interactive console are now only really passed to the jython process * Fix: Rename refactoring was not getting some references that mapped to imports initially (and not directly to classes or functions) * Fix: Mark Occurrences marks correctly the keyword parameters in referencing calls Release Highlights in Pydev: ---------------------------------------------- * Pydev Editor: If multiple editors are open for the same file, a parser is shared among them (which greatly improves the performance in this case) * Pydev Editor: Backspace is now indentation-aware (so, it'll try to dedent to legal levels) * Pydev Editor: sometimes the 'import' string was added when it shouldn't * Fix: Code-completion: case where a package shadows a .pyd is now controlled (this happened with mxDateTime.pyd) * Fix: Code-completion: recursion condition was wrongly detected * Fix: Code-completion: halting condition was found and removed * Fix: Project Config: if a closed project was referenced, no project was gathered for any operation (e.g.: code-completion) * Fix: The filter for showing only pydev projects is not active by default anymore 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 b83503104 at yahoo.com Tue Apr 24 23:59:14 2007 From: b83503104 at yahoo.com (bahoo) Date: 24 Apr 2007 20:59:14 -0700 Subject: subprocess.Popen fails, but os.system works Message-ID: <1177473554.399696.236450@n35g2000prd.googlegroups.com> Hi, I am using Windows + Python 2.5. This line of code fails (see error message at the end), last_line = subprocess.Popen(["D:/release/win.exe 0.5 1000 100 D:/ images/img.ppm out.ppm"], stdout=subprocess.PIPE).communicate()[0] but using "os.system" works: os.system('D:/release/win.exe 0.5 1000 100 D:/images/img.ppm out.ppm') ---------- C:/Python25/pythonw.exe -u "D:/run.pyw" Traceback (most recent call last): File "D:/run.pyw", line 59, in process_dir(mydir) File "D:/run.pyw", line 52, in process_dir segmentation (dir,f) File "D:/run.pyw", line 35, in segmentation last_line = subprocess.Popen(["D:/release/win.exe 0.5 1000 100 D:/ images/img.ppm out.ppm"], stdout=subprocess.PIPE).communicate()[0] File "C:\Python25\lib\subprocess.py", line 593, in __init__ errread, errwrite) File "C:\Python25\lib\subprocess.py", line 793, in _execute_child startupinfo) WindowsError: [Error 22] The filename, directory name, or volume label syntax is incorrect ----------- Can anyone tell me why? Thanks bahoo From hayes.tyler at gmail.com Thu Apr 19 21:57:51 2007 From: hayes.tyler at gmail.com (Tyler) Date: 19 Apr 2007 18:57:51 -0700 Subject: wxPython and how to return text entry to main program? In-Reply-To: <1177030290.529322.56210@p77g2000hsh.googlegroups.com> References: <1177011490.435609.155870@o5g2000hsb.googlegroups.com> <1177030290.529322.56210@p77g2000hsh.googlegroups.com> Message-ID: <1177034271.769930.325160@y80g2000hsf.googlegroups.com> Thanks everyone for your help! Cheers, t. From nagle at animats.com Tue Apr 10 22:22:35 2007 From: nagle at animats.com (John Nagle) Date: Wed, 11 Apr 2007 02:22:35 GMT Subject: How to get IP address of client from CGI module? Message-ID: The documentation for Python's CGI module doesn't seem to say how to get the IP address of the client. Don't see an obvious way to get that info from reading the source, either. Ideas? John Nagle From spamtrap at dot-app.org Sun Apr 1 17:33:59 2007 From: spamtrap at dot-app.org (Sherm Pendley) Date: Sun, 01 Apr 2007 17:33:59 -0400 Subject: ISO programming projects References: Message-ID: kj writes: > I'm looking for a collection of useful programming projects, at > the "hobbyist" level. > > My online search did turn up a few collections (isolated projects > are less useful to me at the moment), but these projects are either > more difficult than what I'm looking for (e.g. code a C compiler) > or not terribly useful to the average person (e.g. a function that > efficiently computes the n-th Fibonacci number). > > Any pointers would be much appreciated. Sourceforge.net and Savannah both have "help wanted" pages for open source projects: sherm-- -- Web Hosting by West Virginians, for West Virginians: http://wv-www.net Cocoa programming in Perl: http://camelbones.sourceforge.net From oshecho at gmail.com Mon Apr 9 13:34:36 2007 From: oshecho at gmail.com (Echo) Date: Mon, 9 Apr 2007 13:34:36 -0400 Subject: Having trouble with relative imports Message-ID: <910885da0704091034u5e874dfen10d4846dae2ffc08@mail.gmail.com> Here is my setup: rpg -objects --__init__.py --gameobject.py --material.py -__init__.py -run_tests.py -stats.py the contents of run_test.py is: import objects as o the contents of objects/__init__.py is: from material import * in objects/material.py I have: from .gameobject import GameObject from ..stats import stats When I try to run run_tests.py, I get this traceback: (1:30:59 PM) OshEcho: echo at MobileEcho ~/projects/rpg $ python run_tests.py Traceback (most recent call last): File "run_tests.py", line 4, in import objects as o File "/home/echo/projects/rpg/objects/__init__.py", line 3, in from material import * File "/home/echo/projects/rpg/objects/material.py", line 4, in from ..stats import stats ValueError: Attempted relative import beyond toplevel package Could someone point out to me what I am doing wrong? I'm running Python 2.5 on Gentoo -- -Echo From bronger at physik.rwth-aachen.de Tue Apr 10 06:49:04 2007 From: bronger at physik.rwth-aachen.de (Torsten Bronger) Date: Tue, 10 Apr 2007 12:49:04 +0200 Subject: Why is __getslice__ still implemented? References: <87irc4wpxp.fsf@wilson.homeunix.com> <6BJSh.7607$u03.5881@newssvr21.news.prodigy.net> Message-ID: <87ejmswllr.fsf@wilson.homeunix.com> Hall?chen! James Stroud writes: > [...] > > Which version of python are you using? 2.4 > chernev 20% /sw/bin/python > Python 2.5 (r25:51908, Oct 10 2006, 03:45:47) > [GCC 4.0.1 (Apple Computer, Inc. build 5363)] on darwin > Type "help", "copyright", "credits" or "license" for more information. > py> class Bob(object): This should be Bob(unicode). > ... def __getitem__(self, *args): > ... print args > ... > py> b = Bob() > py> b[4:21:2] > (slice(4, 21, 2),) > py> b[5:18:21,2:9:2,8,14:4] > ((slice(5, 18, 21), slice(2, 9, 2), 8, slice(14, 4, None)),) Tsch?, Torsten. -- Torsten Bronger, aquisgrana, europa vetus Jabber ID: bronger at jabber.org (See http://ime.webhop.org for ICQ, MSN, etc.) From livibetter at gmail.com Mon Apr 16 21:36:21 2007 From: livibetter at gmail.com (livibetter) Date: 16 Apr 2007 18:36:21 -0700 Subject: strange behaviour with keyword arguments and inheritance In-Reply-To: <1176771364.964642.209300@b75g2000hsg.googlegroups.com> References: <1176771364.964642.209300@b75g2000hsg.googlegroups.com> Message-ID: <1176773781.729037.139650@y5g2000hsa.googlegroups.com> On Apr 17, 8:56 am, "matthewperpick" wrote: > Check out this toy example that demonstrates some "strange" behaviour > with keyword arguments and inheritance. > > ================================= > > class Parent: > def __init__(self, ary = []): > self.ary = ary > This should work: class Parent: def __init__(self, ary = []): self.ary = list(ary) And FYI http://groups.google.com/group/comp.lang.python/browse_thread/thread/e203f9cd64125a78/8d89b250ceca1458#8d89b250ceca1458 From apardon at forel.vub.ac.be Fri Apr 20 04:00:44 2007 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 20 Apr 2007 08:00:44 GMT Subject: Do other Python GUI toolkits require this? References: <462697A6.6010007@codebykevin.com> <1177014799.004875.262060@y80g2000hsf.googlegroups.com> Message-ID: On 2007-04-19, sjdevnull at yahoo.com wrote: > On Apr 19, 6:54 am, Antoon Pardon wrote: >> I don't know how you come to the conclusion that it is a mathematical >> absurdity but consider this: If you find that common usage propagates >> something that is incorrect, should we just shrug it off or should we >> attemp a correction? > > a) In English, "learning curve" is not restricted to a mathematical > plot--Webster's also defines it as "the course of progress made in > learning something". In that context, adding the adjective steep > ("extremely or excessively high...STEEP implies such sharpness of > pitch that ascent or descent is very difficult") makes sense. How much sense does it really make? Suppose we would talk about an income curve. Would you not prefer a steep curve over a shalow one? What about a productivity curve? It is all about the progress made in something. So how much sense does it make that a steep curve in earnings and productivity is good but a steep curve in learning is bad? > Trying to apply a mathematical definition to an English-language > phrase is prone to incorrect outcomes. > > b) The purpose of language is to communicate. In English, if a phrase > now means something in common usage, then that is (one of) its current > definition(s)--this is possibly different from some other languages > where there is an attempt to have an "officially sanctioned" set of > definitions and spellings that may differ from common usage. If you > find that everyone else means something when they say a phrase, you'd > best learn what they mean if you want to be speaking the same language > (and hence be able to communicate with them). But the problem is that even if this would be only a way to communicate in englishi, a lot of people get the wrong idea about real curves from this idiom, as this thread shows. So even if you only want to communicate one specific idea that comes accross as intended, you also propagate a lot of nonsense with it. -- Antoon Pardon From aleax at mac.com Wed Apr 11 10:58:00 2007 From: aleax at mac.com (Alex Martelli) Date: Wed, 11 Apr 2007 07:58:00 -0700 Subject: run function in separate process References: <1176301427.183706.321920@n76g2000hsh.googlegroups.com> Message-ID: <1hweao8.1t99a5vdqygvbN%aleax@mac.com> wrote: ... > somebody points me to a web page/reference that says how to call a > function then reclaim the whole memory back in python. > > Meanwhile, the best that I could do is fork a process, compute the > results, and return them back to the parent process. This I That's my favorite way to ensure that all resources get reclaimed: let the operating system do the job. > implemented in the following function, which is kinda working for me > now, but I am sure it can be much improved. There should be a better > way to return the result that a temporary file, for example. I You can use a pipe. I.e. (untested code): def run_in_separate_process(f, *a, **k): import os, sys, cPickle pread, pwrite = os.pipe() pid = os.fork() if pid>0: os.close(pwrite) with os.fdopen(pread, 'rb') as f: return cPickle.load(f) else: os.close(pread) result = f(*a, **k) with os.fdopen(pwrite, 'wb') as f: cPickle.dump(f, -1) sys.exit() Using cPickle instead of pickle, and a negative protocol (on the files pedantically specified as binary:-), meaning the latest and greatest available pickling protocol, rather than the default 0, should improve performance. Alex From steveo at syslang.net Sat Apr 21 22:36:42 2007 From: steveo at syslang.net (Steven W. Orr) Date: Sat, 21 Apr 2007 22:36:42 -0400 (EDT) Subject: Can __init__ not return an object? Message-ID: When I go to create an object I want to be able to decide whether the object is valid or not in __init__, and if not, I want the constructor to return something other than an object, (like maybe None). I seem to be having problems. At the end of __init__ I say (something like) if self.something < minvalue: del self return None and it doesn't work. I first tried just the return None, then I got crafty and tried the del self. Is what I'm trying to do possible in the constructor or do I have to check after I return? Or would raising an exception in the constructor be appropriate? Am I even being clear? -- 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 hlubenow2 at gmx.net Sat Apr 7 11:33:38 2007 From: hlubenow2 at gmx.net (hlubenow) Date: Sat, 07 Apr 2007 17:33:38 +0200 Subject: Can't Get Email Interface Working References: Message-ID: Eric Price wrote: > Hi; > I'm writing a script that includes an email function. So I went to the > cookbook and dug up this, and tweaked it just a bit to make it easier to > get it to work, but it throws an error: > >>>>def createMail(sender, recipient, subject, html, text): > ... import MimeWriter, mimetools, cStringIO > ... out = cStringIO.StringIO() > ... # txtin = cStringIO.StringIO(msg) > ... writer = MimeWriter.MimeWriter(out) > ... writer.addheader("From", sender) > ... writer.addheader("To", recipient) > ... writer.addheader("Subject", subject) > ... writer.addheader("MIME-Version", "1.0") > ... writer.startmultipartbody("alternative") > ... writer.flushheaders() > ... subpart = writer.nextpart() > ... subpart.addheader("Content-Transfer-Encoding", "quoted-printable") > ... pout = subpart.startbody("text/plain", [("charset", 'us-ascii')]) > ... mimetools.encode(txtin, pout, 'quoted-printable') > ... txtin.close() > ... subpart = writer.nextpart() > ... subpart.addheader("Content-Transfer-Encoding", "quoted-printable") > ... pout = subpart.startbody("text/html", [("charset", 'us-ascii')]) > ... mimetools.encode(htmlin, pout, 'quoted-printable') > ... htmlin.close() > ... writer.lastpart() > ... msg = "test" > ... out.close() > ... return msg > ... >>>># --------------------------------------------------------------- > ... def sendMail(sender, recipient, subject, html, text): > ... import smtplib > ... message = createMail(sender, recipient, subject, html, text) > ... server = smtplib.SMTP("localhost") > ... server.sendmail(sender, recipient, message) > ... server.quit() > ... >>>>if __name__=="__main__": > ... sendMail("root at mail.example.com", "joe at yahoo.com", "Web Stie(s) > Down!!!", "", "text") > ... > Traceback (most recent call last): > File "", line 2, in ? > File "", line 4, in sendMail > File "", line 10, in createMail > File "/usr/local/lib/python2.4/MimeWriter.py", line 153, in > startmultipartbody > self._boundary = boundary or mimetools.choose_boundary() > File "/usr/local/lib/python2.4/mimetools.py", line 130, in > choose_boundary > hostid = socket.gethostbyname(socket.gethostname()) > socket.gaierror: (8, 'hostname nor servname provided, or not known') >>>> > > Now, I can send email from my server no problem. In fact, I have my script > working already...but with a shell script instead of this python code. :lol: > Please advise. > TIA, > Eric You may want to take a look at simplemail.py: http://gelb.bcom.at/trac/simplemail/browser/trunk/simplemail.py that does sending mails in Python comfortably. HTH H. From codecraig at gmail.com Tue Apr 3 13:33:58 2007 From: codecraig at gmail.com (abcd) Date: 3 Apr 2007 10:33:58 -0700 Subject: Retrieve an item from a dictionary using an arbitrary object as the key In-Reply-To: <1175617854.977507.236730@n59g2000hsh.googlegroups.com> References: <1175617563.169153.150430@d57g2000hsg.googlegroups.com> <1175617854.977507.236730@n59g2000hsh.googlegroups.com> Message-ID: <1175621638.588320.70790@b75g2000hsg.googlegroups.com> > You'll need __eq__ for testing if two objects are equivalent, and > __hash__ for calculating object's hash value. > > class Type: > def __init__(self, val): > self.val = val > > def __eq__(self, other): > return self.val == other.val > > def __hash__(self): > return hash(self.val) that's exactly what I needed, thanks. From cam.ac.uk at mh391.invalid Sat Apr 28 05:25:59 2007 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Sat, 28 Apr 2007 10:25:59 +0100 Subject: getting rid of EOL character ? In-Reply-To: <46327f48$1@news.eftel.com.au> References: <268cc$4631f634$83aef404$27224@news1.tudelft.nl> <46327f48$1@news.eftel.com.au> Message-ID: John Machin wrote: > On 27/04/2007 11:19 PM, Michael Hoffman wrote: >> stef wrote: >>> hello, >>> >>> In the previous language I used, >>> when reading a line by readline, the EOL character was removed. > > Very interesting; how did you distinguish between EOF and an empty line? > Did you need to call an isEOF() method before each read? > >>> >>> Now I'm reading a text-file with CR+LF at the end of each line, >>> Datafile = open(filename,'r') line = Datafile.readline() >>> >>> now this gives an extra empty line >>> print line >>> >>> and what I expect that should be correct, remove CR+LF, >>> gives me one character too much removed >>> print line[,-2] > > Stef, that would give you a syntax error. I presume that you meant to > type line[:-2] > >>> >>> while this gives what I need ??? >>> print line[,-1] >>> >>> Is it correct that the 2 characters CR+LF are converted to 1 character ? > > In text mode (the default), whatever is the line ending on your platform > is converted to a single "newline" '\n' which is the same as LF. > > Using line[:-1] is NOT recommended, as the last line in your file may > not be terminated, and in that case you would lose the last data character. > >>> Is there a more automatic way to remove the EOL from the string ? >> >> line = line.rstrip("\r\n") should take care of it. If you leave out >> the parameter, it will strip out all whitespace at the end of the >> line, which is what I do in most cases. > > If you want *exactly* what is in the line, use line.rstrip('\n') -- this > will remove only the trailing newline (if it exists). > > If you want to strip all trailing whitespace, use line.rstrip() as > Michael suggested. > > Michael, note carefully that line.rstrip('\r\n') removes instances of > '\r' OR '\n' -- the arg is a set of characters to be removed, not a > suffix to be removed. In Stef's situation, it "works" only by accident. > Using that would not always give you the correct answer -- e.g. if your > (Windows) file had a line ending in CR CR LF [I've seen stranger]. I knew that about line.rstrip, but didn't consider the possibility of \r\r\n, while still wanting the first \r. Yuck. Honestly, I almost always use line.rstrip()--it is seldom that I care about closing whitespace. -- Michael Hoffman From gagsl-py2 at yahoo.com.ar Sun Apr 15 01:38:27 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sun, 15 Apr 2007 02:38:27 -0300 Subject: Reading the first line of a file (in a zipfile) References: <1176318822.811661.115730@q75g2000hsh.googlegroups.com> <1176322548.710970.315610@d57g2000hsg.googlegroups.com> <1176465570.907000.86150@b75g2000hsg.googlegroups.com> Message-ID: En Fri, 13 Apr 2007 08:59:30 -0300, escribi?: > That works fine if I am using the interpreter, but I get 'cannot open > file' when i try to read from an archive.. > Does that make sense? Sorry, this is my 2nd python script. Try a small, failing example and post the code and the full error traceback - else it's hard to tell what's happening. -- Gabriel Genellina From paul at boddie.org.uk Fri Apr 6 09:56:11 2007 From: paul at boddie.org.uk (Paul Boddie) Date: 6 Apr 2007 06:56:11 -0700 Subject: tuples, index method, Python's design In-Reply-To: References: Message-ID: <1175867771.114540.61810@n76g2000hsh.googlegroups.com> C.L. wrote: > > That doesn't change the fact that this is unfriendly design. It's an ugly > inconsistent chunk of a Python's past in which built-in types didn't behave like > objects. It sticks out like a sore thumb, maybe just not very often. When this topic last appeared on my radar, I ended up writing a long message about it: http://groups.google.com/group/comp.lang.python/msg/30e89128bdeb59c0 [...] > *sighs* just what I expected: another idle troll defending something just for > the sake of defending it. On the other hand, thanks 7stud, for the truly helpful > response. The problem with 7stud's quote from GvR is that it's out of date: tuples do have methods now, as you've noticed, but just not the index method. Previously, I've missed that method, and it wouldn't be hard to add it to the tuple class (in CPython's own source code), but one has to wonder whether it's really necessary, or at least as necessary as for other classes. Certainly, there's a trade-off between essential functionality and having, say, 100 methods which are all useful to someone but which make interactive introspection a rather tedious and confusing business. Paul From gagsl-py2 at yahoo.com.ar Wed Apr 4 22:12:58 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 04 Apr 2007 23:12:58 -0300 Subject: pyc file [Newbie Question] References: Message-ID: En Tue, 03 Apr 2007 12:40:23 -0300, Jim Aikin escribi?: > The Tutorial is very good, but there are numerous topics that it slides > past > (as it would have to do, in order to avoid being ten times as long). I > haven't yet gotten deep enough into Python to even know where to look > for a > full explanation of what "import" does or what alternatives there might > be > to using it. There are many books about Python: http://wiki.python.org/moin/IntroductoryBooks "Dive into Python" may be a good choice if you have some programming experience in another languages. -- Gabriel Genellina From kay.schluehr at gmx.net Sun Apr 15 15:08:01 2007 From: kay.schluehr at gmx.net (Kay Schluehr) Date: 15 Apr 2007 12:08:01 -0700 Subject: is laziness a programer's virtue? In-Reply-To: <1176654319.273907.167280@q75g2000hsh.googlegroups.com> References: <1176654319.273907.167280@q75g2000hsh.googlegroups.com> Message-ID: <1176664081.454781.46060@n76g2000hsh.googlegroups.com> On Apr 15, 6:25 pm, "Xah Lee" wrote: > Laziness, Perl, and Larry Wall > > Xah Lee, 20021124 > > In the unix community there's quite a large confusion and wishful > thinking about the word laziness. In this post, i'd like to make some > clarifications. > > American Heritage Dictionary third edition defines laziness as: > ?Resistant to work or exertion; disposed to idleness.? > > When the sorcerer Larry Wall said ?The three chief virtues of a > programmer are: Laziness, Impatience and Hubris?, he used the word > ?laziness? to loosely imply ?natural disposition that results in being > economic?. As you can see now, ?Resistant to work or exertion? is > clearly not positive and not a virtue, but ?natural disposition that > results in economy? is a good thing if true. > > When Larry Wall said one of programer's virtue is laziness, he wants > the unix morons to conjure up in their brains the following > proposition as true: ?Resistant to work or exertion is a natural human > disposition and such disposition actually results behaviors being > economic?. This statement may be true, which means that human laziness > may be intuitively understood from evolution. However, this statement > is a proposition on all human beings, and is not some ?virtue? that > can be applied to a group of people such as programers. > > Demagogue Larry Wall is smart in creating a confusion combined with > wishful thinking. By making subtle statements like this, he semi- > intentionally confuses average programers to think that it is OK to be > not thorough, it is OK to be sloppy, it is OK to disparage computer > science. (like the incompetent unixers and perlers are) > > Can you see the evil and its harm in not understanding things clearly? > This laziness quote by Wall is a tremendous damage to the computing > industry. It is a source among others that spurs much bad fashion > trends and fuckups in the industry. It is more damaging than any > single hack or virus. It is social brain-washing at work, like the > diamond company De Beers' tremendously successful sales slogan: ?A > Diamond is Forever? or Apple's grammatically fantastic ?Think > Different?. > > The most fundamental explanation of why Larry Wall's sophistry are > damaging to society is simply this: What he said is not true and they > are widely spread and conceived as worthwhile. This is a form of mis- > information. This is a manifestation of Love without Knowledge as i > expounded before, with subtle but disastrous consequences (already). > > [DISCLAIMER: all mentions of real persons are opinion only.] > > ---- > This post is archived at:http://xahlee.org/UnixResource_dir/writ/perl_laziness.html > > Xah > x... at xahlee.org > ?http://xahlee.org/ I like Larry Wall, despite being not a Perl programmer, and when he secretly subverts the american, protestant working ethos I like him even better :) From philippe.dalet at ac-toulouse.fr Tue Apr 24 11:01:25 2007 From: philippe.dalet at ac-toulouse.fr (pdalet) Date: 24 Apr 2007 08:01:25 -0700 Subject: getting scancodes In-Reply-To: References: Message-ID: <1177426885.069491.76280@c18g2000prb.googlegroups.com> On 24 avr, 02:39, andma... at gmail.com wrote: > Anyone knows if its possible to get scan codes ??? > I tried with getch () but with no success, just keycodes. > May be using the something in the sys.stdin module ?? > > Pleasee, any help would be very appreciated. > > -- > Andr?s M. > --------------------------------------------- > .--. > |o_o | > |:_/ | > // \ \ > (| | ) > /'\_ _/`\ > \___)=(___/ > --------------------------------------------- On windows, you have this package http://newcenturycomputers.net/projects/wconio.html Ph DALET FRANCE From steve at REMOVEME.cybersource.com.au Tue Apr 3 05:44:00 2007 From: steve at REMOVEME.cybersource.com.au (Steven D'Aprano) Date: Tue, 03 Apr 2007 19:44:00 +1000 Subject: Question about text in Python References: <4610c366$0$15022$5a62ac22@per-qv1-newsreader-01.iinet.net.au> <57cbejF2cataiU1@mid.individual.net> <4611af55$0$15038$5a62ac22@per-qv1-newsreader-01.iinet.net.au> <87wt0ugplk.fsf@benfinney.id.au> Message-ID: On Tue, 03 Apr 2007 12:26:47 +1000, Ben Finney wrote: > "Steve" writes: > >> Yes it is [a homework question]. >> >> Where else to ask for help but here. > > That's between you, your teacher, and your teaching institute's > plagiarism guidelines. Plagiarism is a serious example of fraud, which is not only a crime but is unethical as well. You don't need to be a student or an academic to commit plagiarism. Anybody can commit plagiarism. If we applied the plagiarism guidelines that university students labour under to the rest of us, perhaps we'd be a little less quick to toss accusations of plagiarism around so easily. If it is plagiarism for a student to ask how to detect an empty line, then it is plagiarism for any of us to ask how to do anything. At the point that students are unable to ask for information because they're accused of plagiarism, well, that's "a total collapse of critical reasoning", to quote Professor Steven Dutch of the University of Wisconsin. Citation: http://www.uwgb.edu/dutchs/PSEUDOSC/PlagShame.HTM Accessed 2007-04-03. If the Original Poster _accidentally_ sees a newsgroup post that answers his question -- "Oh, so that's how you exit a loop in Python!" -- is that plagiarism? Or is it only plagiarism if he _asks_ for the information first? Does he have to spend the rest of his life as a Python coder giving credit to J. Random Hacker for using "his" technique of "using break to exit a while loop"? None of this is to excuse students who try to have their homework done for them, or well-meaning but foolish people who, in response to a simple question end up providing an entire working piece of code, essentially doing the student's homework for them. Plagiarism does exist, and it is fraud. But I'm sickened and saddened to see how plagiarism has been bastardised by academia, turning it from serious fraud to trivial re-use of phrases and ideas, and even _learning things from anyone someone other than your lecturer_. That's what it has come to. If you ask "how do I detect the user has entered an empty line in raw_input?", you're deemed to be committing fraud. WTF? There's a gulf the size of the Atlantic Ocean between _learning_ and _committing fraud_, and we're so frightened by the thought that somebody might fraudulently claim another person's ideas (which begs the question of whether people can own ideas) that we're prohibiting learning except through a couple of narrowly approved channels. If you think I'm exaggerating, I challenge you to read Professor Dutch's pages on plagiarism: http://www.uwgb.edu/dutchs/PSEUDOSC/PlagShame.HTM http://www.uwgb.edu/dutchs/PSEUDOSC/PlagiarNonsense.HTM I challenge you to try to work as a coder, whether professional or amateur, under the same restrictions that we've been placing on students. I can't count the number of times people write to comp.lang.python asking "How do I transmogrify the frombulator?" And let's not even mention copying code snippets posted on Usenet. These things are not fraud. They are learning. This is not a call to turn a blind eye for plagiarism, or to do students homework for them. It's a plea for common-sense. We're not bound by university guidelines, or universities' over-broad definition of plagiarism, and we don't have to live by them. We are ethically bound not to do student's homework for them -- but that doesn't mean we're bound to refuse to answer their reasonable questions, or to treat those who are looking for help as frauds _just because they are a student_. -- Steven D'Aprano From spradml at gmail.com Tue Apr 10 11:35:37 2007 From: spradml at gmail.com (Pradnyesh Sawant) Date: Tue, 10 Apr 2007 21:05:37 +0530 Subject: installing pyqt4 on ubuntu 6.06 In-Reply-To: <80628d680704100833y197473d2wb421bdec5cd79aae@mail.gmail.com> References: <80628d680704100833y197473d2wb421bdec5cd79aae@mail.gmail.com> Message-ID: <80628d680704100835y302a575bqe4dd126879f67ec3@mail.gmail.com> Hello, I have a newly installed ubuntu 6.06 system. I am trying to install pyqt4 on it, but without success. The contents of the /etc/apt/sources.list file are: ******************************************************************************** deb http://in.archive.ubuntu.com/ubuntu/ dapper main restricted universe deb http://in.archive.ubuntu.com/ubuntu/ dapper-backports main restricted universe multiverse deb http://security.ubuntu.com/ubuntu dapper-security main universe deb http://in.archive.ubuntu.com/ubuntu/ dapper-updates main restricted ******************************************************************************** I've tried installing everything related to python2.4 and qt4, including sip, pyqt-tools, etc. However, on running a pyqt script, it gives me the following error: ******************************************************************************** Traceback (most recent call last): File "findFiles.py", line 16, in ? from PyQt4 import QtCore, QtGui ImportError: No module named PyQt4 ******************************************************************************** Any pointers regarding what packages should i install to get the system into working condition would be very helpful Thanks a lot -- warm regards, Pradnyesh Sawant -- Be yourself......everyone else is taken. --Anon From brendon at christian.net Sun Apr 1 08:29:28 2007 From: brendon at christian.net (Brendon Costa) Date: Sun, 01 Apr 2007 22:29:28 +1000 Subject: Converting _node* to a Code object? In-Reply-To: References: <460F36AF.5030607@christian.net> Message-ID: <460FA5A8.8030402@christian.net> Gabriel Genellina wrote: > En Sun, 01 Apr 2007 01:35:59 -0300, Brendon Costa > escribi?: > >> How do i convert a _node* object returned from: >> PyParser_SimpleParseStringFlagsFilename() >> >> into a code object i can use as a module to import with: >> PyImport_ExecCodeModule() > > Using PyNode_Compile. But why don't you use Py_CompileXXX instead? > And look into import.c, maybe there is something handy. > Thanks for the pointer. I am not using Py_CompileXXX because i could only find Py_CompileString... i could not find a file version of it (Which i thought should exist). My original email though i copied and pasted the wrong function into. Instead of: PyParser_SimpleParseStringFlagsFilename() i meant to use: PyParser_SimpleParseFileFlags() Basically i will open a FILE* for the file requested, parse it and load it into the module. Using this method i don't have to load its contents first into a string to be compiled, but just get the python library to parse directly from the file. It all seems to work fine now. Thanks for the help. Brendon. From gagsl-py2 at yahoo.com.ar Mon Apr 30 21:02:14 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 30 Apr 2007 22:02:14 -0300 Subject: [Q] module name available in 'from ... import ...' statement References: <1177975194.782804.155070@n76g2000hsh.googlegroups.com> Message-ID: En Mon, 30 Apr 2007 20:19:54 -0300, kwatch escribi?: > Could you teach me the condition of module name which is available > in 'from ... import ...' statement? > > The goal what I want to do is to create a module by 'new' module > and specify that module name in 'from ...' statement. You can create the module with imp.new_module, populate it, and then insert it inside sys.modules: py> from imp import * py> m = new_module("foo") py> m py> m.a = 1 py> def test(): ... print "Function test inside foo module" ... py> m.test = test py> import sys py> sys.modules["foo"]=m py> m py> foo Traceback (most recent call last): File "", line 1, in NameError: name 'foo' is not defined py> import foo py> foo.test() Function test inside foo module But, why do you want to do this exactly? -- Gabriel Genellina From howe.steven at gmail.com Fri Apr 27 11:21:11 2007 From: howe.steven at gmail.com (Steven Howe) Date: Fri, 27 Apr 2007 08:21:11 -0700 Subject: How can I save command prompt screen In-Reply-To: <8843bd8a0704270224t57b7f295wf09b0a3ae1866224@mail.gmail.com> References: <8843bd8a0704270224t57b7f295wf09b0a3ae1866224@mail.gmail.com> Message-ID: <463214E7.8090507@gmail.com> ozan SARI wrote: > Hi , > > I run a python acript with os.system('script.py') > > I want save command prompt screen in a text file (everything ) > how can I do this? > > Thanks for your help > > > Ozan check out using the subprocess module http://docs.python.org/lib/node529.html It seems to be the new replacement for os.system spawn, popen .... It has specific stdout, stderr and stdin handling. sph -------------- next part -------------- An HTML attachment was scrubbed... URL: From jstroud at mbi.ucla.edu Sun Apr 15 06:35:47 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Sun, 15 Apr 2007 03:35:47 -0700 Subject: Getting started with python In-Reply-To: <1176598011.463543.96990@q75g2000hsh.googlegroups.com> References: <1176598011.463543.96990@q75g2000hsh.googlegroups.com> Message-ID: <2enUh.4325$H_5.3894@newssvr23.news.prodigy.net> Eric wrote: > Hello, after reading some of the book Programming Python it seems that > python is something I would like to delve deeper into. The only thing > is, I have no idea what I should try and write. So I was hoping that > someone here could help point me to a group/project that would be a > good starting place for a person with limited python knowledge, but > that is willing to learn whatever is necessary. I'm hoping that with a > goal I can start to learn python instead of just playing around with > it. Thanks. > Here is a protocol I have used in the past: 1. Realize there is a program you really wish you had. 2. Find out that, upon relentless googling, no such program exists that meets your needs exactly. 3. If 2 fails and a program exists, go back to 1. 4. Proceed to write this program no matter what it takes--you may even face some "sitdowns" with your friends, family, and/or employers. 5. (Very important) A. Refer to this list periodically for help but making sure to properly phrase you questions. B. Try not to rewrite any libraries by first ascertaining whether a library doesn't already exist for the sub-task you are programming. 6. Enjoy the new program you have written and the new knowledge you have gained. James From duncan.booth at invalid.invalid Mon Apr 30 07:21:19 2007 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 30 Apr 2007 11:21:19 GMT Subject: Beginner Ping program References: <1177739647.737759.32610@u30g2000hsc.googlegroups.com> <1177782861.332626.169020@n76g2000hsh.googlegroups.com> Message-ID: "petercable at gmail.com" wrote: > There is no (that I am aware of) ICMP module in the standard library. > See http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/409689 for > an example of a Python implementation of ping. Google also finds another implementation at: http://www.gnist.org/~lars/code/ping/ping.py From antroy at gmail.com Sun Apr 1 16:58:12 2007 From: antroy at gmail.com (Ant) Date: 1 Apr 2007 13:58:12 -0700 Subject: Overlapping matches In-Reply-To: References: Message-ID: <1175461092.405542.73420@d57g2000hsg.googlegroups.com> On Apr 1, 9:38 pm, Rehceb Rotkiv wrote: > In the re documentation, it says that the matching functions return "non- > overlapping" matches only, but I also need overlapping ones. Does anyone > know how this can be done? Something like the following: import re s = "oooooooo" p = re.compile("oo") out = [] while pos < endpos: m = p.search(s, pos) if not m: break out.append(m) pos = m.start() + 1 From martin at v.loewis.de Sat Apr 7 05:29:54 2007 From: martin at v.loewis.de (=?ISO-8859-15?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sat, 07 Apr 2007 11:29:54 +0200 Subject: Custom Python Runtime In-Reply-To: <2NudnVn5jsm2QIvbnZ2dnUVZ_vqpnZ2d@comcast.com> References: <2NudnVn5jsm2QIvbnZ2dnUVZ_vqpnZ2d@comcast.com> Message-ID: <46176493$0$4042$9b622d9e@news.freenet.de> > Is there a way to customize the Windows build? In my case, there is no need > to build an installer. The best way is to have everything in a directory, as > long as I know where to find Python and Python knows where to find the > necessary libs. Any online docs describing this? Thanks! The interpreter will search for its libraries relative to the location of the .exe file. So if you place python.exe and pythonxy.dll into a directory, you need to add a Lib directory Inside Lib, the minimum file you need to have is os.py: Python will use it as a landmark. If you run 'python.exe -S', this is all you need. If you want site.py to work, you also need (tested for 2.4): - site, codecs, copy_reg, locale, ntpath, stat, types UserDict, encodings/__init__, encodings/aliases If you eliminate the aliasmbcs function from site.py, you can drop codecs, locale, encodings/*. If you eliminate the copy_reg references from os.py, you can also drop copy_reg. HTH, Martin From gregcorradini at gmail.com Wed Apr 11 12:53:51 2007 From: gregcorradini at gmail.com (Greg Corradini) Date: Wed, 11 Apr 2007 09:53:51 -0700 (PDT) Subject: Creating Unique Dictionary Variables from List Message-ID: <9943320.post@talk.nabble.com> Hello All, I'm attempting to create multiple dictionaries at once, each with unique variable names. The number of dictionaries i need to create depends on the length of a list, which was returned from a previous function. The pseudo code for this problem would be: returnedlist = [x,y,z] count = 0 for i in returnedlist: if count < len(returnedlist): # then create a dictionary (beginning with variable dic) and add a unique ending such that # my final dictionary name would be dic + count for each i Any ideas about this? Greg -- View this message in context: http://www.nabble.com/Creating-Unique-Dictionary-Variables-from-List-tf3560470.html#a9943320 Sent from the Python - python-list mailing list archive at Nabble.com. From google at mrabarnett.plus.com Thu Apr 26 18:30:20 2007 From: google at mrabarnett.plus.com (MRAB) Date: 26 Apr 2007 15:30:20 -0700 Subject: Feedback on Until recipe In-Reply-To: References: <1177430903.027128.86480@o40g2000prh.googlegroups.com> Message-ID: <1177626620.704830.223220@t39g2000prd.googlegroups.com> On Apr 26, 11:58 am, Antoon Pardon wrote: > On 2007-04-24, Thomas Nelson wrote: > > > Occasionally someone posts to this group complaining about the lack of > > "repeat ... until" in python. I too have occasionally wished for such > > a construct, and after some thinking, I came up with the class below. > > I'm hoping to get some feedback here, and if people besides me think > > they might use it someday, I can put it on the python cookbook. I'm > > pretty happy with it, the only ugly thing is you have to use a > > lambda. Ideally i'd like to just see > > while Until(i<3) > > but that doesn't work. > > Please tell me what you think, and thanks for your time. > > Maybe we should try to get the developers revive PEP 315. > > This PEP whould introduce a do-while statement that looks > like the folowing: > > do > statements > while condition > statements > > this would be equivallent to: > > while 1: > statements > if not condition: > break > statements > > Those wanting something like: > > repeat > statements > until condition > > Could then write something like: > > do > statements > while not condition > pass > > Still not the most elegant but a vast improvement IMO. > At http://mail.python.org/pipermail/python-dev/2006-February/060718.html Raymond Hettinger suggested removing the final colon after the 'while' if there's no statement after it, which I agree with, although I would prefer 'repeat' instead of 'do' (IMHO that doesn't suggest repetition clearly enough): repeat: statements while condition: statements and: repeat: statements while condition From goodTweetieBird at hotmail.com Thu Apr 26 16:52:34 2007 From: goodTweetieBird at hotmail.com (gtb) Date: 26 Apr 2007 13:52:34 -0700 Subject: Atribute error Message-ID: <1177620754.659481.66240@s33g2000prh.googlegroups.com> In file Test1.py below I get a attribute error on the line "self.logon()". It worked earlier when Test1 was derived from class newLogon but that does not seem logical to me. Any suggestions? Thanks, john #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #File Test1.py # Generated by MaxQ [com.bitmechanic.maxq.generator.CompactGenerator] #Test1.py from CompactTest import CompactTest from newLogon import newLogon class Test1(CompactTest): # Recorded test actions. def runTest(self): self.msg('Test started') self.logon() # ^^^ Insert new recordings here. (Do not remove this line.) # Code to load and run the test if __name__ == 'main': Test1('Test1').Run() #~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #File newLogon.py # Generated by MaxQ [com.bitmechanic.maxq.generator.CompactGenerator] from CompactTest import CompactTest class newLogon(CompactTest): # Recorded test actions. def logon(self): self.msg('Test started') # ^^^ Insert new recordings here. (Do not remove this line.) # Code to load and run the test if __name__ == 'main': newLogon('newLogon').Run() From sjmachin at lexicon.net Fri Apr 6 20:58:25 2007 From: sjmachin at lexicon.net (John Machin) Date: 6 Apr 2007 17:58:25 -0700 Subject: Cant access http://cheeseshop.python.org/ or wiki In-Reply-To: References: Message-ID: <1175907505.093655.259100@o5g2000hsb.googlegroups.com> On Apr 7, 10:43 am, cyb wrote: > For some reason I can ping these two sites fine, but when I try to go to > them I cannot get to them. Normal python.org homepage works just fine. > This is preventing me from getting setuptools and using pyOpenGL =( > > I'm using COmcast in savannah, GA FWIW: Same story for me with the cheeseshop; I'm in Australia. Possibilities: (a) it's become a a Norwegian blue cheeseshop (b) it's Lent; try fishshop.python.org From bbxx789_05ss at yahoo.com Thu Apr 12 15:08:38 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: 12 Apr 2007 12:08:38 -0700 Subject: wxPython, mac, wx.HSCROLL not working In-Reply-To: <1176392605.298630.8210@y5g2000hsa.googlegroups.com> References: <1176364597.741079.25840@n59g2000hsh.googlegroups.com> <586qvsF2fbq3rU1@mid.individual.net> <1176392605.298630.8210@y5g2000hsa.googlegroups.com> Message-ID: <1176404918.079527.148440@d57g2000hsg.googlegroups.com> On Apr 12, 9:43 am, kyoso... at gmail.com wrote: > On Apr 12, 8:37 am, Bjoern Schliessmann > > > mail-0306.20.chr0n... at spamgourmet.com> wrote: > > 7stud wrote: > > > I'm trying to allow for a horizontal scrollbar on a textarea, but > > > the scrollbar won't appear when I enter a long string of text(by > > > leaning on one character on my keyboard): > > > Works for me (Linux, self-built Python 2.5 and wxPython 2.8.3.0). > > > Regards, > > > Bj?rn > > > -- > > BOFH excuse #285: > > > Telecommunications is upgrading. > > This works for me too. I'm using Python 2.4, Windows XP Pro, wxPython > 2.6. > > You may want to post this to the wxpython users group list. It could > be a Mac-specific bug. > Where is that list? Are you talking about the google group list wxpython? It's inactive--there are only 5 posts in the last few years. From olsonas at gmail.com Thu Apr 26 11:32:40 2007 From: olsonas at gmail.com (Drew) Date: 26 Apr 2007 08:32:40 -0700 Subject: Simple csv read/write In-Reply-To: <462EA247.1030708@lexicon.net> References: <1177453628.474670.301330@t38g2000prd.googlegroups.com> <462EA247.1030708@lexicon.net> Message-ID: <1177601560.057927.132980@t39g2000prd.googlegroups.com> On Apr 24, 8:35 pm, John Machin wrote: > On 25/04/2007 8:27 AM, Drew wrote: > > > Ok, I'm trying to do the simplest read/write from one csv file to > > another. For some reason, every other row on the output file is a > > blank row. What am I doing wrong? > > > import csv > > > reader = csv.reader(open('current.csv')) > > writer = csv.writer(open('new.csv','w')) > > > for line in reader: > > writer.writerow(line) > > 1. Try reading the responses already posted to your previous questions. > > 2. Try reading the documentation; for each of csv.reader and csv.writer, > it says "If csvfile is a file object, it must be opened with the 'b' > flag on platforms where that makes a difference." My apologies to the rest of the list, issues with groups.google.com cause the multiple posts. From grflanagan at yahoo.co.uk Mon Apr 9 13:29:08 2007 From: grflanagan at yahoo.co.uk (Gerard Flanagan) Date: 9 Apr 2007 10:29:08 -0700 Subject: Breaking up Strings correctly: In-Reply-To: References: Message-ID: <1176139748.613321.8770@y80g2000hsf.googlegroups.com> On Apr 9, 1:19 pm, "Michael Yanowitz" wrote: > Hello: > > I have been searching for an easy solution, and hopefully one > has already been written, so I don't want to reinvent the wheel: > > Suppose I have a string of expressions such as: > "((($IP = "127.1.2.3") AND ($AX < 15)) OR (($IP = "127.1.2.4") AND ($AY != > 0))) > I would like to split up into something like: > [ "OR", > "(($IP = "127.1.2.3") AND ($AX < 15))", > "(($IP = "127.1.2.4") AND ($AY != 0))" ] > > which I may then decide to or not to further split into: > [ "OR", > ["AND", "($IP = "127.1.2.3")", "($AX < 15)"], > ["AND", "(($IP = "127.1.2.4")", ($AY != 0))"] ] > > Is there an easy way to do this? If you look into infix to prefix conversion algorithms it might help you. The following seems to work with the example you give, but not tested further: data = ''' ((($IP = "127.1.2.3") AND ($AX < 15)) OR (($IP = "127.1.2.4") AND ($AY != 0))) ''' import tokenize from cStringIO import StringIO opstack = [] valstack = [] s = '' g = tokenize.generate_tokens(StringIO(data).readline) # tokenize the string for _, tokval, _, _, _ in g: if tokval in ['(', ')', 'AND', 'OR']: if tokval != ')': opstack.append(tokval) else: if s: valstack.append(s) s = '' while opstack[-1] != '(': op = opstack.pop() rhs = valstack.pop() lhs = valstack.pop() valstack.append([op, lhs, rhs]) opstack.pop() else: s += tokval.strip() print valstack [['OR', ['AND', '$IP="127.1.2.3"', '$AX<15'], ['AND', '$IP="127.1.2.4"', '$AY!=0']]] Gerard From kelvin.you at gmail.com Tue Apr 10 23:08:23 2007 From: kelvin.you at gmail.com (=?utf-8?B?5Lq66KiA6JC95pel5piv5aSp5rav77yM5pyb5p6B5aSp5rav5LiN6KeB5a62?=) Date: 10 Apr 2007 20:08:23 -0700 Subject: Does python have the static function member like C++ Message-ID: <1176260903.362329.59370@o5g2000hsb.googlegroups.com> I define the class like this: class AAA: counter = 0 def __init__(self): pass def counter_increase(): AAA.counter += 1 print "couter now :", AAA.counter But how could I call the function "counter_incrrease" ? Thanks ! From Roka100 at gmail.com Fri Apr 13 03:16:16 2007 From: Roka100 at gmail.com (Jia Lu) Date: 13 Apr 2007 00:16:16 -0700 Subject: Problem with algorithm In-Reply-To: <1176434937.258002.162220@p77g2000hsh.googlegroups.com> References: <1176434160.047703.214600@q75g2000hsh.googlegroups.com> <1176434937.258002.162220@p77g2000hsh.googlegroups.com> Message-ID: <1176448576.047996.12930@d57g2000hsg.googlegroups.com> > for m in test: > for n in test: > for o in test: > for p in test: > print m+n+o+p Thanx for your anwser. But if I consider about a combination of over 26 letter's list just like: "abcdefssdzxcvzxcvzcv" "asllxcvxcbbedfgdfgdg" ..... Need I write 26 for loops to do this? Thanx Jia LU From paul at boddie.org.uk Fri Apr 20 06:24:48 2007 From: paul at boddie.org.uk (Paul Boddie) Date: 20 Apr 2007 03:24:48 -0700 Subject: Do other Python GUI toolkits require this? In-Reply-To: References: <462697A6.6010007@codebykevin.com> <465B30B4-5BA0-459A-BE6F-1038874FA74B@jedimindworks.com> Message-ID: <1177064687.963629.94100@y80g2000hsf.googlegroups.com> On 20 Apr, 09:21, Antoon Pardon wrote: > > Indeed I have no wish to bow before common usage. Then nobody will understand you properly if you start referring to a "steep learning curve" when in their terminology you actually mean a "shallow learning curve". Certainly, this discussion has alerted me to a level of ambiguity with the term that would dissuade me from using it, but then it's a hand-waving kind of term, anyway, which would be better replaced with a proper description of whatever effect is supposed to be observable. It seems to me that the original term isn't directly applicable to most situations where it is applied in general usage. For example, someone talking about the learning curve involved in riding a bicycle is taking a term originally used to describe effects observed when people carry out the same task repeatedly and applying it to an activity which involves a number of different cooperating tasks or processes. > I prefer to think about things and dare to speak out when they don't seem to make sense. > > Just repeating common usage propagates a lot of nonsense. Languages and their constituent parts change over time. Here's a relevant article on the topic: http://groups.google.com/group/alt.usage.english/msg/face58f687589a6c Paul From michael at jedimindworks.com Fri Apr 13 06:33:25 2007 From: michael at jedimindworks.com (Michael Bentley) Date: Fri, 13 Apr 2007 05:33:25 -0500 Subject: reading from sys.stdin In-Reply-To: <1176457624.259636.197030@p77g2000hsh.googlegroups.com> References: <1176366058.261031.111870@p77g2000hsh.googlegroups.com> <1176387908.406115.270630@w1g2000hsg.googlegroups.com> <1176438754.995753.50190@d57g2000hsg.googlegroups.com> <1176454871.538968.176620@n76g2000hsh.googlegroups.com> <1176457007.589050.285400@d57g2000hsg.googlegroups.com> <1176457624.259636.197030@p77g2000hsh.googlegroups.com> Message-ID: <79BBB7F1-459F-49DD-91FF-E8FCFFB6418C@jedimindworks.com> On Apr 13, 2007, at 4:47 AM, 7stud wrote: > On Apr 13, 3:36 am, "7stud" wrote: >> >>> It is if the file is smaller than the buffer size. >> >> How is that relevant? >> > > If I put 100 lines of text in a file with each line having 50 > characters, and I run this code: > > import sys > > lst = [] > for line in open("aaa.txt"): > print "an iteration" > lst.append(line) > break > > print lst > > > The output is: > > $ python test1.py > > an iteration > ['helleo haljdfladj ahdflasdjf ds hdljfalsdjfdsljfds \n'] > > It seems clear to me that the whole file wasn't first read into a > buffer before the code started processing the data. The break statement causes it to bail after the first iteration, so that doesn't really prove your point. For example: lst = [] for line in ['we', 'all live', 'in a yellow', 'submarine']: print "an iteration" lst.append(line) break print lst The output is: an iteration ['we'] From liqfemail at gmail.com Sun Apr 8 03:33:43 2007 From: liqfemail at gmail.com (liqfemail at gmail.com) Date: 8 Apr 2007 00:33:43 -0700 Subject: Why does not my wx.html.HtmlWindow work? In-Reply-To: References: <1176003505.794328.62170@n76g2000hsh.googlegroups.com> Message-ID: <1176017623.353256.14360@w1g2000hsg.googlegroups.com> On 4?8?, ??2?29?, Thomas Kr?ger wrote: > liqfem... at gmail.com schrieb: > > > html.LoadPage("http://www.pythonthreads.com/articles/python/incorporating-into-wxpyt...") > > Quickshot: There's a space at the start of your URI. > > Thomas It seems it's not the problem. In my final program there is no such mistake. From nospam at invalid.com Wed Apr 25 01:55:34 2007 From: nospam at invalid.com (Jack) Date: Tue, 24 Apr 2007 22:55:34 -0700 Subject: MS SQL Server Extension? Message-ID: Hi all, in my next project, my Python code needs to talk to an MS SQL 2000 Server. Internet search gives me http://pymssql.sourceforge.net/ I wonder what module(s) people are using. My code runs on a Linux box so the module has to build on Linux. Any hints/pointers are welcome. From thorsten at thorstenkampe.de Mon Apr 2 12:02:25 2007 From: thorsten at thorstenkampe.de (Thorsten Kampe) Date: Mon, 2 Apr 2007 17:02:25 +0100 Subject: I18n issue with optik References: Message-ID: * paul (Mon, 02 Apr 2007 17:49:15 +0200) > Thorsten Kampe schrieb: > [snipp] > > I got the tip to set a different encoding by > > sys.stdout = codecs.EncodedFile(sys.stdout, 'utf-8') > > > > but unfortunately this does not change the encoding of any Terminal. > > So my question is: how can I set a different encoding to sys.stdout > > (or why can I set it without any error but nothing changes?) > AFAIK you can't. If the terminal is limited to ascii it won't be able to > display anything else; it might not even have the right font, so how are > you supposed to fix that? Actually rxvt, Poderosa and console have the ability to display non- ASCII characters. I use the dejavu fonts that support non-ASCII, too. But the problem is even simpler: I can't even set the standard Windows console ("cmd") to Windows 1252 in Python. Although directly executing "chcp 1252" works. Thorsten From carsten at uniqsys.com Mon Apr 30 16:00:09 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Mon, 30 Apr 2007 16:00:09 -0400 Subject: re-importing modules In-Reply-To: <1177962288.575008.48490@q75g2000hsh.googlegroups.com> References: <8%pZh.18192$Kd3.76@newssvr27.news.prodigy.net> <1177962288.575008.48490@q75g2000hsh.googlegroups.com> Message-ID: <1177963209.4090.30.camel@dot.uniqsys.com> On Mon, 2007-04-30 at 12:44 -0700, kyosohma at gmail.com wrote: > On Apr 30, 12:49 pm, "T. Crane" wrote: > > Hi, > > > > When troubleshooting code that's saved in a text file, I often find that I > > want to make a change to it, re-save it, then reimport it. However, just > > typing > > > > import myTestCode > > > > doesn't always seem to import the newer version. Is it supposed to? I find > > that right now I often have to close my iPython window, then reopen it and > > import my recently modified code. I know this can't be the best way to do > > this, but I don't know what is. > > > > any suggestions/help welcome and appreciated, > > trevis > > Hi, > > Another person posted the same thing today. As with that person, you > probably need to use the reload() function. See this post for more > details: > > http://www.python.org/search/hypermail/python-1993/0342.html > > Mike > In addition to the warning that reload() does not recursively reload modules that the reloaded module depends on, be warned that reloading a module does not magically affect any functions or objects from the old version that you may be holding on to. For example: Module code: # dog.py class dog(object): def bark(self): print "Arf!" Interactive session: >>> import dog >>> d = dog.dog() >>> d.bark() Arf! >>> # Now the module code is being changed in another window... >>> reload(dog) >>> # A new dog instance will now say Woof: >>> d2 = dog.dog() >>> d2.bark() Woof! >>> # But the dog instance from before still says Arf: >>> d.bark() Arf! This may or may not be a problem for you, but the bottom-line is that reload must be used with caution. -Carsten From apardon at forel.vub.ac.be Tue Apr 17 09:32:52 2007 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 17 Apr 2007 13:32:52 GMT Subject: Queue enhancement suggestion References: <7x4pngluel.fsf_-_@ruckus.brouhaha.com> Message-ID: On 2007-04-17, Hendrik van Rooyen wrote: > > "Antoon Pardon" wrote: > >> On 2007-04-17, Hendrik van Rooyen wrote: >> > "Antoon Pardon" wrote: >> > >> > >> >> The problem is this doesn't work well if you have multiple producers. >> >> One producer can be finished while the other is still putting values >> >> on the queue. >> >> >> >> The solution I have been thinking on is the following. >> >> >> >> Add an open and close operation. Only threads that have the queue >> >> open can access it. The open call should specify whether you >> >> want to read or write to the queue or both. When all writers >> >> have closed the queue and the queue is empty a q.get will >> >> raise an exception. This may be done by putting a sentinel >> >> on the queue when the last writer closed the queue. >> >> >> > >> > This is beginning to look like a named pipe to me. >> > >> > The nice thing about queues is that there is currently so little >> > BS about them - you just import the module, create one by binding >> > a name to it, and you are in business, and anyone can read and/or >> > write to it. >> >> And if you are not carefull you have a deadlock. I tried queues >> in a threaded gui application. Al the advise you get about such >> applications tell you to have one thread doing all the gui-stuff. > > This is true - and worse - it needs to be the main thread too. I think that is a window condition. On linux it can be any thread. >> So you basically have n producers and one consumer. Unfortunatly >> the gui thread sometimes has things of its own it want to show. >> So when the gui thread wants to put things on the queue you >> risk a deadlock. > > Not sure I understand this - it sounds vaguely incestous to me. > I normally use a GUI with two queues, one for input, one for > output, to two threads that front end two named pipes to > the next process - I try to avoid more than one thing reading or > writing to one end of a queue or a pipe, so the dataflow diagram > for my stuff always looks like a TinkerToy... The problem is that sometimes the gui thread has something to show too. With the added problem that the code wanting to show something doesn't know when it is executing the gui thread or an other. So it is very difficult to avoid the gui thread putting things on the queue. But since the gui thread is the single reader, it will dead lock if the queue happens to be full at the moment the gui thread want to add another item. -- Antoon Pardon From heikki at osafoundation.org Sat Apr 7 18:23:47 2007 From: heikki at osafoundation.org (Heikki Toivonen) Date: Sat, 07 Apr 2007 15:23:47 -0700 Subject: Debugging multithreaded program using Eclipse/Pydev In-Reply-To: <1175887942.192837.187600@n76g2000hsh.googlegroups.com> References: <1175887942.192837.187600@n76g2000hsh.googlegroups.com> Message-ID: John Henry wrote: >>From what I can gather, it appears the only *real* option I have is to > debug under Eclipse/Pydev. I did a google search of this newsgroup > and didn't turn up too many hits. Before I invest the time to learn > Eclipse/Pydev, I like to hear from somebody that have gone this path. > Have you been successful in using Eclipse/Pydev to debug multi- > threaded Python applications? Is so, what was the learning curve like > to you? ActiveState Komodo can also do multithreaded debugging. And if all else fails, you can insert: import pdb pdb.set_trace() in your code and that way you will break on any thread. Currently I am using pydev myself, having gone through WingIDE and Komodo. -- Heikki Toivonen From bj_666 at gmx.net Mon Apr 16 02:47:12 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Mon, 16 Apr 2007 08:47:12 +0200 Subject: sqlite3 question References: Message-ID: In , Gabriel Genellina wrote: > En Thu, 12 Apr 2007 08:43:49 -0300, Marc 'BlackJack' Rintsch > escribi?: > >> In , Jorgen Bodde >> wrote: >> >>>>>> r = c.execute('select * from song where id = 1') >>>>>> for s in r: >>> ... print s >>> ... >>> (1, u'Spikedrivers Blues', u'Mississippi John Hurt') > >> This should not work because `r` should not be a `Cursor` object. The >> `execute()`-Method returns an integer with the number of "affected rows". > > Actually DBAPI 2.0 says the return value is undefined. I just remembered the number of affected rows, but that's just for data manipulation statements like ``UPDATE`` or ``INSERT``. For ``SELECT`` the method should return `None`. My bad. Ciao, Marc 'BlackJack' Rintsch From nogradi at gmail.com Sun Apr 22 10:25:08 2007 From: nogradi at gmail.com (Daniel Nogradi) Date: Sun, 22 Apr 2007 16:25:08 +0200 Subject: serializable object references In-Reply-To: <1242622.P0zHLAfcMH@beaureve.gmx.net> References: <1242622.P0zHLAfcMH@beaureve.gmx.net> Message-ID: <5f56302b0704220725t3ca95942of63afee5d311ed22@mail.gmail.com> > Is it possible to convert an object into a string that identifies the > object in a way, so it can later be looked up by this string. > Technically this should be possible, because things like > > <__main__.Foo instance at 0xb7cfb6ac> > > say everything about an object. But how can I look up the real object, > when I only have this string? > > I know such a thing can be achieved with a dictionary that holds > reference-object pairs. Is there another way? There is the pickle module for serializing objects into strings: http://docs.python.org/lib/module-pickle.html If you need to store objects and later look them up by some key I would recommend using a database. There are plenty: http://docs.python.org/lib/persistence.html HTH, Daniel From ptmcg at austin.rr.com Mon Apr 9 11:39:44 2007 From: ptmcg at austin.rr.com (Paul McGuire) Date: 9 Apr 2007 08:39:44 -0700 Subject: Breaking up Strings correctly: In-Reply-To: References: Message-ID: <1176133184.373854.110520@d57g2000hsg.googlegroups.com> On Apr 9, 7:19 am, "Michael Yanowitz" wrote: > Hello: > > I have been searching for an easy solution, and hopefully one > has already been written, so I don't want to reinvent the wheel: > > Suppose I have a string of expressions such as: > "((($IP = "127.1.2.3") AND ($AX < 15)) OR (($IP = "127.1.2.4") AND ($AY != > 0))) > I would like to split up into something like: > [ "OR", > "(($IP = "127.1.2.3") AND ($AX < 15))", > "(($IP = "127.1.2.4") AND ($AY != 0))" ] > > which I may then decide to or not to further split into: > [ "OR", > ["AND", "($IP = "127.1.2.3")", "($AX < 15)"], > ["AND", "(($IP = "127.1.2.4")", ($AY != 0))"] ] > > Is there an easy way to do this? > I tried using regular expressions, re, but I don't think it is > recursive enough. I really want to break it up from: > (E1 AND_or_OR E2) and make that int [AND_or_OR, E1, E2] > and apply the same to E1 and E2 recursively until E1[0] != '(' > > But the main problem I am running to is, how do I split this up > by outer parentheseis. So that I get the proper '(' and ')' to split > this upper correctly? > > Thanks in advance: > Michael Yanowitz This problem is right down the pyparsing fairway! Pyparsing is a module for defining recursive-descent parsers, and it has some built- in help just for applications such as this. You start by defining the basic elements of the text to be parsed. In your sample text, you are combining a number of relational comparisons, made up of variable names and literal integers and quoted strings. Using pyparsing classes, we define these: varName = Word("$",alphas, min=2) integer = Word("0123456789").setParseAction( lambda t : int(t[0]) ) varVal = dblQuotedString | integer varName is a "word" starting with a $, followed by 1 or more alphas. integer is a "word" made up of 1 or more digits, and we add a parsing action to convert these to Python ints. varVal shows that a value can be an integer or a dblQuotedString (a common expression included with pyparsing). Next we define the set of relational operators, and the comparison expression: relationalOp = oneOf("= < > >= <= !=") comparison = Group(varName + relationalOp + varVal) The comparison expression is grouped so as to keep tokens separate from surrounding expressions. Now the most complicated part, to use the operatorPrecedence method from pyparsing. It is possible to create the recursive grammar explicitly, but this is another application that is very common, so pyparsing includes a helper for it too. Here is your set of operations defined using operatorPrecedence: boolExpr = operatorPrecedence( comparison, [ ( "AND", 2, opAssoc.LEFT ), ( "OR", 2, opAssoc.LEFT ), ]) operatorPrecedence takes 2 arguments: the base-level or atom expression (in your case, the comparison expression), and a list of tuples listing the operators in descending priority. Each tuple gives the operator, the number of operands (1 or 2), and whether it is right or left associative. Now the only thing left to do is use boolExpr to parse your test string: results = boolExpr.parseString('((($IP = "127.1.2.3") AND ($AX < 15)) OR (($IP = "127.1.2.4") AND ($AY != 0)))') pyparsing returns parsed tokens as a rich object of type ParseResults. This object can be accessed as a list, dict, or object instance with named attributes. For this example, we'll actually create a nested list using ParseResults' asList method. Passing this list to the pprint module we get: pprint.pprint( results.asList() ) prints [[[['$IP', '=', '"127.1.2.3"'], 'AND', ['$AX', '<', 15]], 'OR', [['$IP', '=', '"127.1.2.4"'], 'AND', ['$AY', '!=', 0]]]] Here is the whole program in one chunk (I also added support for NOT - higher priority than AND, and right-associative): test = '((($IP = "127.1.2.3") AND ($AX < 15)) OR (($IP = "127.1.2.4") AND ($AY != 0)))' from pyparsing import oneOf, Word, alphas, dblQuotedString, nums, \ Literal, Group, operatorPrecedence, opAssoc varName = Word("$",alphas) integer = Word(nums).setParseAction( lambda t : int(t[0]) ) varVal = dblQuotedString | integer relationalOp = oneOf("= < > >= <= !=") comparison = Group(varName + relationalOp + varVal) boolExpr = operatorPrecedence( comparison, [ ( "NOT", 1, opAssoc.RIGHT ), ( "AND", 2, opAssoc.LEFT ), ( "OR", 2, opAssoc.LEFT ), ]) import pprint pprint.pprint( boolExpr.parseString(test).asList() ) The pyparsing wiki includes some related examples, SimpleBool.py and SimpleArith.py - go to http://pyparsing.wikispaces.com/Examples. -- Paul From bbxx789_05ss at yahoo.com Tue Apr 3 21:11:42 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: 3 Apr 2007 18:11:42 -0700 Subject: heap doesn't appear to work as described In-Reply-To: References: <1175641694.226975.258820@n76g2000hsh.googlegroups.com> Message-ID: <1175649101.985195.223570@n76g2000hsh.googlegroups.com> On Apr 3, 5:27 pm, s... at pobox.com wrote: > >> My book says that in a heap, a value at position i will be smaller > >> than the values at positions 2*i and 2*i + 1. > > Check the heapq docs for the constraints the Python heapq module maintains: > > http://docs.python.org/dev/lib/module-heapq.html > > They are different than what you stated above: > > Heaps are arrays for which heap[k] <= heap[2*k+1] and heap[k] <= > heap[2*k+2] for all k, counting elements from zero. > > Skip Thanks From aleax at mac.com Sun Apr 22 23:27:15 2007 From: aleax at mac.com (Alex Martelli) Date: Sun, 22 Apr 2007 20:27:15 -0700 Subject: Dictionaries and dot notation References: <23087554.X5dcTmlj7P@beaureve.gmx.net> <462B6227.5070405@web.de> <5296241.Dh78hTc8ZZ@beaureve.gmx.net> Message-ID: <1hwzndv.1licthzy6aocnN%aleax@mac.com> Martin Drautzburg wrote: > > mydata = data( ) > > mydata.foo = 'foo' > > mydata.bar = 'bar' > > > > print mydata.foo > > print mydata.bar > > I am aware of all this. > Okay let me rephrase my question: is there a way of using dot notation > without having to create a class? Sure, all you need to create is an *INSTANCE* of a suitable type or class. For example: >>> d = dict(foo=23, bar=45) >>> m = new.module('for_martin') >>> m.__dict__.update(d) >>> m.foo 23 >>> m.bar 45 >>> A module may be appropriate, since it's little more than a "wrapper around a dict to access items by dot notation":-). Alex From jstroud at mbi.ucla.edu Thu Apr 26 06:08:57 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Thu, 26 Apr 2007 03:08:57 -0700 Subject: Video: Professor of Physics, Phd at Cal Tech says: 911 Inside Job In-Reply-To: <1177563723.864674.162300@s33g2000prh.googlegroups.com> References: <1177563723.864674.162300@s33g2000prh.googlegroups.com> Message-ID: stj911 at rock.com wrote: > Video: Professor of Physics, Phd at Cal Tech says: 911 Inside Job > > Cal Tech is the ELITE of ELITE in physics. > > If Feynman were alive, he would point his finger straight at the 911 > criminal operators, the yank bastards themselves ....... > > http://www.911blogger.com/node/8101 > > No self-respecting scientist should keep his mouth shut. Its a > fundamental challenge to the method of science, a detective work most > demanding of INTELLECTUAL HONESTY. > Holy crap! (Not being facetious). I am a scientist. I do have a PhD. I have an enviable publication record in premier journals--and I am astounded by the theory and supporting evidence. Google me--I have no record of promoting conspiracy theories but I am at this moment asking myself why I didn't know about World Trade Center Building 7....Did you know about it? Check out this video: http://video.google.com/videoplay?docid=4026073566596731782 One hour of your life--its worth that to consider alternate hypotheses. You may have to wade through some preliminary melodrama, but watch it for the whole hour. You'll be happy you did. James From mik3l3374 at gmail.com Sat Apr 7 05:31:16 2007 From: mik3l3374 at gmail.com (mik3l3374 at gmail.com) Date: 7 Apr 2007 02:31:16 -0700 Subject: os.path.isfile() error In-Reply-To: <1175936167.548551.289600@n76g2000hsh.googlegroups.com> References: <1175936167.548551.289600@n76g2000hsh.googlegroups.com> Message-ID: <1175938276.097739.28480@n76g2000hsh.googlegroups.com> On Apr 7, 4:56 pm, "7stud" wrote: > Here's the code: > ------------ > import os, os.path, pprint > > mydir = "/Users/me/2testing" > > files = [file for file in os.listdir(mydir)] > pprint.pprint(files) > > print os.path.join(mydir, "helloWorld.py") > > files = [file > for file in os.listdir(mydir) > if os.path.isfile(os.path.join(dir, file) ) > ] > > pprint.pprint(files) > ----output:---------------- > > ['.DS_Store', 'cpTest', 'dir1', 'testfile1', 'xmlFile.xml'] > /Users/me/2testing/helloWorld.py > Traceback (most recent call last): > File "test1.py", line 16, in ? > files = [file > File "/System/Library/Frameworks/Python.framework/Versions/2.3/lib/ > python2.3/posixpath.py", line 62, in join > elif path == '' or path.endswith('/'): > AttributeError: 'builtin_function_or_method' object has no attribute > 'endswith' is 'dir' defined? or is it 'mydir'? From mail at microcorp.co.za Sun Apr 15 05:07:31 2007 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Sun, 15 Apr 2007 11:07:31 +0200 Subject: Lists and Tuples and Much More References: <1176419437.278359.52800@q75g2000hsh.googlegroups.com> Message-ID: <014101c77f3d$80ae7d00$03000080@hendrik> "James Stroud" wrote: > Hendrik van Rooyen wrote: > > > > But if you limit it to one thing and its inverse, its quite useful, and it > > would be nice to have one "doubledict" that can be accessed as speedily > > from either end... > > > > Sort of an internally linked list of mixed hashed immutables, where: > > > > doubledict["Frank Everyman"] yields addy, and > > doubledict[addy] yields "Frank Everyman" > > > > It would have direct applicability in things like the label table in > > an assembler, for debugging and so on. > > > > - Hendrik > > > > I'm thinking that, to avoid big a lot of ambiguity, such a double dict > would need to be implemented as two distinctly referenced data structures: not sure that I agree with this - what I have in mind is almost like this: {a:b,b:a,.....} - but avoiding the overhead of storing the "keys" and "data" twice... Guess at notation: {,,....} - I know the <> is ugly so lets try: {(a:b),(c:d),...} - not much better... > > class DD(object): > def __init__(self, adict): > self._fwd = {} > self._fwd.update(adict) > self._bkwk = dict(v,k for k,v in adict.items()) > def fwd(self, k) > return self._fwd[k] > def bkwd(self, k) > return self._bkwd[k] > def __setitem__(self, k, v): > self._fwd[k] = v > self._bkwd[v] = k > def __getitem__(self, k): > if (k in self._fwd) and (k in self._bkwd): > raise KeyError, 'Which do I look in first?' > else: > raise KeyError, 'Too much guesswork. Use fwd() or bkwd().' > > James This is the problem - you can also do it with two dicts, but then you have to do try-except and handle KeyError if you guess wrong. This is what I have been doing. I think that trying to go "back and forth" is a mistake - easier to just have one link, and store "thing" and "pointer to thing's partner". In practice you would probably either "know" what you are dealing with because of where you got the thing you are looking up from, or in true duck typing style you would not "care". On the other hand, if you store two links, then you can have: "thing", "pointer to next thing in group", "pointer to previous thing in group" and then you can have something like: dd={(a:b:c),(d:e:f:g:h),....} and that would return a list [a,b,c], from any of dd[a], dd[b], dd][c], and likewise for "entry points" of d,e,f,g, or h, to yield [d,e,f,g,h] This makes me think that the correct notation would be: {[a,b,c],[d,e,f,g,h],...} but maybe not because it looks like a set of lists... then how about: {[a:b:c],[d:e:f:g:h],...} and yes I know that: {[a:b:c:f],[d:e:f:g:h],...} - can't be done using only two pointers, not even with fancy footwork - Hendrik From carsten at uniqsys.com Tue Apr 10 15:51:16 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Tue, 10 Apr 2007 15:51:16 -0400 Subject: OT: Question about RGB color method In-Reply-To: <461be63b$0$31839$c3e8da3@news.astraweb.com> References: <461be63b$0$31839$c3e8da3@news.astraweb.com> Message-ID: <1176234676.3430.102.camel@dot.uniqsys.com> On Tue, 2007-04-10 at 15:32 -0400, John Salerno wrote: > Sorry for this non-Python question, but since it's computer related I > know you guys will have an answer, and I don't really know where else to > ask. Mainly I'm just curious anyway. > > I'm wondering, why do computers use a RGB color scheme instead of the > primary colors? Is there something you can't do with yellow? It seems > weird that RGB can be combined to make all colors, when that's supposed > to be the job of the primary colors. I'm sure there some technical > computer-related reason that it had to be this way. You'll find your answer in great detail at http://en.wikipedia.org/wiki/Primary_colors. Television sets and computer screens use the additive color system because they emit light rather than reflect light. Yellow is a subtractive primary color. The additive primary colors are red, green, and blue. -Carsten From nogradi at gmail.com Thu Apr 19 17:36:25 2007 From: nogradi at gmail.com (Daniel Nogradi) Date: Thu, 19 Apr 2007 23:36:25 +0200 Subject: Python Threads - In-Reply-To: <001801c78208$c21b8080$fa936540@cisco.com> References: <001801c78208$c21b8080$fa936540@cisco.com> Message-ID: <5f56302b0704191436m2946f986i82cfbb4fbaae4e1a@mail.gmail.com> > Can you please suggest a technique in Python where we can spawn few number > of worker threads and later map them to a function/s to execute individual > Jobs. Have a look at the threading module: http://docs.python.org/lib/module-threading.html HTH, Daniel From psdasilvaX at esotericaX.ptX Thu Apr 12 23:24:22 2007 From: psdasilvaX at esotericaX.ptX (Paulo da Silva) Date: Fri, 13 Apr 2007 04:24:22 +0100 Subject: "Cloning" file attributes and permissions In-Reply-To: <1176423910.777066.45850@y80g2000hsf.googlegroups.com> References: <1176394818.428367@jubilee.claranet.pt> <1176406707.711609.211110@q75g2000hsh.googlegroups.com> <1176419326.395692@jubilee.claranet.pt> <1176423552.199317.129400@n59g2000hsh.googlegroups.com> <1176423910.777066.45850@y80g2000hsf.googlegroups.com> Message-ID: <1176434728.43319@jubilee.claranet.pt> attn.steven.kuo at gmail.com escreveu: > On Apr 12, 5:19 pm, attn.steven.... at gmail.com wrote: >> On Apr 12, 4:09 pm, Paulo da Silva wrote: >> ... > > After poking around a bit I also discovered the > shutil module. It looks like you can use > shutil.copy2. More Pythonic, yes? > I have seen that in the index but I thought it was a different thing because it was referenced as "high-level operations". Anyway that helps but I still need to copy the whole file or to use stat and chown for the user/group ids. From python.technofreak at gmail.com Mon Apr 16 00:07:46 2007 From: python.technofreak at gmail.com (Parthan SR) Date: Mon, 16 Apr 2007 09:37:46 +0530 Subject: Qt4 in ubuntu In-Reply-To: <1176668662.770066.208350@n76g2000hsh.googlegroups.com> References: <1176668662.770066.208350@n76g2000hsh.googlegroups.com> Message-ID: <9d6d3deb0704152107n5e6fae28w3d2aac09dcb4d3ae@mail.gmail.com> On 15 Apr 2007 13:24:22 -0700, Marcpp wrote: > > Is possible install Qt4 pyqt4 under kubuntu? > Few times ago i tried to run pyqt in ubuntu (gnome) but i can't > do it. > Installation as in [1] Installing using the apt-get/synaptic/adept/aptitude which is present in Ubuntu/Kubuntu or [2] Installing from the source ? I have both of the above in both Ubuntu and Kubuntu. To install from the Ubuntu repository, try $ sudo apt-get install qt4 pyqt4 Or, you can download the source tar ball of Qt4 from Trolltech website and build it on your computer :) If you have any problem during source installation, ask it down here. -- With Regards Parthan "Technofreak" http://technofreakatchennai.wordpress.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From deets at nospam.web.de Mon Apr 30 07:46:28 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 30 Apr 2007 13:46:28 +0200 Subject: I can't inherit from "compiled" classes ? References: Message-ID: <59m38kF2khtrnU2@mid.uni-berlin.de> > I understand what you are saying, and at the same time don't > understand why it doesn't work. Isn't "everything an object" in > python? And if something is an object does it not implies it's an > instance of some class? It means that, but it seems that you can't subclass everything, especially functions: >>> ft = type(lambda x: x) >>> ft >>> class FunctionSubclass(ft): pass ... Traceback (most recent call last): File "", line 1, in ? TypeError: Error when calling the metaclass bases type 'function' is not an acceptable base type >>> But even _if_ you could - what good does it do to you? select being an _instance_ of function, it doesn't help you anything to subclass from it's class. This doesn't affect select itself, in the same sense that instances of some class Foo aren't affected by a subclass Bar(Foo). Besides that, the semantics of "subclassing" a function type are unclear. What would you expect? > Does this mean I can't somehow make this work: """class > PollingSocket(socket.socket, select):""" ? As I point out above, this is a non-sensical thing to do anyway. Maybe you should tell us what you want to accomplish here? Diez From mail at microcorp.co.za Tue Apr 10 02:38:51 2007 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Tue, 10 Apr 2007 08:38:51 +0200 Subject: [offtopic?] problem with UDP broadcast on Windows XP References: <461a271c$0$323$e4fe514c@news.xs4all.nl> <461a6523$0$327$e4fe514c@news.xs4all.nl> Message-ID: <012e01c77b3c$09bd3ec0$03000080@hendrik> "Irmen de Jong" wrote: > Gabriel Genellina wrote: > > > Try running the service impersonating another user (not LOCAL_SERVICE, > > the default). > > You can change that from the service control panel. > > Alas, that didn't change anything. > I made it run as a user account that has admin privileges even, > and it still doesn't respond to the broadcasts. :-( > I am not sure if this is at all relevant - but I seem to recall seeing something once that had a list of socket numbers, splitting them between UDP & TCP - can the socket actually rx UDP? - Hendrik From martin at v.loewis.de Sun Apr 1 02:09:39 2007 From: martin at v.loewis.de (=?UTF-8?B?Ik1hcnRpbiB2LiBMw7Z3aXMi?=) Date: Sun, 01 Apr 2007 08:09:39 +0200 Subject: Unicode list In-Reply-To: References: Message-ID: <460F4CA3.8090904@v.loewis.de> > 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? Python does not live in the ancient and evi land of iso-8859; it lives in the ancient and evil land of ASCII. When printing a list, the individual elements are converted with repr(), not with str(). For a string object, repr() adds escape codes for all bytes that are not printable ASCII characters. To avoid this call to repr, you need to iterate over the list yourself, and print it: if matches: for m in matches: print m, print HTH, Martin From danfan1981 at yahoo.com Fri Apr 20 19:48:39 2007 From: danfan1981 at yahoo.com (danfan1981 at yahoo.com) Date: 20 Apr 2007 16:48:39 -0700 Subject: how to get a wrap aound slice of numpy array In-Reply-To: References: <1177100936.803752.54890@y5g2000hsa.googlegroups.com> Message-ID: <1177112919.420067.21960@q75g2000hsh.googlegroups.com> Thanks. I didn't know numpy can do vector indexing as in Matlab. From kw at codebykevin.com Thu Apr 5 11:48:34 2007 From: kw at codebykevin.com (Kevin Walzer) Date: Thu, 05 Apr 2007 11:48:34 -0400 Subject: Review/commit patch? In-Reply-To: <1175787825.722182.93410@n59g2000hsh.googlegroups.com> References: <1175787825.722182.93410@n59g2000hsh.googlegroups.com> Message-ID: <141cf$46151a53$4275d90a$2820@FUSE.NET> Raymond Hettinger wrote: > [Kevin Walzer] >> How long does it take for a patch at the Python SF tracker to be >> reviewed and/or committed? I am unfamiliar with how the process works. >> >> (I originally submitted a bug report, then figured out how to patch the >> item in question, and subsequently submitted a patch.) > > Which bug report and patch is yours? > > > Raymond > > bug: https://sourceforge.net/tracker/?func=detail&atid=105470&aid=1691411&group_id=5470 patch: https://sourceforge.net/tracker/?func=detail&atid=305470&aid=1693258&group_id=5470 -- Kevin Walzer Code by Kevin http://www.codebykevin.com From esther at bitranch.com Mon Apr 30 12:45:50 2007 From: esther at bitranch.com (estherschindler) Date: 30 Apr 2007 09:45:50 -0700 Subject: OT somewhat: Do you telecommute? What do you wish the boss understood about it? Message-ID: <1177951550.535520.144460@h2g2000hsg.googlegroups.com> For a lot of IT people -- everyone from software developers to tech writers to network support folks -- telecommuting is the best personal option. They get a flexible schedule, they aren't bothered by noisy cube-mates, they can code during whichever hours work for them (with the help of IM and email), and so on. Many of us are lucky enough to live this lifestyle; I include myself in this set, as I've been a full time telecommuter for several years. So I proposed to my boss that I write another in my "5 Things the CIO Should Know..." series (along with "5 Things the CIO Should Know about Fighting Spam" [http://www.cio.com/article/101475] and "...about Software Requirements" [http://www.cio.com/article/29903]), this time about telecommuting. He was enthusiastic about the idea, and I'm anxious to get started. My question has two parts: * If you telecommute, full- or part-time, what *one* thing do you wish the CIO or IT Management would understand that they don't currently "get"? * If you don't telecommute, the question is the same -- what do you wish the CIO would understand about telecommuting -- but I expect the answers will be different (such as "they should let me do it"). Or perhaps you want to tell management something about the difficulty of dealing with telecommuters ("I really hate that THEY always seem to do email during teleconferences but nobody would let us get away with that in person.") Note, though, that most of my attention will be given to the people who DO telecommute because my context is "if you're going to do this, we'll tell you how to do it right." There is, of course, a manager's view to the same question. (I can imagine a manager saying, "Telecommuting doesn't mean you can stay home and play with your baby. You still need to get your work done.") But mostly I'm trying to represent the concerns of the telecommuter herself. I realize that you may have more than one "...and THEN I'd say...!" item. But I ask people to keep it to one answer to help me clarify priorities. As you can probably tell, I will collect opinions from a wide variety of people who work in IT, over the next week or so. I'll collate the results and then turn them into a brilliant essay which will be published on CIO.com. I promise to post the URL when the article is posted, too. I'm happiest when I can quote someone specifically ("Esther Schindler is a programmer at the Groovy Corporation") but it's okay to have an indirect reference too ("Esther is a programmer at a financial services firm in the midwest"). I can even accept anonymity if necessary ("a programmer named Esther said..."). You can write to me privately if you like, but I suspect the question is of interest to the larger community, so feel free to respond to the thread here. (It does help if you cc me so that I see your message sooner.) Esther Schindler senior online editor, CIO.com http://advice.cio.com/taxonomy/term/34 From bytecolor at yahoo.com Tue Apr 3 04:37:31 2007 From: bytecolor at yahoo.com (bytecolor) Date: 3 Apr 2007 01:37:31 -0700 Subject: Tkinter <> and bindtags ordering In-Reply-To: <1175584600.221378.143380@n59g2000hsh.googlegroups.com> References: <1175572841.269301.275100@q75g2000hsh.googlegroups.com> <1175584600.221378.143380@n59g2000hsh.googlegroups.com> Message-ID: <1175589451.633609.216190@e65g2000hsc.googlegroups.com> On Apr 3, 3:16 am, "Rob Wolfe" wrote: > What about instead of: > > > t.bind('<>', text_changed) > > this event: > > t.bind('', text_changed) > > > root.mainloop() > > -- > HTH, > Rob Hey Rob, I actually started with that event, until I came across the modified event. I'm working on syntax highlighting. So I need any text change. Also, colorizing on a key release is annoyingly noticeable to the user. I tried it :) I'm sure there are going to be other perils along the way as this is my first attempt at syntax highlighing. I can load a file and the highlighting works very well. I used an elaborate regex with named groups and re.finditer(). I either use the names directly as edit tags, or they help me look up other tags in a dict. It's quite fast. screenshot with random (ugly) colors: http://bytecolor.homelinux.org/~bytecolor/vapt_colorizing.png That part wasn't bad at all. Now I need to code the text change logistics but this bindtags ordering has got me perplexed. -- bytecolor From phreaki at gmail.com Sun Apr 22 16:23:59 2007 From: phreaki at gmail.com (phreaki) Date: 22 Apr 2007 13:23:59 -0700 Subject: pickled object, read and write.. In-Reply-To: <1177267228.603237.113070@n59g2000hsh.googlegroups.com> References: <1177267228.603237.113070@n59g2000hsh.googlegroups.com> Message-ID: <1177273439.953235.140790@d57g2000hsg.googlegroups.com> On Apr 22, 2:40 pm, "israph... at googlemail.com" wrote: > Hi all. > > I have to put together some code that reads high scores from a saved > file, then gives the user the opportunity to add their name and score > to the high scores list, which is then saved. > > Trouble is, I can't tell the program to read a file that doesn't > exist, that generates an error. > > So I must have a file created, problem HERE is everytime the program > is run, it will overwrite the current list of saved high scores. > > Advice would be much appreciated. What did adding the standard try statement do? From gagsl-py2 at yahoo.com.ar Thu Apr 12 00:01:17 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 12 Apr 2007 01:01:17 -0300 Subject: Writing XML Logs References: <34571.2746413939$1176302815@news.gmane.org> Message-ID: En Wed, 11 Apr 2007 11:43:19 -0300, Robert Rawlins - Think Blue escribi?: > I'm trying to write an application that will log to an XML file, that'll > be > later parsed by another application. > Can anyone offer any advice on how best to get started with this kind of > thing? I'm running python 2.4.4 but when I've tried running any examples > with SAX involved they seem to say 'no module found: sax" or something to > that effect, I was under the impression that sax came bundled with python > 2.0 and above? You could use ElementTree. It's bundled with Python 2.5 but you can dowload it from http://effbot.org/zone/element-index.htm It's quite simple to use. Writing XML incrementally is a bit tricky if you want the file to be always well formed: you have to overwrite the last closing tag each time. -- Gabriel Genellina From steve at REMOVE.THIS.cybersource.com.au Wed Apr 11 19:02:42 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Thu, 12 Apr 2007 09:02:42 +1000 Subject: Creating Unique Dictionary Variables from List References: <461d27d5$0$3630$426a74cc@news.free.fr> Message-ID: On Wed, 11 Apr 2007 21:03:20 +0200, Bruno Desthuilliers wrote: > Greg Corradini a ?crit : >> Hello All, >> I'm attempting to create multiple dictionaries at once, each with unique >> variable names. The number of dictionaries i need to create depends on the >> length of a list, which was returned from a previous function. >> The pseudo code for this problem would be: >> >> returnedlist = [x,y,z] >> count = 0 >> for i in returnedlist: >> if count < len(returnedlist): >> # then create a dictionary (beginning with variable dic) for each i >> with a unique name such that >> # my unique name would be dic + count >> >> Any ideas about this? > > Yes : use a dict to store your dicts: > > returnedlist = [x,y,z] > dicts = dict() > for num, item in enumerate(returnedlist): > dicts['dict%s' % num] = dict() Given that num is unique each time around the loop, what do you gain by using 'dictN' for the key instead of just N (=num)? returnedlist = [x,y,z] dicts = {} for num, item in enumerate(returnedlist): # presumably you would use item somewhere dicts[num] = {item: None} And that suggests that storing the dicts in a dict may be unnecessary -- just put them in a list: returnedlist = [x,y,z] dicts = [None] * len(returnedlist) for num, item in enumerate(returnedlist): dicts[num] = {item: None} -- Steven. From nick at craig-wood.com Tue Apr 24 13:30:03 2007 From: nick at craig-wood.com (Nick Craig-Wood) Date: Tue, 24 Apr 2007 12:30:03 -0500 Subject: Convert a string to a list References: <1177426760.164877.104990@t38g2000prd.googlegroups.com> Message-ID: rh0dium wrote: > I am using pexpect to drive another tool. Some of the data I get back > would be better suited as a list and I want to know a simple way to > parse the data to push it into a list. > > For example > > I get the following string back. I want to convert this to a list: > > '("." ".." "cdslib_cleanup.py" "cadence.py" > "cdsinit_cdsenv_cleanup.py")' > > should be: > ["." ".." "cdslib_cleanup.py" "cadence.py" > "cdsinit_cdsenv_cleanup.py"] > > It should be able to handle embeded lists like this: > '("." ("cadence.py" "foo_cleanup.py") "cdslib_cleanup.py" "cadence.py" > "cdsinit_cdsenv_cleanup.py")' > > should become > ["." ["cadence.py" "foo_cleanup.py"] "cdslib_cleanup.py" "cadence.py" > "cdsinit_cdsenv_cleanup.py"] Here is a cheap, nasty and insecure solution >>> a='("." ".." "cdslib_cleanup.py" "cadence.py" "cdsinit_cdsenv_cleanup.py")' >>> eval(a.replace('" "', '", "').replace('" (', '", (').replace(') "', '), "')) ('.', '..', 'cdslib_cleanup.py', 'cadence.py', 'cdsinit_cdsenv_cleanup.py') >>> b='("." ("cadence.py" "foo_cleanup.py") "cdslib_cleanup.py" "cadence.py" "cdsinit_cdsenv_cleanup.py")' >>> eval(b.replace('" "', '", "').replace('" (', '", (').replace(') "', '), "')) ('.', ('cadence.py', 'foo_cleanup.py'), 'cdslib_cleanup.py', 'cadence.py', 'cdsinit_cdsenv_cleanup.py') >>> It made tuples rather than lists but I expect that won't matter. Someone normally chimes in with pyparsing at this point... -- Nick Craig-Wood -- http://www.craig-wood.com/nick From surekap at gmail.com Sun Apr 22 06:35:02 2007 From: surekap at gmail.com (Prateek) Date: 22 Apr 2007 03:35:02 -0700 Subject: Support for new items in set type In-Reply-To: References: <1177211624.069474.3960@y5g2000hsa.googlegroups.com> Message-ID: <1177238102.086296.148070@q75g2000hsh.googlegroups.com> On Apr 22, 11:09 am, Steven D'Aprano wrote: > On Sat, 21 Apr 2007 20:13:44 -0700, Prateek wrote: > > I have a bit of a specialized request. > > > I'm reading a table of strings (specifically fixed length 36 char > > uuids generated via uuid.uuid4() in the standard library) from a file > > and creating a set out of it. > > Then my program is free to make whatever modifications to this set. > > > When I go back to save this set, I'd like to be able to only save the > > new items. > > This may be a silly question, but why? Why not just save the modified set, > new items and old, and not mess about with complicated transactions? I tried just that. Basically ignored all the difficulties of difference calculation and just overwrote the entire tablespace with the new set. At about 3000 entries per file (and 3 files) along with all the indexing etc. etc. just the extra I/O cost me 28% performance. I got 3000 entries committed in 53s with difference calculation but in 68s with writing the whole thing. > > After all, you say: > > > PS: Yes - I need blazing fast performance - simply pickling/unpickling > > won't do. Memory constraints are important but definitely secondary. > > Disk space constraints are not very important. > > Since disk space is not important, I think that you shouldn't care that > you're duplicating the original items. (Although maybe I'm missing > something.) > > Perhaps what you should be thinking about is writing a custom pickle-like > module optimized for reading/writing sets quickly. I already did this. I'm not using the pickle module at all - Since I'm guaranteed that my sets contain a variable number of fixed length strings, I write a header at the start of each tablespace (using struct.pack) marking the number of rows and then simply save each string one after the other without delimiters. I can do this simply by issuing "".join(list(set_in_question)) and then saving the string after the header. There are a few more things that I handle (such as automatic tablespace overflow) Prateek From attn.steven.kuo at gmail.com Sun Apr 22 11:46:22 2007 From: attn.steven.kuo at gmail.com (attn.steven.kuo at gmail.com) Date: 22 Apr 2007 08:46:22 -0700 Subject: function minimization In-Reply-To: <1177250114.342886.160520@o5g2000hsb.googlegroups.com> References: <1177250114.342886.160520@o5g2000hsb.googlegroups.com> Message-ID: <1177256782.182142.229330@b75g2000hsg.googlegroups.com> On Apr 22, 6:55 am, "marksc... at gmail.com" wrote: > Is anyone aware of python library that does function minimization a la > Minuit (http://wwwasdoc.web.cern.ch/wwwasdoc/minuit/) used by CERN? > > thanks If you have a C complier and the lapack, blas, and levmar libraries, you could try pylevmar: http://projects.liquidx.net/python/browser/pylevmar/trunk/setup.py -- Hope this helps, Steven From rw at smsnet.pl Tue Apr 3 03:16:40 2007 From: rw at smsnet.pl (Rob Wolfe) Date: 3 Apr 2007 00:16:40 -0700 Subject: Tkinter <> and bindtags ordering In-Reply-To: <1175572841.269301.275100@q75g2000hsh.googlegroups.com> References: <1175572841.269301.275100@q75g2000hsh.googlegroups.com> Message-ID: <1175584600.221378.143380@n59g2000hsh.googlegroups.com> bytecolor wrote: [...] > changing = False > root = tk.Tk() > t = tk.Text(master=root) > t.pack() > t.focus_set() > t.tk.call(t._w, 'edit', 'modified', 0) What about instead of: > t.bind('<>', text_changed) this event: t.bind('', text_changed) > root.mainloop() -- HTH, Rob From wojciech_mula at poczta.null.onet.pl.invalid Tue Apr 24 14:48:47 2007 From: wojciech_mula at poczta.null.onet.pl.invalid (=?ISO-8859-2?Q?Wojciech_Mu=B3a?=) Date: Tue, 24 Apr 2007 20:48:47 +0200 Subject: tkinter paint program In-Reply-To: References: Message-ID: Gigs_ wrote: > I'm working on tkinter paint program, mostly to learn tkinter canvas. > I have method which create buttons for oval, rectangle, line, polygon etc. > How to make oval button to be sunken when i click it and to remain > sunken until i click on another button (like rectangle and than is > another button sunken)? You can use radiobuttons. If attribute indicatoron is 0, then radiobuttons are drawn as regular buttons. With attribute selectcolor you can set background color of selected button. w. From bearophileHUGS at lycos.com Mon Apr 2 10:27:48 2007 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 2 Apr 2007 07:27:48 -0700 Subject: Shed Skin Python-to-C++ Compiler 0.0.21, Help needed In-Reply-To: <1175513253.595204.220110@o5g2000hsb.googlegroups.com> References: <576vhbF2ca1guU1@mid.individual.net> <1175376373.241744.6220@y80g2000hsf.googlegroups.com> <1175413310.295953.230840@e65g2000hsc.googlegroups.com> <1175455529.936887.249170@e65g2000hsc.googlegroups.com> <1175496721.899984.193690@n76g2000hsh.googlegroups.com> <1175509861.292455.226280@b75g2000hsg.googlegroups.com> <1175511923.323321.30220@n76g2000hsh.googlegroups.com> <1175513253.595204.220110@o5g2000hsb.googlegroups.com> Message-ID: <1175524068.528095.217300@y80g2000hsf.googlegroups.com> Paul Boddie: > Prior to that PEP being written/published, I made this proposal: > http://wiki.python.org/moin/CodingProjectIdeas/StandardLibrary/Restru... On first sight it looks good. Python 3.0-3.1 is the best and probably only possibility for such improvement (I have said 3.1 too because I think Guido will allow some corrections in the version successive to 3.0). Bye and thank you, bearophile From dstromberg at datallegro.com Wed Apr 18 20:55:48 2007 From: dstromberg at datallegro.com (Dan Stromberg) Date: Thu, 19 Apr 2007 00:55:48 GMT Subject: indexing web pages - in python? Message-ID: Are there any open source search engines written in python for indexing a given collection of (internal only) html pages? Right now I'm talking about dozens, but hopefully it'll be hundreds or thousands at some point. I'm thinking some sort of CGI script, with perhaps a cron job that updates the indexes. I'm not particularly looking for something that has a full RDBMS behind it - just a file that stores indexes. I'll go with an RDBMS-based solution if I must, but I don't think that's really needed at this point. TIA From aleax at mac.com Wed Apr 18 22:45:49 2007 From: aleax at mac.com (Alex Martelli) Date: Wed, 18 Apr 2007 19:45:49 -0700 Subject: python - dll access (ctypes or swig) References: <1hwq9na.98800513op6liN%aleax@mac.com> <1hwr93q.ym0vh4baceh6N%aleax@mac.com> Message-ID: <1hws6o2.2zv7ax11bavarN%aleax@mac.com> Thomas Heller wrote: ... > > and some technical issues such as threading (if COM client and server ... > I think that the latter problem (incompatible threading models in the same > process) are solved by COM apartments - aren't they? "apartment" is one threading model, but it still means that your application and your in-process server must be compatible with it (again, we're discussing the fact that out-of-process servers, at a performance price, can do away with these minor limitations). Alex From aleax at mac.com Tue Apr 17 00:41:00 2007 From: aleax at mac.com (Alex Martelli) Date: Mon, 16 Apr 2007 21:41:00 -0700 Subject: script for seconds in given month? References: <1176740556.859125.221980@l77g2000hsb.googlegroups.com> Message-ID: <1hwokmz.1ropcwj17pg55dN%aleax@mac.com> edfialk wrote: > Hi, does anyone happen to know of a script that would return the > number of seconds in a month if I give it a month and a year? > > My python is a little weak, but if anyone could offer some suggestions > I think I could handle it myself, or if anyone happens to know of a > script already written that performs this I would be extremely > grateful. import calendar def seconds_in_month(month, year): nomatter, daysinmonth = calendar.monthrange(year, month) return daysinmonth * 24 * 60 * 60 Alex From aisaac at american.edu Thu Apr 12 17:59:58 2007 From: aisaac at american.edu (Alan Isaac) Date: Thu, 12 Apr 2007 21:59:58 GMT Subject: tuples, index method, Python's design References: Message-ID: "Terry Reedy" wrote in message news:mailman.6428.1176408049.32031.python-list at python.org... > The main point of immutability is hashability by value (rather than by id). You are treating an effect as a cause. This is the main point *because* of an artifical constraint on tuples. Cheers, Alan Isaac From spohle at gmail.com Mon Apr 30 11:24:37 2007 From: spohle at gmail.com (spohle) Date: 30 Apr 2007 08:24:37 -0700 Subject: import structures In-Reply-To: References: <1177945378.731721.137080@o5g2000hsb.googlegroups.com> Message-ID: <1177946677.365039.311480@e65g2000hsc.googlegroups.com> On Apr 30, 8:16 am, "Hamilton, William " wrote: > > -----Original Message----- > > From: python-list-bounces+whamil1=entergy.... at python.org > [mailto:python- > > list-bounces+whamil1=entergy.... at python.org] On Behalf Of spohle > > Sent: Monday, April 30, 2007 10:03 AM > > To: python-l... at python.org > > Subject: Re: import structures > > > On Apr 30, 8:00 am, Paul McGuire wrote: > > > On Apr 30, 9:56 am, spohle wrote: > > > > > hi, > > > > > i have written a small project for myself all in seperate classes > and > > > > each of the classes lives in a seperate file. now i am looking for > an > > > > import structure something like import wx, and then have access to > all > > > > my classes just like wx.Button or wx.BoxSizer etc. > > > > > as of now i have a __init__.py file in the directory with: > > > > from pkgutil import extend_path > > > > __path__ = extend_path(__path__, __name__) > > > > > but i still have to import each class by it's own. im really > looking > > > > for something like import wx > > > > and then get all my access right away under this new namespace. > > > > > thank you in advance > > > > If it really is a small project, consider just putting all the > classes > > > into a single module, say spohlePkg.py. Then your users would > import > > > this module using "import spohlePkg", and would access the classes > as > > > "spohlePkg.ClassA", "spohlePkg.ClassB", etc. > > > > -- Paul > > > yeah i had that, but my classes grew really fast and i decided to > > split them up. but you're right that in one file that would solve my > > problem. still hoping to find a way for the seperate files. > > If you've got modules a, b, and c, you can create a wrapper module d > that imports from each of those. > > from a import * > from b import * > from c import * > > Then, import d and use it as the module name. So if a had a SomeThing > class, you could do this: > > import d > x = d.SomeThing() > > --- > -Bill Hamilton that doesn't seem to work for me. the from a import * will only give me a not d.a From andrew.jefferies at gmail.com Wed Apr 25 13:38:50 2007 From: andrew.jefferies at gmail.com (andrew.jefferies at gmail.com) Date: 25 Apr 2007 10:38:50 -0700 Subject: File not read to end Message-ID: <1177522730.327454.121120@s33g2000prh.googlegroups.com> Hi, I'm trying to write a simple log parsing program. I noticed that it isn't reading my log file to the end. My log is around 200,000 lines but it is stopping at line 26,428. I checked that line and there aren't any special characters. This is the file reading code segment that I'm using: sysFile=open(sysFilename,'r') lineCount = 0 for line in sysFile: lineCount +=1 print str(lineCount) + " -- " + line I also stuck this same code bit into a test script and it was able to parse the entire log without problem. Very quirky. This is my first foray from Perl to Python so I appreciate any help. Thanks in advance. --Andrew From steve at holdenweb.com Fri Apr 13 08:48:34 2007 From: steve at holdenweb.com (Steve Holden) Date: Fri, 13 Apr 2007 08:48:34 -0400 Subject: treating str as unicode in legacy code? In-Reply-To: <1176407869.541038.212410@p77g2000hsh.googlegroups.com> References: <1176407869.541038.212410@p77g2000hsh.googlegroups.com> Message-ID: Ben wrote: > I'm left with some legacy code using plain old str, and I need to make > sure it works with unicode input/output. I have a simple plan to do > this: > > - Run the code with "python -U" so all the string literals become > unicode litrals. > - Add this statement > > str = unicode > > to all .py files so the type comparison (e.g., type('123') == str) > would work. > > > Did I miss anything? Does this sound like a workable plan? > > Thanks! > Well, don't forget that the assignment to str *shadows* the built-in rather than replacing it, so there may be places (imported modules being the example that most readily springs to mind) where that replacement won't be effective. Plus which in CPython the C parts of the code may well be creating and expecting objects of type str but they won't use the Python naming mechanism at all, so you will have no way to effect changes in those behaviors. This will probably account for about 95% of any strangeness you see, but it's probably a good first step in the conversion process. 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 deitel at gmail.com Thu Apr 5 13:23:47 2007 From: deitel at gmail.com (deitel at gmail.com) Date: 5 Apr 2007 10:23:47 -0700 Subject: Python Instructor Needed Message-ID: <1175793827.558925.116890@q75g2000hsh.googlegroups.com> We have an immediate need for a four- or five-day Intro to Python course in the Midwest United States for late May/early June 2007. We are looking for a Python instructor with outstanding credentials and a proven track record. You would be teaching this course as a third- party contractor. If you are interested, please contact Abbey immediately at 978 823 0130. We will also need the following information: 1. Your daily rate (US$). 2. Your availability. 3. Please indicate which materials you would use for the course and the price of the materials. From carsten at uniqsys.com Fri Apr 13 15:41:34 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Fri, 13 Apr 2007 15:41:34 -0400 Subject: attribute save restore In-Reply-To: <7_ydnZt7B8WqSILbnZ2dnUVZ_uOmnZ2d@comcast.com> References: <7_ydnZt7B8WqSILbnZ2dnUVZ_uOmnZ2d@comcast.com> Message-ID: <1176493294.3428.46.camel@dot.uniqsys.com> On Fri, 2007-04-13 at 14:08 -0500, Carl K wrote: > Is there a more elegant way of coding this: > > x=o.p # save .p > o.p=0 > o.m() > o.p=x # restore .p In Python 2.5, you could leverage the new "with" statement with a properly crafted context manager along these lines: """ from __future__ import with_statement class TempAttrSetter(object): def __init__(self, obj, **attrs): self.obj = obj self.attrs = attrs def __enter__(self): self.saved_attrs = {} for attr, newval in self.attrs.iteritems(): self.saved_attrs[attr] = getattr(self.obj, attr) setattr(self.obj, attr, newval) def __exit__(self, *args): for attr in self.saved_attrs.keys(): setattr(self.obj, attr, self.saved_attrs[attr]) class Bag(object): pass b = Bag() b.x = 1 print b.x # prints 1 with TempAttrSetter(b, x=3): print b.x # prints 3 print b.x # prints 1 """ -Carsten From anglozaxxon at gmail.com Thu Apr 5 15:43:27 2007 From: anglozaxxon at gmail.com (anglozaxxon) Date: 5 Apr 2007 12:43:27 -0700 Subject: Looping issues In-Reply-To: <7dWdnYepWOY6oojbnZ2dnUVZ_ompnZ2d@comcast.com> References: <1175796069.501575.157410@w1g2000hsg.googlegroups.com> <7dWdnYepWOY6oojbnZ2dnUVZ_ompnZ2d@comcast.com> Message-ID: <1175802207.238128.284410@o5g2000hsb.googlegroups.com> On Apr 5, 2:27 pm, Larry Bates wrote: > brochu... at gmail.com wrote: > > What I am trying to do is compare two files to each other. > > > If the 2nd file contains the same line the first file contains, I want > > to print it. I wrote up the following code: > > > correct_settings = open("C:\Python25\Scripts\Output > > \correct_settings.txt","r") > > current_settings = open("C:\Python25\Scripts\Output\output.txt","r") > > > for line in correct_settings: > > for val in current_settings: > > if val == line: > > print line + " found." > > > correct_settings.close() > > current_settings.close() > > > For some reason this only looks at the first line of the > > correct_settings.txt file. Any ideas as to how i can loop through each > > line of the correct_settings file instead of just looking at the first? > > If the files aren't terribly large (not tested): > > correct_lines=open(r"C:\Python25\Scripts\Output" \ > "\correct_settings.txt", "r").readlines() > > current_lines=open(r"C:\Python25\Scripts\Output\output.txt", > "r").readlines() > > for line in current_settings: > if line in correct_lines: > print line + " found" > > This does what you asked for but somehow I don't think it is > what you want. I would suggest that you take a look at difflib. > > Somththing along the lines of: > > import difflib > > correct_lines=open(r"C:\Python25\Scripts\Output" \ > "\correct_settings.txt", "r").readlines() > > current_lines=open(r"C:\Python25\Scripts\Output\output.txt", > "r").readlines() > > delta=difflib.unified_diff(correct_lines, current_lines) > diffs=''.join(delta) > > print diffs > > Will show you the lines that are different and some lines > around it for context. > > -Larry Sorry my solution didn't work. The only other thing I can think of is that something is screwy with the newlines, although this seems silly. I've heard Python has "universal newline" support, meaning \n = \r = \r\n, etc. Try printing the contents of the file in its entirety: print current_settings.read() And see if it prints the entire file, or just the first line. I can't imagine it won't print the whole thing. Next, do print current_settings.read().replace('\\','\\\\'). This will make the escape characters visible, so you can see exactly what type of newlines it's printing. If the file is in Unix format and you're on Windows, Python may be assuming the latter and not breaking lines correctly. Post what it prints. Nick From carsten at uniqsys.com Tue Apr 17 21:01:19 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Tue, 17 Apr 2007 21:01:19 -0400 Subject: Python COM iterator In-Reply-To: References: Message-ID: <1176858079.3305.19.camel@localhost.localdomain> On Tue, 2007-04-17 at 16:54 -0500, Larry Bates wrote: > Does anyone know if there is a way to make a Python COM object > act like a proper iterator in VB/Delphi? I don't use COM, VB, or Delphi, but Google turned up these two references: http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcn7/html/vaconUsingForEach.asp http://17slon.com/blogs/gabr/2007/03/fun-with-enumerators-part-1.html Judging from those links, an object is iterable in VB and Delphi (or as they call it, it is enumerable) if it exposes a GetEnumerator method that returns an enumerator. The enumerator in turn needs to expose a MoveNext method and a Current property. Assuming that the Enumerable and the Enumerator are allowed to be the same object, you'll probably need code that looks something like this: class foo: _public_methods_=['GetEnumerator','MoveNext'] # You'll need to figure out how to expose "self.Current" def __init__(self): self.numbers=[1,2,3,4,5,6,7,8] self.Current = None def MoveNext(self): try: self.Current = self.numbers.pop(0) return True except IndexError: return False def GetEnumerator(self): return self Good luck, Carsten. From bdesth.quelquechose at free.quelquepart.fr Wed Apr 11 17:09:25 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Wed, 11 Apr 2007 23:09:25 +0200 Subject: text file vs. cPickle vs sqlite a design question In-Reply-To: References: Message-ID: <461d4561$0$6091$426a34cc@news.free.fr> Dag a ?crit : > I have an application which works with lists of tuples of the form > (id_nr,'text','more text',1 or 0). I'll have maybe 20-50 or so of these > lists containing anywhere from 3 to over 30000 tuples. The actions I > need to do is either append a new tuple to the end of the list, display > all the tuples or display all the tuples where the last element is a 1 > > Basically what I'm wondering is the best way to store these data stuctures > to disc. As the subject mentioned I've basically got three approaches. > Store each list as a text file, pickle each list to file or shove the > whole thing into a bunch of database tables. I can see pros and cons > with each approach. Does anybody have any advice as to whether any of > these approaches is obviously better than any other? On one hand I like > the text file approach since it lets me append without loading > everything into memory, on the other hand the sqlite approach makes it > easy to select stuff with SELECT * FROM foo WHERE... which could be > handy if ever need to add more advanced filtering. Given your specs, I'd go for SQLite without any hesitation. Your data structure is obviously relational (a list of tuples is a pretty good definition of a relation), so a relational DBMS is the obvious solution, and you'll get lots of other benefits from it (SQL being only one of them - you can also think about free optimization, scalability, and interoperability). And if you don't like raw SQL and prefer something more pythonic, then you have SQLAlchemy and Elixir. My 2 cents... From newsgroups at nospam.nowire.org Wed Apr 4 17:52:35 2007 From: newsgroups at nospam.nowire.org (=?ISO-8859-1?Q?Thomas_Kr=FCger?=) Date: Wed, 04 Apr 2007 23:52:35 +0200 Subject: Why NOT only one class per file? In-Reply-To: <1175721799.714907.52770@o5g2000hsb.googlegroups.com> References: <1175721799.714907.52770@o5g2000hsb.googlegroups.com> Message-ID: Chris Lasher schrieb: > why should we NOT be > placing classes in their own separate files? > > Thoughts, comments, and insight much appreciated, At first: if he really like it he can place every class in a single file. But there are some reasons why Python "allows" you to place many classes in one file: - It's (a little bit) faster, no additional file system lookup is needed. ;) - You can define a class in a class. Django, for example, uses this for it's data models. If you do this you are forced to have multiple classes in on file. Example: http://www.djangoproject.com/documentation/tutorial02/#make-the-poll-app-modifiable-in-the-admin See also: http://mail.python.org/pipermail/python-list/2006-December/418363.html Thomas From rene at korteklippe.de Sun Apr 22 06:44:06 2007 From: rene at korteklippe.de (=?UTF-8?B?UmVuw6kgRmxlc2NoZW5iZXJn?=) Date: Sun, 22 Apr 2007 12:44:06 +0200 Subject: Do other Python GUI toolkits require this? In-Reply-To: References: <462697A6.6010007@codebykevin.com> Message-ID: <462b3c76$0$10200$9b4e6d93@newsspool4.arcor-online.net> Antoon Pardon schrieb: >> Who says the axes are labeled "familiarity" and "learning period"? I >> just assume they are labeled (y-axis) "Effort" and (x-axis) "Knowledge" >> (or "skill" or ....). > > You can assume all you want, but no serious person processing numbers > would choose axes like that. The vast majority of world population is not into "processing numbers", so why should they care? -- Ren? From george.sakkis at gmail.com Sat Apr 21 21:49:25 2007 From: george.sakkis at gmail.com (George Sakkis) Date: 21 Apr 2007 18:49:25 -0700 Subject: Handy short cut for formatting elapsed time in floating point seconds In-Reply-To: <1177204141.785661.203320@n59g2000hsh.googlegroups.com> References: <1177204141.785661.203320@n59g2000hsh.googlegroups.com> Message-ID: <1177206565.619901.56670@o5g2000hsb.googlegroups.com> On Apr 21, 9:09 pm, Paul McGuire wrote: > I am doing some simple timing of some elements of Python scripts, and > the simplest is to just call time.time() before and after key elements > of the script: > > t1 = time.time() > > # do lengthy operation > > t2 = time.time() > print "That took %f seconds" % (t2-t1) > > Unfortunately, this gives very ugly timing output, as just a floating > point number of seconds. After several iterations of writing a > formatter (strftime is not straightforward to use - it omits > milliseconds for one thing), I came up with this: > > def secondsToStr(t): > rediv = lambda ll,b : list(divmod(ll[0],b)) + ll[1:] > return "%d:%02d:%02d.%03d" % tuple(reduce(rediv,[[t*1000,], > 1000,60,60])) > > Now I can write: > > print "That took", secondsToStr(t2-t1),"seconds" > > and get nicely-formatted 0:00:12.345 style output. > > (I also posted this to the Python Cookbook.) > > -- Paul Cute... for obfuscated python contests :-) Whenever I needed this, a simple "Completed in %d minutes and %.1f seconds" % divmod(end-start, 60) was more than enough. George From plutoinchina at gmail.com Wed Apr 4 06:52:29 2007 From: plutoinchina at gmail.com (autin) Date: 4 Apr 2007 03:52:29 -0700 Subject: bool value 'False' no memory address? In-Reply-To: <461381ef$0$15440$426a74cc@news.free.fr> References: <1175682972.507206.29000@n76g2000hsh.googlegroups.com> <461381ef$0$15440$426a74cc@news.free.fr> Message-ID: <1175683949.859068.213240@q75g2000hsh.googlegroups.com> My false!uh,i didnot understand it clearly. On Apr 4, 6:46 am, Bruno Desthuilliers wrote: > autin a ?crit : > > > such as: > >>>> b = False > >>>> id(b) > > Traceback (most recent call last): > > File "", line 1, in ? > > TypeError: 'bool' object is not callable > > IMVHO, you shadowed the builtin id() function with a boolean somewhere > else... > > 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. > >>> b = False > >>> id(b) > 135506080 > >>> > >>> id = False > >>> id(b) > Traceback (most recent call last): > File "", line 1, in ? > TypeError: 'bool' object is not callable > >>> > > My 2 cents... From skip at pobox.com Sun Apr 15 21:14:01 2007 From: skip at pobox.com (skip at pobox.com) Date: Sun, 15 Apr 2007 20:14:01 -0500 Subject: Portably generating infinity and NaN In-Reply-To: References: <462008d1$0$11763$9b622d9e@news.freenet.de> Message-ID: <17954.52697.17924.718089@montanaro.dyndns.org> Michael> Will float("NaN") work on these systems? (I don't know.) I Michael> guess it probably works on some system that isn't IEEE 754. My thought was that in configure you could test if strtof("NaN") and strtof("Inf") worked. If not, calculate the necessary bit patterns at that point and use conditional compilation in floatmodule.c to generate them. Skip From steve at holdenweb.com Tue Apr 24 10:00:51 2007 From: steve at holdenweb.com (Steve Holden) Date: Tue, 24 Apr 2007 10:00:51 -0400 Subject: Would You Write Python Articles or Screencasts for Money? In-Reply-To: <462DCCE6.9060908@taupro.com> References: <462DCCE6.9060908@taupro.com> Message-ID: <462E0D93.3090705@holdenweb.com> Jeff Rush wrote: > There is discussion by the Python Software Foundation of offering cash > bounties or perhaps periodic awards to the "best of" for magazine articles, > video/screencast clips and such. > > If YOU would be swayed to get involved in producing content in exchange for > cash, please speak up on the advocacy mailing list and also drop an email to > Steve Holden , current champion of this idea and looking > for encouragement. Ideas on how to evaluate contributions, how frequently to > do this and critical thresholds of cash amounts necessary to induce YOUR > participation are wanted. > Thanks for posting this, Jeff. I have already had a couple of replies. Allow me to expand on my current thinking before this gets off-track. Lest people be lulled into thinking that the PSF is going into the "articles for cash" business, let me say that isn't really the idea. I don't really think we will necessarily improve the quality of information about Python simply by throwing cash incentives at authors, and I was more looking for a way to reward authors of excellence, as judged by some subset of the Python community - this might have to be the PSF membership given the impracticality of running a meaningful poll with a larger set of voters. So the intention is not so much to encourage people who wouldn't otherwise write to start writing (desirable though this outcome might be, I don't think cash incentives are the right way to achieve it) but rather to reward *excellence* in Python writing and underline the fact that standards are important. There are many other possibilities too. What about an award for "most helpful responses on c.l.py" over some period? I think one of the reasons people find Python so useful is its helpful community, and it would be nice to see the tireless fielders of questions rewarded for their community contribution. However, these are only my ideas and I am open to any and all suggestions from the broader Python community about how awards might be used to provide incentives to improve the available information about Python, and possibly even the software that's available in Python. I have undertaken to make a proposal to the PSF Board for an incentive scheme. So please let me have your ideas. regards Steve -- Steve Holden +1 571 484 6266 +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 kyosohma at gmail.com Wed Apr 18 17:30:38 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: 18 Apr 2007 14:30:38 -0700 Subject: tkinter canvas In-Reply-To: References: Message-ID: <1176931838.804999.186070@n59g2000hsh.googlegroups.com> On Apr 18, 3:43 pm, Gigs_ wrote: > how to write text on canvas. i know that i need to use canvas.create_text, but > how to write text than when i create_text? > or how to access object ID in canvas and change some options? > > thanks in advance! All you need to do is canvas.create_text(x, y, text='Hello World') where x and y are coordinates on the canvas. You can also add fg and/ or bg to set foreground and background colors, respectively. Mike From yinglcs at gmail.com Sat Apr 28 14:53:51 2007 From: yinglcs at gmail.com (yinglcs at gmail.com) Date: 28 Apr 2007 11:53:51 -0700 Subject: how can I put an Exception as the key of a hash table Message-ID: <1177786431.935154.89510@y5g2000hsa.googlegroups.com> I want to keep track of the number of different exception happens in my python program: ErrorHash = {} try: # come code ... except Exception, e: print e errcode = e if (ErrorHash.has_key(errcode)): ErrorFailNo = ErrorHash[errcode] ErrorHash[errcode] = ErrorFailNo + 1 else: ErrorHash[errcode] = 1 But when i print out the ErrorHash like this: print ErrorHash i get an empty string. Can you please tell me how can I put an Exception as the key of a hash table ? Or how can i dump out all the content of the hashtable. Thank you. From a-alpha at otenet.gr Wed Apr 25 02:24:33 2007 From: a-alpha at otenet.gr (M M) Date: Wed, 25 Apr 2007 09:24:33 +0300 Subject: Angelina Joli Paris Hilton MARISA MILLER Message-ID: Angelina Joli Paris Hilton MARISA MILLER www.alphasearch.gr -------------- next part -------------- An HTML attachment was scrubbed... URL: From lorenzo at excitement.com Sun Apr 8 19:02:14 2007 From: lorenzo at excitement.com (Lorenzo) Date: Sun, 08 Apr 2007 18:02:14 -0500 Subject: How do I get a slice of a string held in a tuple? References: <25ine4-rvt.ln1@Hedley.internal.thethurmans.com> <1176050876.835238.68560@d57g2000hsg.googlegroups.com> <1176056948.721586.48460@o5g2000hsb.googlegroups.com> Message-ID: In article <1176056948.721586.48460 at o5g2000hsb.googlegroups.com>, "mensanator at aol.com" wrote: > On Apr 8, 12:29???pm, Lorenzo wrote: > > In article <1176050876.835238.68... at d57g2000hsg.googlegroups.com>, > > > > > > > > > > > > ?"mensana... at aol.com" wrote: > > > On Apr 8, 11:34?am, Lorenzo Thurman > > > wrote: > > > > I have tuple which hold a string in tup[0]. I want to get a slice of > > > > that string. I thought I would do something like: > > > > tup[0][start:end] > > > > But this fails. > > > > > No, it doesn't. > > > > > >>> a = ('abcdefg','hijkl') > > > >>> a[0] > > > 'abcdefg' > > > >>> a[0][1:2] > > > 'b' > > > > > > How do I go about it? > > > > > Do it correctly. Post your actual example that fails > > > and the related error message. Possibnly your indexes > > > were out of range. > > > > > > I googled this and found a couple > > > > of references, but no solution. > > > > > Well, there wouldn't be ?a solution to a non-existent > > > problem, would there? > > > > > > TIA > > > > Here's the code: > > > > ?elapsedTime = mydata[1] > > ?index = elapsedTime.find("real") > > ?# the index will have a value 0f 110 > > ?totaltime = elapsedTime[index:] > > ?# instead of this returning a shortened html string, i only > > ?# get the left angle bracket '<' > > This implies that '<' is the 111th character (counting > from 0) and that it is the last character since you used > [index:]. > > Print out the entire string elapsedTime, count from > 0 to the characters you want and see if you have the > correct index numbers (verify them). > > > > > > -- > > "My Break-Dancing days are over, but there's always the Funky Chicken" > > --The Full Monty Oops! I sent the wrong piece of code. The above is actually the work around which actually works. The bad code is this: index = mydata[0].find("real") elapsedTime = mydata[0][index:] My apologies, but this is what fails. -- "My Break-Dancing days are over, but there's always the Funky Chicken" --The Full Monty From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Fri Apr 20 14:30:29 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Fri, 20 Apr 2007 20:30:29 +0200 Subject: Python Feature Request: Explicit variable declarations References: <1176546078.934340.253810@y5g2000hsa.googlegroups.com> <1hwu43c.dp5yo01rsqhjfN%aleax@mac.com> Message-ID: <58sf65F2b1q8tU2@mid.individual.net> Dennis Lee Bieber wrote: > Unless it should be interpreted as (C/C)++, which would result in > 2 No, since postfix ++ "returns before and increments after". But what you say is true for ++(C/C). Regards, Bj?rn -- BOFH excuse #274: It was OK before you touched it. From ejensen at visi.com Fri Apr 6 11:16:44 2007 From: ejensen at visi.com (Ed Jensen) Date: Fri, 06 Apr 2007 15:16:44 -0000 Subject: Python and Java References: <131araimq483n27@corp.supernews.com> Message-ID: <131cp2sk7h45g43@corp.supernews.com> Steve Holden wrote: > Ed Jensen wrote: >> Steve Holden wrote: >>> Jython is an implementation of Python that compiles to Java bytecode, >>> but at the moment there's some version lag so it won't handle the mos >>> recent language enhancements. Probably worth a look, though. >>> >>> http://www.jython.org/ >> >> Does Jython compile to Java bytecode, or is Jython a Java >> implementation of a Python interpreter? > > Please read what I wrote again. I read it and understood it just fine. My question was meant more along the lines of, "Are you SURE it compiles to Java bytecode, and isn't a Python interpreter written in Java?" I guess I didn't make that clear. Anyway, I checked the Jython home page, and sure enough, Jython compiles Python code to Java bytecode, as stated in the FAQ which can be found at the following URL (in case anyone else reading this message is following along and is interested): http://www.jython.com/Project/userfaq.html#what-is-jython In particular: 1.1 What is Jython? Jython implements the Python programming language on the Java(tm) Platform. It consists of a compiler to compile Python source code down to Java bytecodes which can run directly on a JVM, a set of support libraries which are used by the compiled Java bytecodes, and extra support to make it trivial to use Java packages from within Jython. Sorry if I bothered/annoyed you, Steve. From steve at REMOVE.THIS.cybersource.com.au Sat Apr 21 01:35:04 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Sat, 21 Apr 2007 15:35:04 +1000 Subject: Significance of "start" parameter to string method "endswith" References: <1177016236.700474.16170@n59g2000hsh.googlegroups.com> <1177107716.353954.223460@p77g2000hsh.googlegroups.com> Message-ID: On Fri, 20 Apr 2007 23:20:39 -0300, Gabriel Genellina wrote: >>> ... but increases the care and attention required when coding: >> >> There are always trade-offs. > > ... and you still need more attention when replying - read again your own > reply :) D'oh! -- Steven. From ask at me Sat Apr 14 14:04:07 2007 From: ask at me (alf) Date: Sat, 14 Apr 2007 13:04:07 -0500 Subject: compiling modules with VS 2008 for python 2.4 prepared with Visual Studio 2003 In-Reply-To: <46210c73$0$15280$9b622d9e@news.freenet.de> References: <1hw2ak4.1cxnvt81nzd971N%aleax@mac.com> <461f1a5a$0$996$9b622d9e@news.freenet.de> <46210c73$0$15280$9b622d9e@news.freenet.de> Message-ID: <8OednbUcYt0FirzbnZ2dnUVZ_o2vnZ2d@comcast.com> Martin v. L?wis wrote: > You either would have to create a import library for mscvr71.dll > by hand, or you have to copy one from VS 2003 (breaking its license). I wonder if copying the probstat.pyd from internet where I it finnaly found is not breaking the license:-). it was my final solution. otherwise I would probaly it somehow link. I hardly give up. > P.S. Why does the subject say "VS 2008", anyway? That product has > not been released yet, and Microsoft is still hoping that it will > be called VS 2007. just a mistake. i am not Microsoft fan. Just happened that python app I develop is executed on win32. thx for all insight From steve at REMOVEME.cybersource.com.au Mon Apr 30 23:43:08 2007 From: steve at REMOVEME.cybersource.com.au (Steven D'Aprano) Date: Tue, 01 May 2007 13:43:08 +1000 Subject: Is it possible to merge xrange and slice? References: <1177956139.320184.50590@n76g2000hsh.googlegroups.com> Message-ID: On Mon, 30 Apr 2007 21:00:15 +0000, BJ?rn Lindqvist wrote: > On 30 Apr 2007 11:02:19 -0700, Bas wrote: >> stupid question, but would it be possible to somehow merge xrange >> (which is supposed to replace range in py3k) and slice? Both have very >> similar start, stop and step arguments and both are lightweight >> objects to indicate a range. But you can't do a[xrange(10,20)] and >> 'for i in slice(10,20)'. The only difference is see is some behavior >> with infinities (e.g. object[3:] gives a slice(3,maxint) inside >> _getitem_ , but I think this should not be a large problem >> (xrange(0,infinity) could just yield a generator that never stops). >> >> Which problems am I overlooking that prevent this? > > Novel idea but how would slice(3,-1) work? Since the semantics of slice and xrange are different, you get very different results: >>> slice(3, -1) slice(3, -1, None) >>> range(10)[3:-1] [3, 4, 5, 6, 7, 8] >>> xrange(3, -1) xrange(0) I don't see why you would want to mix'n'match slice objects and xrange objects like Bas wants. I *think* what he's imagining is that if you say something like: alist[5:10] # a slice from a list it should be the same as alist[xrange(5, 10)] That would, I think, only make sense if Python lists allowed sequence arguments for slicing, as well as ranges: alist[5] # gives the fifth element alist[5:11] # gives the fifth through tenth elements alist[5,7,10] # gives the 5th, 7th and 10th elements Then alist[xrange(5, 10)] would be the same as alist[5, 6, 7, 8, 9]. I can see that could be useful, especially if (like slicing) it was tolerant of errors. We could imagine list's __*slice__ methods accepting either a single integer index, a slice object, or a tuple object. The actual mechanics of what something like this would mean: del alist[2, 4, 7, 1, 1] I leave open. While this could be interesting, I'm not sure that it belongs in slicing. Although if not, that would mean growing three methods, a getter, a setter and a deleter. Hmmm. Maybe slicing should be extended to accept a sequence of indices... ... enough dreaming... even if list slicing accepted a sequence argument, passing an xrange object would not be the way to do it. That would be like replacing: result = alist[5:10] with: result = [] for i in (5, 6, 7, 8, 9): result.append(alist[i]) -- Steven D'Aprano From gagsl-py2 at yahoo.com.ar Thu Apr 5 17:49:29 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 05 Apr 2007 18:49:29 -0300 Subject: grandparent method with super References: <20070405161939.694d51a1@localhost> <20070405163845.2ffa8d32@localhost> <20070405171306.0264fb70@localhost> Message-ID: En Thu, 05 Apr 2007 18:13:06 -0300, Martin Manns escribi?: > On Thu, 5 Apr 2007 16:55:38 -0400 > "John Clark" wrote: >> Because the MRO isn't just a depth first traversal, the term "first >> grandparent" gets tricky to define... > > Not really. The first grandparent would be the first occurrence in the > list from left to right, which satisfies the requirement that its > shortest path to the current class is 2. > The only problem: How do I get it? Calling super() twice? F.mro()[1]? But really I don't think it's a good idea - depending on the *other* classes in your hierarchy, what you call "grandparent" may be almost anyone. If you *have* to bypass your parent, it feels like there is something wrong in the class hierarchy. -- Gabriel Genellina From kyosohma at gmail.com Tue Apr 3 09:42:26 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: 3 Apr 2007 06:42:26 -0700 Subject: print the screen shot in python In-Reply-To: <1175549083.627721.315170@y80g2000hsf.googlegroups.com> References: <1175549083.627721.315170@y80g2000hsf.googlegroups.com> Message-ID: <1175607746.643094.193320@q75g2000hsh.googlegroups.com> On Apr 2, 4:24 pm, "gslm" wrote: > Hi! > I want to print an application view in python.I use labels and frames > in my program.And ? want to know if it is possible to print all of the > view of my program? > Thanks a lot... You need to give us more details. Are you using wxPython, Tkinter, pyQT or what? And what version of python and OS? Do you want to take a picture of the programs interface and print that with Python? Mike From http Thu Apr 5 22:50:05 2007 From: http (Paul Rubin) Date: 05 Apr 2007 19:50:05 -0700 Subject: Welch essential for learning Tkinter well? References: Message-ID: <7x8xd6fc82.fsf@ruckus.brouhaha.com> Dick Moores writes: > In a couple of places recently I've seen Brent Welch's _Practical > Programming in Tcl & Tk_ () recommended for > learning Tkinter well. I'm skeptical of the value of learning Tkinter really well. No matter how thoroughly you learn it, your GUI's are going to look crude and have a limited widget set. For lots of applications, a basic GUI which implements the needed functions straightforwardly is fine and Tkinter is good for that kind of thing. I've used it that way based on the online tutorials and it's been good enough for my purposes. But if I needed something fancier I'd probably go to a more advanced toolkit rather than trying to push the limits of tkinter. I mainly use http://infohost.nmt.edu/tcc/help/pubs/tkinter/ as tkinter docs and it's pretty good. From iansan at gmail.com Thu Apr 19 19:35:42 2007 From: iansan at gmail.com (IamIan) Date: 19 Apr 2007 16:35:42 -0700 Subject: Nested dictionaries trouble In-Reply-To: References: <1176317876.917874.58040@n59g2000hsh.googlegroups.com> <1176325715.951076.4790@w1g2000hsg.googlegroups.com> <1176923772.011976.116190@p77g2000hsh.googlegroups.com> Message-ID: <1177025742.252000.231430@e65g2000hsc.googlegroups.com> Thank you again for the great suggestions. I have one final question about creating a httpMonths dictionary like {'Jan':'01' , 'Feb':'02' , etc} with a minimal amount of typing. My code follows (using Python 2.3.4): import calendar # Create years list, formatting as strings years = map(str, xrange(1990,2051)) # Create months list with three letter abbreviations months = list(calendar.month_abbr) # Create monthTotals dictionary with default value of zero monthTotals = dict.fromkeys(months[1:],0) # Create yearTotals dictionary with years for keys # and copies of the monthTotals dictionary for values yearTotals = dict([(year, monthTotals.copy()) for year in years]) # Create httpMonths dictionary to map month abbreviations # to Apache numeric month representations httpMonths = {"Jan":"01","Feb":"02","Mar":"03","Apr":"04","May":"05","Jun":"06","Jul":"07","Aug":"08","Sep":"09","Oct":"10","Nov":"11","Dec":"12"} It is this last step I'm referring to. I got close with: httpMonths = {} for month in months[1:]: httpMonths[month] = str(len(httpMonths)+1) but the month numbers are missing the leading zero for 01-09. Thanks! Ian From irstas at gmail.com Tue Apr 3 12:30:55 2007 From: irstas at gmail.com (irstas at gmail.com) Date: 3 Apr 2007 09:30:55 -0700 Subject: Retrieve an item from a dictionary using an arbitrary object as the key In-Reply-To: <1175617563.169153.150430@d57g2000hsg.googlegroups.com> References: <1175617563.169153.150430@d57g2000hsg.googlegroups.com> Message-ID: <1175617854.977507.236730@n59g2000hsh.googlegroups.com> On Apr 3, 7:26 pm, "abcd" wrote: > Hi, > I have a class such as, > > class Type: > def __init__(self, val): > self.val = val > > class Person: > def __init__(self, name, age): > self.name = name > self.age = age > > So I have a dictionary which maps an instance of Type to an instance > of Person. Now I need to retrieve a particular Person given a Type > object. What method in Type do I need to implement to allow it to be > retrieved? > > For example (this is just an example): > > t = Type(19) > p = Person("bob", 99) > > x = {t : p} > > ........ > > def getPerson(val): > return x[Type(val)] > > getPerson(19) ....should return me the Person with name "bob" and age > 99. I am thinking there is some method that is used by the dictionary > to know if the key exists, just not sure which. > > thanks You'll need __eq__ for testing if two objects are equivalent, and __hash__ for calculating object's hash value. class Type: def __init__(self, val): self.val = val def __eq__(self, other): return self.val == other.val def __hash__(self): return hash(self.val) From michael at jedimindworks.com Sun Apr 22 15:24:36 2007 From: michael at jedimindworks.com (Michael Bentley) Date: Sun, 22 Apr 2007 14:24:36 -0500 Subject: recursion depth problem In-Reply-To: <1177267774.416169.276780@e65g2000hsc.googlegroups.com> References: <1177267774.416169.276780@e65g2000hsc.googlegroups.com> Message-ID: On Apr 22, 2007, at 1:49 PM, proctor wrote: > i have a small function which mimics binary counting. it runs fine as > long as the input is not too long, but if i give it input longer than > 8 characters it gives > > RuntimeError: maximum recursion depth exceeded in cmp > > i'm not too sure what i am doing improperly. is there really a lot of > recursion in this code? > > ================== > > import sys > > def ch4(item, n=0): > if n < len(item): > if item[n] == '0': > item[n] = '1' > print ''.join(item) > ch4(item) > elif item[n] == '1': > item[n] = '0' > ch4(item, n+1) > > ch4(list(sys.argv[1])) > > ================== Yes. There really is *that* much recursion in that code. 502 levels with input length of 8 characters, 1013 with 9 characters, 2035 with 10 characters... There's a pattern there ;-) From kyosohma at gmail.com Mon Apr 30 15:44:48 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: 30 Apr 2007 12:44:48 -0700 Subject: re-importing modules In-Reply-To: <8%pZh.18192$Kd3.76@newssvr27.news.prodigy.net> References: <8%pZh.18192$Kd3.76@newssvr27.news.prodigy.net> Message-ID: <1177962288.575008.48490@q75g2000hsh.googlegroups.com> On Apr 30, 12:49 pm, "T. Crane" wrote: > Hi, > > When troubleshooting code that's saved in a text file, I often find that I > want to make a change to it, re-save it, then reimport it. However, just > typing > > import myTestCode > > doesn't always seem to import the newer version. Is it supposed to? I find > that right now I often have to close my iPython window, then reopen it and > import my recently modified code. I know this can't be the best way to do > this, but I don't know what is. > > any suggestions/help welcome and appreciated, > trevis Hi, Another person posted the same thing today. As with that person, you probably need to use the reload() function. See this post for more details: http://www.python.org/search/hypermail/python-1993/0342.html Mike From steve at holdenweb.com Tue Apr 24 12:17:17 2007 From: steve at holdenweb.com (Steve Holden) Date: Tue, 24 Apr 2007 12:17:17 -0400 Subject: [python-advocacy] Would You Write Python Articles or Screencasts for Money? In-Reply-To: References: <462DCCE6.9060908@taupro.com> <462E0D93.3090705@holdenweb.com> Message-ID: Facundo Batista wrote: > 2007/4/24, Steve Holden : > >> and I was more looking for a way to reward authors of excellence, as >> judged by some subset of the Python community - this might have to be >> the PSF membership given the impracticality of running a meaningful poll >> with a larger set of voters. > > Why? Because of spammers and/or false voters? > Among other complex possibilities, yes. > When I first read about this, I thought about a web page where anybody > could "propose" articles for voting, and anybody could vote them. > Monthly, an award goes for the top 1, and that article goes out from > the poll. > I think allowing anyone to *propose* the articles is a good idea. Where PSF money is concerned I am less happy about the prospect of anyone being allowed to vote. Particularly more than once :-) > Why can't that be done? > I don't necessarily believe that articles should stay on the list until they win an award - I'd like to see a regular cycle. There'd be nothing to stop the same article being proposed in several cycles, but repeated failure to win an award would definitely send a message to an article's sponsor(s), who would eventually stop proposing them. Is monthly too often? > Other point: what happens with all the non-english articles? Other categories? > There I'd have to call on the help of foreign Python user groups, and that might require more in the way of formal affiliation than the PSF has currently implemented. While I am not xenophobic I simply don't have the language skills to evaluate publications in other languages than English. But we certainly shouldn't forget them, and it might be nice to encourage translation efforts in both directions. > >> There are many other possibilities too. What about an award for "most >> helpful responses on c.l.py" over some period? I think one of the > > How do you evaluate such thing? I think this is too complicated... > You are possibly right. regards Steve -- Steve Holden +1 571 484 6266 +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 whamil1 at entergy.com Wed Apr 11 12:56:28 2007 From: whamil1 at entergy.com (Hamilton, William ) Date: Wed, 11 Apr 2007 11:56:28 -0500 Subject: pop() clarification In-Reply-To: Message-ID: <588D53831C701746A2DF46E365C018CE01D2CA6E@LITEXETSP001.etrsouth.corp.entergy.com> > -----Original Message----- > From: python-list-bounces+whamil1=entergy.com at python.org [mailto:python- > list-bounces+whamil1=entergy.com at python.org] On Behalf Of Scott > > I understand all that. What I don't understand is why all the > documentation > I see says, "When removing a specific element from a list using pop() it > must be in this format: list.pop([i]). > At first I took that to mean that list.pop(i) would return some type of > error, but it doesn't. > I can't find any documentation saying that this rule that I keep reading > about (again list.pop([i]) ) is the only format to use when removing a > specific element because......with the explaination to follow. I believe that the [i] notation is to indicate that it has to be a valid index to your list. If i isn't a valid index, you get an IndexError. >>> spam=['this', 'is', 'a', 'list'] >>> spam.pop(1) 'is' >>> spam.pop(4) Traceback (most recent call last): File "", line 1, in -toplevel- spam.pop(4) IndexError: pop index out of range --- -Bill Hamilton From apardon at forel.vub.ac.be Fri Apr 13 03:46:58 2007 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 13 Apr 2007 07:46:58 GMT Subject: tuples, index method, Python's design References: <1176210960.3430.20.camel@dot.uniqsys.com> <740c3aec0704100810g5f962e8eu614fbaedecf3608e@mail.gmail.com> <1176219856.3430.76.camel@dot.uniqsys.com> <740c3aec0704101021i1fd79ef2l99eac4ced1e252d9@mail.gmail.com> <1176226682.3430.86.camel@dot.uniqsys.com> <4866bea60704101104r4600d281h135286b66378f4d4@mail.gmail.com> <740c3aec0704101534y3c65f5a7je382f97e1f6301b7@mail.gmail.com> <1176305859.581010.199600@n76g2000hsh.googlegroups.com> Message-ID: On 2007-04-12, Steven D'Aprano wrote: > On Thu, 12 Apr 2007 07:37:38 +0000, Antoon Pardon wrote: > >> I once had a problem I like to solve by having a dictionary >> where the keys were multidimensional points on an integer grid. >> For a number of reasons I thought it would be easier if I could >> use lists, but most people argued that would be a bad idea and >> that I should use tuples, because they are immutable. > > Also because code that raises "TypeError: list objects are unhashable" is > probably not going to work very well. > > >> Of course if I now would want to find out if the point is on an axis and >> which axis that is, I cannot use index because that is not available. > > If memory is more important to you than speed: > > class IndexTuple(tuple): > def index(self, target): > for i, x in enumerate(self): > if x == target: return i > raise ValueError > > Or if speed is more important to you than memory: > > class IndexTuple2(tuple): > def index(self, target): > return list(self).index(target) > > If you prefer not to subclass, you can write an index function: > > def index(sequence_or_mapping, target): > try: > return sequence_or_mapping.index(target) > except AttributeError: > return list(sequence_or_mapping).index(target) > > > So much fuss over such a little thing... yes it would be nice if tuples > grew an index method, but it isn't hard to work around the lack. Yes it is a little thing. But if it is such a little thing why do the developers don't simply add it? Python like any other human product has it shortcomings. I can live with them. If a wart turns up and the general answer would be, yes we know it is a wart but it is the result of how python grew or it was the best compromise we could think of and too much depends on it now to change it. This kind of threads would die quickly. Instead we often enough see the warts getting defended as good design. -- Antoon Pardon From detlev at die-offenbachs.de Sat Apr 21 08:18:58 2007 From: detlev at die-offenbachs.de (Detlev Offenbach) Date: Sat, 21 Apr 2007 14:18:58 +0200 Subject: ANN: eric3 version 3.9.5 released Message-ID: Hi, this is to inform you about the release of eric3 version 3.9.5. This release fixes a few bugs and includes an updated PyLint interface. As usual it is available via http://www.die-offenbachs.de/detlev/eric.html Regards, Detlev -- Detlev Offenbach detlev at die-offenbachs.de From steve at holdenweb.com Sun Apr 22 21:01:02 2007 From: steve at holdenweb.com (Steve Holden) Date: Sun, 22 Apr 2007 21:01:02 -0400 Subject: Can __init__ not return an object? In-Reply-To: References: Message-ID: Steven W. Orr wrote: > When I go to create an object I want to be able to decide whether the > object is valid or not in __init__, and if not, I want the constructor to > return something other than an object, (like maybe None). I seem to be > having problems. At the end of __init__ I say (something like) > > if self.something < minvalue: > del self > return None > > and it doesn't work. I first tried just the return None, then I got crafty > and tried the del self. Is what I'm trying to do possible in the > constructor or do I have to check after I return? Or would raising an > exception in the constructor be appropriate? > > Am I even being clear? > The trouble you have is that it's too late by the time you get to __init__. The object has been created. The reason that "del self" doesn't work is that all it does is remove the local name "self" from the namespace of the method - you will find that if __init__ returns anything *except* None you get an exception. Don't think of __init__ as a constructor - that's __new__, which *is* expected to return a newly-created instance. Raising an exception in __init__ is perfectly permissible, but adopting the new-style classes (inheriting from object) might give you a more efficient solution to your 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 aleax at mac.com Sat Apr 21 20:04:03 2007 From: aleax at mac.com (Alex Martelli) Date: Sat, 21 Apr 2007 17:04:03 -0700 Subject: Python for Vcard Parsing in UTF16 References: <132l7inssigkted@corp.supernews.com> Message-ID: <1hwxj91.8glol65h3dmhN%aleax@mac.com> R Wood wrote: ... > alias Linus_Torvalds Linus Torvalds > > To me this was a natural task for Perl. Turns out however, there's a catch. > Apple exports the file in UTF-16 to ensure anyone with Chinese characters in > their addressbook gets a legitimate Vcard file. And of course Perl somewhat > chokes on UTF. I've found several ways to do it that involve complicated > downloads and installations of Perl modules, but that defeats the purpose of > making it simple. In an ideal world you should be able to say "try this cool > script" and be done with it. Once you have to say "go to CPAN, download and > compile this module, then ..." it gets less exciting. > > I know nothing about Python except that it interests me and has interested me > since I first learned the Rekall database frontend (Linux) runs on it. I just > ordered Learning Python and if that works out satisfactorily I'm going to go > back for Programming Python. In the meantime, I thought I would pose the > question to this newsgroup: would Python be useful for a parsing exercise like > this one? Sure, Python and Perl (and Ruby) should be equally suitable for the task, so, if Python appears more suitable by having built-in unicode capabilities, go for it. I'm a bit uncertain about the UTF-16 export though; I know some applications do use it (e.g., Microsoft Entourage), but I thought Apple's Address Book didn't, and, having just tried a VCard export from mine, it looks quite ASCII to me. Maybe you've set some kind of preference, or...? Alex From alberto at toscat.net Sun Apr 22 17:41:29 2007 From: alberto at toscat.net (Alberto Valverde) Date: 22 Apr 2007 14:41:29 -0700 Subject: file.read() returns an emtpy even if its currenet position is not at the end In-Reply-To: References: Message-ID: <1177278089.827367.18720@e65g2000hsc.googlegroups.com> On Apr 22, 6:51 pm, "js " wrote: > Hi list. > > I'm writing a tail -f like program in python > and I found file.read() doesn't work as I think it should. > > Here's the code illustrating my problem. > > ### > #!/usr/bin/env python > import os, sys > filename = "test.out" > > f = open(filename, "w+") > f.write("Hello") > f.flush() > > f.seek(0, 2) > > statinfo = os.stat(filename) > print "file size: %d" % statinfo.st_size > print "position : %d" % f.tell() > line = f.read() > print "line : [%s]" % line > > # Writing the same file using another fd > f2 = open(filename, "a+") > f2.write("World") > f2.flush() > f2.close() > > statinfo = os.stat(filename) > print "file size: %d" % statinfo.st_size > print "position : %d" % f.tell() > line = f.read() # read() returns emtpy!! readlines?() works ok > ### > > Running the above, I got the following. > ### > file size: 5 > position : 5 > line : [] > file size: 10 > position : 5 > ### > > So my question is > why the second f.read() returns an emtpy?>From tell() and its st_size I'm sure that file descriptor is not at the EOF > > and read()'s doc says > "An empty string is returned when EOF is encountered immediately". > Using readline() or readlines() instead of read() works great though. > > I'm using Python 2.4.3 on OS X. > > Probably I'm missing something but I could't figure out. > > Thanks in advance. I've hit into the same issue recently when implementing more or less the same thing and found that doing f.seek(f.tell()) on the file object when empty strings start to come out allows you to continue read()ing after hitting EOF if the file grows again. I finally dropped the "hack" and used readline instead since it made me a little bit uneasy though... Alberto From redtiger84 at googlemail.com Fri Apr 6 10:31:34 2007 From: redtiger84 at googlemail.com (Christoph Krammer) Date: 6 Apr 2007 07:31:34 -0700 Subject: How to access multiple group matches? Message-ID: <1175869893.960239.194850@p77g2000hsh.googlegroups.com> Hello, I want to use the re module to split a data stream that consists of several blocks of data. I use the following code: iter = re.finditer('^(HEADER\n.*)+$', data) The data variable contains binary data that has the word HEADER in it in some places and binary data after this word till the next appearance of header or the end of the file. But if I iterate over iter, I only get one match and this match only contains one group. How to access the other matches? Data may contain tens of them. Thanks in advance, Christoph From mmanns at gmx.net Sat Apr 14 21:54:41 2007 From: mmanns at gmx.net (Martin Manns) Date: Sat, 14 Apr 2007 21:54:41 -0400 Subject: Method calls and stack consumption Message-ID: Hi, Calling methods of other object instances seems quite expensive on the stack (see example below). Is there a better way of traversing through methods of instances that are connected in a cyclic graph? (The real program's graph contains multiple successors in lists.) class A(object): def __init__(self): self.i = 0 def a(self): if self.i % 1000 == 0: print self.i self.i += 1 return S[self].a() a = A() b = A() S = {a:b, b:a} import sys sys.setrecursionlimit(1000000) print a.a() 0 0 1000 1000 [...] 69000 69000 Segmentation fault ~ $ ulimit -s 65536 ~ $ Thus, each call seems to be about 480 bytes on the stack. Is there a good way to reduce stack consumption per call? Could and should I resort to stackless? If yes, how can the graph structure be realized? Would I need a tasklet for each instance? I am currently hesitant to depend on something from svn. How stable and robust is stackless? Martin From pythoncurious at gmail.com Tue Apr 17 03:47:11 2007 From: pythoncurious at gmail.com (pythoncurious at gmail.com) Date: 17 Apr 2007 00:47:11 -0700 Subject: script for seconds in given month? In-Reply-To: <1hwokmz.1ropcwj17pg55dN%aleax@mac.com> References: <1176740556.859125.221980@l77g2000hsb.googlegroups.com> <1hwokmz.1ropcwj17pg55dN%aleax@mac.com> Message-ID: <1176796031.889407.323950@b75g2000hsg.googlegroups.com> On Apr 17, 6:41 am, a... at mac.com (Alex Martelli) wrote: > edfialk wrote: > > Hi, does anyone happen to know of ascriptthat would return the > > number ofsecondsin amonthif I give it amonthand a year? > > > My python is a little weak, but if anyone could offer some suggestions > > I think I could handle it myself, or if anyone happens to know of a > >scriptalready written that performs this I would be extremely > > grateful. > > import calendar > > def seconds_in_month(month, year): > nomatter, daysinmonth = calendar.monthrange(year,month) > return daysinmonth * 24 * 60 * 60 > > Alex That works if you define the number of seconds in a month a the number of days * 24 * 60 * 60. If you have DST then that's not always the truth. The difference in seconds (clock time) is according to your example, but the number of seconds that passed during the month differs. Not sure which one was requested in the original post though. From bj_666 at gmx.net Tue Apr 10 18:04:10 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Wed, 11 Apr 2007 00:04:10 +0200 Subject: menu drop down icons (inactive) look horrible in Windows Classic Theme References: <1176241554.152632.79090@o5g2000hsb.googlegroups.com> Message-ID: In <1176241554.152632.79090 at o5g2000hsb.googlegroups.com>, ilikewine wrote: > The menu drop down icons (only the gray inactive icons) look horrible > in Windows Classic Theme. Once they are active and have color, they > look fine. If we switch to XP theme, they look just fine. Anyone else > run into this problem with python rewriting "shotty" inactive icons in > the Windows Classic Theme? > > ANY help appreciated. What the heck are you talking about? Tkinter? Ciao, Marc 'BlackJack' Rintsch From gil.horen at gmail.com Wed Apr 4 09:01:18 2007 From: gil.horen at gmail.com (Gil_H) Date: 4 Apr 2007 06:01:18 -0700 Subject: Pexpect: SSH, Command and Password In-Reply-To: References: <1175685883.565899.282450@q75g2000hsh.googlegroups.com> Message-ID: <1175691678.778259.26230@n76g2000hsh.googlegroups.com> On 4 Apr, 15:14, Ganesan Rajagopal wrote: > >>>>> "Gil" == Gil H writes: > > classSSH: > > def __init__(self, user, password, host): > > self.child =pexpect.spawn("ssh%s@%s"%(user, host)) > > Try adding the following line here > > self.child.logfile = sys.stdout > > That should give you some clue. > > Ganesan > > -- > Ganesan Rajagopal Thanks, That's all i needed! From aisaac at american.edu Thu Apr 19 12:54:36 2007 From: aisaac at american.edu (Alan Isaac) Date: Thu, 19 Apr 2007 16:54:36 GMT Subject: comparison with None References: <_JAVh.1700$jR5.897@trnddc08> <462709FB.9020607@gmail.com> Message-ID: "Steve Holden" wrote in message news:mailman.6711.1176985146.32031.python-list at python.org... > Steven Howe wrote: > > Alan Isaac wrote: [type comparison stuff] > > I love scripting languages ... but sometimes an explicit evaluation that > > one would find in > > a compiled language is better. Actually all that language is Steve Howe's, not mine. (Just to be clear.) Alan Isaac From pekka.jarvinen at gmail.com Thu Apr 19 21:32:24 2007 From: pekka.jarvinen at gmail.com (=?iso-8859-15?q?Pekka_J=E4rvinen?=) Date: 19 Apr 2007 18:32:24 -0700 Subject: Calculating CIDR blocks Message-ID: <1177032744.375099.248380@q75g2000hsh.googlegroups.com> # I have list of free IP addresses. One IP per line. Now I'm trying to # share them to CIDR blocks /24 - /32. For example: if 1.1.1.0 - 1.1.1.255 # is free, it returns list['1.1.1.0/24'] but let's say that 1.1.1.1 is # used, then function should return list['1.1.1.128/25', # '1.1.1.127/26', '1.1.1.32/27', etc until free block doesn't fit]. import string import network # http://cheeseshop.python.org/pypi/Adytum-NetCIDR/0.0.1 ips = ['192.168.0.0', '192.168.0.1', '192.168.0.2', '192.168.0.3', '192.168.0.4', '192.168.0.5', '192.168.0.6', '192.168.0.7', '192.168.0.8', '192.168.0.9', '192.168.0.10', '192.168.0.11', '192.168.0.12', '192.168.0.13', '192.168.0.14', '192.168.0.15', '192.168.0.16', '192.168.0.17', '192.168.0.18', '192.168.0.19', '192.168.0.20', '192.168.0.21', '192.168.0.22', '192.168.0.23', '192.168.0.24', '192.168.0.25', '192.168.0.26', '192.168.0.27', '192.168.0.28', '192.168.0.29', '192.168.0.30', '192.168.0.31', '192.168.0.32', '192.168.0.33', '192.168.0.34', '192.168.0.35', '192.168.0.36', '192.168.0.37', '192.168.0.38', '192.168.0.39', '192.168.0.40', '192.168.0.41', '192.168.0.42', '192.168.0.43', '192.168.0.44', '192.168.0.45', '192.168.0.46', '192.168.0.47', '192.168.0.48', '192.168.0.49', '192.168.0.50', '192.168.0.51', '192.168.0.52', '192.168.0.53', '192.168.0.54', '192.168.0.55', '192.168.0.56', '192.168.0.57', '192.168.0.58', '192.168.0.59', '192.168.0.60', '192.168.0.61', '192.168.0.62', '192.168.0.63', '192.168.0.64', '192.168.0.65', '192.168.0.66', '192.168.0.67', '192.168.0.68', '192.168.0.69', '192.168.0.70', '192.168.0.71', '192.168.0.72', '192.168.0.73', '192.168.0.74', '192.168.0.75', '192.168.0.76', '192.168.0.77', '192.168.0.78', '192.168.0.79', '192.168.0.80', '192.168.0.81', '192.168.0.82', '192.168.0.83', '192.168.0.84', '192.168.0.85', '192.168.0.86', '192.168.0.87', '192.168.0.88', '192.168.0.89', '192.168.0.90', '192.168.0.91', '192.168.0.92', '192.168.0.93', '192.168.0.94', '192.168.0.95', '192.168.0.96', '192.168.0.97', '192.168.0.98','192.168.0.99', '192.168.0.100', '192.168.0.101', '192.168.0.102', '192.168.0.103', '192.168.0.104', '192.168.0.105', '192.168.0.106', '192.168.0.107', '192.168.0.108', '192.168.0.109', '192.168.0.110', '192.168.0.112', '192.168.0.113', '192.168.0.114', '192.168.0.115', '192.168.0.116', '192.168.0.117', '192.168.0.118', '192.168.0.119', '192.168.0.120', '192.168.0.121', '192.168.0.122', '192.168.0.123', '192.168.0.124', '192.168.0.125', '192.168.0.126', '192.168.0.127', '192.168.0.128', '192.168.0.129', '192.168.0.130', '192.168.0.131', '192.168.0.132', '192.168.0.133', '192.168.0.134', '192.168.0.135', '192.168.0.136', '192.168.0.137', '192.168.0.138', '192.168.0.139', '192.168.0.140', '192.168.0.141', '192.168.0.142', '192.168.0.143', '192.168.0.144', '192.168.0.145', '192.168.0.146', '192.168.0.147', '192.168.0.148', '192.168.0.149', '192.168.0.150', '192.168.0.151', '192.168.0.152', '192.168.0.153', '192.168.0.154', '192.168.0.155', '192.168.0.156', '192.168.0.157', '192.168.0.158', '192.168.0.159', '192.168.0.160', '192.168.0.161', '192.168.0.162', '192.168.0.163', '192.168.0.164', '192.168.0.165', '192.168.0.166', '192.168.0.167', '192.168.0.168', '192.168.0.169', '192.168.0.170', '192.168.0.171', '192.168.0.172', '192.168.0.173', '192.168.0.174', '192.168.0.175', '192.168.0.176', '192.168.0.177', '192.168.0.178', '192.168.0.179', '192.168.0.180', '192.168.0.181', '192.168.0.182', '192.168.0.183', '192.168.0.184', '192.168.0.185', '192.168.0.186', '192.168.0.187', '192.168.0.188', '192.168.0.189', '192.168.0.190', '192.168.0.191', '192.168.0.192', '192.168.0.193', '192.168.0.194', '192.168.0.195', '192.168.0.196', '192.168.0.197', '192.168.0.198', '192.168.0.199', '192.168.0.200', '192.168.0.201', '192.168.0.202', '192.168.0.203', '192.168.0.204', '192.168.0.205', '192.168.0.206', '192.168.0.207', '192.168.0.208', '192.168.0.209', '192.168.0.210', '192.168.0.211', '192.168.0.212', '192.168.0.213', '192.168.0.214', '192.168.0.215', '192.168.0.216', '192.168.0.217', '192.168.0.218', '192.168.0.219', '192.168.0.220', '192.168.0.221', '192.168.0.222', '192.168.0.223', '192.168.0.224', '192.168.0.225', '192.168.0.226', '192.168.0.227', '192.168.0.228', '192.168.0.229', '192.168.0.230', '192.168.0.231', '192.168.0.232', '192.168.0.233', '192.168.0.234', '192.168.0.235', '192.168.0.236', '192.168.0.237', '192.168.0.238', '192.168.0.239', '192.168.0.240', '192.168.0.241', '192.168.0.242', '192.168.0.243', '192.168.0.244', '192.168.0.245', '192.168.0.246', '192.168.0.247', '192.168.0.248', '192.168.0.249', '192.168.0.250', '192.168.0.251', '192.168.0.252', '192.168.0.253', '192.168.0.254', '192.168.0.255'] # note: 192.168.0.111 is missing cidrs = [24, 25, 26, 27, 28, 29, 30, 31, 32] free = [] for cidr in cidrs: c = 0 for ip in ips: ip_addr = network.CIDR("%s/32" % ip) my_network = "%s/%d" % (ip, cidr) network_CIDR = network.CIDR(my_network) myn = network.Networks([network_CIDR]) freelist = [] if len(free) > 0: for i in free: freelist.append(network.CIDR("%s" % i)) freeh = network.Networks(freelist) net_len = network_CIDR.getHostCount() if ip_addr in myn and ip_addr not in freeh: c = c + 1 if c == net_len: hr = network.CIDR(my_network).getHostRange() free.append("%s/%s" % (hr[0], cidr)) c = 0 print free # Outputs: # ['192.168.0.128/25', '192.168.0.64/26', '192.168.0.32/27', '192.168.0.16/28', '192.168.0.8/29', '192.168.0.4/30'] # That 192.168.0.64/26 cannot be there because it's 192.168.0.64 - 192.168.0.127 and 192.168.0.111 does not exist in ips list! # Any ideas? From steve at holdenweb.com Tue Apr 24 12:26:03 2007 From: steve at holdenweb.com (Steve Holden) Date: Tue, 24 Apr 2007 12:26:03 -0400 Subject: noob questions In-Reply-To: <1177428999.023481.98160@b40g2000prd.googlegroups.com> References: <1177428999.023481.98160@b40g2000prd.googlegroups.com> Message-ID: T.Crane wrote: > I'm new to python and I seem to get different behavior depending on... > well who knows what. Here's my question concerning importation of > packages/modules. > > I want to use scipy. So at the prompt (using iPython, installed with > Enthought edition on Windows XP) I type: > > ln [1]: from scipy import * > > Now, I know integrate is a package this is in scipy. I want to use > the ode class/module that's in integrate. So I type: > > ln [2]: from integrate import * > > And I'm told > > ImportError: No module named integrate > > In order to get access to the ode class, I end up having to type: > > ln [3]: from scipy.integrate import * > > Then it works. Will someone explain to me what I'm misunderstanding? > I don't understand why after importing everything in scipy (which > includes integrate), I was told there was no module named integrate. > What gives? I there are sevarl functions (modules) that I want to use > that are a few levels down from the root package, what's the most > economical method of importing them? > > Any clarification would be appreciated. > Remember that scipy is a *package*. So when you say you have "imported everything in scipy" that's not necessarily the case. You have imported the scipy package, which has run the __init__.py in the package's base directory. This doesn't necessarily do anything for scipy.integrate. The statement from integrate import * tells the interpreter to search its sys.path looking for a module or package called integrate. Just having imported scipy doesn't change sys.path to put subdirectories of the scipy package's base directory onto the path. from scipy.integrate import * however, tells the interpreter to look for a module or package *inside a module or package called scipy* that can be found in one of the directories on sys.path. Since the first import worked, and because scipy is a package not just a plain module, this correctly locates the integrate module (or package). By the way, be careful with those from xxx import * statements. If scipy is specifically designed to support such usage then you should be OK, but in general this can "pollute" your namespace by bringing in all the names defined in the imported package or module within your local namespace. This might overwrite bindings you have already made within that namespace. Just a point to watch. regards Steve -- Steve Holden +1 571 484 6266 +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 rwood at therandymon.com Fri Apr 20 22:07:44 2007 From: rwood at therandymon.com (R Wood) Date: Sat, 21 Apr 2007 03:07:44 +0100 Subject: Python for Vcard Parsing in UTF16 References: <132l7inssigkted@corp.supernews.com> <1hwxj91.8glol65h3dmhN%aleax@mac.com> Message-ID: <132m7qe8apdene9@corp.supernews.com> Alex Martelli wrote: > R Wood wrote: > ... >> alias Linus_Torvalds Linus Torvalds >> >> To me this was a natural task for Perl. Turns out however, there's a >> catch. Apple exports the file in UTF-16 to ensure anyone with Chinese >> characters in >> their addressbook gets a legitimate Vcard file. And of course Perl >> somewhat >> chokes on UTF. > > Sure, Python and Perl (and Ruby) should be equally suitable for the > task, so, if Python appears more suitable by having built-in unicode > capabilities, go for it. I'm a bit uncertain about the UTF-16 export > though; I know some applications do use it (e.g., Microsoft Entourage), > but I thought Apple's Address Book didn't, and, having just tried a > VCard export from mine, it looks quite ASCII to me. Maybe you've set > some kind of preference, or...? > > > Alex I did the same thing. Apple's clever. If your addressbook doesn't have any higher characters, ie nothing but ASCII, it will export your addressbook in ASCII. But if you have anything else (in my case, Spanish, French, and Italian) it goes for UTF16. I first thought it was UTF8 but realized since Apple supports all sorts of Asian languages really well they need UTF16 to deal with it, and importing the exported file into Jedit using UTF16 encoding confirmed that's what it is. From tkpmep at hotmail.com Thu Apr 26 15:36:51 2007 From: tkpmep at hotmail.com (tkpmep at hotmail.com) Date: 26 Apr 2007 12:36:51 -0700 Subject: Generalized range In-Reply-To: References: <1177598743.352743.290730@t39g2000prd.googlegroups.com> Message-ID: <1177616211.476888.38360@r30g2000prh.googlegroups.com> Thanks - you have covered a fair bit of gorund here - I will modify myRange taking your suggestions into account. The one suggestion that I'm going to have to think through is repeatedly incrementing res. I deliberately did not use this as repeated addition can cause rounding errors to accumulate, making the loop run a little longer or shorter than necessary. I thought I would be far less likely to run into rounding issues with a multiplicative construct - hence my use of epsilon, and my question about an appropriate value for it From torbenm at app-5.diku.dk Mon Apr 16 05:16:19 2007 From: torbenm at app-5.diku.dk (Torben =?iso-8859-1?Q?=C6gidius?= Mogensen) Date: Mon, 16 Apr 2007 11:16:19 +0200 Subject: is laziness a programer's virtue? References: <1176654319.273907.167280@q75g2000hsh.googlegroups.com> Message-ID: <7zr6qk1xy4.fsf@app-5.diku.dk> Dan Bensen writes: > Xah Lee wrote: >> Laziness, Perl, and Larry Wall >> When the sorcerer Larry Wall said ???The three chief virtues of a >> programmer are: Laziness, Impatience and Hubris???, he used the word >> ???laziness??? to loosely imply ???natural disposition that results in being >> economic???. > > Programming by definition is the process of automating repetitive > actions to reduce the human effort required to perform them. A good > programmer faced with a hard problem always looks for ways to make > his|her job easier by delegating work to a computer. That's what > Larry means. Automation is MUCH more effective than repetition. Indeed. A programmer is someone who, after doing similar tasks by hand a few times, writes a program to do it. This extends to programming tasks, so after writing similar programs a few times, a (good) programmer will use programming to make writing future similar programs easier. This can be by abstracting the essence of the task into library functions so new programs are just sequences of parameterized calls to these, or it can be by writing a program generator (such as a parser generator) or it can be by designing a domain-specific language and writing a compiler or interpreter for this. Torben From mail at microcorp.co.za Wed Apr 4 02:37:30 2007 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Wed, 4 Apr 2007 08:37:30 +0200 Subject: how to remove multiple occurrences of a string within a list? References: <1175624433.206953.214290@n59g2000hsh.googlegroups.com><1175625098.269660.184790@o5g2000hsb.googlegroups.com> <1175627593.307674.11280@w1g2000hsg.googlegroups.com> Message-ID: <024b01c77685$3eed1040$03000080@hendrik> "bahoo" wrote: > On Apr 3, 2:31 pm, "Matimus" wrote: > > It depends on your application, but a 'set' might really be what you > > want, as opposed to a list. > > > > >>> s = set(["0024","haha","0024"]) > > >>> s > > > > set(["0024","haha"])>>> s.remove("0024") > > >>> s > > > > set(["haha"]) > > This sounds cool. > But is there a command I can convert the "set" back to a "list"? > Here is a general way to find the duplicates: >>> duplist [1, 2, 3, 4, 'haha', 1, 2, 3, 4, 5] >>> copylist = duplist[:] >>> for x in duplist: del(copylist[copylist.index(x)]) if x in copylist: fullset.remove(x) >>> fullset set([5, 'haha']) >>> list(fullset) [5, 'haha'] >>> hth - Hendrik From steven.bethard at gmail.com Mon Apr 30 11:11:34 2007 From: steven.bethard at gmail.com (Steven Bethard) Date: Mon, 30 Apr 2007 09:11:34 -0600 Subject: regexp match string with word1 and not word2 In-Reply-To: <1177920984.247487.54620@c35g2000hsg.googlegroups.com> References: <1177920984.247487.54620@c35g2000hsg.googlegroups.com> Message-ID: <9rGdnQGHaNy1mqvbnZ2dnUVZ_v_inZ2d@comcast.com> Flyzone wrote: > Hello, > i have again problem with regexp :-P > I need to match all lines that contain one word but not contain > another. > Like to do "grep one | grep -v two:" You don't need a regexp:; if 'one' in line and 'two:' not in line: ... do something... STeVe From rzantow at gmail.com Sat Apr 21 09:31:44 2007 From: rzantow at gmail.com (rzed) Date: Sat, 21 Apr 2007 13:31:44 +0000 Subject: Nested dictionaries trouble References: <1176317876.917874.58040@n59g2000hsh.googlegroups.com> <1176325715.951076.4790@w1g2000hsg.googlegroups.com> <1176923772.011976.116190@p77g2000hsh.googlegroups.com> <1177025742.252000.231430@e65g2000hsc.googlegroups.com> Message-ID: IamIan wrote in news:1177025742.252000.231430 at e65g2000hsc.googlegroups.com: > Thank you again for the great suggestions. I have one final > question about creating a httpMonths dictionary like {'Jan':'01' > , 'Feb':'02' , etc} with a minimal amount of typing. My code > follows (using Python 2.3.4): > > import calendar > > # Create years list, formatting as strings > years = map(str, xrange(1990,2051)) > > # Create months list with three letter abbreviations > months = list(calendar.month_abbr) > > # Create monthTotals dictionary with default value of zero > monthTotals = dict.fromkeys(months[1:],0) > > # Create yearTotals dictionary with years for keys > # and copies of the monthTotals dictionary for values > yearTotals = dict([(year, monthTotals.copy()) for year in > years]) > > # Create httpMonths dictionary to map month abbreviations > # to Apache numeric month representations > httpMonths = > {"Jan":"01","Feb":"02","Mar":"03","Apr":"04","May":"05","Jun":"0 6 > ","Jul":"07","Aug":"08","Sep":"09","Oct":"10","Nov":"11","Dec":" 1 > 2"} > > It is this last step I'm referring to. I got close with: > httpMonths = {} > for month in months[1:]: > httpMonths[month] = str(len(httpMonths)+1) > > but the month numbers are missing the leading zero for 01-09. > Thanks! > Maybe something like: httpMonths = dict((k,"%02d" % (x+1)) for x,k in enumerate(months[1:]) ) -- rzed From __peter__ at web.de Thu Apr 26 12:08:21 2007 From: __peter__ at web.de (Peter Otten) Date: Thu, 26 Apr 2007 18:08:21 +0200 Subject: function object.func_default off the console References: <1177601163.140674.108320@t39g2000prd.googlegroups.com> Message-ID: castironpi at gmail.com wrote: > On Apr 25, 1:56 am, Peter Otten <__pete... at web.de> wrote: >> Aaron Brady wrote: >> >>>> f.func_defaults[0] >> > [2, 3] >> >>>> f.func_defaults[0]+=[4] >> > Traceback (most recent call last): >> > File "", line 1, in >> > TypeError: 'tuple' object does not support item assignment >> >>>> f.func_defaults[0] >> > [2, 3, 4] >> >> > V. interesting. Operation succeeds but with a throw. Er, raise. >> >> This is not specific to func_defaults: >> >> >>> t = ([1],) >> >>> t[0] += [2] >> >> Traceback (most recent call last): >> File "", line 1, in >> TypeError: 'tuple' object does not support item assignment>>> t >> >> ([1, 2],) >> >> t[0] += [2] >> >> is resolved to >> >> t.__setitem__(t[0].__iadd__([2])) >> >> where list.__iadd__() succeeds but __setitem__() fails (because tuples >> don't have that method). >> >> Peter > > Curious why t.__setitem__ is called. Wouldn't it still refer to the > same list? How is Python to know? Consider >>> items = [[], 0] >>> items[0] += [42] # could do without __setitem__() >>> items[1] += 42 # __setitem__() required >>> items [[42], 42] When the item is immutable the += operation can only work by replacing it with another value. Peter From steve at REMOVE.THIS.cybersource.com.au Sun Apr 15 18:09:21 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Mon, 16 Apr 2007 08:09:21 +1000 Subject: combination function in python References: <1176615838.830315.160210@b75g2000hsg.googlegroups.com> <1176629911.409257.149780@l77g2000hsb.googlegroups.com> <1176654363.696340.283330@d57g2000hsg.googlegroups.com> <1176665609.470089.211190@y80g2000hsf.googlegroups.com> <1176670718.329927.288920@l77g2000hsb.googlegroups.com> Message-ID: On Sun, 15 Apr 2007 13:58:38 -0700, Mark Dickinson wrote: > ... for large n and k it's difficult to imagine any real-world > applications that wouldn't be better served by using the lngamma > function instead. That is, the natural log of n choose k can be > computed much more quickly as > > lngamma(n+1) - lngamma(k+1) - lngamma(n-k+1) Yes, but if you actually want the number of combinations, not the log of the number of combinations, you then have to raise e to that power to get the answer you want -- and that takes time. Is it still faster? How about round-off error due to floating point? Should you be truncating or rounding? What about overflow error for large enough n, k? What exactly are we doing with a five hundred digit long integer anyway? Exact (long) integer maths still is useful. > I assume that lngamma is implemented somewhere in either numpy or > scipy, but right now I can't find it... You know what they say about what happens when you ASS_U_ME :-) -- Steven. From robert.rawlins at thinkbluemedia.co.uk Mon Apr 30 05:05:40 2007 From: robert.rawlins at thinkbluemedia.co.uk (Robert Rawlins - Think Blue) Date: Mon, 30 Apr 2007 10:05:40 +0100 Subject: Dict Copy & Compare In-Reply-To: <4635AB95.4010309@timgolden.me.uk> References: <00da01c78b01$3e80b900$bb822b00$@rawlins@thinkbluemedia.co.uk> <4635AB95.4010309@timgolden.me.uk> Message-ID: <000601c78b06$b9fb0950$2df11bf0$@rawlins@thinkbluemedia.co.uk> Thanks for that Tim, The first part for copying the dict seems to work nicely but I'm struggling to get the second part working properly. Let me explain a little more specifically what I'm trying to do. I have two dicts, one named 'this' and the other named 'that'. I want to get all the unique keys from 'this' and log them into a file, I then want to take all the unique values from 'that' and log them into a separate file. I have functions set up for the logging, so I can call it like logThis(uniquekey) and logThat(uniquekey). So it's just a case of firstly returning a list of all keys that are in 'this' but NOT in 'that' and then visa versa, then loop over them performing the function. Rob -----Original Message----- From: python-list-bounces+robert.rawlins=thinkbluemedia.co.uk at python.org [mailto:python-list-bounces+robert.rawlins=thinkbluemedia.co.uk at python.org] On Behalf Of Tim Golden Sent: 30 April 2007 09:41 Cc: python-list at python.org Subject: Re: Dict Copy & Compare Robert Rawlins - Think Blue wrote: > I'm looking for a little advice on dicts, firstly I need to learn how to > copy a dict, I suppose I could just something like. > Self.newdict = self.olddict > But I fear that this only creates a reference rather than an actual copy, > this means that as soon as I clear out the old one, the new one will > effectively be empty. What's the best way to ACTUALY copy a dict into a new > variable? Unless you have specialised needs, you can just say: d2 = dict (d1) which will initialise d2 from d1's key/value pairs: d1 = dict (a=1, b=2) d2 = dict (d1) d2['a'] = 5 print d1 print d2 > Next up I'm looking to compare two different dictionaries, then loop through > the unique results that are in each and print them out. Is there a more > efficient way of doing this other than a loop with an if/else statement? This comes up not infrequently on the list. I think there's even a few recipes in the cookbook. One (fairly recent) technique is to use set versions of your dictionary keys, but it depends on what you want to do next. From my example above: # relies on the fact that dictionary iterators # iterate over the keys of the dict. s1 = set (d1) s2 = set (d2) # do whatever set-ops you want, eg s3 = s1 | s2 for key in s3: print "Key:", key print "d1 =>", d1[key] print "d2 =>", d2[key] TJG -- http://mail.python.org/mailman/listinfo/python-list From laurent.pointal at limsi.fr Mon Apr 30 08:42:41 2007 From: laurent.pointal at limsi.fr (Laurent Pointal) Date: Mon, 30 Apr 2007 14:42:41 +0200 Subject: [ANN] Update to Python Quick Reference Card (for Python 2.4) (v0.67) Message-ID: PQRC (Python Quick Reference Card) is a condensed documentation for Python and its main libraries, targetting production of printed quick reference cards. Its available as OpenDocument .odt files and as A4 and USLetter formatted PDF files ready to print. Its distributed under a Creative Commons Attribution - NonCommercial - ShareAlike - 2.5 License, with allowing in-house print for curses. Modifications since previous publication: Switching to DejaVu font. Rework styles. Get around bad index page numbers generation bug. Small corrections. Its here: http://www.limsi.fr/Individu/pointal/python/pqrc/ Note: Next version will target Python 2.5. I'll keep version for Python 2.4 but should only make minor updates. -- Laurent POINTAL CNRS-LIMSI d?pt. CHM, groupes AMI et PS Courriel: laurent.pointal at limsi.fr (prof) laurent.pointal at laposte.net (perso) Ouebe: http://www.limsi.fr/Individu/pointal/ T?l. 01 69 85 81 06 (prof) Fax. 01 69 85 80 88 From gagsl-py2 at yahoo.com.ar Wed Apr 11 14:26:37 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 11 Apr 2007 15:26:37 -0300 Subject: py script modify it's Modified Time? References: <1176290057.625687.15150@y80g2000hsf.googlegroups.com> <1176298437.784719.146850@o5g2000hsb.googlegroups.com> Message-ID: En Wed, 11 Apr 2007 10:33:57 -0300, escribi?: > On Apr 11, 6:14 am, "est" wrote: >> I guess os.stat() could retrieve information about ctime, mtime of a >> path, but how can I change them? Is it possible to make it work both >> under Win32 and Linux? > > I am not sure if you can change a creation time of a file on NT, but > the rest sounds possible; according to this post anyway: > > http://mail.python.org/pipermail/python-list/2001-August/100214.html That post is rather old... With os.utime you can set the access and modified time, and it's portable. Creation time isn't stored on [the normal filesystems used by] Linux, and on Windows you can use win32file.SetFileTime > It mentions using the win32 modules, which can be found here: > http://aspn.activestate.com/ASPN/docs/ActivePython/2.4/pywin32/win32_modules.html Better https://sourceforge.net/projects/pywin32/ -- Gabriel Genellina From tgrav at mac.com Fri Apr 20 08:42:43 2007 From: tgrav at mac.com (Tommy Grav) Date: Fri, 20 Apr 2007 08:42:43 -0400 Subject: comparison with None In-Reply-To: <1hwu26k.oyynyowsbxvcN%aleax@mac.com> References: <3IqdnfRnCNWPC7vbnZ2dnUVZ_jqdnZ2d@rcn.net> <2qzVh.7373$xL6.982@trnddc05> <_JAVh.1700$jR5.897@trnddc08> <1hwu26k.oyynyowsbxvcN%aleax@mac.com> Message-ID: <107262C4-87D1-49D4-8BD7-C6617BD660C8@mac.com> On Apr 19, 2007, at 11:00 PM, Alex Martelli wrote: > Alan Isaac wrote: > >> currently documented behavior: >> "objects of different types always compare unequal". > > Where is that documented? URL please? > >>>> 1.0 == 1 > True >>>> type(1.0), type(1) > (, ) > Isn't this an example of numerical comparison (= or !=) versus object comparison (is or is not). I think the documentation needs to state that there is a difference between the two types. Cheers Tommy From azi.stdout at gmail.com Mon Apr 9 08:19:16 2007 From: azi.stdout at gmail.com (azi.stdout at gmail.com) Date: 9 Apr 2007 05:19:16 -0700 Subject: Nice "bug" to loose a contest In-Reply-To: <1176032438.921825.42730@b75g2000hsg.googlegroups.com> References: <1176029528.528010.210230@n59g2000hsh.googlegroups.com> <1176032438.921825.42730@b75g2000hsg.googlegroups.com> Message-ID: <1176121156.470714.256010@y80g2000hsf.googlegroups.com> On Apr 8, 1:40 pm, "aspineux" wrote: > This code works like the python one, > I dont use buffered stdio f... functions, > but the more 'system call' read and write > > int main() > { > char buf[120]; > int len; > > while (len=read(1, buf, sizeof(buf))) { > write(1, buf, len); > } > return 0; > > } > Yeah, I've noticed that too, altough I'm clueless on how stdio handles that differently. Now I'm wondering, what's the behaviour of the Python snippet that reads from stdout in Windows.. Can someone on Windows try it and report please? From nagle at animats.com Sat Apr 7 23:32:02 2007 From: nagle at animats.com (John Nagle) Date: Sun, 08 Apr 2007 03:32:02 GMT Subject: block scope? In-Reply-To: <7xmz1jsihq.fsf@ruckus.brouhaha.com> References: <7xr6qwal50.fsf@ruckus.brouhaha.com> <7xtzvseqzo.fsf@ruckus.brouhaha.com> <1hw72cg.115yokgarr9enN%aleax@mac.com> <1hw7kzo.1hepj3c1who5zhN%aleax@mac.com> <1hw7lxn.18itayl1fua6w0N%aleax@mac.com> <7xodlzofw2.fsf@ruckus.brouhaha.com> <1hw7rf0.1p2nwloex6vupN%aleax@mac.com> <7xmz1jsihq.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > aleax at mac.com (Alex Martelli) writes: > I have no opinion of this, locals() has always seemed like a crazy > part of the language to me and I never use it. I'd be happy to see it > gone since it makes compiling a lot easier. I think of that, from a compiler perspective, as one of the features that, if used, means you have to switch to a more inefficient representation. I encourage the hard-code optimizing compiler people to keep plugging away on Python. It's a convenient way to program, but the implementations are slower than they should be a decade into the language's life cycle. John Nagle From slug57_98 at yahoo.com Thu Apr 12 16:28:37 2007 From: slug57_98 at yahoo.com (Chad) Date: 12 Apr 2007 13:28:37 -0700 Subject: Need help with the get() method of a Text entry Message-ID: <1176409717.585710.184960@y80g2000hsf.googlegroups.com> I have a simple little program that brings up asks the user to enter a note, then is supposed to place that note into a text file when the user hits the submit button. However, when the user hits the submit button, absolutely nothing happens. IDLE doesn't give an error message and the note is not entered into the text file. For troubleshooting puposes, I wanted to see if IDLE would at least print the user's input; it doesn't do that either. Can someone please help me? Here is the code: from Tkinter import * class Application(Frame): """ GUI application that creates a story based on user input. """ def __init__(self, master): """ Initialize Frame. """ Frame.__init__(self, master) self.grid() self.create_widgets() def create_widgets(self): """ Create widgets to get note information. """ # create instruction label and text entry for notes Label(self, text = "Notes" ).grid(row = 0, column = 0, columnspan = 2 ) self.notes_ent = Text(self, width = 75, height = 10, wrap = WORD) self.notes_ent.grid(row = 2, column = 0 ,columnspan = 7, rowspan = 3, sticky = W) create submit button text1 = StringVar(self) text1 = self.notes_ent.get(1.0, END) self.notes_ent.config(state=NORMAL) Button(self, text = "Add Note", command = self.add_note(text1) ).grid(row = 1, column = 0, sticky = W) def add_note(self, text1): print text1 text_file = open("write_it.txt", "a+") text_file.write(text1) root = Tk() root.title("Mad Lib") app = Application(root) root.mainloop() From cam.ac.uk at mh391.invalid Thu Apr 26 11:54:40 2007 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Thu, 26 Apr 2007 16:54:40 +0100 Subject: Generalized range In-Reply-To: <1177598743.352743.290730@t39g2000prd.googlegroups.com> References: <1177598743.352743.290730@t39g2000prd.googlegroups.com> Message-ID: tkpmep at hotmail.com wrote: > I need to create ranges that can start and end with real numbers. > Searching this newsgroup brought me to a function that I then modified > as follows: > > def myRange(iMin, iMax=None, iStep=1): > """Extends range to real numbers. Wherever possible, use Python's > range . > In other cases, make the behavior follow the spirit of Python's > range """ > epsilon = 1.e-8 > > if iMax == None and iStep == 1: > return range(int(iMin)) > > elif type(iMin).__name__.lower() in ('int', 'long') and \ > type(iMax).__name__.lower() in ('int', 'long') and \ > type(iStep).__name__.lower() in ('int', 'long') and iStep != > 0: > return range( iMin, iMax, iStep) > > elif iMin <= iMax and iStep > 0: > return [ iMin+i*iStep for i in range( int(math.ceil((iMax - > iMin - epsilon)/iStep)) )] > > elif iMin >= iMax and iStep < 0: > return [ iMin+i*iStep for i in range(-int(math.ceil((iMin - > iMax + epsilon)/iStep)) )] > > else: > raise ValueError, 'Cannot construct a range with steps of size > ' + str(iStep) + ' between ' + str(iMin) + ' and ' + str(iMax) > > > The one part of my implementation that has me a bit queasy (i.e. > works in my current application, but I can see it misbehaving > elsewhere) is the addition/subtraction of a fixed epsilon to ensure > that my rounding goes the right way. A clean implementation would > modify epsilon based on the achievable level of precision given the > particular values of iMax, iMin and iStep. I suspect this requires a > detailed understanding of the implementation of floating point > arithmetic, and would appreciate hearing any thoughts you might have > on gilding this lily. In addition to the comments of Stargaming, most of which I agree with, I think you would be far better dropping the epsilon business and doing something like: # requires that minimum <= maximum; swap values if necessary res = minimum while res < maximum: yield res res += step -- Michael Hoffman From steve at REMOVE.THIS.cybersource.com.au Thu Apr 19 03:14:38 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Thu, 19 Apr 2007 17:14:38 +1000 Subject: What makes an iterator an iterator? References: <1hwr9pv.13v4ci6106qn0aN%aleax@mac.com> <1176936067.315082.17970@y80g2000hsf.googlegroups.com> <1hws6rd.u0a6hd78fhhpN%aleax@mac.com> Message-ID: On Wed, 18 Apr 2007 19:45:50 -0700, Alex Martelli wrote: > 7stud wrote: > ... >> Can you explain some of the details of why this code fails: > ... >> def next(self): >> for word in "Norwegian Blue's have beautiful >> plumage!".split(): >> yield word > > Sure, easily: a loop like "for x in y:" binds an unnamed temporary > variable (say _t) to iter(y) and then repeatedly calls _t.next() [or to > be pedantic type(_t).next(t)] until that raises StopIteration. > > Calling a generator, such as this next method, returns an iterator > object; calling it repeatedly returns many such iterator objects, and > never raises StopIteration, thus obviously producing an unending loop. Thank you for that answer Alex, even though I didn't ask the question I was wondering the same thing myself. -- Steven. From facundo at taniquetil.com.ar Thu Apr 26 08:48:31 2007 From: facundo at taniquetil.com.ar (Facundo Batista) Date: Thu, 26 Apr 2007 12:48:31 +0000 (UTC) Subject: File not read to end References: <1177522730.327454.121120@s33g2000prh.googlegroups.com> <-LWdnRS04OCCCLLbnZ2dnUVZ_uSgnZ2d@comcast.com> <1177589949.885985.164380@c18g2000prb.googlegroups.com> Message-ID: andrew.jefferies at gmail.com wrote: > I've attached the whole script. Thanks again for your help. > > --Andrew Andrew, tip: If you attach the whole script, what you get is that a lot of people goes away from the thread. Me for example. I won't read 100 lines of code to see where is the problem, and then try to solve. The best way to handle this, and effectively getting more help from the community, is start to trim your code. So, you take those 20 lines away, and the problem persist. You cut off another 15, and the problem persist. After ten minutes of work, you get a 15 lines code, which still shows your problem. You send that to the community, and surely you'll get more help. As a fantastic side effect of that process, normally you actually *find* the problem by yourself, which is always better, :) Regards, -- . Facundo . Blog: http://www.taniquetil.com.ar/plog/ PyAr: http://www.python.org/ar/ From claird at lairds.us Wed Apr 18 16:30:48 2007 From: claird at lairds.us (Cameron Laird) Date: Wed, 18 Apr 2007 20:30:48 +0000 Subject: Future Python Gui? References: <1176859699.906386.326720@b75g2000hsg.googlegroups.com> <1176863948.526051.186210@n76g2000hsh.googlegroups.com> <1176909848.455264.174730@e65g2000hsc.googlegroups.com> Message-ID: In article <1176909848.455264.174730 at e65g2000hsc.googlegroups.com>, bcwhite at pobox.com wrote: . . . >I wouldn't mind using just Tkinter, despite it's primative look, >except that it doesn't support more advanced widgets like "notebook". . . . "Tile" has already been mentioned in this thread, and I know there'll be at least one more follow-up on the subject. Tile includes a ("native"!) notebook, as well as a combobox, tree- view, ... . I recognize that Tile might not be widely installed until 2.6 or so. From steve at holdenweb.com Sun Apr 15 12:57:25 2007 From: steve at holdenweb.com (Steve Holden) Date: Sun, 15 Apr 2007 12:57:25 -0400 Subject: That might be the case for more complex objects... In-Reply-To: References: <1176546078.934340.253810@y5g2000hsa.googlegroups.com> <1176557734.456820.275780@p77g2000hsh.googlegroups.com> <7saUh.37$4S1.2@newsfe12.lga> Message-ID: James Stroud wrote: > Bart Willems wrote: >> Dennis Lee Bieber wrote: [...] >> Lists behave as described above, integers and floats don't. >> >> By the way, a classic language like C has features like this too; >> they're called pointers. > > I think that after a += 1, a memory location with a 6 is created and now > a points to that because += has assignment buried in it. This is the difference between mutable and immutable types. >>> a = 5 >>> b = a >>> a += 1 >>> a 6 >>> b 5 >>> a = [1,2,3,4,5] >>> b = a >>> a += [6,7,8] >>> a [1, 2, 3, 4, 5, 6, 7, 8] >>> b [1, 2, 3, 4, 5, 6, 7, 8] >>> 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 jstroud at mbi.ucla.edu Wed Apr 11 16:47:31 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Wed, 11 Apr 2007 13:47:31 -0700 Subject: Seeking list of Python applications on OS X In-Reply-To: References: Message-ID: Kevin Walzer wrote: > Hello, > > I am seeking to update this wiki page, which lists Mac OS X applications > using Python in a significant way: > > http://wiki.python.org/moin/MacPython/MacSoftwareUsingPython > > This query is directed at developers of cross-platform Python > applications who provide full support for the Mac. By "full support," I > mean that you have Mac-specific builds of your application, deployed in > a Mac-specific manner (wrapped with py2app or bundlebuilder into a > standalone application with its own icon, for drag-and-drop > installation), and that the application run natively in the Mac Aqua > environment (no X11). This query focuses mainly on desktop applications > developed with one of the major cross-platform toolkits (Tkinter, > wxPython, PyQt; Gtk does not run natively on the Mac). > > Please post to c.l.p. with your replies and I will add the appropriate > response to the wiki. Thanks. > To learn Tkinter, I wrote a password keeper called passerby. "Double-Click" installers for Mac, Linux (x86), and Windows. OSS compliant license. http://passerby.sf.net James From aleax at mac.com Sun Apr 8 22:14:12 2007 From: aleax at mac.com (Alex Martelli) Date: Sun, 8 Apr 2007 19:14:12 -0700 Subject: shelve error References: <1175746456.995618.186190@e65g2000hsc.googlegroups.com> <1175746966.023613.178830@n76g2000hsh.googlegroups.com> <1175756092.643182.142420@n76g2000hsh.googlegroups.com> Message-ID: <1hw9lxy.ldrc541w507xyN%aleax@mac.com> 7stud wrote: > On Apr 4, 10:22 pm, mik3l3... at gmail.com wrote: > > how did you generate aaa.txt? > > Ok, I got it to work by supplying a filename that didn't previously > exist. Neither the book I am reading, "Beginning Python: From Novice > to Professional" nor the book I am using as a reference, "Python in > Nutshell", happens to mention that important fact. I notice that the Nutshell (2nd ed) has a small errata that may be what's confusing you. On p. 284, under "The shelve module", I say: shelve supplies a function open that is polymorphic to anydbm.open . On p. 286, you find the whole page explaining anydbm.open (which is why I didn't want to duplicate all that info), including the detail that the default value for argument flag is 'r' (meaning read-only operation, and on a file that must already exist). However, shelve.open is not _entirely_ polymorphic to anydbm.open, in this small but crucial detail: the defaulf value for argument flag is 'c' (meaning, as p. 286 correctly says, that it creates a new file if it doesn't exist, but also accepts and opens an existing file, and operation is read-write). Of course, if the existing file was not created by the shelve module, there may well be errors -- shelve uses DBM-like archive files, as clearly explained on p. 284, not arbitrary text files (nor for that matter arbitrary binary files). As the documentation for anydbm.open explicitly says, it's all about DBM files; adding "will not work right if you try to open just any random textfile or other file you may happen to have laying around on your favourite storage device" would be insulting to the reader and a waste of space, so I don't consider it a valid errata. But if you open an errata for the missing explanation for the different default value of the flag argument (use URL ), I'll be glad to fix it for the next printing, changing the previously quoted sentence to: shelve supplies a function open that is polymorphic to anydbm.open (except that the default value of argument flag is 'c' rather than 'n'). BTW, if you DO want to call shelve.open on a path f that may correspond to an arbitrary existing file (and want to toss away the previous contents of that file, if any) the correct way to call is then: s = shelve.open(whatever_path, 'n') since 'n' truncates an existing file, or creates a new one, as needed. That is also shown in the code example for module shelve in the Nutshell (the 'n' occurs just at the top of p. 285). Alex From turbana at gmail.com Sat Apr 28 20:25:37 2007 From: turbana at gmail.com (Ian Clark) Date: Sat, 28 Apr 2007 17:25:37 -0700 Subject: strip newline from string In-Reply-To: References: Message-ID: On 4/28/07, James wrote: [snip] > username = getuser() > string.strip > (username) > print "username is %s" % username [snip] > > > The autoconf.txt contains two lines, which first has an ip address and > second a username. The problem I'm having is that the string.strip() doesn't > appear to be stripping the newline off the username. > > > Any ideas? If you need more information, just ask! > > > James string.strip() returns a copy of the string with whitespace removed, it does not modify it in place. What you really want is: > username = getuser().strip() Someone correct me if I'm wrong, but I believe just about all functions from the string module are deprecated. Use the methods from the string class. As I'm assuming getuser() returns a string object, just use the string functions on that directly. Ian From hq4ever at gmail.com Thu Apr 12 16:11:05 2007 From: hq4ever at gmail.com (Maxim Veksler) Date: Thu, 12 Apr 2007 23:11:05 +0300 Subject: ulimit on open sockets ? In-Reply-To: <58086qF2dlcviU1@mid.individual.net> References: <58086qF2dlcviU1@mid.individual.net> Message-ID: On 4/10/07, Bjoern Schliessmann wrote: > Maxim Veksler wrote: > > > I've written this code, the general idea was to listen on all > > 65535 port of tcp for connection. > > Please excuse the question: Why would anyone want to do such a manic > thing (instead of, e. g., using raw sockets)? > That's OK :) Well first because I can. Now to be a bit more serious, because I do stress testing on the system, because that's a handy utility to have (a "port catcher" to see how you application handles with that), because at the time I didn't knew about RAW sockets, because I want to do TCP connections from one side of the firewall to the other and implementing the TCP stacks by my self (If I choose to go the raw socket way) is something I wouldn't like to do (at least for now). More... > Regards, > > > Bj?rn > Maxim. > -- > BOFH excuse #326: > > We need a licensed electrician to replace the light bulbs in the > computer room. > > -- > http://mail.python.org/mailman/listinfo/python-list > -- Cheers, Maxim Veksler "Free as in Freedom" - Do u GNU ? From sjmachin at lexicon.net Sat Apr 14 16:49:51 2007 From: sjmachin at lexicon.net (John Machin) Date: 14 Apr 2007 13:49:51 -0700 Subject: Python Feature Request: Allow changing base of member indices to 1 In-Reply-To: <1176546465.632410.52630@w1g2000hsg.googlegroups.com> References: <1176546465.632410.52630@w1g2000hsg.googlegroups.com> Message-ID: <1176583791.568505.241530@n59g2000hsh.googlegroups.com> On Apr 14, 8:27 pm, samj... at gmail.com wrote: > This is like the previous one. Please check for sanity and approve for > posting at python-dev. > > I would like to have something like "option base" in Visual Basic. > IIRC it used to allow me to choose whether 0 or 1 should be used as > the base of member indices of arrays. In Python, the same can be used > with strings, lists, tuples etc. > > This would mean: > foo = "foo" > => foo[1] == 'f' > > foo = ['foo', 'bar', 'spam' ] > => foo[1] == 'foo' > > foo = ('spam', 'eggs') > => foo[1] == 'spam' > > For convenience it should also affect the range function so that: > > range(3) = [1, 2, 3] > > because this is often used where arrays would be used in VB. > > Finally, when the programmer does not specify his choice of base at > the beginning of the program, the current behaviour of using 0 as base > should continue so that there is no problem with backward > compatibility. +1 F***ed Concept of the Year From kevin.haynes at auxilior.co.uk Mon Apr 23 19:04:28 2007 From: kevin.haynes at auxilior.co.uk (Kevin Haynes) Date: Tue, 24 Apr 2007 00:04:28 +0100 Subject: Learning Python - First Project In-Reply-To: <1177367890.088488.93290@l77g2000hsb.googlegroups.com> References: <1177339942.371167.93970@b75g2000hsg.googlegroups.com> <1177367541.059834.18420@o5g2000hsb.googlegroups.com> <1177367890.088488.93290@l77g2000hsb.googlegroups.com> Message-ID: <200704240004.29299.kevin.haynes@auxilior.co.uk> Hello I was a python newbie just a month ago and found the following books a great help. Beginning Python: From Novice to Professional (Beginning: From Novice to Professional) by Magnus L. Hetland (Paperback - 29 Sep 2005) http://www.amazon.co.uk/Beginning-Python-Novice-Professional/dp/159059519X/ref=pd_bbs_sr_2/026-1738001-7066018?ie=UTF8&s=books&qid=1177369262&sr=8-2 WxPython in Action by Noel Rappin and Robin Dunn (Paperback - 30 Mar 2006) http://www.amazon.co.uk/WxPython-Action-Noel-Rappin/dp/1932394621/ref=pd_bbs_sr_1/026-1738001-7066018?ie=UTF8&s=books&qid=1177369390&sr=8-1 Kevin On Monday 23 April 2007, 7stud wrote: > Uhhmm...how are you supposed to close a ShapedWindow(under > Miscellaneous)? From robert.rawlins at thinkbluemedia.co.uk Wed Apr 25 03:04:36 2007 From: robert.rawlins at thinkbluemedia.co.uk (Robert Rawlins - Think Blue) Date: Wed, 25 Apr 2007 08:04:36 +0100 Subject: If Dict Contains a particular key In-Reply-To: References: <000001c78695$ed321540$c7963fc0$@rawlins@thinkbluemedia.co.uk> Message-ID: <001c01c78708$07b30790$171916b0$@rawlins@thinkbluemedia.co.uk> Thanks guys for this, glad it was so simple. I used mikes solution in the end, and it worked a charm. Thanks again, Rob From: python-list-bounces+robert.rawlins=thinkbluemedia.co.uk at python.org [mailto:python-list-bounces+robert.rawlins=thinkbluemedia.co.uk at python.org] On Behalf Of Michael Bentley Sent: 24 April 2007 18:37 To: python-list at python.org Subject: Re: If Dict Contains a particular key On Apr 24, 2007, at 12:28 PM, Robert Rawlins - Think Blue wrote: Hello Guys, I'm Looking to build a quick if/else statement that checks a dictionary for a key like follows. If myDict contains ThisKey: Do this... Else Do that... Thats the best way of doing this? if ThisKey in myDict: pass # do this else: pass # do that -------------- next part -------------- An HTML attachment was scrubbed... URL: From dailylama at gmail.com Thu Apr 26 14:35:03 2007 From: dailylama at gmail.com (Sergiy) Date: Thu, 26 Apr 2007 21:35:03 +0300 Subject: wtf Message-ID: <9d7816d30704261135ta3cf99n854519e843bdd6e7@mail.gmail.com> print 1 / 2 print -1 / 2 0 -1 correct? From apardon at forel.vub.ac.be Tue Apr 10 03:31:13 2007 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 10 Apr 2007 07:31:13 GMT Subject: tuples, index method, Python's design References: <1175867771.114540.61810@n76g2000hsh.googlegroups.com> <1175884427.779950.267220@y80g2000hsf.googlegroups.com> Message-ID: On 2007-04-06, Carsten Haese wrote: > On Fri, 2007-04-06 at 11:33 -0700, 7stud wrote: >> On Apr 6, 7:56 am, "Paul Boddie" wrote: >> > The problem with 7stud's quote from GvR is that it's out of date: >> >> I would argue that it shows the very guy who invented the language >> stated publicly there was no good reason for tuples not to have an >> index method---except for consistency; tuples had no other methods. >> Now that tuples have other methods, the only justification he stated >> no longer exists. > > Except that that wasn't the only justification. GvR also said: > > """ > For tuples, I suspect such a function would rarely be used; I think > that is most cases where x.index() would be useful, x is generally a > list, whose contents varies in time, rather than a tuple (which cannot > change easily). > """ > > The lack of convincing use cases is still a pertinent reason today. Note > that the original poster on this thread did not present a use case for > tuple.index, they were only asking out of curiosity. > > If you have a use case for tuple.index, please show it to me, and I'll > show you what you should be using instead of a tuple. No wonder no convincing use cases for tuples have shown up. You just defined use cases of tuples as unconvincing. My personal opinion is that lack of use cases are used too much as an excuse. Limiting the development of your language to use cases makes your language less consistent and so makes your language less easy to learn. Of course it also limits the language to what the developers can think off. I once thought it would be usefull to have something like a slice but with extended functionality. So I first tried this: class Islice(slice): ... and I got: type 'slice' is not an acceptable base type then I just tried: class Islice: ... But an instance of such a class can't be used as an index, despited the propoganda that is made for duck typing in this news group. I guess the developers just couldn't see the use case of this. But you do have to wonder when the developers started to unify classes and types, why they just didn't go the whole wayr?. Making all types subclassable, means you have only one case to code and the user doesn't has to wonder whether a particular type is subclassable or not. I think that is a bigger gain, than the potential loss one may experience because some type that now are subclassable will never actually be subclassed. -- Antoon Pardon From adam at atlas.st Mon Apr 9 23:28:22 2007 From: adam at atlas.st (Adam Atlas) Date: 9 Apr 2007 20:28:22 -0700 Subject: Breaking up Strings correctly: In-Reply-To: References: Message-ID: <1176175701.971632.164360@l77g2000hsb.googlegroups.com> On Apr 9, 8:19 am, "Michael Yanowitz" wrote: > Hello: > > I have been searching for an easy solution, and hopefully one > has already been written, so I don't want to reinvent the wheel: Pyparsing is indeed a fine package, but if Paul gets to plug his module, then so do I! :) I have a package called ZestyParser... a lot of it is inspired by Pyparsing, actually, but I'm going in a different direction in many areas. (One major goal is to be crazily dynamic and flexible on the inside. And it hasn't failed me thus far; I've used it to easily parse grammars that would make lex and yacc scream in horror.) Here's how I'd do it... from ZestyParser import * from ZestyParser.Helpers import * varName = Token(r'\$(\w+)', group=1) varVal = QuoteHelper() | Int sp = Skip(Token(r'\s*')) comparison = sp.pad(varName + CompositeToken([RawToken(sym) for sym in ('=','<','>','>=','<=','!=')]) + varVal) #Maybe I should "borrow" PyParsing's OneOf idea :) expr = ExpressionHelper(( comparison, (RawToken('(') + Only(_top_) + RawToken(')')), oper('NOT', ops=UNARY), oper('AND'), oper('OR'), )) Now you can scan for `expr` and get a return value like [[['IP', '=', '127.1.2.3'], ['AX', '<', 15]], [['IP', '=', '127.1.2.4'], ['AY', '! =', 0]]] (for the example you gave). Note that this example uses several features that won't be available until the next release, but it's coming soon. So Michael, though you'd still be able to parse this with the current version, the code wouldn't look as nice as this or the Pyparsing version. Maybe just add it to your watchlist. :) - Adam From mail at microcorp.co.za Tue Apr 17 08:42:27 2007 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Tue, 17 Apr 2007 14:42:27 +0200 Subject: Queue enhancement suggestion References: <7x4pngluel.fsf_-_@ruckus.brouhaha.com> Message-ID: <007501c780ee$ba7d63e0$03000080@hendrik> "Antoon Pardon" wrote: > On 2007-04-17, Hendrik van Rooyen wrote: > > "Antoon Pardon" wrote: > > > > > >> The problem is this doesn't work well if you have multiple producers. > >> One producer can be finished while the other is still putting values > >> on the queue. > >> > >> The solution I have been thinking on is the following. > >> > >> Add an open and close operation. Only threads that have the queue > >> open can access it. The open call should specify whether you > >> want to read or write to the queue or both. When all writers > >> have closed the queue and the queue is empty a q.get will > >> raise an exception. This may be done by putting a sentinel > >> on the queue when the last writer closed the queue. > >> > > > > This is beginning to look like a named pipe to me. > > > > The nice thing about queues is that there is currently so little > > BS about them - you just import the module, create one by binding > > a name to it, and you are in business, and anyone can read and/or > > write to it. > > And if you are not carefull you have a deadlock. I tried queues > in a threaded gui application. Al the advise you get about such > applications tell you to have one thread doing all the gui-stuff. This is true - and worse - it needs to be the main thread too. > So you basically have n producers and one consumer. Unfortunatly > the gui thread sometimes has things of its own it want to show. > So when the gui thread wants to put things on the queue you > risk a deadlock. Not sure I understand this - it sounds vaguely incestous to me. I normally use a GUI with two queues, one for input, one for output, to two threads that front end two named pipes to the next process - I try to avoid more than one thing reading or writing to one end of a queue or a pipe, so the dataflow diagram for my stuff always looks like a TinkerToy... > > If I were faced with the sort of thing addressed by this thread, I would > > probably use some sort of time out to decide when the end has happened. > > After all - if the task is long running, it never stops (hopefully), and if its > > a batch type job, it runs out of input and stops putting stuff on the queue. > > This is unworkable for worker threads in a gui environment. This is also true - when input comes from a user, time outs are no good. - Hendrik From http Sun Apr 15 01:17:08 2007 From: http (Paul Rubin) Date: 14 Apr 2007 22:17:08 -0700 Subject: proposed PEP: iterator splicing Message-ID: <7xirbyi5d7.fsf_-_@ruckus.brouhaha.com> The boilerplate def some_gen(): ... for x in some_other_gen(): yield x ... is so common (including the case where some_other_gen is the same as some_gen, i.e. it's a recursive call) that I find myself wanting a more direct way to express it: def some_gen(): ... yield *some_other_gen() comes to mind. Less clutter, and avoids yet another temp variable polluting the namespace. Thoughts? From jzgoda at o2.usun.pl Wed Apr 4 16:47:56 2007 From: jzgoda at o2.usun.pl (Jarek Zgoda) Date: Wed, 04 Apr 2007 22:47:56 +0200 Subject: calling super() In-Reply-To: References: <1175714555.413502.77390@o5g2000hsb.googlegroups.com> Message-ID: Laszlo Nagy napisa?(a): > Definitely, this is not true. Well, it depends what the OP wanted to do > here, but in 99.9% of the cases, you want to use Hah! I cancelled this message but seconds too late... -- Jarek Zgoda http://jpa.berlios.de/ From broek at cc.umanitoba.ca Fri Apr 13 10:44:27 2007 From: broek at cc.umanitoba.ca (Brian van den Broek) Date: Fri, 13 Apr 2007 09:44:27 -0500 Subject: tuples, index method, Python's design In-Reply-To: References: <1176210960.3430.20.camel@dot.uniqsys.com> <740c3aec0704100810g5f962e8eu614fbaedecf3608e@mail.gmail.com> <1176219856.3430.76.camel@dot.uniqsys.com> <740c3aec0704101021i1fd79ef2l99eac4ced1e252d9@mail.gmail.com> <1176226682.3430.86.camel@dot.uniqsys.com> <4866bea60704101104r4600d281h135286b66378f4d4@mail.gmail.com> <740c3aec0704101534y3c65f5a7je382f97e1f6301b7@mail.gmail.com> <1176305859.581010.199600@n76g2000hsh.googlegroups.com> Message-ID: <461F974B.6060508@cc.umanitoba.ca> Antoon Pardon said unto the world upon 04/13/2007 02:46 AM: > On 2007-04-12, Steven D'Aprano wrote: >> So much fuss over such a little thing... yes it would be nice if tuples >> grew an index method, but it isn't hard to work around the lack. > > Yes it is a little thing. But if it is such a little thing why do > the developers don't simply add it? It's wafer thin! -- Brian vdB From paul at boddie.org.uk Mon Apr 2 11:33:38 2007 From: paul at boddie.org.uk (Paul Boddie) Date: 2 Apr 2007 08:33:38 -0700 Subject: YouTube showing repr() of a tuple In-Reply-To: References: <460b9f48$0$30100$4d3efbfe@news.sover.net> <460bc895$0$30091$4d3efbfe@news.sover.net> Message-ID: <1175528018.544324.177390@y66g2000hsf.googlegroups.com> On 2 Apr, 16:19, Steve Holden wrote: > > Both fixed by the time I managed to follow the links. There wasn't much to see, and putting apostrophes into the input didn't seem to cause "proper" repr() behaviour. So I suspect that the Python resemblance was coincidental. Paul From bbxx789_05ss at yahoo.com Thu Apr 12 06:44:35 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: 12 Apr 2007 03:44:35 -0700 Subject: Calling private base methods In-Reply-To: References: Message-ID: <1176374675.347453.89340@n76g2000hsh.googlegroups.com> On Apr 12, 2:47 am, "Jorgen Bodde" wrote: > Is it possible to call a private base method? I come from a C++ > background, and I liked this construction as my base class has helper > methods so that I do not have to duplicate code. > I'd like to see some C++ code that does that! From mail at microcorp.co.za Tue Apr 3 02:17:36 2007 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Tue, 3 Apr 2007 08:17:36 +0200 Subject: socket read timeout References: <17930.25631.86693.827473@montanaro.dyndns.org><000e01c771d2$2f3dd240$03000080@hendrik> <000401c77471$5ee152a0$03000080@hendrik> Message-ID: <00ee01c775c8$1d87da60$03000080@hendrik> "Steve Holden" wrote: > > Right, but collisions are *so* twentieth-century, aren't they. With a > properly-implemented switched infrastructure Ethernet interfaces can > transmit and receive at the same time. This is true, while "A" and "B" are not simultaneously trying to address "C" - Then you need something like store and forward, on the fly... : - ) better known as "routing"... Some (most?) of the little switches I have seen are too dumb even to allow "A" to talk to "B" while "C" is talking to "D" - they just broadcast the first "talker"'s message to all the "listeners" - little better than active hubs, destroying the end point's hardware capability to talk and listen at the same time. I think the keywords here are "properly implemented" - its actually not a trivial problem, as the switch has to know or learn who is where, and set up paths accordingly, in real time. This is hard to do without store and forward. - Hendrik From bbxx789_05ss at yahoo.com Sun Apr 15 21:26:22 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: 15 Apr 2007 18:26:22 -0700 Subject: pyparsing Catch-22 Message-ID: <1176686782.270354.164630@l77g2000hsb.googlegroups.com> To the developer: 1) I went to the pyparsing wiki to download the pyparsing module and try it 2) At the wiki, there was no index entry in the table of contents for Downloads. After searching around a bit, I finally discovered a tiny link buried in some text at the top of the home page. 3) Link goes to sourceforge. At sourceforge, there was a nice, green 'download' button that stood out from the page. 4) I clicked on the download button and got the warning: ----- You have selected to download the pyparsing-1.4.6 release. Below is a list of files contained in this release. Before downloading, you may want to read the release notes. ----- 5) Can't find any release notes, nor any button to click to download the package. 6) Give up in frustration. 7) A few minutes later, I decide: I will not give up. 8) I go back to sourceforge and start clicking every link on the page. (Hello, porn sites! Just kidding.) Still no luck. 9) Finally. I click on something and a download begins. I cancel it. 10) Now I know what to click on, and I download the docs and pyparsing-1.4.6.tar 11) Now what? I'm new to mac os x, and I have no idea what to do. The wiki is devoid of any installation instructions. 12) I give up again. For as hard as you push pyparsing on this forum, I would think you would make it easier to download and install your module. In my opinion, the wiki should provide detailed installation instructions for all supported os's, and the sourceforge downloading process is too complicated. From rdm at rcblue.com Thu Apr 5 06:41:46 2007 From: rdm at rcblue.com (Dick Moores) Date: Thu, 05 Apr 2007 03:41:46 -0700 Subject: Welch essential for learning Tkinter well? Message-ID: <20070405104150.842321E4002@bag.python.org> In a couple of places recently I've seen Brent Welch's _Practical Programming in Tcl & Tk_ () recommended for learning Tkinter well. So a couple of questions: 1) Is it really good for learning Tkinter, even though it doesn't mention Tkinter at all (in the 4th edition at least)? 2) If it is good for learning Tkinter, can I get by with a cheaper, used copy of the 3rd edition? Thanks, Dick Moores From mensanator at aol.com Sat Apr 14 12:32:07 2007 From: mensanator at aol.com (mensanator at aol.com) Date: 14 Apr 2007 09:32:07 -0700 Subject: Making a tree out of a 2 column list In-Reply-To: References: Message-ID: <1176568327.669229.22910@b75g2000hsg.googlegroups.com> On Apr 14, 9:37???am, "Sebastian Bassi" wrote: > I have a two column list like: > > 2,131 > 6,335 > 7,6 > 8,9 > 10,131 > 131,99 > 5,10 > > And I want to store it in a tree-like structure. > So if I request 131, it should return all the child of 131, like 2, 10 > and 5 (since 5 is child of 10). > If I request 335, it should return: 6 and 7. > If I request 9, it should return 8. > I guess I could use tuples or dictionaries to do it, but I can't figure out how. There are probably better ways. def tree_path(key,tree,indent): print '\t'*indent,key if tree.has_key(key): for m in tree[key]: tree_path(m,tree,indent+1) return print 'original data' print source = [(2,131),(6,335),(7,6),(8,9),(10,131),(131,99),(5,10)] tree = {} for s in source: if tree.has_key(s[1]): tree[s[1]].append(s[0]) else: tree[s[1]] = [s[0]] for t in tree: print '%3d ' % (t),tree[t] print print tree_path(99,tree,0) print print 'extended data' print source_extend = [(666,2),(777,2),(888,2)] for s in source_extend: if tree.has_key(s[1]): tree[s[1]].append(s[0]) else: tree[s[1]] = [s[0]] for t in tree: print '%3d ' % (t),tree[t] print print tree_path(99,tree,0) ## original data ## ## 99 [131] ## 6 [7] ## 9 [8] ## 10 [5] ## 335 [6] ## 131 [2, 10] ## ## ## 99 ## 131 ## 2 ## 10 ## 5 ## ## extended data ## ## 2 [666, 777, 888] ## 99 [131] ## 6 [7] ## 9 [8] ## 10 [5] ## 335 [6] ## 131 [2, 10] ## ## ## 99 ## 131 ## 2 ## 666 ## 777 ## 888 ## 10 ## 5 > > Best, > SB. > > -- > Sebasti?n Bassi > Diplomado Ciencia y Tecnolog?a. > Club de la raz?n (www.clubdelarazon.org) From martin at v.loewis.de Sat Apr 14 07:01:12 2007 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sat, 14 Apr 2007 13:01:12 +0200 Subject: Python Feature Request: Allow changing base of member indices to 1 In-Reply-To: <1176546465.632410.52630@w1g2000hsg.googlegroups.com> References: <1176546465.632410.52630@w1g2000hsg.googlegroups.com> Message-ID: <4620b47b$0$14410$9b622d9e@news.freenet.de> samjnaa at gmail.com schrieb: > This is like the previous one. Please check for sanity and approve for > posting at python-dev. This one is not sane. It's not possible to change the indexing of objects on a per-module basis, as objects may cross module boundaries. Suppose you have this code: option base import sys print sys.path[1] So should the be 0-based (because path is in module sys), or should it be one-based (because the access occurs in a module that uses 1-indexing)? Regards, Martin From gnewsg at gmail.com Mon Apr 16 11:24:18 2007 From: gnewsg at gmail.com (billiejoex) Date: 16 Apr 2007 08:24:18 -0700 Subject: Python and SSL Message-ID: <1176737058.203036.53170@n59g2000hsh.googlegroups.com> Hi, I developed an ftp-server library and now I would like to add support for SSL/TLS as described in RFC 2228: http://tools.ietf.org/html/rfc2228 Currenlty I'm searching for documentation about this subject and I would like to start to ask some questions: - I noticed that socket module provides an SSL class (socket.ssl) but even if documentation reports that it does not do any certificate verification a lot of stdlib modules (imaplib, poplib, smtplib, httplib and urllib2) provides SSL extension classes wherein socket.ssl is used. What does it mean? - On top of that why such extension classes [examples: 1, 2, 3] accepts key-files and cert-files as optional argouments if no certificate verification occurs? [1] poplib.POP3_SSL( host[, port[, keyfile[, certfile]]]) [2] imaplib.IMAP4_SSL( [host[, port[, keyfile[, certfile]]]]) [3] smtplib.starttls( [keyfile[, certfile]]) - By searching through the web I found some daemons supporting SSL such as this one: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/442473 By looking at the code I notice that pyopenssl package is used and that a certificate file is required. Why do I need to use pyopenssl and how do I generate the cert file? Could someone point me in the right direction? Thanks in advance. From bhochstetler at gmail.com Tue Apr 3 14:24:32 2007 From: bhochstetler at gmail.com (bhochstetler at gmail.com) Date: 3 Apr 2007 11:24:32 -0700 Subject: troubles building python 2.5 on Windows XP x64 Windows Server 2003 sp1 Platform SDK In-Reply-To: References: <1175622506.730227.37060@p77g2000hsh.googlegroups.com> Message-ID: <1175624672.570370.248710@y80g2000hsf.googlegroups.com> On Apr 3, 2:04 pm, Steven Bethard wrote: > bhochstet... at gmail.com wrote: > > I am needing to build python 2.5 on Windows XP x64 Windows Server 2003 > > sp1 Platform SDK and am not finding anything documented on the process > > to use. Has anyone had any success with this? If so has anyone > > documented it? The documentation that resides in pcbuild/readme.txt is > > not helpful at all. > > What have you tried already? From the readme: > > All you need to do is open the workspace "pcbuild.sln" in MSVC++, > select the Debug or Release setting (using "Solution Configuration" > from the "Standard" toolbar"), and build the projects. > > Did that not work for you? If not, how did it fail? > > STeVe There is no IDE available with the 64 bit compiler on Windows Server 2003 Platform SDK, so that is not an option. From bbxx789_05ss at yahoo.com Thu Apr 12 06:36:41 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: 12 Apr 2007 03:36:41 -0700 Subject: Newbie help with array handling In-Reply-To: <1176371455.510269.43630@y5g2000hsa.googlegroups.com> References: <1176364734.439383.252930@o5g2000hsb.googlegroups.com> <1176368561.245625.251270@y5g2000hsa.googlegroups.com> <1176370313.386948.260930@p77g2000hsh.googlegroups.com> <1176371455.510269.43630@y5g2000hsa.googlegroups.com> Message-ID: <1176374201.275243.284890@b75g2000hsg.googlegroups.com> On Apr 12, 3:50 am, "7stud" wrote: > On Apr 12, 3:31 am, "loial" wrote: > > lst = mydict["keyvalue1"] > lst[0] = 4 > list.append("red") Rather the last line there should read: lst.append("red") From xuxu_1009 at 163.com Fri Apr 13 22:38:08 2007 From: xuxu_1009 at 163.com (Ann) Date: 13 Apr 2007 19:38:08 -0700 Subject: How to get a forum for your free site? Message-ID: <1176518288.373349.237050@w1g2000hsg.googlegroups.com> If you have something good and want to show or share it with eachother ,what would you do then? Send it one by one ?It's so slow and boring that you will be tired and have no interested to do that again.The buoyant you will be lost,are you ? http://www.forumgogo.com this is the place where can provide you all things and functions what you want. The forum is free.It's a very good flat roof for you to communicate with the other one ,upload things. As you like Beauty & Style?football or Pets?you can create a special topic such as Football Forum . We can provide you a free?stable?high-speed ?Professional and technical Forum.So what are you waiting for? Come on ! From laurent.pointal at wanadoo.fr Sun Apr 1 13:45:15 2007 From: laurent.pointal at wanadoo.fr (Laurent Pointal) Date: Sun, 01 Apr 2007 19:45:15 +0200 Subject: Python Based API References: <1175441871.933442.152630@p77g2000hsh.googlegroups.com> Message-ID: <460fee80$0$25945$ba4acef3@news.orange.fr> Dean.Brotzel at gmail.com wrote: > Hi, > > I work on a project that is built entirely using python and Tkinter. > We are at the point where we would like to give access to our > functionality to others via some sort of API. People who would use > our API develop in all kinds of languages from C/C++ to Pascal. > > Ideas that come to mind that allow us to build such an API are: > > 1) Require others to imbed the python interpreter via the c API to be > able to utilize our functionality. > 2) Build an XML RPC interface around our code. > 3) Rewrite our code base in C/C++, which should make it accessible to > all modern languages. > > I'm looking for more and potentially better ideas that will allow us > to offer an API to our customers without having to throw away or redo > a lot of the python code that we have already written. > > Thanks in advance, > Dean IMHO the simplest solution is XML RPC, and unless you have huge data to transmit or time constraint, it may be enough. From Robert.Katic at gmail.com Wed Apr 11 05:00:04 2007 From: Robert.Katic at gmail.com (goodwolf) Date: 11 Apr 2007 02:00:04 -0700 Subject: Does python have the static function member like C++ In-Reply-To: <461c98a7$0$15948$426a74cc@news.free.fr> References: <1176260903.362329.59370@o5g2000hsb.googlegroups.com> <1176261542.704649.240350@n76g2000hsh.googlegroups.com> <1176273559.047449.263710@n76g2000hsh.googlegroups.com> <461c895f$0$2128$426a74cc@news.free.fr> <1176277228.056538.268290@o5g2000hsb.googlegroups.com> <461c98a7$0$15948$426a74cc@news.free.fr> Message-ID: <1176282004.503283.247560@q75g2000hsh.googlegroups.com> On Apr 11, 10:15 am, Bruno Desthuilliers wrote: > goodwolf a ?crit : > > > > > On Apr 11, 9:09 am, Bruno Desthuilliers > 42.desthuilli... at wtf.websiteburo.oops.com> wrote: > >> goodwolf a ?crit : > >> (snip) > > >>> 1. In this case you will prefer a classmethod instead a staticmethod. > >>> 2. If counter is the number of instances of class AAA then you will > >>> incrase counter inside __init__ method. > >>> class AAA (object): > >>> counter = 0 > >>> def __init__(self): > >>> type(self).counter_increase() > >> You can call a class method on an instance: > >> self.counter_increase() > > >> And FWIW, this is probably something I'd put in the constructor (the > >> __new__ method), not in the initializer. > > >>> @classmethod > >>> def counter_increase(cls): > >>> cls.counter += 1 > >>> or > >>> class AAA (object): > >>> counter = 0 > >>> def __init__(self): > >>> type(self).counter += 1 > >> Instances have a reference to their class, so you can also write this: > >> self.__class__.counter += 1 > > > OK, you will use something like this: > > > class AAA (object): > > counter = 0 > > def __new__(cls): > > cls.counter += 1 > > return super(cls, cls).__new__(cls) > > return super(AAA, cls).__new__(cls) > > > but I think that __new__ is more "low level" and not necessary here, > > It's of course 'not necessary'. But (IMHO): > - increasing the class's instance counter is more a responsability of > the class than a responsability of the instance - and it has nothing to > do with initializing the instance's state > - if someone is to subclass AAA, there are fewer chances that he'll > override the constructer than the initializer, and if he does, there are > more chances that he won't forget to call on the parent's constructor. > > IOW, this is actually *because* it is 'lower level' that I think it's a > better place for such operations. > > But YMMV, of course !-) > > My 2 cents... OK, but then you will use an more flexible constructor: class AAA (object): counter = 0 def __new__(cls, *args, **kwargs): cls.counter += 1 return super(AAA, cls).__new__(cls, *args, **kwargs) then you see that you will pay lot resources for a "lower level" operation. However if your counter is to consider a low level think, than You are right, but it's more a personal consideration. From whamil1 at entergy.com Thu Apr 5 15:15:39 2007 From: whamil1 at entergy.com (Hamilton, William ) Date: Thu, 5 Apr 2007 14:15:39 -0500 Subject: Objects, lists and assigning values Message-ID: <588D53831C701746A2DF46E365C018CE01D2CA62@LITEXETSP001.etrsouth.corp.entergy.com> -----Original Message----- From: python-list-bounces+whamil1=entergy.com at python.org [mailto:python-list-bounces+whamil1=entergy.com at python.org] On Behalf Of Manuel Graune Sent: Thursday, April 05, 2007 12:14 PM To: python-list at python.org Subject: Objects, lists and assigning values Hello, while trying to learn how to program using objects in python (up to now simple scripts were sufficient for my needs) I stumbled over the a problem while assigning values to an object. The following piece of code shows what I intend to do: <---snip---> class new_class(object): def __init__( self, internal_list=[]): self.internal_list= internal_list external_list=[[b*a for b in xrange(1,5)] for a in xrange(1,5)] print external_list first_collection=[new_class() for i in xrange(4)] temporary_list=[[] for i in xrange(4)] for i in xrange(4): for j in xrange(4): temporary_list[i].append(external_list[i][j]) first_collection[i].internal_list=temporary_list[i] #Now everything is as I want it to be: for i in xrange(4): print first_collection[i].internal_list #Now I tried to get the same result without the temporary #variable: second_collection=[new_class() for i in xrange(4)] for i in xrange(4): for j in xrange(4): second_collection[i].internal_list.append(external_list[i][j]) #Which obviously leads to a very different result: for i in xrange(4): print second_collection[i].internal_list <---snip---> Can someone explain to me, what's happening here and why the two approaches do not lead to the same results? Thanks in Advance. ---------------------------------------------------- Changing the definition of the class init function to: def __init__( self, internal_list=None): if internal_list: self.internal_list= internal_list else: self.internal_list= [] fixes it. The list in the default parameter of your version is created once; every time an instance of the class is created, the self.internal_list in that new class is assigned the same list instance as all the other class instances. When you append something to any of those classes' lists, all of the classes' lists appear to change because they're all actually the same list. Your first_collection works because you're reassigning the class parameter to a new list. The second_collection doesn't work because you're appending to the (flawed) existing list assignment. --- -Bill Hamilton whamil1 at entergy.com From jstroud at mbi.ucla.edu Wed Apr 4 04:21:02 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Wed, 04 Apr 2007 08:21:02 GMT Subject: Requirements For A Visualization Software System For 2010 In-Reply-To: <1175628186.459945.290750@d57g2000hsg.googlegroups.com> References: <1175628186.459945.290750@d57g2000hsg.googlegroups.com> Message-ID: Check out pymol. James From nagle at animats.com Sat Apr 7 20:13:12 2007 From: nagle at animats.com (John Nagle) Date: Sat, 07 Apr 2007 17:13:12 -0700 Subject: block scope? In-Reply-To: <7xtzvseqzo.fsf@ruckus.brouhaha.com> References: <7xr6qwal50.fsf@ruckus.brouhaha.com> <7xtzvseqzo.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > John Nagle writes: > >> In a language with few declarations, it's probably best not to >>have too many different nested scopes. Python has a reasonable >>compromise in this area. Functions and classes have a scope, but >>"if" and "for" do not. That works adequately. > > > I think Perl did this pretty good. If you say "my $i" that declares > $i to have block scope, and it's considered good practice to do this, > but it's not required. You can say "for (my $i=0; $i < 5; $i++) { ... }" > and that gives $i the same scope as the for loop. Come to think of it > you can do something similar in C++. Those languages have local declarations. "my" is a local declaration. If you have explicit declarations, explict block scope is no problem. Without that, there are problems. Consider def foo(s, sname) : if s is None : result = "" else : result = s msg = "Value of %s is %s" % (sname, result) return(msg) It's not that unusual in Python to initialize a variable on two converging paths. With block scope, you'd break code that did that. John Nagle From http Sat Apr 14 01:51:42 2007 From: http (Paul Rubin) Date: 13 Apr 2007 22:51:42 -0700 Subject: Append data to a list within a dict References: Message-ID: <7xejmnbj0x.fsf@ruckus.brouhaha.com> Tina I writes: > ListDict = { > 'one' : ['oneone' , 'onetwo' , 'onethree'], > 'two' : ['twoone' , 'twotwo', 'twothree'], > 'three' : ['threeone' , 'threetwo', threethree']} > > Now I want to append 'twofour' to the list of the 'two' key but I > can't figure out how to that? Is this a class exercise? Hint: 1) figure out how to access the list of the 'two' key 2) append 'twofour' to it. From theo at van-werkhoven.nl.invalid Sat Apr 28 07:50:55 2007 From: theo at van-werkhoven.nl.invalid (Theo v. Werkhoven) Date: Sat, 28 Apr 2007 13:50:55 +0200 Subject: Program runs in all directories, except one.. Message-ID: Goodday, Something strange going on here. A piece of code I wrote bombs out in one of de directories under $HOME, but not in others. Here's a snipped: #v+ def bin2asc(c): s='' for i in range(0,8): if c & 1<<(7-i): s+='1' else: s+='0' return 'b'+s def shiftout(numoctets): os.system('clear') ser = serial.Serial(0) from array import array octarray = [0] for i in range(0,numoctets-1): octarray.append(0) for octet in range(numoctets,0,-1): octarray[octet-1]=1 for shift in range(0,8): strg = array("B",octarray).tostring() for oct in range(len(strg)): print 'octet%-11s' % oct, print for byte in array("B",octarray): print '%-2s' % bin2asc(int(byte)), print '%-6s' % hex(int(byte)), print; print try: dummy = raw_input("Druk op een toets om de bytes te verzenden ") except KeyboardInterrupt, msg: print; usage("Exiting..") sys.exit() ser.write(strg) octarray[octet-1] = octarray[octet-1] << 1 os.system('clear') octarray[octet-1]=0 print "done.. #v- Here's the output from the directory it bombs out in: #v+ theo:/home/theo/Devel/Python $ python serialLEDtest-cli.py Hoeveel chips van het type HC595 zitten er op het LED board? 2 0 7865 8162 8220 17307 251430 5886084 5886182 5891527 5892283 5901048 5901062 Traceback (most recent call last): File "serialLEDtest-cli.py", line 96, in main() File "serialLEDtest-cli.py", line 93, in main shiftout(numoctets) File "serialLEDtest-cli.py", line 62, in shiftout strg = array("B",octarray).tostring() TypeError: 'list' object is not callable #v- Where the numbers come from I don't know, python internal? #v+ theo:/home/theo/Devel/Python$ stat serialLEDtest-cli.py File: `serialLEDtest-cli.py' Size: 2641 Blocks: 8 IO Block: 4096 regular file Device: fd00h/64768d Inode: 69113 Links: 4 Access: (0644/-rw-r--r--) Uid: ( 1000/ theo) Gid: ( 100/ users) Access: 2007-04-28 13:28:23.000000000 +0200 Modify: 2007-04-28 13:00:33.000000000 +0200 Change: 2007-04-28 13:22:38.000000000 +0200 #v- Now i've made hard links to other directories, like $HOME and $HOME/bin #v+ theo:/home/theo $ stat serialLEDtest-cli.py File: `serialLEDtest-cli.py' Size: 2641 Blocks: 8 IO Block: 4096 regular file Device: fd00h/64768d Inode: 69113 Links: 4 Access: (0644/-rw-r--r--) Uid: ( 1000/ theo) Gid: ( 100/ users) Access: 2007-04-28 13:30:02.000000000 +0200 Modify: 2007-04-28 13:00:33.000000000 +0200 Change: 2007-04-28 13:22:38.000000000 +0200 #v- And when I run (the same script) from that location: #v+ theo:/home/theo $ python serialLEDtest-cli.py Hoeveel chips van het type HC595 zitten er op het LED board? 2 octet0 octet1 b00000000 0x0 b00000001 0x1 Druk op een toets om de bytes te verzenden #v- Not a problem there, and neither in other directories I made links in, or copied the file to, only in that one directory.. Anyone have ideas? Tnx. Theo -- theo at van-werkhoven.nl ICQ:277217131 SuSE Linux linuxcounter.org: 99872 Jabber:muadib at jabber.xs4all.nl AMD XP3000+ 1024MB "ik _heb_ niets tegen Microsoft, ik heb iets tegen de uitwassen *van* Microsoft" From gagsl-py2 at yahoo.com.ar Thu Apr 12 15:15:39 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 12 Apr 2007 16:15:39 -0300 Subject: Inconsistent result from urllib.urlopen References: <1176402303.340868.165510@o5g2000hsb.googlegroups.com> Message-ID: En Thu, 12 Apr 2007 15:25:03 -0300, escribi?: > Any ideas why I don't get the same result from the python script as I > do from a web browser? This problem seems to be a recent > development. The scripts I wrote like this worked fine for a while > and then stopped working within the past couple of weeks. The server (that is, Wikipedia) may choose to send a different response based on the User-Agent header you provide. -- Gabriel Genellina From mail at timgolden.me.uk Thu Apr 19 10:54:29 2007 From: mail at timgolden.me.uk (Tim Golden) Date: Thu, 19 Apr 2007 15:54:29 +0100 Subject: Byte-Array to String In-Reply-To: <000f01c7828f$8b8ce770$a2a6b650$@rawlins@thinkbluemedia.co.uk> References: <000f01c7828f$8b8ce770$a2a6b650$@rawlins@thinkbluemedia.co.uk> Message-ID: <462782A5.5060000@timgolden.me.uk> Robert Rawlins - Think Blue wrote: > I have a byte array passed to me by dbus and I'm looking to convert it into > a string? Is that possible? Sorry for seeming like a putts with these > questions, I'm not used to all these complex data types :-D > > dbus.Array([dbus.Byte(54), dbus.Byte(0), dbus.Byte(24), dbus.Byte(9), > dbus.Byte(0), dbus.Byte(0), dbus.Byte(10), dbus.Byte(0), dbu > s.Byte(0), dbus.Byte(0), dbus.Byte(0), dbus.Byte(9), dbus.Byte(0), > dbus.Byte(1), dbus.Byte(53), dbus.Byte(3), dbus.Byte(25), dbus. > Byte(16), dbus.Byte(0), dbus.Byte(9), dbus.Byte(2), dbus.Byte(0), > dbus.Byte(53), dbus.Byte(3), dbus.Byte(9), dbus.Byte(1), dbus.By > te(1)], signature=dbus.Signature('y')) No idea, but what happens when you iterate over it? for i in array_thingy: print i Or does it support the buffer interface? for i in buffer (array_thingy): print i If it did then you can at least get access to its innards and construct some kind of string representation. I've no idea what the numbers are supposed to represent, so I don't know what "convert it to a string" is likely to imply. This looks rather more like a dbus question than a strictly Python one. Is there a DBus mailing list or what-have-you? TJG From bironelynch at gmail.com Tue Apr 3 13:50:52 2007 From: bironelynch at gmail.com (Birone Lynch) Date: Tue, 3 Apr 2007 19:50:52 +0200 Subject: Retrieve an item from a dictionary using an arbitrary object as the key Message-ID: > > > > getPerson(19) ....should return me the Person with name "bob" and age > > 99. I am thinking there is some method that is used by the dictionary > > to know if the key exists, just not sure which. Were you thinking of get: a.get(k[, x]) returns a[k] if k in a, else x But do you want to lookup by the object itself, or by its val attribute? (Your code suggests the latter, but that's not what your title says...) ---------- Forwarded message ---------- > From: tom at finland.com > To: python-list at python.org > Date: Tue, 03 Apr 2007 16:35:13 GMT > Subject: Re: Stack experiment > Ok, I got it running. Thank you! > > I removed the space and top of that I had foul indentation in return > statement. > > I'll try the approaches you suggest. > > > > ---------- Forwarded message ---------- > From: Steven Bethard > To: python-list at python.org > Date: Tue, 03 Apr 2007 10:38:41 -0600 > Subject: Re: getattr/setattr q. > Steve Holden wrote: > > You don't need setattr/getattr if you know in advance the name of the > > attribute you need to access and you can get a reference to the object > > whose attribute it is. So: > > > > >>> x = "Hello, Paulo" > > >>> import sys > > >>> sys.modules['__main__'].x > > 'Hello, Paulo' > > a.k.a > > >>> import __main__ > >>> __main__.x > 'Hello, Paulo' > > STeVe > > > > ---------- Forwarded message ---------- > From: Steve Holden > To: python-list at python.org > Date: Tue, 03 Apr 2007 12:43:17 -0400 > Subject: Re: getattr/setattr q. > Steven Bethard wrote: > > Steve Holden wrote: > >> You don't need setattr/getattr if you know in advance the name of the > >> attribute you need to access and you can get a reference to the object > >> whose attribute it is. So: > >> > >> >>> x = "Hello, Paulo" > >> >>> import sys > >> >>> sys.modules['__main__'].x > >> 'Hello, Paulo' > > > > a.k.a > > > > >>> import __main__ > > >>> __main__.x > > 'Hello, Paulo' > > > Indeed. Any handle on the right object will do. > > 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 > > > > > ---------- Forwarded message ---------- > From: Steve Holden > To: python-list at python.org > Date: Tue, 03 Apr 2007 12:44:53 -0400 > Subject: Re: Stack experiment > kyosohma at gmail.com wrote: > [...] > > > > Steve, > > > > How do you do "tokenList = split(expr)"? There is no builtin called > > "split". > > > > Mike > > > > Sorry, that should have been a call to the .split() method of expr, i.e.: > > tokenList = expr.split() > > 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 > > > > > ---------- Forwarded message ---------- > From: "olive" > To: python-list at python.org > Date: 3 Apr 2007 10:09:48 -0700 > Subject: Re: XML DTD analysis, diffing ... > Thank you Stephane, > > it is almost what I want. > > I'm going to improve it a little and then provide the code back. > Where is the best place ? > > Olive. > > > > > > ---------- Forwarded message ---------- > From: Robert Kern > To: python-list at python.org > Date: Tue, 03 Apr 2007 12:21:44 -0500 > Subject: Re: Numeric compiling problem under QNX 4.25 > bernhard.voigt at gmail.com wrote: > > Hi, > > > > unfortunately I don't have a solution. However, if you're not forced > > to use Python2.2 and Numeric you should use Numpy (the successor for > > both, Numeric and Numarray). Numpy requires Python2.3, though. > > He's already asked about numpy. He is stuck with 2.2. > > -- > 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 > > > > > ---------- Forwarded message ---------- > From: care02 at gmail.com > To: python-list at python.org > Date: 3 Apr 2007 10:21:59 -0700 > Subject: How can I kill a running thread when exiting from __main__ > Hi! > > I have the following problem: I have written a short Python server > that creates an indefinite simulation thread that I want to kill when > quitting (Ctrl-C) from Python. Googling around has not given me any > hints on how to cleanly kill running threads before exiting. Any help > is appreciated! > > Carl > > ### CODE EXTRACT ### > > import pythoncom > > class QueueThread( threading.Thread): > def __init__(self, command): > threading.Thread.__init__(self) > self.command = command > > def run(self): > pythoncom.CoInitialize() > try: > object = Dispatch('application') > execute = getattr(object, 'Execute') > execute(self.command ) > finally: > object = None > pythoncom.CoUnitialize() > > queuethread = QueueThread("queuehandler") > queuethread.setDaemon(True) > queuethread.start() > > ## How can I kill "queuethread" when exiting (Ctrl-C)? > > > > > ---------- Forwarded message ---------- > From: Robert Kern > To: python-list at python.org > Date: Tue, 03 Apr 2007 12:22:50 -0500 > Subject: Re: Numeric compiling problem under QNX 4.25 > ZMY wrote: > > Dear all, > > > > I am a real newbie for both python and QNX, but I am still trying to > > compile Numeric-24.2 under QNX4.25 with python 2.2. I got following > > error message: > > > > > > $ sudo python setup.py install > > Password: > > running install > > ... > > building '_numpy' extension > > skipping Src/_numpymodule.c (build/temp.qnx-O-PCI-2.2/_numpymodule.o > > up-to-date) > > skipping Src/arrayobject.c (build/temp.qnx-O-PCI-2.2/arrayobject.o up- > > to-date) > > skipping Src/ufuncobject.c (build/temp.qnx-O-PCI-2.2/ufuncobject.o up- > > to-date) > > ld build/temp.qnx-O-PCI-2.2/_numpymodule.o build/temp.qnx-O-PCI-2.2/ > > arrayobject.o build/temp.qnx-O-PCI-2.2/ufuncobject.o -o build/lib.qnx- > > O-PCI-2.2/_numpy.so > > unable to execute ld: No such file or directory > > error: command 'ld' failed with exit status 1 > > It looks like it can't find the command ld. Can you compile any other > extension > modules? > > -- > 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 > > > > > ---------- Forwarded message ---------- > From: "Boudreau, Emile" > To: > Date: Tue, 3 Apr 2007 13:26:54 -0400 > Subject: Extracting a file from a tarball > > I am trying to extract one file from a tarball, without success. This is > the code I'm using to open the tarball and extract the file: > > tar = tarfile.open(component+'-win32-app-'+bestVersion+'-dev.tar.gz', 'r') > extractedFile = tar.extractfile('symbols.xml') > > And this is my error: > > Traceback (most recent call last): > File "C:\CognosInstalls\AutoTest\PollDir.py", line 121, in > main() > File "C:\CognosInstalls\AutoTest\PollDir.py", line 119, in main > extract('c:\\', 'I:\\daily\\'+components[i], components[i]) > File "C:\CognosInstalls\AutoTest\PollDir.py", line 27, in extract > filelike = tar.extractfile('symbols.xml') > File "C:\Python25\lib\tarfile.py", line 1488, in extract > tarinfo = self.getmember(member) > File "C:\Python25\lib\tarfile.py", line 1171, in getmember > raise KeyError("filename %r not found" % name) > KeyError: "filename 'symbols.xml' not found" > > I know that the tarball contants this file "symbols.xml" but I don't > understand why it's not extracting it. Any help will be greatly appreciated. > > Thanks, > > 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. > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From erikwickstrom at gmail.com Thu Apr 5 11:31:35 2007 From: erikwickstrom at gmail.com (erikcw) Date: 5 Apr 2007 08:31:35 -0700 Subject: AttributeError: 'tuple' object has no attribute 'encode' Message-ID: <1175787095.862712.297480@n76g2000hsh.googlegroups.com> Hi, I'm trying to build a SQL string sql = """INSERT INTO ag ('cid', 'ag', 'test') VALUES(%i, %s, %d)""", (cid, ag, self.data[parent][child]['results']['test']) It raises this error: AttributeError: 'tuple' object has no attribute 'encode' Some of the variables are unicode (test and ag) - is that what is causing this error? What do I need to do to make it work? Thanks! Erik From aleax at mac.com Wed Apr 4 23:07:06 2007 From: aleax at mac.com (Alex Martelli) Date: Wed, 4 Apr 2007 20:07:06 -0700 Subject: Prevent Modification of Script? References: <1175735097.856840.177510@e65g2000hsc.googlegroups.com> <877isrh7yr.fsf@benfinney.id.au> Message-ID: <1hw2agv.ium2dr1ngwufmN%aleax@mac.com> Ben Finney wrote: > "ts-dev" writes: > > > Is it possible to prevent modification of a python file once its been > > deployed? > > Prevent modification by whom? > > You can't prevent modification by the person who owns the > machine. It's in their possession, and presumably it's out of yours; > they can do whatever they like. Hmmm -- if the file is deployed on read-only media it might be possible to prevent modification. Of course, one could COPY it to read-write media, and modify the copy, but that would still entirely satisfy the requirement of "preventing modification of the file" as stated. Alex From steve at REMOVE.THIS.cybersource.com.au Thu Apr 12 17:46:38 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Fri, 13 Apr 2007 07:46:38 +1000 Subject: tuples, index method, Python's design References: <1176210960.3430.20.camel@dot.uniqsys.com> <740c3aec0704100810g5f962e8eu614fbaedecf3608e@mail.gmail.com> <1176219856.3430.76.camel@dot.uniqsys.com> <740c3aec0704101021i1fd79ef2l99eac4ced1e252d9@mail.gmail.com> <1176226682.3430.86.camel@dot.uniqsys.com> <4866bea60704101104r4600d281h135286b66378f4d4@mail.gmail.com> <740c3aec0704101534y3c65f5a7je382f97e1f6301b7@mail.gmail.com> <1176305859.581010.199600@n76g2000hsh.googlegroups.com> Message-ID: On Thu, 12 Apr 2007 07:37:38 +0000, Antoon Pardon wrote: > I once had a problem I like to solve by having a dictionary > where the keys were multidimensional points on an integer grid. > For a number of reasons I thought it would be easier if I could > use lists, but most people argued that would be a bad idea and > that I should use tuples, because they are immutable. Also because code that raises "TypeError: list objects are unhashable" is probably not going to work very well. > Of course if I now would want to find out if the point is on an axis and > which axis that is, I cannot use index because that is not available. If memory is more important to you than speed: class IndexTuple(tuple): def index(self, target): for i, x in enumerate(self): if x == target: return i raise ValueError Or if speed is more important to you than memory: class IndexTuple2(tuple): def index(self, target): return list(self).index(target) If you prefer not to subclass, you can write an index function: def index(sequence_or_mapping, target): try: return sequence_or_mapping.index(target) except AttributeError: return list(sequence_or_mapping).index(target) So much fuss over such a little thing... yes it would be nice if tuples grew an index method, but it isn't hard to work around the lack. -- Steven. From gagsl-py2 at yahoo.com.ar Thu Apr 12 04:47:46 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 12 Apr 2007 05:47:46 -0300 Subject: reading from sys.stdin References: <1176366058.261031.111870@p77g2000hsh.googlegroups.com> Message-ID: En Thu, 12 Apr 2007 05:20:58 -0300, 7stud escribi?: > I can't break out of the for loop in this example: > > ------ > import sys > > lst = [] > for line in sys.stdin: > lst.append(line) > break > > print lst > ----------- Python 2.5.1c1 (r251c1:54692, Apr 5 2007, 09:19:18) [MSC v.1310 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. py> import sys py> lst = [] py> for line in sys.stdin: ... lst.append(line) ... break ... hola que tal como estan ^Z py> print lst ['hola\n'] ----------- I typed many lines, but lst contains only one item, as expected. Same as your regular file example: the file contains many lines, but only the first goes into the list. -- Gabriel Genellina From irmen.NOSPAM at xs4all.nl Tue Apr 10 16:30:34 2007 From: irmen.NOSPAM at xs4all.nl (Irmen de Jong) Date: Tue, 10 Apr 2007 22:30:34 +0200 Subject: [offtopic?] problem with UDP broadcast on Windows XP In-Reply-To: References: <461a271c$0$323$e4fe514c@news.xs4all.nl> <461a6523$0$327$e4fe514c@news.xs4all.nl> <012e01c77b3c$09bd3ec0$03000080@hendrik> Message-ID: <461bf42a$0$326$e4fe514c@news.xs4all.nl> > Hendrik van Rooyen wrote: >> I am not sure if this is at all relevant - but I seem to recall seeing >> something once that had a list of socket numbers, splitting them >> between UDP & TCP - can the socket actually rx UDP? Yeah, as I wrote: when I'm sending UDP packets to the port directly on the server's IP address, it responds just fine. It's just the broadcast packets that don't seem to arrive. (sent to ('',9090) ) Steve Holden wrote: > It's most likely, I suspect without knowing to much about it, that the > service is stalling because of a failure to "pump" Windows messages. > Irmen, are you taking any action in your service to ignore Windows > messages that your service process receives? Hm, seeing that it processes TCP and "directed" UDP packets just fine, there shouldn't be a problem here? No I'm not knowingly doing stuff that ignores windows messages... (I could maybe put up the code if someone wants to take a look but not right now. Need to rip a fair deal out - there's a lot of other stuff in there that's not relevant to the problem.) --Irmen From mike.klaas at gmail.com Mon Apr 23 16:43:26 2007 From: mike.klaas at gmail.com (Klaas) Date: 23 Apr 2007 13:43:26 -0700 Subject: Select weirdness In-Reply-To: References: Message-ID: <1177361006.052666.282060@n76g2000hsh.googlegroups.com> On Apr 23, 9:51 am, Ron Garret wrote: > In article , > Jean-Paul Calderone wrote: > > > Twisted does this out of the box, for what it's worth. > > Thanks. I will look at that. There is also asyncore in the standard library, which is a very light pythonic wrapper around select() dispatching to handlers. Works great. -Mike From half.italian at gmail.com Thu Apr 19 16:44:42 2007 From: half.italian at gmail.com (half.italian at gmail.com) Date: 19 Apr 2007 13:44:42 -0700 Subject: NFS Help In-Reply-To: <1177007562.103413.310390@o5g2000hsb.googlegroups.com> References: <1177007562.103413.310390@o5g2000hsb.googlegroups.com> Message-ID: <1177015482.628567.15650@l77g2000hsb.googlegroups.com> On Apr 19, 11:32 am, Clement wrote: > how to get the file from NFS share in python...... You need to be more specific. If you just want to copy a file try shutil http://docs.python.org/lib/module-shutil.html ~Sean From pyguido at hotmail.fr Thu Apr 12 10:58:49 2007 From: pyguido at hotmail.fr (pierre-yves guido) Date: Thu, 12 Apr 2007 16:58:49 +0200 Subject: help Message-ID: hello (I hope my english is not so bad), I'm doing a training course and I'm a newbie in Python. My problem : I have a form, and when I click, I make an update. But all the parameters are all required to make the update. So I'd like to put in my code something like [optional]... My code (simplyfied) : prg.ev_ind_update(wf_pk_ev_ind=wf_pk_ev_ind,wf_fonction=wf_fonction,wf_nom=wf_nom) and so, when I put nothing in wf_nom, it put me that error :"the parameter wf_nom...was omitted from the request...". But sometimes, wf_nom is not required ! Thanks to help a poor young boy _________________________________________________________________ Personnalisez votre Messenger avec Live.com http://www.windowslive.fr/livecom/ From fsckedagain at gmail.com Wed Apr 11 13:13:38 2007 From: fsckedagain at gmail.com (fscked) Date: 11 Apr 2007 10:13:38 -0700 Subject: ValueError: too many values to unpack Message-ID: <1176311618.617765.120560@p77g2000hsh.googlegroups.com> Trying to use CSV to read in a line with 11 fields and I keep getting this error. I have googled a bit and have been unable to figure it out. From martin at v.loewis.de Thu Apr 19 03:29:39 2007 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Thu, 19 Apr 2007 09:29:39 +0200 Subject: unicode and __repr__() In-Reply-To: <3017205.ViBn82uq2M@beaureve.gmx.net> References: <3017205.ViBn82uq2M@beaureve.gmx.net> Message-ID: <46271A63.4040009@v.loewis.de> Martin Drautzburg schrieb: > I am using UTF-8 and assembling the string expression > manually works okay and the umlaute appear correctly in the browser (so > I could probably write my own serializer and it would work). That's what you should do. Or you can use one that people have already written, e.g. http://cheeseshop.python.org/pypi/simplejson Regards, Martin From schpok at gmail.com Wed Apr 25 18:31:53 2007 From: schpok at gmail.com (Joshua Schpok) Date: Wed, 25 Apr 2007 15:31:53 -0700 Subject: pydoc and imported modules In-Reply-To: <462FCE41.2030400@ronadam.com> References: <1177080853.261895.224440@q75g2000hsh.googlegroups.com> <462FCE41.2030400@ronadam.com> Message-ID: <7aa19c250704251531n3dd155c8q7e6bec127d282990@mail.gmail.com> I see. To make sure all my modules imported * are included in the pydocs, I'll add: __all__ = dir() to the end of my __init__.py file. Sometimes I implement a module with submodules, and flatten them out in __init__.py so the user sees it all as one single module. For example, module 'foobar' may be implemented in _foo and _bar, though I want their contents exposed in the single module 'foobar'. So my __init__.py would look like: from _foo import * from _bar import * I noticed their pydocs weren't getting expanded if they were a) implemented in python, or b) bound using boost::python (regular c bindings and pyrex work). Apparently these approaches don't add their members to __all__. It's odd to me that you can still call _foo's member 'baz' through the foobar namespace, as though it is a member of foobar. I'm not sure if this is something that needs to be changed in pydoc. If __all__ represents the public interface of a module, that should be the thing we document. I was confused that __all__ behavior varied with implementation, and understand that my python and boost::python implementations may not be exporting their interface. Thanks for illuminating the problem, Schpok On 4/25/07, Ron Adam wrote: > schpok at gmail.com wrote: > > When I "from foo import *" in my __init__.py, sometimes module foo's > > docs will be expanded in the pydocs. It seems to depend in what > > language foo was implemented. > > > > For example, if you "from math import *" in your __init__.py, you will > > see math's members will appear in the resulting pydocs, as though it's > > part of your module. The behavior is consistent across the C modules I > > am writing. > > > > However, if you "from foo import *" in your __init__.py, and foo is a > > python file (not a module written in C), foo's members don't appear in > > the resulting pydocs. This also seems to occur in some boost::python > > bindings. > > > > What is expected behavior? How do ensure foo's docs do or don't appear > > in help, regardless of their implementation language? > > > > Thanks, > > Schpok > > Pydoc doesn't check the __module__ attribute of the items imported, it just > displays what is in the modules name space as if it was defined in that module. > > In __init__.py files where an __all__ variable is defined, it won't show > items that aren't in __all__. This is probably what you are seeing. > > I'm currently rewriting pydoc, so what behavior would you like to see? > > Cheers, > Ron > > From jzgoda at o2.usun.pl Fri Apr 13 16:52:57 2007 From: jzgoda at o2.usun.pl (Jarek Zgoda) Date: Fri, 13 Apr 2007 22:52:57 +0200 Subject: Python editor/IDE on Linux? In-Reply-To: References: Message-ID: Jack napisa?(a): >> pida because it embeds the 'vim' editor which I love and adds useful >> features without really getting in my way. And it's the only IDE I found >> that supports bazaar-ng (bzr) repositories. > > pida screenshots look neat. It's not in xubuntu's repository though. Not > even in universe. > I installed from the source. When running it, I get an error "Service not > found. Tried to > access non-existing service filemanager" I wouldn't recommend PIDA to nobody except real hardcore Vim lovers. If you don't mint occasional crashes, then PIDA might be for you, but don't expect increased productivity, as this is an alpha-quality software and most of expected functionality simply doesn't work as expected. This is an ongoing project and they (community, testers, developers) strive to make it better, but this is a completely "spare-time" project AFAIK. Download it, install it, try to use it, report bugs and omissions, help them make this software better. We would all profit. :) -- Jarek Zgoda http://jpa.berlios.de/ From cam.ac.uk at mh391.invalid Fri Apr 27 10:26:51 2007 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Fri, 27 Apr 2007 15:26:51 +0100 Subject: regex question In-Reply-To: <1177683018.566343.105620@c18g2000prb.googlegroups.com> References: <1177655637.717863.93920@o40g2000prh.googlegroups.com> <1177659238.159411.40640@c18g2000prb.googlegroups.com> <1177683018.566343.105620@c18g2000prb.googlegroups.com> Message-ID: proctor wrote: > On Apr 27, 1:33 am, Paul McGuire wrote: >> On Apr 27, 1:33 am, proctor <12cc... at gmail.com> wrote: >>> rx_test = re.compile('/x([^x])*x/') >>> s = '/xabcx/' >>> if rx_test.findall(s): >>> print rx_test.findall(s) >>> ============ >>> i expect the output to be ['abc'] however it gives me only the last >>> single character in the group: ['c'] > >> As Josiah already pointed out, the * needs to be inside the grouping >> parens. > so my question remains, why doesn't the star quantifier seem to grab > all the data. Because you didn't use it *inside* the group, as has been said twice. Let's take a simpler example: >>> import re >>> text = "xabc" >>> re_test1 = re.compile("x([^x])*") >>> re_test2 = re.compile("x([^x]*)") >>> re_test1.match(text).groups() ('c',) >>> re_test2.match(text).groups() ('abc',) There are three places that match ([^x]) in text. But each time you find one you overwrite the previous example. > isn't findall() intended to return all matches? It returns all matches of the WHOLE pattern, /x([^x])*x/. Since you used a grouping parenthesis in there, it only returns one group from each pattern. Back to my example: >>> re_test1.findall("xabcxaaaxabc") ['c', 'a', 'c'] Here it finds multiple matches, but only because the x occurs multiple times as well. In your example there is only one match. > i would expect either 'abc' or 'a', 'b', 'c' or at least just > 'a' (because that would be the first match). You are essentially doing this: group1 = "a" group1 = "b" group1 = "c" After those three statements, you wouldn't expect group1 to be "abc" or "a". You'd expect it to be "c". -- Michael Hoffman From rhamph at gmail.com Sat Apr 14 13:46:15 2007 From: rhamph at gmail.com (Rhamphoryncus) Date: 14 Apr 2007 10:46:15 -0700 Subject: tuples, index method, Python's design In-Reply-To: <7x3b33k0l9.fsf@ruckus.brouhaha.com> References: <7xzm5igbrb.fsf@ruckus.brouhaha.com> <1176200361.260546.280510@n76g2000hsh.googlegroups.com> <740c3aec0704100824m132c45fbi5c4c3ec0c0fa3a67@mail.gmail.com> <1176489534.568939.249910@q75g2000hsh.googlegroups.com> <7x3b33k0l9.fsf@ruckus.brouhaha.com> Message-ID: <1176572775.382873.282850@q75g2000hsh.googlegroups.com> On Apr 13, 11:05 pm, Paul Rubin wrote: > "Rhamphoryncus" writes: > > > i = s.index(e) => s[i] = e > > > Then this algorithm is no longer guaranteed to work with strings. > > It never worked correctly on unicode strings anyway (which becomes the > > canonical string in python 3.0). > > What?! Are you sure? That sounds broken to me. Nope, it's pretty fundamental to working with text, unicode only being an extreme example: there's a wide number of ways to break down a chunk of text, making the odds of "e" being any particular one fairly low. Python's unicode type only makes this slightly worse, not promising any particular one is available. For example, if you had an algorithm designed for ascii that gathered statistics on how common each "character" is, you'd want to redesign it to use either grapheme clusters or scalar values, then improve it to merge duplicate characters. You'd need to roll your own iterator though, Python doesn't provide a method that's specifically grapheme clusters or scalar values (and if I'm wrong I'd love to hear it!). -- Adam Olsen, aka Rhamphoryncus From deets at nospam.web.de Tue Apr 17 11:43:45 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 17 Apr 2007 17:43:45 +0200 Subject: Syntax error References: <9w5Vh.8580$OT4.3503@newsfe19.lga> Message-ID: <58k89hF2hgicvU1@mid.uni-berlin.de> hg wrote: > Hi, > > I've had this problem in the past and still cannot fully understand. > > I latelly passed my source code in Wing IDE wihch asked be to resolve > tab/space/CRLF conflicts and I said yes (initially the code was developped > under Linux ... and now all source got tabs replaced by spaces and all EOL > when switched to Windows CR/LF) > > I sent a new release of the software, tested here first, to the customer > who got a syntax error on a line which visibly did not have any error. > > retyping that line by and made the error jump around the file like crazy. > > I had the customer comment out the first two lines of the file: > > """ > #!/bin/env python > # -*- coding: iso-8859-15 -*- > """ > > ... and the problem disappeared. > > I am at a loss. > > Any clue ? Without a stacktrace? It's spring, not crystal ball season. Diez From http Sat Apr 14 15:44:43 2007 From: http (Paul Rubin) Date: 14 Apr 2007 12:44:43 -0700 Subject: nonstandard XML character entities? References: <7xfy73ae08.fsf@ruckus.brouhaha.com> <46207e75$0$5795$9b622d9e@news.freenet.de> Message-ID: <7xwt0e7nbo.fsf@ruckus.brouhaha.com> "Martin v. L?wis" writes: > If they contain such things, and do not contain a document type > definition, they are not well-formed XML files (i.e. can't be > called "XML" in a meaningful sense). The documents do have a DTD, however the DTD file doesn't say anything about these entities. > It would have been helpful if you had given an example of such > a document. I can't post a whole document because these docs are very large and I'm not sure that the data is public. It does look like the DTD is public: the document begins with ... and that url points to the DTD which is online. Basically the doc has elements like Diana Montané and both ElementTree and xmllint complain about the character entities (and there are a lot of them). > If there is a document type declaration in the document, the best > way is to parse it in a mode where the parser downloads the DTD > when parsing it, and resolves the entity references itself. Hmm, ok, I see there are a lot of directives in the DTD but nothing about those character entities--am I looking in the right place? > In ElementTree, the XMLTreeBuilder has an attribute entity > which is a dictionary used to map entity names in entity references > to their definitions. Whether you can make the parser download > the DTD itself, I don't know. Chuck Rhode posted some code for something like this so I'll try it on Monday. Thanks! From Andy Tue Apr 24 04:35:20 2007 From: Andy (Andy) Date: Tue, 24 Apr 2007 18:35:20 +1000 Subject: *** Watch BOMBSHELL video of Senator John Kerry admitting 911 was in INSIDE JOB ??? References: <1177387965.127809.175390@l77g2000hsb.googlegroups.com> Message-ID: On 23 Apr 2007 21:12:45 -0700, lemnitzer at india.com wrote: >http://www.911blogger.com/node/8053 > >Senator John Kerry was questioned concerning 9/11 during an appearance >at Book People in Austin, Texas. Members of Austin 9/11 Truth Now >asked Kerry about the officially unexplained collapse of WTC Building >7." > >Kerry responded: > > "I do know that that wall, I remember, was in danger and I think >they made the decision based on the danger that it had in destroying >other things-- that they did it in a controlled fashion." > >http://www.jonesreport.com/articles/220407_kerry_wtc7.html > >Thanks to the dozen or so people who submitted this as a blog entry :) > >"Mr. Kerry?!?" > >"Just a follow-up or two... > >WHAT THE HELL|?| Are you saying that building was wired that day? Or >well in advance? 'Splain, please. > >Does your fellow Bonesman George Walker Bush appreciate you letting >the cat out of the bag on this? Is that your cell phone I hear >ringing? > >Why is your wife squirming like that? Stop it, Theresa! Stop it!" This is much more funny. http://www.youtube.com/watch?v=HCkYfYa8ePI&mode=related&search= From steve at holdenweb.com Thu Apr 26 10:23:33 2007 From: steve at holdenweb.com (Steve Holden) Date: Thu, 26 Apr 2007 10:23:33 -0400 Subject: Tutorial creates confusion about slices In-Reply-To: References: <1177535739.431386.77300@s33g2000prh.googlegroups.com> Message-ID: Michael Hoffman wrote: > Neil Cerutti wrote: >>> On Apr 23, 1:38 pm, Antoon Pardon wrote: >>>> The following is part of the explanation on slices in the >>>> tutorial: >>>> >>>> The best way to remember how slices work is >>> ... >>>> +---+---+---+---+---+ >>>> | H | e | l | p | A | >>>> +---+---+---+---+---+ >>>> 0 1 2 3 4 5 >>>> -5 -4 -3 -2 -1 > > >> I object only to the word "best". I don't like the above model >> because it divorces the indexes that appear in subscripts from >> those that appear in slices. I 't find it complicated to think: >> a[2:4] is the contiguous slice of elements starting at the gap >> between element 1 and 2, and ending at the gap between element 3 >> and 4. I've always found thinking of [2:4] as a half-open range >> much easier. >> >> I suppose the above model could avoid this notational problem if >> you say that a[k] means the one element slice a[k:k+1] >> (technically true for strings, but false for lists), rather than >> ever thinking of item indexes as pointing directly at an item. >> >> So I vote that the word "best" be removed. > > I agree. It would be better to say that, "One way to help you understand > how slices work is to think of..." I have just checked in that change. regards Steve -- Steve Holden +1 571 484 6266 +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 michael at jedimindworks.com Sun Apr 15 06:48:05 2007 From: michael at jedimindworks.com (Michael Bentley) Date: Sun, 15 Apr 2007 05:48:05 -0500 Subject: OverflowError: mktime argument out of range ??? In-Reply-To: <11e49df10704150341p1a9056e7hfba36a523517fad3@mail.gmail.com> References: <11e49df10704150341p1a9056e7hfba36a523517fad3@mail.gmail.com> Message-ID: On Apr 15, 2007, at 5:41 AM, Jorgen Bodde wrote: > This is what I try: > >>>> time.mktime((1928, 12,28, 0, 0, 0, 0, 0, 0)) > Traceback (most recent call last): > File "", line 1, in > OverflowError: mktime argument out of range Probably depends on your system. It doesn't break for me: >>> import time >>> time.mktime((1928, 12,28, 0, 0, 0, 0, 0, 0)) -1294164000.0 --- Simplicity is the ultimate sophistication. -Leonardo da Vinci From bdesth.quelquechose at free.quelquepart.fr Sat Apr 21 15:22:41 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sat, 21 Apr 2007 21:22:41 +0200 Subject: When are immutable tuples *essential*? Why can't you just use lists *everywhere* instead? In-Reply-To: <1177088796.622928.224890@d57g2000hsg.googlegroups.com> References: <1177088796.622928.224890@d57g2000hsg.googlegroups.com> Message-ID: <462a5b0f$0$4231$426a74cc@news.free.fr> seberino at spawar.navy.mil a ?crit : > Please help me think of an example where immutable tuples are > essential. Well, I don't know if they are "essential" - much of Python can be seen as 'unessential' syntactic sugar (my, even the class statement is not "essential" if you go that way). > It seems that everywhere a tuple is used one could just as easily use > a list instead. Ever tried using a list as key in a dict ? From aleax at mac.com Wed Apr 4 23:19:30 2007 From: aleax at mac.com (Alex Martelli) Date: Wed, 4 Apr 2007 20:19:30 -0700 Subject: pyc file [Newbie Question] References: Message-ID: <1hw2aoe.1svnyq71h0ah1xN%aleax@mac.com> Gabriel Genellina wrote: > En Tue, 03 Apr 2007 12:40:23 -0300, Jim Aikin > escribi?: > > > The Tutorial is very good, but there are numerous topics that it slides > > past > > (as it would have to do, in order to avoid being ten times as long). I > > haven't yet gotten deep enough into Python to even know where to look > > for a > > full explanation of what "import" does or what alternatives there might > > be > > to using it. > > There are many books about Python: > http://wiki.python.org/moin/IntroductoryBooks > "Dive into Python" may be a good choice if you have some programming > experience in another languages. OTOH, it doesn't really offer "a full explanation" and even alternatives, as Jim requests; I know of no _introductory_ book that meets that requirement as stated. Hey, even "Python in a Nutshell" might fall a little short, since "a full explanation" of all subtle intricacies of "import" (never mind "alternatives") might take at least a hundred pages, and I don't devote more than 50 to the subject; I figured that covering 99% of the subject in 50 pages was better than taking twice as many pages to cover 100%... or try to... hey, just today, at work, Guido and I and a couple of other colleagues had a disagreement on how exactly importing would work in a certain subtle case, and we settled it by careful _experiments_ -- and, remember, he INVENTED the language, and I wrote the best-selling reference book on the language -- thinking of a *full* explanation of subtleties that can momentarily confound us, in an *introductory* book, boggles the mind!-) Alex From codecraig at gmail.com Fri Apr 20 15:26:04 2007 From: codecraig at gmail.com (abcd) Date: 20 Apr 2007 12:26:04 -0700 Subject: regular expression for parsing an html element Message-ID: <1177097164.906533.252830@d57g2000hsg.googlegroups.com> I have some HTML such as.... blah blah blah.... I wnat to pull out the text that lies inside the quotes of the src attribute. So in this example I would get image/blah/a.jpg My regex so far is: src=\"(.*)\" ....however the group in this case would end up being, image/blah/a.jpg" id="ddddd">blah blah blah..... how can I tell the regex group (.*) to end when it gets to the first " ? thanks From ptmcg at austin.rr.com Tue Apr 10 21:39:58 2007 From: ptmcg at austin.rr.com (Paul McGuire) Date: 10 Apr 2007 18:39:58 -0700 Subject: Please help!!! In-Reply-To: <1176238783.257926.67310@30g2000cwc.googlegroups.com> References: <1176234239.436463.195870@n33g2000cwc.googlegroups.com> <1176236179.443346.162070@h3g2000cwc.googlegroups.com> <1176238783.257926.67310@30g2000cwc.googlegroups.com> Message-ID: <1176255598.488821.156110@q75g2000hsh.googlegroups.com> On Apr 10, 3:59 pm, "gslm" wrote: > On 10 Nisan, 23:16, "Paul McGuire" wrote: > > > > > On Apr 10, 2:43 pm, "gslm" wrote: > > > In fact ? know this, but I asked some questions like this, but ? haven't get any answer.And I thought that may be it could be better to use a header like this for help.Sorry! > > > > Hi to all! > > > I want to do a calendar with pictures near months. > > > I have designed the form's view.But unfortunately, I am not be able to > > > save this view as an image file.And so I am not be able to print this > > > image file too. > > > Question: > > > How can I determine the coordinates of a button?Namely How can I use > > > the comand ImageGrab for this purpose? > > > > But only I wan to get the button's ares.Because my applicationis on > > > this. > > > > Or if it's possible, how can I print the area of this button with the > > > components on it? > > > > Thanks... > > > Suggestion 1: "Please help!!!" is just about the worst newsgroup > > subject line there is (other than those related to government > > conspiracies or earthquake prediction). You are unlikely to attract > > the attention of those who really know anything - they are quite busy > > and must husband their time carefully. Instead, you'll get those who > > are idly curious, to see what sort of junk is floating about Usenet. > > > Suggestion 2: Consider your audience. What the heck are you talking > > about?! Your post goes on about calendars and buttons and views. In > > fact, trying to make sense of your post, it sounds like you've done > > something truly bizarre, like making the whole view one giant button > > with lots of images on it, and you want to print it out when the > > "button" is clicked. Is this even a Python question? Any particular > > GUI package you are using, such as Tk, wxPython, QT, your own homebrew > > invention? ImageGrab? Sounds promising, what do the docs say? > > > A more thorough discussion of these suggestions:http://www.catb.org/~esr/faqs/smart-questions.html > > > -- Paul- Al?nt?y? gizle - > > > - Al?nt?y? g?ster -- Hide quoted text - > > - Show quoted text - Just go do some homework for yourself. Then if you still need help, imagine the person you want to help you reading the subject and your question - how will they know what you need help with? how will they recognize what software you are using, what version of the software, what things you have tried and didn't work, and how did they fail? If you got a traceback, include it, plus the *actual code* that caused it. Then come back with a posting (and posting subject) that that person can understand and respond to. But don't post with "Please help!!!" - that's like posting on a job board with the subject "Need a job". -- Paul From half.italian at gmail.com Thu Apr 19 05:39:05 2007 From: half.italian at gmail.com (half.italian at gmail.com) Date: 19 Apr 2007 02:39:05 -0700 Subject: About installing new Python version. In-Reply-To: <1176973387.967130.27370@y80g2000hsf.googlegroups.com> References: <1176973387.967130.27370@y80g2000hsf.googlegroups.com> Message-ID: <1176975545.693682.51870@q75g2000hsh.googlegroups.com> On Apr 19, 2:03 am, king kikapu wrote: > Hi to all, > > i started with Python at v2.5 and now i see that a new version is > released. > As i already have a lot of stuff for Python installed in the site- > packages directory, which is the correct way to install a new Python > version without do any damage ? > > Remove Python and ALL Python related software and install them all > over again (painful)? > Remove Python and do not touch anything else and install new version > on top of them at the same directory ? > Any other choice available ? > > Thanks a lot for any help! Just install the new version. It should link everything back up so the new version is active, but the old versions are intact. ~Sean From wojciech_mula at poczta.null.onet.pl.invalid Sat Apr 7 11:48:51 2007 From: wojciech_mula at poczta.null.onet.pl.invalid (=?ISO-8859-2?Q?Wojciech_Mu=B3a?=) Date: Sat, 07 Apr 2007 17:48:51 +0200 Subject: Saving output of Turtle Graphics? In-Reply-To: References: Message-ID: Dick Moores wrote: >> Turtle module uses Tk canvas element to draw graphics ('_canvas' >> attribute). I've written module, that exports canvas graphics to SVG >> file: http://wmula.republika.pl/proj/canvas2svg/ -- it may be useful >> for you. > > I afraid I'm totally unfamiliar with SVG. Would it be possible for you > or someone else on the list to show how to use your module to export the > simple product of this simple script to an SVG file? > > =============================================== > import turtle as T import canvasvg > from random import randint > T.setup(width=1000, height=700, startx=0, starty=0) > T.color(1, .5, .5) > T.begin_fill() > # 2 connected lines will fill as a triangle > for x in range(2): > coord = (randint(-500,500), randint(-350,350)) > T.goto(coord) > T.end_fill() canvasvg.saveall("image.svg", T._canvas) > T.done() > ================================================ w. From ptmcg at austin.rr.com Fri Apr 20 15:16:47 2007 From: ptmcg at austin.rr.com (Paul McGuire) Date: 20 Apr 2007 12:16:47 -0700 Subject: Beautiful Soup iterator question.... In-Reply-To: References: <1177094168.548423.115730@y80g2000hsf.googlegroups.com> Message-ID: <1177096607.034365.220400@y80g2000hsf.googlegroups.com> On Apr 20, 2:05 pm, Steve Holden wrote: > > did you try something like (untested) > > cell1, cell2, cell3, cell4, cell5, \ > cell6, cell7, cell8 = row.findAll("td") > > No need for the "for" if you want to handle each cell differently, you > won;t be iterating over htem . And, as you saw, it doesn't work unless > row.findAll(...) returns a sequence of eight-item containers. > One defensive approach to handle rows that might have too few or too many elements, is to construct a larger list, and then slice the right number of elements from it. cell1, cell2, cell3, cell4, cell5, \ cell6, cell7, cell8 = (row.findAll("td") + [None]*8)[: 8] -- Paul From jan.m.danielsson at gmail.com Fri Apr 20 04:41:43 2007 From: jan.m.danielsson at gmail.com (Jan Danielsson) Date: Fri, 20 Apr 2007 10:41:43 +0200 Subject: Do other Python GUI toolkits require this? In-Reply-To: References: <462697A6.6010007@codebykevin.com> <1177014799.004875.262060@y80g2000hsf.googlegroups.com> Message-ID: <46287CC7.1080100@gmail.com> Antoon Pardon wrote: >> a) In English, "learning curve" is not restricted to a mathematical >> plot--Webster's also defines it as "the course of progress made in >> learning something". In that context, adding the adjective steep >> ("extremely or excessively high...STEEP implies such sharpness of >> pitch that ascent or descent is very difficult") makes sense. > > How much sense does it really make? Suppose we would talk about > an income curve. Would you not prefer a steep curve over a shalow > one? What about a productivity curve? It is all about the progress > made in something. I don't think I have seen "steep learning curve" used in that sense prior to reading your post. I have seen it being used as "what a steep cliff to climb!" (i.e. would would have been much easier with a "flatter" one). OTOH, I just went to an (Am.) English school my first school year, and language is not one of my fields of interest. So I'll just shut up and go away. -- Kind regards, Jan Danielsson From fatuheeva at yahoo.com Tue Apr 3 16:36:40 2007 From: fatuheeva at yahoo.com (Michael Castleton) Date: Tue, 3 Apr 2007 13:36:40 -0700 (PDT) Subject: File Object behavior In-Reply-To: References: <9821538.post@talk.nabble.com> Message-ID: <9825806.post@talk.nabble.com> Thank you to both Steve and 7stud. You were right on with binary flag! I thought I had tried everything... Mike -- View this message in context: http://www.nabble.com/File-Object-behavior-tf3520070.html#a9825806 Sent from the Python - python-list mailing list archive at Nabble.com. From Eric_Dexter at msn.com Mon Apr 30 12:35:40 2007 From: Eric_Dexter at msn.com (Eric_Dexter at msn.com) Date: 30 Apr 2007 09:35:40 -0700 Subject: fix an example of wxwindows listed on rentacoder.com Message-ID: <1177950940.661288.144680@n76g2000hsh.googlegroups.com> The code in question is at https://sourceforge.net/projects/dex-tracker I am trying to get rid of the part of the example where you have to use run.py. since I am stuck and it is driving me nuts I have put it up for bid at http://www.rentacoder.com/RentACoder/misc/BidRequests/ShowBidRequest.asp?lngBidRequestId=676174 If I can get this to work well I have another small c project that will allow me to compete with sep (stienburg) :) From bdesth.quelquechose at free.quelquepart.fr Fri Apr 13 17:42:39 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Fri, 13 Apr 2007 23:42:39 +0200 Subject: Any way to refactor this? In-Reply-To: <461fe75c$0$11278$c3e8da3@news.astraweb.com> References: <461fe75c$0$11278$c3e8da3@news.astraweb.com> Message-ID: <461ff01c$0$29118$426a74cc@news.free.fr> John Salerno a ?crit : > Setting aside, for the moment, the utility of this method or even if > there's a better way, I'm wondering if this is an efficient way to do > it. I admit, there was some copying and pasting, which is what prompts > me to ask the question. Here's the method. (I hope it looks ok, because > it looks really weird for me right now) > > def _create_3D_xhatches(): > for x in xrange(-axis_length, axis_length + 1): > if x == 0: continue > visual.cylinder(pos=(x,-hatch_length,0), > axis=(0,hatch_length*2,0), radius=hatch_radius) > visual.cylinder(pos=(x,0,-hatch_length), > axis=(0,0,hatch_length*2), radius=hatch_radius) > visual.cylinder(pos=(-hatch_length,x,0), > axis=(hatch_length*2,0,0), radius=hatch_radius) > visual.cylinder(pos=(0,x,-hatch_length), > axis=(0,0,hatch_length*2), radius=hatch_radius) > visual.cylinder(pos=(-hatch_length,0,x), > axis=(hatch_length*2,0,0), radius=hatch_radius) > visual.cylinder(pos=(0,-hatch_length,x), > axis=(0,hatch_length*2,0), radius=hatch_radius) > > Since each call to cylinder requires a slightly different format, I > figured I had to do it this way. From a purely efficiency POV, there are some obviously possible improvements. The first one is to alias visual.cylinder, so you save on lookup time. The other one is to avoid useless recomputation of -hatch_length and hatch_length*2. def _create_3D_xhatches(): cy = visual.cylinder for x in xrange(-axis_length, axis_length + 1): if x == 0: continue b = -hatch_length c = hatch_length*2 cy(pos=(x, b, 0), axis=(0, c, 0), radius=hatch_radius) cy(pos=(x, 0, b), axis=(0, 0, c), radius=hatch_radius) cy(pos=(b, x, 0), axis=(c, 0, 0), radius=hatch_radius) cy(pos=(0, x, b), axis=(0, 0, c), radius=hatch_radius) cy(pos=(b, 0, x), axis=(c, 0, 0), radius=hatch_radius) cy(pos=(0, b, x), axis=(0, c, 0), radius=hatch_radius) A second step would be to try and generate the permutations by code instead of writing them all by hand, but I suppose the order is significant... There's still an obvious pattern, which is that the position of 'c' in the axis tuple mirrors the position of 'b' in the pos tuple. There might be some way to use this to let the computer handle some part of the repetition... My 2 cents... From sjmachin at lexicon.net Wed Apr 25 20:12:59 2007 From: sjmachin at lexicon.net (John Machin) Date: Thu, 26 Apr 2007 10:12:59 +1000 Subject: bitwise shift? In-Reply-To: References: Message-ID: <462FEE8B.2030701@lexicon.net> On 26/04/2007 7:10 AM, Sherm Pendley wrote: > Shift left is *not* the same as multiplying by k. It is the same as multi- > plying by 2^k. Where I come from, ^ is the exclusive-or operator. Of course YMMV in WV :-) From kirkjobsluder at gmail.com Tue Apr 17 22:39:08 2007 From: kirkjobsluder at gmail.com (kirkjobsluder) Date: 17 Apr 2007 19:39:08 -0700 Subject: Future Python Gui? In-Reply-To: <1176859699.906386.326720@b75g2000hsg.googlegroups.com> References: <1176859699.906386.326720@b75g2000hsg.googlegroups.com> Message-ID: <1176863948.526051.186210@n76g2000hsh.googlegroups.com> On Apr 17, 9:28 pm, "bcwh... at pobox.com" wrote: > I've been trying to find out what the future of Python is with regard > to Tk. It seems there are several interfaces that make use of new > functionality, including "Tile" and "Ttk". > > If I want to write a program that will run under the standard Python > distribution of the future, what extension module should I work with > today? I've been doing a lot of reading this month. At the moment, none of the toolkits available strike me as being in a position to become the next tkinter, and it seems like core python development is moving away from extensions that might be better produced by other parties. Everyone and their cousin have different ideas about how a GUI should be built including how it hooks into other services. Cross-platform, it seems like wxPython has a considerable edge over jython+SWT or Swing. But platform-specific frameworks are also pretty important. I'd say that the best bet is to learn swig and similar bridging, expanding, and embedding mechanisms. Python GUI programming is likely to involve either python hooking into frameworks like Cocoa, Qt, or wxWidgets, python embedded in frameworks like Java or .NET, or flavors of python used as domain-specific languages in applications such as emacs, vim, and OpenOffice.org. > Thanks! > > -- Brian From steve at holdenweb.com Sat Apr 28 11:01:56 2007 From: steve at holdenweb.com (Steve Holden) Date: Sat, 28 Apr 2007 11:01:56 -0400 Subject: Python CGI and Browser timeout In-Reply-To: References: <1177624109.532664.105840@t39g2000prd.googlegroups.com> <9e2f512b0704261601s39e0772fp39636ff09b98521e@mail.gmail.com> Message-ID: Steve Holden wrote: > Sebastian Bassi wrote: >> On 26 Apr 2007 14:48:29 -0700, skulka3 at gmail.com wrote: >>> In order to work around this problem, I started printing empty strings >>> (i.e. print "") so that the browser does not timeout. >> How do you print something while doing the query and waiting for the results? >> I saw some pages that display something like: "This page will be >> updated in X seconds to show the results" (X is an estimated time >> depending of server load), after a JS countdown, it refresh itself and >> show the result or another "This page will be updated in X seconds to >> show the results". > > The usual way is by "client pull": send the content you want the user to > see, and include a Refresh: header - the easiest way is to include a > META tag in the html content section like > > > > So the page can continually check whether the user's job is finished, if > it isn't just sending out the same content and then when it is printing > the details. > I should have pointed out that N is the number of seconds to wait before refreshing. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden ------------------ Asciimercial --------------------- Get Python in your .sig and on the web. Blog and lens holdenweb.blogspot.com squidoo.com/pythonology tag items: del.icio.us/steve.holden/python All these services currently offer free registration! -------------- Thank You for Reading ---------------- From bbxx789_05ss at yahoo.com Fri Apr 6 04:41:26 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: 6 Apr 2007 01:41:26 -0700 Subject: Objects, lists and assigning values In-Reply-To: References: Message-ID: <1175848886.065401.269260@w1g2000hsg.googlegroups.com> On Apr 6, 1:23 am, Manuel Graune wrote: > Hello Gabriel, hello William, > > thanks to both of you for your answers. I seem to need a > better book about python. > What book are you reading? From sender at sender.send Tue Apr 10 07:50:05 2007 From: sender at sender.send (Passer By) Date: Tue, 10 Apr 2007 11:50:05 GMT Subject: NLTK, Random Sentence Generators? References: <87slb8d3uj.fsf@localhost.localdomain> <3CJSh.7608$u03.3757@newssvr21.news.prodigy.net> Message-ID: <87k5wkcuv6.fsf@localhost.localdomain> James Stroud writes: > Passer By wrote: > > > Has any created or not of examples of random sentence generators > > using n-gram models (or other models might be interesting). I > > know of one example from a course at MIT, but besides that > > nothing. Any help would be great. > > > > Best is to just cull text from your spam folder as these are often > generated by similar means--but somehow I think you knew that. > Emotive on Usenet? Thats original. From mansonmuni at alexandria.cc Mon Apr 23 20:40:35 2007 From: mansonmuni at alexandria.cc (Glen) Date: Mon, 23 Apr 2007 19:40:35 -0500 Subject: Beginner: Formatting text output (PyQt4) Solved References: Message-ID: <7mcXh.4365$ns5.1139@newssvr17.news.prodigy.net> Sorry I've been away a while, figuring stuff out. It absolutely wasn't a monospaced font that I was using. I'm still getting used to Qt Designer and didn't see the expandable item under 'font' where I could easily select another font. I felt pretty stupid when I saw it. My program output the contents of my data file perfectly once I selected a fixed pitch font. Thanks a lot for the replies. I didn't know how long to wait, since I'm new around here, and I kind of gave up. I got some good info from you guys anyway. Thanks. You'll probably be hearing from me pretty regularly, since I'm in the process of learning Python and PyQt simultaneously. Glen From kyosohma at gmail.com Tue Apr 3 13:32:49 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: 3 Apr 2007 10:32:49 -0700 Subject: How can I kill a running thread when exiting from __main__ In-Reply-To: <1175620919.478708.292150@p77g2000hsh.googlegroups.com> References: <1175620919.478708.292150@p77g2000hsh.googlegroups.com> Message-ID: <1175621569.420250.7550@d57g2000hsg.googlegroups.com> On Apr 3, 12:21 pm, car... at gmail.com wrote: > Hi! > > I have the following problem: I have written a short Python server > that creates an indefinite simulation thread that I want to kill when > quitting (Ctrl-C) from Python. Googling around has not given me any > hints on how to cleanly kill running threads before exiting. Any help > is appreciated! > > Carl > > ### CODE EXTRACT ### > > import pythoncom > > class QueueThread( threading.Thread): > def __init__(self, command): > threading.Thread.__init__(self) > self.command = command > > def run(self): > pythoncom.CoInitialize() > try: > object = Dispatch('application') > execute = getattr(object, 'Execute') > execute(self.command ) > finally: > object = None > pythoncom.CoUnitialize() > > queuethread = QueueThread("queuehandler") > queuethread.setDaemon(True) > queuethread.start() > > ## How can I kill "queuethread" when exiting (Ctrl-C)? If you can get the pid of the process you created, you should be able to use the killProcName function that's included with the win32 package...if you're server is a Windows box. You should be able to use the join() method if you don't set your thread to a Daemon. This post talks about using the os module to kill a thread as well: http://www.daniweb.com/techtalkforums/thread36752.html The wxPython wiki has one of the best threading examples I've seen: http://wiki.wxpython.org/index.cgi/LongRunningTasks Mike From jstroud at mbi.ucla.edu Mon Apr 30 19:52:34 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Mon, 30 Apr 2007 16:52:34 -0700 Subject: python TK scrollbar problem In-Reply-To: References: Message-ID: Ray wrote: > Hi, > > would someone tell me how to make scrollbar work under grid? > I think I'm missing something to connect scrollbar with the grid. > following is some sample code. it shows the scrollbar, but it do not work. > > Thanks a lot for the help! > > Ray > > #####code begin######## > from Tkinter import * > def mygrid(text,M = []): > while M: > x = M.pop() > x.destroy() > rows = [] > count=int(text) > yscroll = Scrollbar(frame_grid, orient='vertical') > yscroll.grid(rowspan=count, column=5, sticky=NS) > M.append(yscroll) > for i in range(count): > cols = [] > for j in range(4): > e = Entry(frame_grid, relief=RIDGE) > M.append(e) > e.grid(row=i, column=j, sticky=NSEW) > e.insert(END, '%d.%d' % (i, j)) > cols.append(e) > rows.append(cols) > > root=Tk() > frame_entry=Frame(root, width=550, height=100) > frame_entry.pack() > text=Entry(frame_entry) > text.pack(side=LEFT) > button=Button(frame_entry, text='generate grid', > command=(lambda:mygrid(text.get()))) > button.pack() > frame_space=Frame(root, width=550, height=100) > frame_space.pack() > frame_grid=Frame(root, width=550, height=300, relief=GROOVE) > frame_grid.pack() > frame_exit=Frame(root, width=550, height=100) > frame_exit.pack() > button2=Button(frame_exit, text='exit', command=root.quit) > button2.pack() > root.mainloop() You are not binding to the Scrollbar.set() method nor are you assigning the Scrollbar a command. You should try to emulate this: http://www.pythonware.com/library/tkinter/introduction/x7583-patterns.htm You need to also determine exactly what it is you want to scroll. You probably don't want to scroll frame_grid as that contains your scrollbar. Google "tkinter scrolled frame". Here is an example: http://mail.python.org/pipermail/python-list/2007-February/427886.html So, a suggestion would be to create a new frame to hold frame_grid and yscroll and then use yscroll to scroll frame_grid. James From jzgoda at o2.usun.pl Sun Apr 29 01:11:19 2007 From: jzgoda at o2.usun.pl (Jarek Zgoda) Date: Sun, 29 Apr 2007 07:11:19 +0200 Subject: Asynchronous XML-RPC client library? Message-ID: Is there anything like that? Googling yields many articles on async servers, but virtually nothing on clients. I have to talk to remote in an environment that does not allow threads... -- Jarek Zgoda http://jpa.berlios.de/ From hankgong at gmail.com Thu Apr 12 14:06:12 2007 From: hankgong at gmail.com (Hank Gong) Date: 12 Apr 2007 11:06:12 -0700 Subject: Can anybody give me an example about how to write the image drawn by the canvas in WxPython into postscript file Message-ID: <1176401172.168699.118510@o5g2000hsb.googlegroups.com> Hi, all I programmed by python to draw some simple images on the canvas in wxPython. I found there is a PostScriptDC in wxPython. However, I can not find an example about how to use it. Can anyone give me a simple example to show how to do it? From theo at van-werkhoven.nl.invalid Sat Apr 28 15:06:32 2007 From: theo at van-werkhoven.nl.invalid (Theo v. Werkhoven) Date: Sat, 28 Apr 2007 21:06:32 +0200 Subject: Program runs in all directories, except one.. References: Message-ID: The carbonbased lifeform Carsten Haese inspired comp.lang.python with: > On Sat, 2007-04-28 at 13:50 +0200, Theo v. Werkhoven wrote: >> Goodday, >> >> Something strange going on here. >> A piece of code I wrote bombs out in one of de directories under $HOME, >> but not in others. > > This usually means that the directory where your script doesn't work > contains some .py file that has the same name as a standard library > module that you need. Since the only import in your code snippet is > "from array import array", and calling array() raises the exception that > a list object is not callable, I am guessing that the culprit is a file > named array.py that defines a list called array. Rename that file. And you were right on the spot too, Cartsen, see my reply to John. Thank you too. Cheers, Theo -- theo at van-werkhoven.nl ICQ:277217131 SuSE Linux linuxcounter.org: 99872 Jabber:muadib at jabber.xs4all.nl AMD XP3000+ 1024MB "ik _heb_ niets tegen Microsoft, ik heb iets tegen de uitwassen *van* Microsoft" From aleax at mac.com Sun Apr 1 20:56:23 2007 From: aleax at mac.com (Alex Martelli) Date: Sun, 1 Apr 2007 17:56:23 -0700 Subject: manually implementing staticmethod()? References: <1175115664.288706.183390@p77g2000hsh.googlegroups.com> <1hvqagu.mn0e7yxfqvmrN%aleax@mac.com> <1175280526.733006.153540@e65g2000hsc.googlegroups.com> Message-ID: <1hvwjvx.1bn4t8c8ukaqhN%aleax@mac.com> 7stud wrote: ... > 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__(). Not sure what you mean by "overrides" in this context. Accessing an attribute that's a descriptor in the class invokes __get__ (having a __get__ is the definition of "being a descriptor"); here, we have no conceivable use for __get__, thus we simply omit it, so that instances of smethod aren't descriptors and accessing them as attributes does nothing special whatsoever. __call__ operates when a call is made, an operation that is completely separate (and temporally later than) the "accessing as an attribute" (or whatever other "accessing"). Not sure what you mean by "a functor" (a terminology that's alien to Python, though I'm sure other languages embrace it whole-heartedly). If you mean "a callable that's not a function", why, sure, an instance of smethod is callable, and it's not a function. Of course, there are many other ways of building objects that are callable and aren't functions: def smethod(f): def __new__(cls, *a, **k): return f(*a, **k) return type(f.__name__,(),dict(__new__=__new__)) Is this "a functor", too? I don't really know, nor care -- it's just a somewhat more intricate way to make callables that aren't functions. Alex From jstroud at mbi.ucla.edu Sat Apr 14 18:27:08 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Sat, 14 Apr 2007 15:27:08 -0700 Subject: Really badly structured Python Books. In-Reply-To: <1176577234.860922.216800@l77g2000hsb.googlegroups.com> References: <1176575848.526066.254520@y80g2000hsf.googlegroups.com> <1176577234.860922.216800@l77g2000hsb.googlegroups.com> Message-ID: 7stud wrote: > On Apr 14, 12:37 pm, "Andre P.S Duarte" > wrote: > >>I started reading the beginning Python book. It is intended for people >>who are starting out in the Python world. But it is really >>complicated, because he tries to explain, then after a bad explanation >>he puts out a bad example. I really recommend NOT reading the book. >>For it will make you want not to continue in Python. This is just me >>letting the air out of my lungs. No need to reply this is just a >>recommendation. Txs for the opportunity . > > > There are several beginning python books. You might want to be a > little more explicit about the book you are talking about. What is > the title? > I think he means the Apress book _Beginning_Python_. Funny, though, that it gets such good reviews on Amazon. Not every book is meant for every student. James From jstroud at mbi.ucla.edu Thu Apr 26 20:20:44 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Thu, 26 Apr 2007 17:20:44 -0700 Subject: My python annoyances so far In-Reply-To: References: <1177541453.471959.120830@c18g2000prb.googlegroups.com> Message-ID: Steve Holden wrote: > flifus at gmail.com wrote: > >> Hi all. I'm learning python these days. I'm going to use this thread >> to post, from time to time, my annoyances with python. I hope someone >> will clarify things to me where I have misunderstood them. >> >> Annoyances: >> 2. There are modules, there are functions, and there are classes- >> methods! Wouldn't it have been easier had everything either been a >> function or a class method? >> > Actually, it's really simple. When you get right down to it, > *everything* in *every* current implementation of Python is either a one > or a zero. Would you like us to make it all zeros? > > Perhaps you should meditate on the idea to the concept of "sufficient > and necessary complexity" ... Here is something on which to meditate: classes become functions when you get the quantum mechanics just so! py> class add(object): ... def __new__(self, a, b): ... return a + b ... py> c = add(3, 1) py> c 4 py> type(c) py> add py> def add(a, b): ... return a + b ... py> add(3, 1) 4 From tjreedy at udel.edu Wed Apr 4 00:30:03 2007 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 4 Apr 2007 00:30:03 -0400 Subject: heap doesn't appear to work as described References: <1175641694.226975.258820@n76g2000hsh.googlegroups.com> <17938.58082.317522.331513@montanaro.dyndns.org> Message-ID: wrote in message news:17938.58082.317522.331513 at montanaro.dyndns.org... | | >> My book says that in a heap, a value at position i will be smaller | >> than the values at positions 2*i and 2*i + 1. I am sure your book either uses 1-based arrays or a 0-based arrays with the first not used. The need to keep these alternatives in mind is an unfortunate fact of programming life. | Check the heapq docs for the constraints the Python heapq module maintains: | | http://docs.python.org/dev/lib/module-heapq.html | | They are different than what you stated above: | | Heaps are arrays for which heap[k] <= heap[2*k+1] and heap[k] <= | heap[2*k+2] for all k, counting elements from zero. If you shift indexes down and substitute i = k+1, then i, 2*i, 2*i+1 are transformed to (k+1)-1, 2*(k+1)-1, 2*(k+1)+1-1 == k, 2*k+1, 2*(k+1). So the Python invariant is the same thing in different 'coordinates'. In the first case h1 is smaller than h2,h3; h2 smaller than h4,h5; etc. In the second, h0 is smaller than h1,h2; h1 smaller than h3,h4, etc. Terry Jan Reedy From whamil1 at entergy.com Wed Apr 11 10:28:03 2007 From: whamil1 at entergy.com (Hamilton, William ) Date: Wed, 11 Apr 2007 09:28:03 -0500 Subject: tuples, index method, Python's design In-Reply-To: <4866bea60704110712p52c0e870v1e0d7b7a27383714@mail.gmail.com> Message-ID: <588D53831C701746A2DF46E365C018CE01D2CA6C@LITEXETSP001.etrsouth.corp.entergy.com> > -----Original Message----- > From: python-list-bounces+whamil1=entergy.com at python.org [mailto:python- > list-bounces+whamil1=entergy.com at python.org] On Behalf Of Chris Mellon > Sent: Wednesday, April 11, 2007 9:12 AM > To: python-list at python.org > Subject: Re: tuples, index method, Python's design > > > So, when you have a) a third party module that you cannot change and > b) it shouldn't return a tuple but it does anyway and c) it's a big > enough tuple that is large enough that conversion to a list is > prohibitive, that's a "general" use case for tuple.index? > > Has this supposedly general and common use case actually happened? To me? No. Is it reasonable to believe it could happen? Yes. Is it reasonable to say, "We don't think this is likely to happen often, so we won't provide a simple way to deal with it?" Well, I'm not a developer, so it's not my decision. --- -Bill Hamilton whamil1 at entergy.com From robert.rawlins at thinkbluemedia.co.uk Fri Apr 13 12:38:08 2007 From: robert.rawlins at thinkbluemedia.co.uk (Robert Rawlins - Think Blue) Date: Fri, 13 Apr 2007 17:38:08 +0100 Subject: Class Dependancy Injection In-Reply-To: References: <15088.0762412728$1176479941@news.gmane.org> Message-ID: <002601c77dea$2105b570$63112050$@rawlins@thinkbluemedia.co.uk> Thanks Steve that's good to here. I'll give it a shot this evening and if I have any problems then 'I'll be back';-) Rawlins -----Original Message----- From: python-list-bounces+robert.rawlins=thinkbluemedia.co.uk at python.org [mailto:python-list-bounces+robert.rawlins=thinkbluemedia.co.uk at python.org] On Behalf Of Steve Holden Sent: 13 April 2007 17:32 To: python-list at python.org Subject: Re: Class Dependancy Injection Robert Rawlins - Think Blue wrote: > Hey again guys, > > > > I'm looking to get an answer about dependency injection in python > classes, what is the best way to deal with this? > > > > For instance, in my application I have a configuration bean which > contains all the applications configuration information. Now in one of > other classes I need access to those configuration settings. What I > would have done in my ColdFusion/JAVA type applications is create an > instance of the configuration bean, and then pass that in as an argument > to the constructor for my other class, then have the other class set > that as a 'self' variable. Then from within my class I can access the > configuration details like self.config.getName() and it would return the > name of the application. > > How is this best handled in python, can I still inject dependencies as a > constructor argument like that? If so then is there anything in > particular I need to watch out for that may cause me trouble? > That indeed sounds like the best way to proceed. You should find that, modulo the language differences, the technique works in just the same way. You shouldn't anticipate trouble. 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 -- http://mail.python.org/mailman/listinfo/python-list From null at example.net Tue Apr 24 13:05:11 2007 From: null at example.net (Richard The Dreaded Libertarian) Date: Tue, 24 Apr 2007 17:05:11 GMT Subject: *** Watch BOMBSHELL video of Senator John Kerry admitting 911 was in INSIDE JOB ??? References: <1177387965.127809.175390@l77g2000hsb.googlegroups.com> Message-ID: On Mon, 23 Apr 2007 21:12:45 -0700, lemnitzer wrote: > WHAT THE HELL|?| Are you saying that building was wired that day? Or > well in advance? 'Splain, please. No, you idiot. That was the Murrah building in OK city. Cheers! Rich From spradml at gmail.com Mon Apr 9 13:26:04 2007 From: spradml at gmail.com (Pradnyesh Sawant) Date: Mon, 9 Apr 2007 22:56:04 +0530 Subject: output of top on a linux box In-Reply-To: <80628d680704072342r60b57995mad6c505505a919a8@mail.gmail.com> References: <80628d680704072342r60b57995mad6c505505a919a8@mail.gmail.com> Message-ID: <80628d680704091026u7e98719co3d63a7913832475a@mail.gmail.com> Hello, I need the cpu usage of a linux box, for which i capture the output of "top" using "popen". However, i am facing problems during string handling. The code snippet is:- top = os.popen("top -n 1") rd = top.read().split("\n") splt = rd[2].split() # cpu = splt[2][:-4] # why ain't this working ??? cpu = splt[2] print "cpu usage: %s, %s" % (cpu, type(cpu)) the "print" statement prints, "cpu usage: 0.5%sy, ". i tried my best to get rid of the "%sy" after the "0.5", but couldn't succeed (even though the type of "cpu" is "string"). Also, one weird thing that was happening was that if i still "split" the cpu string (removed the last 4 characters), the output of the next print statement was wrong (specifically, the first 2 characters got chipped off). This output is totally unexpected, and wrong... Can anyone kindly help me in understanding what exactly is going on here. Thanks a lot! From mensanator at aol.com Wed Apr 18 10:35:42 2007 From: mensanator at aol.com (mensanator at aol.com) Date: 18 Apr 2007 07:35:42 -0700 Subject: The smallest and largest values of numeric types In-Reply-To: References: <1176825226.633555.85860@d57g2000hsg.googlegroups.com> Message-ID: <1176906942.377837.285580@p77g2000hsh.googlegroups.com> On Apr 18, 3:09???am, Steven D'Aprano wrote: > On Wed, 18 Apr 2007 07:15:11 +0200, Hendrik van Rooyen wrote: > > I once made a thing that tried to find the limit of longs and stopped > > when I had two or three screenfulls of numbers. > > You should find that converting longs to strings (say, for printing them) > is *very* slow. E.g. the following code > > big = 10L**100 # one google, a big number > while True: > ? ? print big # so we can see the last value before it fails > ? ? big *= 10 > > will run terribly slow and should be written as: > > big = 10L**100 # one google, a big number > try: > ? ? while True: > ? ? ? ? big *= 10 > except: # don't know what exception will be raised, so catch ANYTHING > ? ? print len(str(big))-1 # the number of digits > > only does the slow conversion to string once, instead of every time around > the loop. However, once your machine starts paging, it will still slow > down a lot. > > > I came to the conclusion that for "integer" arithmetic like this, the > > limit is either your memory size, or some other number that is so big > > that in practice you don't have to worry about it.. > > Yes, longs are limited only by the amount of memory accessible. But there may be other limitations even if you have the memory. For example, this test is limited to generation 10 because tne 11th generation produces "outrageous exponent" error. Here, every 9th 1st generation, starting from the fifth is a second generation, every 9th sencond, starting from the fifth, is a 3rd generation, every 9th 3rd gen, starting from the 5th is a 4th gen, etc. Closed form: Type12MH(k,i) Find ith, kth Generation Type [1,2] Mersenne Hailstone using the closed form equation 2**(6*((i-1)*9**(k-1)+(9**(k-1)-1)/2+1)-1)-1 2**5-1 generation: 1 2**29-1 generation: 2 2**245-1 generation: 3 2**2189-1 generation: 4 2**19685-1 generation: 5 2**177149-1 generation: 6 2**1594325-1 generation: 7 2**14348909-1 generation: 8 2**129140165-1 generation: 9 2**1162261469-1 generation:10 1.797 seconds There is never a number too large to worry about. > > -- > Steven D'Aprano From apardon at forel.vub.ac.be Fri Apr 20 09:22:22 2007 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 20 Apr 2007 13:22:22 GMT Subject: Do other Python GUI toolkits require this? References: <462697A6.6010007@codebykevin.com> <465B30B4-5BA0-459A-BE6F-1038874FA74B@jedimindworks.com> <58rq32F2fo980U1@mid.uni-berlin.de> Message-ID: On 2007-04-20, Diez B. Roggisch wrote: >> So if you have the choice between a steep or a shalow income curve >> you will prefer the shalow curve because a steep curve makes you >> think about verticale clifs and such? >> >> The analogy with a walk is just silly because curves are not like walks. >> Nobody will say something like: I won't invest in that company because >> it has a steep profit curve or the reverse: I'll invest in this company >> because it has an easy looking downhill going profit curve. > > Your whole argumentation bases on the fact that the result of the > learning process, and the success of it, has something to do with the > reached height - or y-axis-value - of your climb. > > Which is nonsense. The goal is to go from A - ignorance - to B - > knowledge - which both lie on the X-Axis. Well if you want to do it that way, nobody can stop you, but people in the habit of processing numbers usually put the time on the X-axis like in time spend learning or exercising and put the other value on the Y-axis. That is because people prefer a curve going up and down while moving to the right instead of going left and right while moving up. -- Antoon Pardon From ralfi at supanet.com Thu Apr 19 06:34:20 2007 From: ralfi at supanet.com (Ralf) Date: Thu, 19 Apr 2007 12:34:20 +0200 Subject: CGI Script using Python Message-ID: <58our9F2fertqU1@mid.individual.net> Hello, is there anybody who can help me. I would like to use a Python Script to download Files from a Server to the Client, to update the Client. Thanx Ralf From satish.nandihalli at gmail.com Mon Apr 9 04:09:24 2007 From: satish.nandihalli at gmail.com (Satish S Nandihalli) Date: 9 Apr 2007 01:09:24 -0700 Subject: how do i configure Python2.3.6 on Solaris 10 Message-ID: <1176106164.815811.229780@o5g2000hsb.googlegroups.com> following errors were found on executing configure file: 1) configure: WARNING: thread.h: present but cannot be compiled configure: WARNING: thread.h: check for missing prerequisite headers? configure: WARNING: thread.h: see the Autoconf documentation configure: WARNING: thread.h: section "Present But Cannot Be Compiled" configure: WARNING: thread.h: proceeding with the preprocessor's result configure: WARNING: thread.h: in the future, the compiler will take precedence 2) configure: WARNING: sys/wait.h: present but cannot be compiled configure: WARNING: sys/wait.h: check for missing prerequisite headers? configure: WARNING: sys/wait.h: see the Autoconf documentation configure: WARNING: sys/wait.h: section "Present But Cannot Be Compiled" configure: WARNING: sys/wait.h: proceeding with the preprocessor's result configure: WARNING: sys/wait.h: in the future, the compiler will take precedenceconfigure: WARNING: ## --------------------------------- ## configure: WARNING: ## Report this to the python lists. ## configure: WARNING: ## --------------------------------- ## Also no ./python executable is getting created on running make. From jzgoda at o2.usun.pl Mon Apr 16 04:17:47 2007 From: jzgoda at o2.usun.pl (Jarek Zgoda) Date: Mon, 16 Apr 2007 10:17:47 +0200 Subject: Python and JMS? In-Reply-To: <4622CAE5.7070006@ieee.org> References: <4622CAE5.7070006@ieee.org> Message-ID: Leonard J. Reder napisa?(a): > Yes indeed, we are using ActiveMQ and I did see the StomPy python > package. But I also saw that it said stomp was done as a student > project that ended. Maybe I will try hjb for now - all I need to do > is listen for messages on a certain topic. > > Maybe some of our internal people will pick stom and make it better for > the future though. I saw there are 2 libraries implementating stomp, the one mentioned by you and one which looked a bit better. The protocol itself also doesn't look very complicated, so this should be relatively easy to implement client library for somebody who works with ActiveMQ on a daily basis. -- Jarek Zgoda "We read Knuth so you don't have to." From robert.kern at gmail.com Thu Apr 12 05:32:00 2007 From: robert.kern at gmail.com (Robert Kern) Date: Thu, 12 Apr 2007 04:32:00 -0500 Subject: About Trolltech QT OpenSource license. In-Reply-To: <1176364905.342440.295520@l77g2000hsb.googlegroups.com> References: <1176233376.712861.67160@o5g2000hsb.googlegroups.com> <1176237050.409742.8760@30g2000cwc.googlegroups.com> <1176285062.178372.15090@d57g2000hsg.googlegroups.com> <1176326271.183571.286710@l77g2000hsb.googlegroups.com> <1176364905.342440.295520@l77g2000hsb.googlegroups.com> Message-ID: king kikapu wrote: > On Apr 12, 1:02 am, Robert Kern wrote: >> All parts of the software have to be licensed compatibly with the GPL. The FSF >> has a fairly comprehensive list of the licenses they believe are GPL-compatible. >> The source that you provide needs to be the preferred form for making >> modifications; i.e., you can't use a tool that obfuscates the code. You need to >> provide the scripts that you use to build the software. You have to be careful >> about using patented techniques in your code. The source code must be offered at >> no extra charge (this part of the license is a bit tricky, so please read the >> license and the commentaries). > > Ok, i see...You said "All parts of the software have to be licensed > compatibly with the GPL". What if, let's say, my application's GUI is > made by Qt (Open Source edition that is indeed under GPL license) and > in this application i use some module(s) that i bought from some other > company and they aren't under GPL, do you see any implication to > this ? You will not be able to distribute your program if that module is under a license which imposes more restrictions than the GPL does. The FSF maintains a list of licenses which are compatible with the GPL: http://www.gnu.org/philosophy/license-list.html -- 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 clajo04 at mac.com Thu Apr 5 18:16:04 2007 From: clajo04 at mac.com (John Clark) Date: Thu, 5 Apr 2007 18:16:04 -0400 Subject: grandparent method with super In-Reply-To: <20070405171306.0264fb70@localhost> References: <20070405161939.694d51a1@localhost> <20070405163845.2ffa8d32@localhost> <20070405171306.0264fb70@localhost> Message-ID: <01d501c777d0$0110a740$fefea8c0@haengma> > Not really. The first grandparent would be the first occurrence in the list from left to right, which satisfies the requirement that its shortest path to the current class is 2. > The only problem: How do I get it? > Martin I suppose you could do a self.__class__.__bases__[0].__bases__[0] (With the appropriate error handling buit in..) But I am not sure if it's a safe assumption to depend on __bases__ returning the classes in the order you want... -jdc -- http://mail.python.org/mailman/listinfo/python-list From simon at asylumfx.com Wed Apr 18 13:16:59 2007 From: simon at asylumfx.com (Simon Cassels) Date: Wed, 18 Apr 2007 10:16:59 -0700 Subject: image sequence to Quicktime movie Message-ID: <7A748DE5-31F6-45EA-8228-F2E9CCE49A24@asylumfx.com> did u ever find anything out about this ? if so can you help me with some leads i am trying to figure an action that can convert image files to quicktime automatically. cheers simon From psdasilvaX at esotericaX.ptX Thu Apr 12 19:09:13 2007 From: psdasilvaX at esotericaX.ptX (Paulo da Silva) Date: Fri, 13 Apr 2007 00:09:13 +0100 Subject: "Cloning" file attributes and permissions In-Reply-To: <1176406707.711609.211110@q75g2000hsh.googlegroups.com> References: <1176394818.428367@jubilee.claranet.pt> <1176406707.711609.211110@q75g2000hsh.googlegroups.com> Message-ID: <1176419326.395692@jubilee.claranet.pt> attn.steven.kuo at gmail.com escreveu: > On Apr 12, 9:20 am, Paulo da Silva wrote: >> Hi! >> >> I need to process a file to produce another file that *must* have >> *exactly* the same attributes and permissions of the former. What is the >> best way to do this? The file must not exist with contents (it may exist >> empty) unless it has the same attributes and permissions. >> I know how to do this using, let me call it, "C type code" (stat, chmod, >> chown, etc). I would like to hear some opinions on if and how it would >> be possible in a more elegant/python way. >> > > > Are you using a system that supports the creation > of a hard link? > > If so, try os.link. May be I missed something exposing my q. I need to process an input file "foo" to produce a different contents file "bar". "bar" must have the same attributes/permissions of "foo". I forgot to say that the OS is Linux. From aleax at mac.com Sat Apr 7 19:43:45 2007 From: aleax at mac.com (Alex Martelli) Date: Sat, 7 Apr 2007 16:43:45 -0700 Subject: block scope? References: <7xr6qwal50.fsf@ruckus.brouhaha.com> <7xtzvseqzo.fsf@ruckus.brouhaha.com> <1hw72cg.115yokgarr9enN%aleax@mac.com> Message-ID: <1hw7kzo.1hepj3c1who5zhN%aleax@mac.com> Steve Holden wrote: > What do you think the chances are of this being accepted for Python 3.0? > It is indeed about the most rational approach, though of course it does > cause problems with dynamic namespaces. What problems do you have in mind? The compiler already determines the set of names that are local variables for a function; all it needs to do is diagnose an error or warning if the set of names for a nested function overlaps with that of an outer one. I shamefully admit that I haven't followed Python 3.0 discussions much lately, so I don't really know what's planned on this issue. Alex From sbassi at clubdelarazon.org Sun Apr 29 00:20:42 2007 From: sbassi at clubdelarazon.org (Sebastian Bassi) Date: Sun, 29 Apr 2007 01:20:42 -0300 Subject: [ANN] Portable SciPy v0.1 released In-Reply-To: <2418d$463275ce$d443bb3a$25239@news.speedlinq.nl> References: <2418d$463275ce$d443bb3a$25239@news.speedlinq.nl> Message-ID: <9e2f512b0704282120l1bca26b2oc5cc6c09b6dc8fb0@mail.gmail.com> On 4/27/07, Stef Mientki wrote: > Portable SciPy, is an easy installer of SciPy for M$ windows users. ... > have fun, > and let me hear what you think of it. It is so portable that I managed to install it under Linux :) (Ubuntu 7.04, using wine). See screenshot: http://img224.imageshack.us/my.php?image=winpythoninubuntuwb7.png (click on image to see full res.) -- Sebasti?n Bassi (???????) Diplomado en Ciencia y Tecnolog?a. GPG Fingerprint: 9470 0980 620D ABFC BE63 A4A4 A3DE C97D 8422 D43D Club de la raz?n (www.clubdelarazon.org) From marco at waven.com Thu Apr 5 22:05:35 2007 From: marco at waven.com (Marco) Date: Fri, 6 Apr 2007 10:05:35 +0800 Subject: communication between two classes which in different threading Message-ID: <5c62a320704051905k1f0c514fuf79ff3ebe109ae99@mail.gmail.com> Hello, I write two class, which one is Gui(PyQt4) other is socket server. I wanna: if socket recv() something, Gui will show it in a label. But it seems that I cannot call the func from other threading. How to reslove it? Thank you! -- LinuX Power From thorstenkranz at googlemail.com Thu Apr 26 07:39:54 2007 From: thorstenkranz at googlemail.com (thorstenkranz) Date: 26 Apr 2007 04:39:54 -0700 Subject: Problem with Matplotlib and the Tk-Backend Message-ID: <1177587594.078411.18720@u32g2000prd.googlegroups.com> Hi everyone, I'm new here and I have a question ( I guess as everybody who is new here ;-) ), I'm having some strange problem with Matplotlib, using it in a Tkinter application. I create a Canvas, a figure, subplot and then a toolbar. It works fine, but only without the toolbar! When I want to add the toolbar, I get an error File "./tkViewer.py", line 102, in setupGUI self.toolbar = NavigationToolbar2TkAgg( self.canvas, master ) File "/usr/lib/python2.4/site-packages/matplotlib/backends/ backend_tkagg.py", line 537, in __init__ NavigationToolbar2.__init__(self, canvas) File "/usr/lib/python2.4/site-packages/matplotlib/backend_bases.py", line 1107, in __init__ self._init_toolbar() File "/usr/lib/python2.4/site-packages/matplotlib/backends/ backend_tkagg.py", line 577, in _init_toolbar borderwidth=2) File "/usr/lib/python2.4/lib-tk/Tkinter.py", line 2378, in __init__ Widget.__init__(self, master, 'frame', cnf, {}, extra) File "/usr/lib/python2.4/lib-tk/Tkinter.py", line 1865, in __init__ self.tk.call( _tkinter.TclError: bad screen distance "500.0" Here is the part my code: self.canvFrame = Frame(master) self.canvFrame.pack(side=TOP, fill=BOTH, expand=1) self.canvFrame2 = Frame(self.canvFrame) self.canvFrame2.pack(side=LEFT, fill=BOTH, expand=1) self.f = Figure(figsize=(5,4), dpi=100) self.a = self.f.add_subplot(111) self.subplAxis = self.f.get_axes() self.canvas = FigureCanvasTkAgg(self.f, master=self.canvFrame2) self.canvas.show() self.canvas.get_tk_widget().pack(side=TOP, fill=BOTH, expand=1) self.toolbar = NavigationToolbar2TkAgg( self.canvas, self.canvFrame2 ) self.toolbar.update() self.canvas._tkcanvas.pack(side=TOP, fill=X, expand=1) master is a parameter passed to my method, which actually is set to Tk() What did I get wrong? What is the problem? Thanks in advance... Thorsten From jorgen.maillist at gmail.com Sun Apr 15 07:15:19 2007 From: jorgen.maillist at gmail.com (Jorgen Bodde) Date: Sun, 15 Apr 2007 13:15:19 +0200 Subject: OverflowError: mktime argument out of range ??? In-Reply-To: <58ee6vF2gtdc4U1@mid.uni-berlin.de> References: <58ee6vF2gtdc4U1@mid.uni-berlin.de> Message-ID: <11e49df10704150415q4dd8b9d5q94df2f86c732649d@mail.gmail.com> Ok thanks, I missed out on datetime where the methods I need are also present. I'll be refactoring my data a bit, thanks again! - Jorgen On 4/15/07, Diez B. Roggisch wrote: > Jorgen Bodde schrieb: > > Hi List > > > > I am working on an app to store guitar songs I am practicing, and for > > the fun of it I want to store the date of songs when they were > > originally made. So far so good.. > > > > However, my taste of music is "Rag Time Blues" and that os OLD, very > > OLD music. So it happened I entered a song from the date " 28 dec > > 1928". > > > > It appears time.mktime cannot handle these 'extremities' ? I get an > > overflow error. is there by any chance a solution to this? I do know > > modern languages support at least 1900 as date (and now that I come to > > think of it, songs from J.S. Bach are excluded from entering as well) > > .. > > > > This is what I try: > > > >>>> time.mktime((1928, 12,28, 0, 0, 0, 0, 0, 0)) > > Traceback (most recent call last): > > File "", line 1, in > > OverflowError: mktime argument out of range > > > > The only solution I can think of is making a custom time class that > > handles all years, dates and months, but that is plain silly. I want > > to be able to use the long date formatting etc, and that would mean > > rewriting that part as well. > > import datetime > datetime.date(1928, 12, 28) > > Diez > -- > http://mail.python.org/mailman/listinfo/python-list > From laurent.pointal at limsi.fr Mon Apr 2 09:18:00 2007 From: laurent.pointal at limsi.fr (Laurent Pointal) Date: Mon, 02 Apr 2007 15:18:00 +0200 Subject: Problem with global variables In-Reply-To: <1311u48bqkehk24@corp.supernews.com> References: <1311u48bqkehk24@corp.supernews.com> Message-ID: Ed Jensen a ?crit : > I'm having a vexing problem with global variables in Python. Please > consider the following Python code: > > #! /usr/bin/env python > > def tiny(): > bar = [] > for tmp in foo: > bar.append(tmp) > foo = bar > > if __name__ == "__main__": > foo = ['hello', 'world'] > tiny() > > When I try to run this, I get: > > Traceback (most recent call last): > File "./xtalk.py", line 11, in ? > tiny() > File "./xtalk.py", line 5, in tiny > for tmp in foo: > UnboundLocalError: local variable 'foo' referenced before assignment > > For some reason, Python can't see the global variable "foo" in the > function tiny(). Why is that? > > If I change the code to this: > > #! /usr/bin/env python > > def tiny(): > for tmp in foo: > print tmp > > if __name__ == "__main__": > foo = ['hello', 'world'] > tiny() > > I get this: > > hello > world > > All of a sudden, tiny() can see the global variable "foo". Very > confusing! Why is it that tiny() sometimes can, and sometimes can't, > see the global variable "foo"? > > If anyone can enlighten me about what's going on with Python and > global variables, I would appreciate it! To complete hg reply, Python compile your tiny function which contains a foo assignment. As foo is not defined "global", it is considered to be local. So the error when you tries to iterate throught foo before assigning it. And so the solution to add "global foo" before using it. A+ Laurent. From steve at holdenweb.com Mon Apr 2 10:17:36 2007 From: steve at holdenweb.com (Steve Holden) Date: Mon, 02 Apr 2007 10:17:36 -0400 Subject: Mastering Python (OT) In-Reply-To: <003301c7746f$859d0300$03000080@hendrik> References: <1174045298.826137.262890@o5g2000hsb.googlegroups.com><1174052358.486071.163280@e65g2000hsc.googlegroups.com><46018fd8$0$18018$426a74cc@news.free.fr><46091cdf$0$19664$426a74cc@news.free.fr> <000f01c771d2$2fc41940$03000080@hendrik> <003301c7746f$859d0300$03000080@hendrik> Message-ID: Hendrik van Rooyen wrote: > "Steve Holden" wrote: > > >> Hendrik van Rooyen wrote: > >>> It comes out something like "Chum-lee", with the ch like chicken... >>> >>> (that's what I have heard - but who knows - It may have been >>> a regional dialect, a case of the blind leading the blind, or >>> someone pulling the piss..) >>> >> You have been correctly informed. It's one of the least intuitive names >> in the English language. > > Oh No! - don't tell me there is worse - this is already enough to drive > a saint to drink! > > I will have to move to "Hants"... > Speaking of which, here's a limerick To read it you need to know not only that Hampshire is colloquially know as Hants, but also that Salisbury's ancient Roman name is Sarum. There once was a young man of Salisbury Whose manners were most halisbury-scalisbury He visited Hampshire Without any pampshire Till somebody told him to walisbury. try-running-a-spell-checker-on-that-ly y'rs - 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.mahurin at gmail.com Sat Apr 14 18:34:27 2007 From: eric.mahurin at gmail.com (Eric Mahurin) Date: 14 Apr 2007 15:34:27 -0700 Subject: descriptor object for an attribute? In-Reply-To: <461d36d5$0$27802$426a34cc@news.free.fr> References: <1176304695.336308.151810@n76g2000hsh.googlegroups.com> <461d36d5$0$27802$426a34cc@news.free.fr> Message-ID: <1176590067.396580.37190@e65g2000hsc.googlegroups.com> On Apr 11, 3:07 pm, Bruno Desthuilliers wrote: > Eric Mahurin a ?crit : > > > Is there a standard way to get a descriptor object for an arbitrary > > object attribute - independent of whether it uses the descriptor/ > > property protocol or not. I want some kind of handle/reference/ > > pointer to an attribute. > > I'm not sure to understand what you want exactly. A concrete example > would probably help. But from what I understood, you could just use a > thin wrapper like: > > _marker = object() > class Accessor(object): > def __init__(self, obj, name): > self._obj = obj > self._name = name > def __call__(self, new_val=_marker): > if new_val is _marker: > return getattr(self._obj, self._name) > else: > setattr(self._obj, self._name, new_val) > > class Foo(object): > def __init__(self, bar, baak=42): > self.bar = bar > self.baak = baak > > foo = Foo('allo') > bar = Accessor(foo, 'bar') > > assert bar() == foo.bar == 'allo' > bar(42) > assert bar() == foo.bar == 42 > > If that doesn't answer your question, please pardon my stupidity and > provide some more concrete example. Thanks Bruno, This does answer my question. The protocol you implemented looks to match a weakref except you can also set the value by giving an argument to __call__ (an of course it implements a "hard" ref). I was considering this one already, but decided to use an attribute/ descriptor for getting/setting for a little better efficiency (no if statement). I also made my reference classes forward/proxy attributes from the underlying object. I used the attribute "_" for getting/ setting the underlying object to reduce the chances of colliding with attributes of the underlying object. I still don't like the resulting syntax, but it is workable. I would have to be able to do one of these: my_ref() # get underlying object - possible with __call__ my_ref() = obj # set underlying object - can't: no calling assign my_ref[] # get underlying object - can't: __getitem__ requires a key/index my_ref[] = obj # set underlying object - can't: __setitem__ requires a key/index Below is a stripped down version of what I'm using now. I'm showing the references (sub-classed to links) being used in a singly linked list (I'm really using them with a directed graph where children are implemented with a singly linked list). When implementing these types of structures, the concept of a "reference" (to an object reference) can be quite handy. With a list/dict, you already have a handle to values in a list/dict - an index/key. This isn't quite a reference, but usually it is good enough. For other structures, a reference becomes much more useful since you don't have this. class Ref(object) : ''' Anonymous reference to an object. ''' def __init__(self, object=None) : ''' >>> r = Ref(-1) >>> r._ -1 >>> r._ = 2 >>> r._ 2 ''' self._ = object def __getattr__(self, name) : ''' >>> r = Ref(-1) >>> r.__abs__() 1 ''' return getattr(self._, name) class LookupRef(Ref) : ''' Reference to a value in a lookup (dict, list, tuple, etc). ''' def __init__(self, lookup, key) : self._lookup = lookup self._key = key _ = property( lambda self: self._lookup.__getitem__(self._key), lambda self, value: self._lookup.__setitem__(self._key, value), doc=''' >>> r = LookupRef(('a','b','c'),1) >>> r._ 'b' >>> v = 0 >>> r = LookupRef(locals(),'v') >>> r._ = 1 >>> v 1 ''') class AttrRef(Ref) : ''' Reference to an object attribute. ''' def __init__(self,obj,attr) : self._obj = obj self._attr = attr _ = property( lambda self: getattr(self._obj, self._attr), lambda self, value: setattr(self._obj, self._attr, value), doc=''' >>> class Foo : bar = 123 >>> f = Foo() >>> r = AttrRef(f,'bar') >>> r._ 123 >>> r._ = 'abc' >>> f.bar 'abc' ''') class Node(object) : ''' Node (including head) in a singly linked-list. ''' def __init__(self, data=None, next=None) : self.data = data self.next = next def __add__(self, node) : ''' >>> t = Node('a')+Node('b') >>> t.data 'b' >>> t.next.data 'a' ''' node.next = self return node def __iter__(self) : ''' An iterator through self and all other nodes linked. >>> [node.data for node in Node(1) + Node(2) + Node(3)] [3, 2, 1] ''' node = self while node : yield node node = node.next def __repr__(self) : ''' Gives the coordinates and the children. >>> Node(1)+Node(2) Node(1) + Node(2) ''' return ' + '.join(reversed( ['Node('+repr(node.data)+')' for node in self] )) def push_next(self, node) : ''' >>> l = Node(1)+Node(2) >>> l.push_next(Node(3)) ''' node.next = self.next self.next = node def pop_next(self) : ''' >>> l = Node(1)+Node(2)+Node(3) >>> l.pop_next() Node(2) >>> l Node(1) + Node(3) ''' node = self.next self.next = node.next node.next = None return node class Link(Ref) : ''' A link (type of reference) to a Node. ''' def pop(self) : ''' Pop off the current linked node (returning it) and link to the next node. >>> l = Link(Node(1)+Node(2)+Node(3)) >>> l.pop() Node(3) >>> l._ Node(1) + Node(2) ''' node = self._ self._ = node.next node.next = None return node def push(self, node) : ''' Link to a new node and make the previous linked node the next one. >>> l = Link(Node(1)+Node(2)) >>> l.push(Node(3)) >>> l._ Node(1) + Node(2) + Node(3) ''' node.next = self._ self._ = node def __iter__(self) : ''' Iterator to self and next links. >>> l = Link(Node(1)+Node(2)+Node(3)+Node(4)+Node(5)) >>> for link in l : ... # remove first node with even data ... if not link.data%2 : ... node = link.pop() ... break >>> l._ Node(1) + Node(2) + Node(3) + Node(5) >>> node Node(4) ''' ref = self while ref._ : yield ref ref = AttrLink(ref._,'next') class AttrLink(AttrRef, Link) : pass class LookupLink(LookupRef, Link) : pass From pict100 at gmail.com Sun Apr 1 07:58:06 2007 From: pict100 at gmail.com (DarkBlue) Date: 1 Apr 2007 04:58:06 -0700 Subject: Mastering Python In-Reply-To: References: <1174045298.826137.262890@o5g2000hsb.googlegroups.com> <000f01c771d2$2fc41940$03000080@hendrik> Message-ID: <1175428686.920389.67840@l77g2000hsb.googlegroups.com> Before we get to far away from the original question... as you have may have noticed you reached one of the best user groups on the net , where help from the top gurus and best minds in the python universe is only a question away. Go for it, you are in good hands. Db From sbassi at clubdelarazon.org Fri Apr 13 22:18:22 2007 From: sbassi at clubdelarazon.org (Sebastian Bassi) Date: Fri, 13 Apr 2007 23:18:22 -0300 Subject: Python editor/IDE on Linux? In-Reply-To: References: Message-ID: <9e2f512b0704131918p25cb9b44sb3e5cebaf31d7dd6@mail.gmail.com> On 4/13/07, Jack wrote: > I wonder what everybody uses for Python editor/IDE on Linux? > I use PyScripter on Windows, which is very good. Not sure if > there's something handy like that on Linux. I need to do some > development work on Linux and the distro I am using is Xubuntu. DrPython is very nice and is already in Ubuntu repos (http://drpython.sourceforge.net/). Eric is also available in Ubuntu (http://www.die-offenbachs.de/detlev/eric.html). From Graham.Dumpleton at gmail.com Sun Apr 22 17:55:52 2007 From: Graham.Dumpleton at gmail.com (Graham Dumpleton) Date: 22 Apr 2007 14:55:52 -0700 Subject: python cgi problem with textarea In-Reply-To: <1177247362.014926.12500@n76g2000hsh.googlegroups.com> References: <1177222084.696307.128620@n59g2000hsh.googlegroups.com> <1177247362.014926.12500@n76g2000hsh.googlegroups.com> Message-ID: <1177278952.534936.210270@p77g2000hsh.googlegroups.com> On Apr 22, 11:09 pm, placid wrote: > On Apr 22, 4:08 pm, Adrian Smith wrote: > > > > > This may be more a cgi thing than a Python one, but I'm trying to get > > this page: > > >http://adrian10.phpwebhosting.com/trial.html > > > consisting basically of this: > > >
> > > >

> >

> > > ...to print out the contents of the textarea with this cgi script: > > > #!/usr/bin/python > > import cgi > > print "Content-type: text/html\n" > > form = cgi.FieldStorage() > > print form["essay"].value > > > ...and I get an internal server error if I have any spaces in the > > textarea, which is really going to limit its usefulness to me. Oddly, > > it seems to work for a friend in the UK who's looked at it, but it > > doesn't work for me here in Japan. > > i just tried it and its working. here it is > > http://yallara.cs.rmit.edu.au/~bevcimen/form.html > > maybe the internal server error is because mod_python isn't installed > assuming your using Apache as your web server You do not need mod_python installed to be able to run CGI scripts, thus has nothing to do with mod_python. Graham From king_of_bellmund at bluewin.ch Mon Apr 9 16:18:45 2007 From: king_of_bellmund at bluewin.ch (Marco) Date: Mon, 9 Apr 2007 22:18:45 +0200 Subject: No subject Message-ID: <9A7C3E4A-1AC6-4331-B59F-004BCE9F1216@bluewin.ch> Hi, I have a problem to install wxPython on my MacBook (Pythonversion 2.5). If would install the wxPython (python setup.py install), then I got this error: Traceback (most recent call last): File "/Users/marco/Desktop/flexo1/wxpython/wxPython-src-2.8.3.0/ wxPython/setup.py", line 49, in copy_file('config.py', 'wx/build', update=1, verbose=1) File "/Users/marco/python//lib/python2.5/distutils/file_util.py", line 119, in copy_file "can't copy '%s': doesn't exist or not a regular file" % src distutils.errors.DistutilsFileError: can't copy 'config.py': doesn't exist or not a regular file Where is the problem and how could i fix it? Thx for your answers. marco From cam.ac.uk at mh391.invalid Wed Apr 18 14:38:26 2007 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Wed, 18 Apr 2007 19:38:26 +0100 Subject: converting currency using locals In-Reply-To: <1a6pqx9mwzy6n$.1up65mccv8fm.dlg@40tude.net> References: <1a6pqx9mwzy6n$.1up65mccv8fm.dlg@40tude.net> Message-ID: Grzegorz ?lusarek wrote: > Hi all. I have situation that I have value that holds price and I must show > this price using national specification(e.g. thousands_sep). Any idea how > this can be done under python 2.4.4? I saw that function format from module > locals can format value with national specification, but this could be done > only in python 2.5. Any solution for 2.4? I think you mean locale, for anyone else who was puzzled by this. -- Michael Hoffman From apardon at forel.vub.ac.be Wed Apr 18 03:37:11 2007 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 18 Apr 2007 07:37:11 GMT Subject: Queue enhancement suggestion References: <7x4pngluel.fsf_-_@ruckus.brouhaha.com> Message-ID: On 2007-04-18, Hendrik van Rooyen wrote: > "Antoon Pardon" wrote: > > >> The problem is that sometimes the gui thread has something to show >> too. With the added problem that the code wanting to show something >> doesn't know when it is executing the gui thread or an other. So >> it is very difficult to avoid the gui thread putting things on the >> queue. But since the gui thread is the single reader, it will dead >> lock if the queue happens to be full at the moment the gui thread >> want to add another item. > > This can happen - I suppose the cure is to have the GUI use a non blocking > put in a try except checking for the full condition - its bad to block the GUI > anyway because then the mouse and kbd become unresponsive. So even > the reads (get) have to be non blocking, or the thing will behave like a > disobedient dog, that knows what to do, but just refuses. My queue module has a "register" call. So you can register it to GTK the same way you can register a pipe or network connection. So the gui will only try to get things from the queue if there is something in it. -- Antoon Pardon From castironpi at gmail.com Thu Apr 26 11:26:03 2007 From: castironpi at gmail.com (castironpi at gmail.com) Date: 26 Apr 2007 08:26:03 -0700 Subject: function object.func_default off the console In-Reply-To: References: Message-ID: <1177601163.140674.108320@t39g2000prd.googlegroups.com> On Apr 25, 1:56 am, Peter Otten <__pete... at web.de> wrote: > Aaron Brady wrote: > >>>> f.func_defaults[0] > > [2, 3] > >>>> f.func_defaults[0]+=[4] > > Traceback (most recent call last): > > File "", line 1, in > > TypeError: 'tuple' object does not support item assignment > >>>> f.func_defaults[0] > > [2, 3, 4] > > > V. interesting. Operation succeeds but with a throw. Er, raise. > > This is not specific to func_defaults: > > >>> t = ([1],) > >>> t[0] += [2] > > Traceback (most recent call last): > File "", line 1, in > TypeError: 'tuple' object does not support item assignment>>> t > > ([1, 2],) > > t[0] += [2] > > is resolved to > > t.__setitem__(t[0].__iadd__([2])) > > where list.__iadd__() succeeds but __setitem__() fails (because tuples don't > have that method). > > Peter Curious why t.__setitem__ is called. Wouldn't it still refer to the same list? From ruiligc at earthlink.net Mon Apr 23 07:25:30 2007 From: ruiligc at earthlink.net (Ray) Date: Mon, 23 Apr 2007 11:25:30 GMT Subject: TK-grid problem, please help In-Reply-To: References: <3CgWh.23821$PL.17381@newsread4.news.pas.earthlink.net> Message-ID: Hi, Thanks for the help! Anton Vredegoor wrote: > Ray wrote: > >> hi, I have a question about how to use .grid_forget (in python/TK) >> >> I need to work on grid repeatly. everytime when a button is pressed, >> the rows of grid is different. such like, first time, it generate 10 >> rows of data. >> 2nd time, it maybe only 5 rows. so I need a way to RESET the grid data >> every time. how can I do it? by grid_forger()?, then would anyone can >> help on >> how to use grid_forget() >> the sample code as following: > > I'm not sure if it solves your problem but this modification of your > code at least *looks* like it works better. The entries are completely > destroyed so that the next time you call the function they can be > recreated. > > The trick I am using is to use a list in the arguments of the function > but that is a bit of a hack, the list 'remembers' its state from the > last time the function was called, I think one should use classes for > bookkeeping such things instead. > > from Tkinter import * > > def mygrid(text,M = []): > ######## how to use grid_forget() to clean the grid??########### > while M: > x = M.pop() > x.destroy() > rows = [] > count=int(text) > for i in range(count): > cols = [] > for j in range(4): > e = Entry(frame3, relief=RIDGE) > M.append(e) > e.grid(row=i, column=j, sticky=NSEW) > e.insert(END, '%d.%d' % (i, j)) > cols.append(e) > rows.append(cols) > > > root=Tk() > > frame1=Frame(root, width=150, height=100) > frame1.pack() > > text=Entry(frame1) > text.pack(side=LEFT) > > button=Button(frame1, text='generate grid', command=(lambda: > mygrid(text.get()))) > > button.pack() > > frame2=Frame(root, width=150, height=100) > frame2.pack() > > button2=Button(frame2, text='exit', command=root.quit) > button2.pack() > > frame3=Frame(root, width=150, height=300) > frame3.pack() > > root.mainloop() > > A. From gary.porter at authentec.com Fri Apr 6 17:54:18 2007 From: gary.porter at authentec.com (garyp) Date: 6 Apr 2007 14:54:18 -0700 Subject: printing longs Message-ID: <1175896458.592054.159470@n76g2000hsh.googlegroups.com> Python 2.3.4 (#1, Oct 26 2004, 16:42:40) [GCC 3.4.2 20041017 (Red Hat 3.4.2-6.fc3)] on linux2 >>> x = int("80000000", 16) >>> x = x | 0x80000000 :1: FutureWarning: hex/oct constants > sys.maxint will return positive values in Python 2.4 and up >>> print "%x" % ( x ) -80000000 >>> How do I get python to print the usual answer: 8000000, not -80000000 Thanks, Gary From kelvin.you at gmail.com Mon Apr 9 04:41:30 2007 From: kelvin.you at gmail.com (=?utf-8?B?5Lq66KiA6JC95pel5piv5aSp5rav77yM5pyb5p6B5aSp5rav5LiN6KeB5a62?=) Date: 9 Apr 2007 01:41:30 -0700 Subject: Is there a simple function to generate a list like ['a', 'b', 'c', ... 'z']? In-Reply-To: References: <1176107364.000517.68580@q75g2000hsh.googlegroups.com> Message-ID: <1176108090.148274.214020@q75g2000hsh.googlegroups.com> On Apr 9, 4:35?pm, Michael Bentley wrote: > On Apr 9, 2007, at 3:29 AM, ????????????? > > ?? wrote: > > Is there a simple function to generate a list like ['a', 'b', 'c', ... > > 'z']? ? The range() just can generate the numeric list. > > import string > list(string.lowercase) Thanks a lot! From mail at microcorp.co.za Sun Apr 29 03:03:45 2007 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Sun, 29 Apr 2007 09:03:45 +0200 Subject: Memory addressing References: <1177702902.156596.52510@n35g2000prd.googlegroups.com><1177703803.179501.95300@n35g2000prd.googlegroups.com><1177715277.592511.296990@h2g2000hsg.googlegroups.com> Message-ID: <02a501c78a31$c947b960$03000080@hendrik> "Steven D'Aprano" wrote: > On Fri, 27 Apr 2007 16:07:57 -0700, castironpi wrote: > > > That's what we need: a CopyMemory() routine. > > What we _really_ need are Poke() and Peek() routines. > Yeah right! - we also need macros, then an assembler johnny like me can hack his own syntax using only macros, peek and poke... And still claim he's writing programmes in python. - Hendrik From ironfroggy at gmail.com Tue Apr 24 21:31:59 2007 From: ironfroggy at gmail.com (Calvin Spealman) Date: Tue, 24 Apr 2007 21:31:59 -0400 Subject: kwarg references Message-ID: <76fd5acf0704241831n5503a8d0rb722908b6f391d43@mail.gmail.com> In the internal API when a C function is called and passed a kwarg dictionary, is there any case where anything else has a reference to it? I checked with the following code and it looks like even if you explicitly pass a dictionary with **kwargs, it still copies the dictionary anyway. -- Read my blog! I depend on your acceptance of my opinion! I am interesting! http://ironfroggy-code.blogspot.com/ From grante at visi.com Sun Apr 1 22:56:49 2007 From: grante at visi.com (Grant Edwards) Date: Mon, 02 Apr 2007 02:56:49 -0000 Subject: How can i compare a string which is non null and empty References: <1175469766.979636.65020@e65g2000hsc.googlegroups.com> <1310puahjesd9b9@corp.supernews.com> Message-ID: <1310s7hfgcgc143@corp.supernews.com> On 2007-04-02, Shane Geiger wrote: >>> how can i compare a string which is non null and empty? >>> >> [...] >> >>> In java,I do this: >>> if (str != null) && (!str.equals("")) .... >>> >>> how can i do that in python? >> >> If you want to litterally do that, it's >> >> if (str != None) and (str != ""): >> >> >> However, the standard idiom for doing that in Python is >> >> if str: >> > > It is probably worth noting that the example is not executable code: > str() is a function. Yea, sorry about that. -- Grant Edwards grante Yow! Now I'm concentrating at on a specific tank battle visi.com toward the end of World War II! From Aurel.Thomi at ruag.com Thu Apr 5 01:40:22 2007 From: Aurel.Thomi at ruag.com (Thomi Aurel RUAG A) Date: Thu, 5 Apr 2007 07:40:22 +0200 Subject: AW: Write to a binary file In-Reply-To: <1317p8ab5216aae@corp.supernews.com> Message-ID: <1A234A2831E39542B982C57BF92174F6BCCCA1@RTHUS5503.rintra.ruag.com> Hy Mike Thanks for your links, unfortunately they weren't very usefull for my specific problem. Hy Grant Edwards Thanks for your hints. A simplified test programm to compare the function for opening a file i used ("file()") and your suggested "os.open()" showed different behaviour. My simple testprogramm: --- START --- import os msg = chr(0x02) + chr(0x36) + chr(0x00) + chr(0x01) + chr(0x0a) + chr(0xb0) + chr(0x77) f = os.open('/dev/pytest', os.O_RDWR) os.write(f,msg) os.close(f) f = file('/dev/pytest', 'wb') f.write(msg) f.close() --- END --- The "pytest" device is a very simple device-driver which prints out (using "printk()") the buffer delivered to the write function in a hexadecimal format ("Pytest write> [buffer in hex format]"). The output was: --- Start --- Pytest write> 02 36 00 01 0a b0 77 Pytest write> 02 36 00 01 0a Pytest write> b0 77 --- END --- Using os.open will work for me, i wasn't aware of the existence of several file interaces. Thanks for your help regards Aurel From hlubenow2 at gmx.net Fri Apr 6 19:35:21 2007 From: hlubenow2 at gmx.net (hlubenow) Date: Sat, 07 Apr 2007 01:35:21 +0200 Subject: Hide the python-script from user References: <8ktie4-0i9.ln1@athlon.my> <1175898877.869321.112310@w1g2000hsg.googlegroups.com> <7ovie4-nfa.ln1@athlon.my> Message-ID: hlubenow wrote: > ts-dev wrote: > >> On Apr 6, 3:19 pm, hlubenow wrote: >>> recently there was a thread about hiding the python-script from the >>> user. The OP could use >> >> Interesting - thanks > > Well, testing it, it doesn't seem to work very well ... > > It seems, Python-code is rather difficult to obfuscate, probably because > of its clear syntax and indentations. Here's yet another approach: > > http://pythonhacker.is-a-geek.net/my_programs/pyfuscate/pyfuscate-0.1.zip/view > > H. That didn't work very well either :(. Ok, but now I can offer a real secure solution: You can have real encryption in Python using this modules: http://www.amk.ca/files/python/crypto/pycrypto-2.0.1.tar.gz and http://sourceforge.net/projects/yawpycrypto Below I post a code-example that I've written some time ago. With it, encrypting text is rather easy. Then you have to program a start-script, that reads in your script and the decryption-key. The decryption-key must be encrypted too. Such a encrypted key can be generated by the modules if you don't pass a password to my function "doEncrypt(). The decryption-key must then be hidden somewhere within the encrypted program-script. That's because, if the user knows where to find the key, he can decrypt the program-script. If your start-script is written, everything should work automatically, one shouldn't nearly notice the decryption-process. Ok, here's my example code, how to encrypt and decrypt some text with the modules: ---------------------------------------------------------------------------- #!/usr/bin/env python import os import sys import base64 from yawPyCrypto.Cipher import DecryptCipher, EncryptCipher from yawPyCrypto.Cipher import ZipDecryptCipher, ZipEncryptCipher from yawPyCrypto.Constants import CIPHER_BLOWFISH, MODE_CBC def doEncrypt(text, passw = None): e = EncryptCipher(passw, CIPHER_BLOWFISH, MODE_CBC) e.feed(text) e.finish() encryptedtext = e.data if passw != None: passwr = passw else: passwr = e.password a = (encryptedtext, passwr) return a def doDecrypt(encryptedtext, passw): d = DecryptCipher(passw) d.feed(encryptedtext) d.finish() decoded = (d.data) return decoded # Calling the encryption routine. # If you just pass the text to encrypt, a password is generated: a = doEncrypt("For your eyes only !", "Melina") # Just trying to clean the screen: if sys.platform == "win32": os.system("cls") else: os.system("clear") print print "Hello !" print print "I just encrypted some text. It looks like this now:" print print base64.b64encode(a[0]) print print 'Please notice, that I just encoded the text once more using "base64.b64encode()" to make it printable.' print print "The password for decryption is: " print print base64.b64encode(a[1]) print print "Let's decrypt again (the original password must be passed without b64encoding):" print print doDecrypt(a[0], a[1]) print ---------------------------------------------------------------------------- See you H. From bbxx789_05ss at yahoo.com Sun Apr 22 22:46:28 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: 22 Apr 2007 19:46:28 -0700 Subject: Python and Javascript equivalence In-Reply-To: References: Message-ID: <1177296388.593111.315600@b58g2000hsg.googlegroups.com> On Apr 22, 7:00 pm, "Sam the Cat" wrote: > Hey All, > > I am writing some COM code in Python to control photoshop. Several > functions of PS require an "Array" argument. In the examples of VBscript or > javascript the Array type is used. I have tried what would appear to be the > equivalent in Python -- Lists and Tuples -- but to no avail. Anyone have > any insight on what via the COM interface is equivalent to an Array in > javascript ? > > Cheers > Sam See if the python array type works: import array y = array.array("i", [2,3,4]) print y From phil.aerts.tln at gmail.com Tue Apr 3 13:56:16 2007 From: phil.aerts.tln at gmail.com (phil.aerts.tln at gmail.com) Date: 3 Apr 2007 10:56:16 -0700 Subject: cli user interface ala cisco IOS or JUNOS In-Reply-To: <87ircdhjbd.fsf@benfinney.id.au> References: <1175588673.340855.130230@q75g2000hsh.googlegroups.com> <87ircdhjbd.fsf@benfinney.id.au> Message-ID: <1175622976.111422.135500@b75g2000hsg.googlegroups.com> On 3 apr, 11:57, Ben Finney wrote: > phil.aerts.... at gmail.com writes: > > for one of mypythonprojects I need an user interface similar to that > > of cisco IOS or even better JuniperJUNOS. > > Does anyone know of existingpythonmodules that gives this kind of > > functionality? > > I suspect you've not checked the standard library index: > > PythonLibrary Reference > > > which lists the 'cmd' module: > > cmd -- Support for line-oriented command interpreters > > > If that doesn't meet your needs, you might need to be more specific > about what you're looking for. > > -- > \ "Success is going from one failure to the next without a loss | > `\ of enthusiasm." -- Winston Churchill | > _o__) | > Ben Finney hehe, your right I did not check the standard library and 'cmd' might just be that what I was looking for. tnx Ben -Philippe From diffuser78 at gmail.com Sun Apr 15 01:43:58 2007 From: diffuser78 at gmail.com (DanielJohnson) Date: 14 Apr 2007 22:43:58 -0700 Subject: combination function in python Message-ID: <1176615838.830315.160210@b75g2000hsg.googlegroups.com> how to use the combination function in python ? For example 9 choose 2 (written as 9C2) = 9!/7!*2!=36 Please help, I couldnt find the function through help. From bdesth.quelquechose at free.quelquepart.fr Fri Apr 27 17:48:05 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Fri, 27 Apr 2007 23:48:05 +0200 Subject: Which are your favorite UML tools? In-Reply-To: References: Message-ID: <463265f0$0$19018$426a34cc@news.free.fr> Anastasios Hatzis a ?crit : > Hello, > > I'm working on the light-weight MDA tool pyswarm, > http://pyswarm.sourceforge.net/ (it is about a code-generator for > Python/PostgreSQL-based software. I plan to add support of UML CASE tools > other than the one supported currently. > > I would like to learn which UML tools you use (if any), Any piece of paper and anything that can be used to write on it. > preferrably if it > comes to modeling a Python application. I stll wait for UML to be able to describe common hi-level dynamic languages idioms and patterns without requiring more space and time than source code. From aleax at mac.com Sun Apr 15 01:03:53 2007 From: aleax at mac.com (Alex Martelli) Date: Sat, 14 Apr 2007 22:03:53 -0700 Subject: function with list argument defaulting to [] - what's going on here??? References: <46217e8f$0$19437$4c368faf@roadrunner.com> Message-ID: <1hwkyl6.12i2494nimceN%aleax@mac.com> Steven D'Aprano wrote: > On Sun, 15 Apr 2007 05:29:01 +0200, BJ?rn Lindqvist wrote: > > >> This comes up so often that I wonder whether Python should issue a warning > >> when it sees [] or {} as a default argument. > >> > >> > >> What do people think? A misuse or good use of warnings? > > > > I think Python should reevaluate the default values. > > That would break code that relies on the current behaviour. That makes it > a "maybe" for Python 3.0, and an absolute "NO!!!" for Python 2.x. If you hope to get any change in Python 3.0, your PEP had better be in before the end of April -- that's the 3.0 deadline for PEPs. Alex From cjw at sympatico.ca Mon Apr 16 10:37:57 2007 From: cjw at sympatico.ca (Colin J. Williams) Date: Mon, 16 Apr 2007 10:37:57 -0400 Subject: Python Feature Request: Add the "using" keyword which works like "with" in Visual Basic In-Reply-To: References: <1176547372.584539.89170@q75g2000hsh.googlegroups.com> Message-ID: James Stroud wrote: > samjnaa at gmail.com wrote: >> Please check for sanity and approve for posting at python-dev. >> >> In Visual Basic there is the keyword "with" which allows an object- >> name to be declared as governing the following statements. For >> example: >> >> with quitCommandButton >> .enabled = true >> .default = true >> end with >> >> This is syntactic sugar for: >> >> quitCommandButton.enabled=true >> quitCommandButton.default=true >> >> This can be very useful especially in GUI programming when we have to >> type the same object name in line-after-line. I personally found >> having to type the word "self" umpteen times inside classes very >> irritating. Such a beautiful language is Python, she should have this >> good feature from VB too. >> >> Now I hear that the word "with" is being discussed for a different >> purpose in Py 3 as a result of a PEP and I don't want to conflict with >> that. So I propose the word "using" as a replacement. This also is >> similar to the C++ "using" keyword which exposes the members of a >> namespace to access without specifying the namespace scope for each >> reference. For example after giving "using namespace std;" I can >> change all references to "std::cout" to "cout", which is similar to >> what I am proposing for Python now. >> >> Some thoughts about how this "using" statement should behave. The word >> using should be followed by an object name and a colon indicating the >> start of a block. The object named after "using" must determine the >> context (or whatever the technical word is) of the of the statements >> in that block. >> >> self.setFixedSize(200, 120) >> self.quit = QtGui.QPushButton("Quit", self) >> self.quit.setGeometry(62, 40, 75, 30) >> self.quit.setFont(QtGui.QFont("Times", 18, QtGui.QFont.Bold)) >> self.connect(self.quit, QtCore.SIGNAL("clicked()"), QtGui.qApp, >> QtCore.SLOT("quit()")) >> >> to be rewritten as: >> >> using self: >> __setFixedSize(200,120) >> __quit = QtGui.QPushButton("Quit", self) >> __using quit: >> ____setGeometry(62, 40, 75, 30) >> ____setFont(QtGui.QFont("Times", 18, QtGui.QFont.Bold)) >> __connect(self.quit, QtCore.SIGNAL("clicked()"), QtGui.qApp, >> QtCore.SLOT("quit()")) >> >> [I don't know whether usenet will retain my indenting, so I changed >> the tabs to underscores.] >> >> This context governing may need to be limited to the first applicable >> member - so that in the above example "self" governs setFixedSize, >> quit, quit and connect only in each sentence and quit (self.quit) >> governs setGeometry and setFont only. (Point is that the parser should >> not search for self.QtGui, self.self or self.QtCore in sentences 3 and >> 7, and self.quit.QtGui in sentence 6.) >> >> Due to my absence of professional experience, my request may be >> somewhat unpolished technical-wise, but I believe that this is a very >> useful feature for Python and hence request the technically- >> knowledgeable to reformat it as necessary. Thank you. >> > > I like this one for some reason. Just the "using self" would save hella > typing in a lot of classes. I would favor a convention with leading dots > to disambiguate from other variables. This wouldn't conflict with, say, > floats, because variable names can't begin with a number. > > James Yes, I like the idea too. It has deeper roots than Visual Basic. In Pascal, Nicklaus Wirth used "with" for record access. It's an idea that can be used with any object which has attributes. The value of an attribute could be a function or a class. It's a pity that the word "with" was used for a context declaration - PEP 343. On the other hand, I believe "using" has been suggested as an alternative, that seems a reasonable alternative. Colin W. From Martin.Drautzburg at web.de Sun Apr 22 11:47:10 2007 From: Martin.Drautzburg at web.de (Martin Drautzburg) Date: Sun, 22 Apr 2007 17:47:10 +0200 Subject: serializable object references References: <1242622.P0zHLAfcMH@beaureve.gmx.net> Message-ID: <25065059.0D4t2YsirZ@beaureve.gmx.net> Gabriel Genellina wrote: > En Sun, 22 Apr 2007 08:07:27 -0300, Martin Drautzburg > escribi?: > >> Is it possible to convert an object into a string that identifies the >> object in a way, so it can later be looked up by this string. >> Technically this should be possible, because things like >> >> <__main__.Foo instance at 0xb7cfb6ac> >> >> say everything about an object. But how can I look up the real >> object, when I only have this string? >> >> I know such a thing can be achieved with a dictionary that holds >> reference-object pairs. Is there another way? > > Without further information, this would be the way. > What do you want to achieve? Maybe you are looking for the pickle > module. > I was thinking that it would be nice if a web application could talk to real objects. The client side does not need to know the internals of an object, it acts as a "view" for server-side models. All it has to be able to do is invoke methods on "its" model. So a view could just store "its" object-reference in an instance variable and pass it to the server, where my problem of looking it up comes in. I am currently learning about web services but my feeling is that "state" is not an integral part of this concept, rather an add-on, but I may be mistaken here. But for any reasonable web application you have to introduce state one way or the other. My impression is, that this is achieved with "session objects", which hold all the state of a session (again I may be mistaken). But this would be a strange concept in an OO world. You might as well put "ALL" state into a global "state" state object, where all the class methods deposit their state and classes would hold behavior only and no state. This is of course nothing an OO programmer would want to do. From zhonghua.m.yang at gmail.com Mon Apr 23 18:34:39 2007 From: zhonghua.m.yang at gmail.com (ZMY) Date: 23 Apr 2007 15:34:39 -0700 Subject: Numpy problem: Arrays in a list of dictionaries In-Reply-To: References: <1176837810.276473.55020@e65g2000hsc.googlegroups.com> Message-ID: <1177367679.113990.156000@q75g2000hsh.googlegroups.com> Dear Robert, So how should I do this? I tried >>>> d1 = {1: array([2, 3, 4]).copy(), 2: ''} >>>> l1 = [] >>>> for i in range(3): l1.append(d1.copy()) and it still doesn't work. I think my problem is: how to create a new array every time I append it to the list... Thanks in advance, - ZMY On Apr 17, 12:36 pm, Robert Kern wrote: > ZMYwrote: > > I am new to Numpy/Pylab, and I am trying to construct a list of > > dictionaries with arrays as the items, for example: > > >>>> dict = {1: array([2, 3, 4]), 2: ''} > >>>> list1 = [] > >>>> for i in range(3): list1.append(dict.copy()) > > ... > >>>> list1 > > [{1: array([2, 3, 4]), 2: ''}, {1: array([2, 3, 4]), 2: ''}, {1: > > array([2, 3, 4]), 2: ''}] > >>>> list1[0][1][1]=100 > >>>> list1 > > [{1: array([ 2, 100, 4]), 2: ''}, {1: array([ 2, 100, 4]), 2: > > ''}, {1: array([ 2, 100, 4]), 2: ''}] > > >>>> list1[0][2]='Jack' > >>>> list1 > > [{1: array([ 2, 100, 4]), 2: 'Jack'}, {1: array([ 2, 100, 4]), > > 2: ''}, {1: array([ 2, 100, 4]), 2: ''}] > > > So the strings can be assigned seperately but arrays can not. What is > > the problem here? > > When you call dict.copy(), all it does is make a copy of the dictionary; each > copy of the dictionary still refers to the same objects. > > list1[i][1] refers to the same array for all i, so when you modify it in-place > like you did, you will see the modifications in every reference to that object. > > list[i][2] also referred to the same string for all i until you *replaced* the > entry in the 0'th dictionary. > > -- > 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 steve at holdenweb.com Thu Apr 19 22:05:59 2007 From: steve at holdenweb.com (Steve Holden) Date: Thu, 19 Apr 2007 22:05:59 -0400 Subject: wxPython and how to return text entry to main program? In-Reply-To: <1177030290.529322.56210@p77g2000hsh.googlegroups.com> References: <1177011490.435609.155870@o5g2000hsb.googlegroups.com> <1177030290.529322.56210@p77g2000hsh.googlegroups.com> Message-ID: 7stud wrote: > On Apr 19, 1:38 pm, Tyler wrote: [after quoting umpteen lines of code] > > You can do this: > > --- > class MyFrame(wx.Frame): > > .. > .. > .. > def OnSubmit(self, event): > globals()["userInput"] = self.txtCtrlName.GetValue() > self.Close() > > app = MyApp() > app.MainLoop() > > print userInput > ----- > Please try to limit your quoting to what's relevant. 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 michael at jedimindworks.com Thu Apr 26 10:26:18 2007 From: michael at jedimindworks.com (Michael Bentley) Date: Thu, 26 Apr 2007 09:26:18 -0500 Subject: Re-ocurring Events In-Reply-To: <008001c787e5$04efe680$0ecfb380$@rawlins@thinkbluemedia.co.uk> References: <008001c787e5$04efe680$0ecfb380$@rawlins@thinkbluemedia.co.uk> Message-ID: On Apr 26, 2007, at 4:26 AM, Robert Rawlins - Think Blue wrote: > A bit more of a complex one this time, and I thought I?d get your > opinions on the best way to achieve this. Basically I?m looking for > a way to describe a re-occurring event, like a calendar event or > appointment I guess. I?m likely to use an XML file for the > definition of the events, but imagine I?ve got an event that looks > something like this. > > > > repeat=?daily? /> > > > > Now what I want to do is be able to build a class which has a > function like ?getCurrentEvent()? which will return any events that > should be occurring at that time. So if the current system time and > date is 2007-01-03 13:00:00 then it will return THAT event to me, > but if it was say 2007-01-03 16:00:00 then it would not, as the > event isn?t ?due? to occur at that time. Make sense? > > > > What?s the best way of handling this? I?m really a little lost as > to how I might get started, checking a static date time isn?t a > problem, it?s when it comes to these re-occurring events that I > struggle a little. The idea is that I would have 5 core > repetitions, none, daily, weekly, monthly and annually. > > > > Or perhaps you guys have a more full proof method of describing the > event in the XML? > > > > Any suggestions are more than welcome guys, thanks again for all > your help recently. This is a *nix based project, right? If so, it might be useful to look into cron. From kyosohma at gmail.com Wed Apr 4 16:01:31 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: 4 Apr 2007 13:01:31 -0700 Subject: How can I make sure my python exit In-Reply-To: <1175716731.915570.236820@w1g2000hsg.googlegroups.com> References: <1175716731.915570.236820@w1g2000hsg.googlegroups.com> Message-ID: <1175716891.317710.292710@l77g2000hsb.googlegroups.com> On Apr 4, 2:58 pm, "ying... at gmail.com" wrote: > Hi, > > I have a python script: > At the end of the script, I have: > > print "Build Done!" > > my question is does that mean my python script exits after it prints > "Build done!" > > I have a java program which calls this python script. But i run into a > problem in which the python script never returns to the java program > after it performs a system call to execute that python script. Typically when the last piece of code executes, the program ends. You could import sys and explicitly exit by calling sys.exit(0). Mike From steve at holdenweb.com Sat Apr 7 17:23:13 2007 From: steve at holdenweb.com (Steve Holden) Date: Sat, 07 Apr 2007 17:23:13 -0400 Subject: block scope? In-Reply-To: <1hw72cg.115yokgarr9enN%aleax@mac.com> References: <7xr6qwal50.fsf@ruckus.brouhaha.com> <7xtzvseqzo.fsf@ruckus.brouhaha.com> <1hw72cg.115yokgarr9enN%aleax@mac.com> Message-ID: Alex Martelli wrote: > Neal Becker wrote: > ... >>> i = 5 >>> for my i in xrange(4): >>> if i: # skips first when i is 0 >>> my i = 100 >>> if i: >>> print i # of course 100 >>> break >>> print i # i is between 0 & 3 here >>> print i # i is 5 here >>> >>> >>> Doesn't leave a particularly bad taste in one's mouth, I guess (except >>> for the intended abuse). >>> >>> James >> Yes, the above is pretty much what I had in mind. +1. > > I prefer Java's approach (14.4.2 in the JLS 2nd edition): forbid "inner" > blocks from shadowing variables in "outer" ones. I quote: > """ > If a declaration of an identifier as a local variable of the same > method, constructor, or initializer block appears within the scope of a > parameter or local variable of the same name, a compile-time error > occurs. > Thus the following example does not compile: > > class Test { > public static void main(String[] args) { > int i; > for (int i = 0; i < 10; i++) > System.out.println(i); > } > } > This restriction helps to detect some otherwise very obscure bugs. > """ > I entirely agree with the JLS here, having fought just such bugs in C++ > and other languages that lack the restriction in question. I just wish > Python had adopted the same restriction regarding nested functions, when > proper lexical scoping was introduced -- I argued for it at the time, > but backwards compatibility blocked its introduction. There are > definitely NOT many Java-specific language characteristics that I like, > but this one is a winner!-) [[but, I disagree with the lack in Java of > a similar restriction against shadowing between instance variables and > local variables, and the weak rationale for that in the JLS:-)]]. > What do you think the chances are of this being accepted for Python 3.0? It is indeed about the most rational approach, though of course it does cause problems with dynamic namespaces. 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 jstroud at mbi.ucla.edu Thu Apr 12 17:01:37 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Thu, 12 Apr 2007 14:01:37 -0700 Subject: Need help with the get() method of a Text entry In-Reply-To: <1176409717.585710.184960@y80g2000hsf.googlegroups.com> References: <1176409717.585710.184960@y80g2000hsf.googlegroups.com> Message-ID: Chad wrote: > I have a simple little program that brings up asks the user to enter a > note, then is supposed to place that note into a text file when the > user hits the submit button. However, when the user hits the submit > button, absolutely nothing happens. IDLE doesn't give an error > message and the note is not entered into the text file. For > troubleshooting puposes, I wanted to see if IDLE would at least print > the user's input; it doesn't do that either. Can someone please help > me? > > Here is the code: > > from Tkinter import * > > class Application(Frame): > """ GUI application that creates a story based on user input. """ > def __init__(self, master): > """ Initialize Frame. """ > Frame.__init__(self, master) > self.grid() > self.create_widgets() > > def create_widgets(self): > """ Create widgets to get note information. """ > # create instruction label and text entry for notes > Label(self, > text = "Notes" > ).grid(row = 0, column = 0, columnspan = 2 ) > > > self.notes_ent = Text(self, width = 75, height = 10, wrap = > WORD) > self.notes_ent.grid(row = 2, column = 0 ,columnspan = 7, > rowspan = 3, sticky = W) > create submit button > text1 = StringVar(self) > text1 = self.notes_ent.get(1.0, END) > self.notes_ent.config(state=NORMAL) > Button(self, > text = "Add Note", > command = self.add_note(text1) > ).grid(row = 1, column = 0, sticky = W) > > > > > def add_note(self, text1): > print text1 > text_file = open("write_it.txt", "a+") > text_file.write(text1) > > > > > > > > > root = Tk() > root.title("Mad Lib") > app = Application(root) > root.mainloop() > On second look, it seems you have deeper problems, some of which are: > text1 = StringVar(self) > text1 = self.notes_ent.get(1.0, END) You obviously added the second because the first will never work. Get rid of both lines. Even if you intended the second, it immediately nullifies the first. Instead of my previous suggestions, do this: 1. delete both "text1 =" lines 2. change "command = self.add_note(text1)" to "command = self.add_note" 3. change "def add_note(self, text1):" to "def add_note(self):" 4. delete "print text1" 5. change "text_file.write(text1)" to "text_file.notes_ent.get(1.0, END) James From irstas at gmail.com Wed Apr 4 14:46:24 2007 From: irstas at gmail.com (irstas at gmail.com) Date: 4 Apr 2007 11:46:24 -0700 Subject: BeautifulSoup vs. real-world HTML comments In-Reply-To: <1175711322.448629.20300@y80g2000hsf.googlegroups.com> References: <1175711322.448629.20300@y80g2000hsf.googlegroups.com> Message-ID: <1175712384.323874.115660@p77g2000hsh.googlegroups.com> Carl Banks wrote: > On Apr 4, 2:08 pm, John Nagle wrote: > > The syntax that browsers understand as HTML comments is much less > > restrictive than what BeautifulSoup understands. I keep running into > > sites with formally incorrect HTML comments which are parsed happily > > by browsers. Here's yet another example, this one from > > "http://www.webdirectory.com". The page starts like this: > > > > > > > > > > > > > > Environment Web Directory > > > > Those are, of course, invalid HTML comments. But Firefox, IE, etc. handle them > > without problems. > > > > BeautifulSoup can't parse this page usefully at all. > > It treats the entire page as a text chunk. It's actually > > HTMLParser that parses comments, so this is really an HTMLParser > > level problem. > > Google for a program called "tidy". Install it, and run it as a > filter on any HTML you download. "tidy" has invested in it quite a > bit of work understanding common bad HTML and how browsers deal with > it. It would be pointless to duplicate that work in the Python > standard library; let HTMLParser be small and tight, and outsource the > handling of floozy input to a dedicated program. That's a good suggestion. In fact it looks like there's a Python API for tidy: http://utidylib.berlios.de/ Tried it, seems to get rid of just fine. From willy at hotmail.com Wed Apr 4 19:38:18 2007 From: willy at hotmail.com (Willy) Date: Wed, 4 Apr 2007 16:38:18 -0700 Subject: Newbie Question about sequence multiplication References: <6cOdnVFCLMXxuYnbnZ2dnUVZ_rCsnZ2d@comcast.com> Message-ID: sentence = raw_input('Sentence: ') screen_width = 80 text_width = len(sentence) box_width = text_width + 6 left_margin = (screen_width - box_width) // 2 print print ' ' * left_margin + '+' + '-' * box_width + '+' print ' ' * left_margin + '|' + ' ' * box_width + '|' print ' ' * left_margin + '| ' + ' ' + sentence + ' ' + '|' print ' ' * left_margin + '|' + ' ' * box_width + '|' print ' ' * left_margin + '+' + '-' * box_width + '+' print "Scott" wrote in message news:6cOdnVFCLMXxuYnbnZ2dnUVZ_rCsnZ2d at comcast.com... > Alright, so I've been trying to teach myself Python which, when compared > to > my attempt to learn C++, is going pretty well. > But I've come across an issue that I can't figure out, so I figured I'd > ask > the pro's. > > Now it looks pretty weird in this format but it was copied exactly from > IDLE > > *****code follows******* > > #What this program is suppose to do is print a sentence centered in a box > > sentence = raw_input('Sentence: ') > > screen_width = 80 > text_width = len(sentence) > box_width = text_width + 6 > left_margin = (screen_width - box_width) // 2 > > print > print ' ' * left_margin + '+' + '-' * (box_width-2) + '+' > print ' ' * left_margin + '| ' + ' ' * text_width + ' |' > print ' ' * left_margin + '| ' + ' ' sentence + ' |' > print ' ' * left_margin + '| ' + ' ' * text_width + ' |' > print ' ' * left_margin + '+' + '-' * (box_width-2) + ' |' > print > > ****end code**** > > Now that, even though copied straight from "Beginning Python: From Novice > to > Professional", returns : > There's an error in your program: invalid syntax > > with the word sentence highlighted (not the sentence when I'm defining the > name, the one in......uhm....the body of the code) > > > Now if i put * before sentence as it is with the rest of the variables, it > actually gets to the point where it asks me for the sentence, but after > inputting my sentence I receive: > Traceback (most recent call last): > File "D:/Programming/Python/sequence string multiplication example", line > 16, in > print ' ' * left_margin + '| ' + ' ' * sentence + ' |' > TypeError: can't multiply sequence by non-int of type 'str' > > Why can't I get it to do what it's supposed to do? What am I > missing/misunderstanding? > Very simply all its supposed to do is something like this (now bear with > me > formating might distort this a bit lol) > +------------------------------------+ > | | > | Like This | > | | > +------------------------------------+ > > Any help would be greatly appreciated > > > -Scott > > > > From jstroud at mbi.ucla.edu Wed Apr 25 23:44:31 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Wed, 25 Apr 2007 20:44:31 -0700 Subject: Where did my post go? In-Reply-To: <1177550534.197992.263190@u32g2000prd.googlegroups.com> References: <1177550534.197992.263190@u32g2000prd.googlegroups.com> Message-ID: flifus at gmail.com wrote: > I posted to this newsgroup earlier about my annoyances with python and > now I can't find the post. What did you do with it? > I guess it depends on your server. Here at UCLA, we still see it. From iltchevi at gmail.com Sat Apr 14 11:32:49 2007 From: iltchevi at gmail.com (ici) Date: 14 Apr 2007 08:32:49 -0700 Subject: Python Feature Request: Allow changing base of member indices to 1 In-Reply-To: <1176546465.632410.52630@w1g2000hsg.googlegroups.com> References: <1176546465.632410.52630@w1g2000hsg.googlegroups.com> Message-ID: <1176564769.308967.165600@e65g2000hsc.googlegroups.com> On Apr 14, 1:27 pm, samj... at gmail.com wrote: ... > This would mean: > foo = "foo" > => foo[1] == 'f' > class Str1(str): def __getitem__(self,i): return str.__getitem__(self,i-1) s1 = Str1("foo") print s1[1] From nogradi at gmail.com Mon Apr 23 17:15:55 2007 From: nogradi at gmail.com (Daniel Nogradi) Date: Mon, 23 Apr 2007 23:15:55 +0200 Subject: Socket exceptions aren't in the standard exception hierarchy In-Reply-To: References: Message-ID: <5f56302b0704231415x1d0d6273hdcae2877d8dc0228@mail.gmail.com> > >>>> 2. File "D:\Python24\lib\socket.py", line 295, in read > >>>> data = self._sock.recv(recv_size) > >>>> error: (10054, 'Connection reset by peer') > >>>> > >>> That looks like M$ Windows version of UNIX/Linux error number 54 > >>> (pretty much all Windows socket errors are UNIX number+10000) > >>> > >>> Errors coming from Windows may not be mapped to specific Python > >>> exceptions, but rather to some general error conditions. {hypothesis} As > >>> such, the Windows errors may not match what UNIX/Linux report. > >> > >> > >> Actually, that's not what's happening. The socket module is > >> explicitly raising "socket.error" in C code. It's not an OSError or > >> a WindowsError, although the text makes it look like one. > >> > >> The problem is not that socket errors aren't entirely portable. > >> It's that they're not even in the Python exception hierarchy. > >> See "http://docs.python.org/lib/module-exceptions.html". > >> They have their own hierarchy, which starts at "socket.error". > >> All built-in exceptions were supposed to be converted to the > >> standard exception hierarchy back before Python 2.0, but these > >> weren't. > >> > >> Either they should be under IOError, or there should be > >> "NetworkError" under EnvironmentError, and they should be under > >> that. "NetworkError", alongside IOError in the hierarchy, > >> would be useful. All the things that go wrong in networking > >> belong under there. Socket-level errors, SSL/TLS-level errors, > >> and HTTP/FTP/etc. level errors all belong under NetworkError. > >> > >> This has to be fixed before PEP 352, when the exception > >> hierarchy is enforced, or the socket exceptions won't even work > >> right. > >> > > John: > > > > Where did you get this information? If true it would certainly need to > > be logged as a bug, but under Windows on 2,4 I see > > > > >>> issubclass(socket.gaierror, Exception) > > True > > >>> > > > > and the same under Cygwin 2.5. I am presuming most other users will see > > the same thing. > > > > regards > > Steve > > Ah. "socket.error" is a subclass of "Exception", but not > of "StandardError". > > issubclass(socket.error,StandardError) > > is False. On linux, python 2.5: >>> import socket >>> issubclass(socket.error,Exception) True From dsampson at NRCan.gc.ca Tue Apr 17 08:18:54 2007 From: dsampson at NRCan.gc.ca (Sampson, David) Date: Tue, 17 Apr 2007 08:18:54 -0400 Subject: VB6 To Python In-Reply-To: References: <2FAA57395C1F914DB27CAA4C376058F202434C96@S0-OTT-X2.nrn.nrcan.gc.ca> Message-ID: <2FAA57395C1F914DB27CAA4C376058F2024352B0@S0-OTT-X2.nrn.nrcan.gc.ca> Thanks for the feedback to this thread. I tried the conversion but unfortunately it did not translate from VB to Python. It wrapped the VB using a lib of python calls. So the language is not pure python. From what I see. So a full rewrite it is. -----Original Message----- From: python-list-bounces+dsampson=nrcan.gc.ca at python.org [mailto:python-list-bounces+dsampson=nrcan.gc.ca at python.org] On Behalf Of Steve Holden Sent: April 13, 2007 08:56 To: python-list at python.org Subject: Re: VB6 To Python Michael Bentley wrote: > > On Apr 12, 2007, at 1:11 PM, Sampson, David wrote: > >> Any experience or insight would be great. > > It has been my experience that when migrating to a dissimilar system, > avoiding the rewrite is a mistake. And futile. > This is good advice. Since your original project had such a clean separation between GUI code and the rest of the logic, however, you might want to investigate the methods discussed in Robinson and Hammond's "Programming Win32 in Python", where they explain how Python logic can make use of COM interfaces to interact with VB (or other COM) GUIs. 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 -- http://mail.python.org/mailman/listinfo/python-list From mensanator at aol.com Thu Apr 26 19:27:29 2007 From: mensanator at aol.com (mensanator at aol.com) Date: 26 Apr 2007 16:27:29 -0700 Subject: If Dict Contains a particular key In-Reply-To: <1hx5dto.hwi9shy3mg47N%aleax@mac.com> References: <000001c78695$ed321540$c7963fc0$@rawlins@thinkbluemedia.co.uk> <1177436682.3441.15.camel@dot.uniqsys.com> <1177565430.992904.149450@n35g2000prd.googlegroups.com> <1hx5dto.hwi9shy3mg47N%aleax@mac.com> Message-ID: <1177630049.320928.63280@r30g2000prh.googlegroups.com> On Apr 26, 12:47 am, a... at mac.com (Alex Martelli) wrote: > mensana... at aol.com wrote: > > ... > > > > if 'a' in thedict: > > > ... > > > > There's no need for the call to keys(). > > > Why not > > > if thedict.has_key('a'): > > pass > > elde: > > pass > > has_key exists only for backwards compatibility; the 'in' operator is > preferable. > > $ python -mtimeit -s'd={}' 'd.has_key(23)' > 1000000 loops, best of 3: 0.289 usec per loop > $ python -mtimeit -s'd={}' '23 in d' > 10000000 loops, best of 3: 0.139 usec per loop > > Why consume twice as much time with no advantages whatever?! Did I wander into comp.lang.perl by mistake? > > Alex From ptmcg at austin.rr.com Thu Apr 26 09:50:53 2007 From: ptmcg at austin.rr.com (Paul McGuire) Date: 26 Apr 2007 06:50:53 -0700 Subject: Convert a string to a list In-Reply-To: <1177552969.604821.267290@c18g2000prb.googlegroups.com> References: <1177426760.164877.104990@t38g2000prd.googlegroups.com> <1177552969.604821.267290@c18g2000prb.googlegroups.com> Message-ID: <1177595453.614126.134670@t38g2000prd.googlegroups.com> On Apr 25, 9:02 pm, Paul McGuire wrote: > On Apr 24, 12:30 pm, Nick Craig-Wood wrote: > > > > > Someone normally chimes in with pyparsing at this point... > > Well it *is* a short pyparsing routine, after all... > > -- Someone > > tests = """\ > ("." ".." "cdslib_cleanup.py" "cadence.py" > "cdsinit_cdsenv_cleanup.py") > ("." ("cadence.py" "foo_cleanup.py") "cdslib_cleanup.py" "cadence.py" > "cdsinit_cdsenv_cleanup.py") """.splitlines() > > import pyparsing as pp > > LPAR,RPAR = map(pp.Suppress,"()") > list_ = pp.Forward() > list_ << ( LPAR + > pp.ZeroOrMore( pp.quotedString | pp.Group(list_) ) + > RPAR ) > > for t in tests: > result = list_.parseString(t) > print result.asList() > > Prints: > ['"."', '".."', '"cdslib_cleanup.py"', '"cadence.py"', > '"cdsinit_cdsenv_cleanup.py"'] > ['"."', ['"cadence.py"', '"foo_cleanup.py"'], '"cdslib_cleanup.py"', > '"cadence.py"', '"cdsinit_cdsenv_cleanup.py"'] Oh, you probably don't want those quotation marks in the parsed strings. Change: pp.ZeroOrMore( pp.quotedString | pp.Group(list_) ) + to: pp.ZeroOrMore( pp.quotedString.setParseAction(pp.removeQuotes) | pp.Group(list_) ) + -- Paul From bcwhite at pobox.com Wed Apr 18 11:24:08 2007 From: bcwhite at pobox.com (bcwhite at pobox.com) Date: 18 Apr 2007 08:24:08 -0700 Subject: Future Python Gui? In-Reply-To: <1176863948.526051.186210@n76g2000hsh.googlegroups.com> References: <1176859699.906386.326720@b75g2000hsg.googlegroups.com> <1176863948.526051.186210@n76g2000hsh.googlegroups.com> Message-ID: <1176909848.455264.174730@e65g2000hsc.googlegroups.com> > I'd say that the best bet is to learn swig and similar > bridging, expanding, and embedding mechanisms. > Python GUI programming is likely to involve either > python hooking into frameworks like Cocoa, Qt, or > wxWidgets, python embedded in frameworks > like Java or .NET, or flavors of python used > as domain-specific languages in applications such as > emacs, vim, and OpenOffice.org. If this were just a tool for me, it wouldn't matter. My concern is distribution. If anybody who wants to run my software then they also have to go through all the trouble to install these extensions, none of which seem to have decent instructions. I'm an old-time hack and I have trouble getting them to work. A simple user won't have a chance! If Python doesn't declare an official Gui system, then it'll be fragmented, inconsistent, and unsupportable. I wouldn't mind using just Tkinter, despite it's primative look, except that it doesn't support more advanced widgets like "notebook". -- Brian From tjreedy at udel.edu Sat Apr 14 19:10:42 2007 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 14 Apr 2007 19:10:42 -0400 Subject: Python Feature Request: Allow changing base of member indices to 1 References: <1176546465.632410.52630@w1g2000hsg.googlegroups.com> Message-ID: wrote in message news:1176546465.632410.52630 at w1g2000hsg.googlegroups.com... | I would like to have something like "option base" in Visual Basic. | IIRC it used to allow me to choose whether 0 or 1 should be used as | the base of member indices of arrays. In Python, the same can be used | with strings, lists, tuples etc. If you access a sequence with an iterator, perhaps now the most common case, the index base becomes an irrelevant internal detail. If you only access a sequence with explicit indexes, you can treat it as 1-based by ignoring the first element. This has been a standard conversion technique for a fewdecades. If you do not like writing range(1,n+1), use def myrange(n): return range(1,n+1). Interface conversion wrappers are another standard technique. Terry Jan Reedy From attn.steven.kuo at gmail.com Fri Apr 6 17:45:28 2007 From: attn.steven.kuo at gmail.com (attn.steven.kuo at gmail.com) Date: 6 Apr 2007 14:45:28 -0700 Subject: Database Timestamp conversion error In-Reply-To: <1175892527.110813.26570@n76g2000hsh.googlegroups.com> References: <1175892527.110813.26570@n76g2000hsh.googlegroups.com> Message-ID: <1175895928.669495.251180@b75g2000hsg.googlegroups.com> On Apr 6, 1:48 pm, kyoso... at gmail.com wrote: (snipped) > If I look in the MS Access database, I see the timestamp as "5/6/112". > Obviously some user didn't enter the correct date and the programmer > before me didn't give Access strict enough rules to block bad dates. > How do I test for a malformed date object so I can avoid this? There > are thousands of records to transfer. > time.strptime ? import time for date in ("5/6/2008", "5/6/118"): try: struct_tm = time.strptime(date, "%m/%d/%Y") print "Good date: " + date print struct_tm except ValueError: print "Bad date: " + date -- Hope this helps, Steven From bruno.42.desthuilliers at wtf.websiteburo.oops.com Wed Apr 4 04:57:38 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Wed, 04 Apr 2007 10:57:38 +0200 Subject: File Object behavior In-Reply-To: References: <9821538.post@talk.nabble.com> <4612bf27$0$29887$426a74cc@news.free.fr> Message-ID: <46136878$0$2129$426a74cc@news.free.fr> Michael Castleton a ?crit : > > > Bruno Desthuilliers wrote: >> Michael Castleton a ?crit : >>> When I open a csv or txt file with: >>> >>> infile = open(sys.argv[1],'rb').readlines() >>> or >>> infile = open(sys.argv[1],'rb').read() >>> >>> and then look at the first few lines of the file there is a carriage >>> return >>> + >>> line feed at the end of each line - \r\n >> Is there any reason you open your text files in binary mode ? >> (snip) > Bruno, > No particular reason in this case. It was probably as a holdover from using > the csv module in the past. I'm wondering though if using binary on very > large > files (>100Mb) would save any processing time - no conversion to system > newline? > What do you think? I think that premature optimization is the root of all evil. You'll have to do the processing by yourself then, and I doubt it'll be as fast as the C-coded builtin newline processing. Anyway, you can easily check it out by yourself - Python has timeit (for micro-benchmarks) and a profiler. From sjmachin at lexicon.net Tue Apr 24 21:46:57 2007 From: sjmachin at lexicon.net (John Machin) Date: Wed, 25 Apr 2007 11:46:57 +1000 Subject: gotcha or bug? random state reset on irrelevant import In-Reply-To: <33yXh.5839$Fc1.4387@trnddc05> References: <33yXh.5839$Fc1.4387@trnddc05> Message-ID: <462EB311.2010508@lexicon.net> On 25/04/2007 11:22 AM, Alan Isaac wrote: > Running test.py will print False. > Is this expected/desirable? > Thanks, > Alan Isaac > > > %%%%%%% test.py %%%%%%%%%%% > from random import seed, getstate > seed(217) > x = getstate() > from test2 import Trivial It's not irrelevant; the test2 module has to be *executed* as part of the import. Yes, "class" is an executable statement. Just about every Python statement is executable. seed(314) is executed. > y = getstate() > print x == y > > > %%%%% test2.py %%%%%%%%%%%%% > from random import seed Insert here: print "before seed call" > seed(314) Insert here: print "have just executed some relevant code" > class Trivial: > pass HTH, John From kyosohma at gmail.com Thu Apr 5 17:33:23 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: 5 Apr 2007 14:33:23 -0700 Subject: Problems with os.spawnv In-Reply-To: <1175807996.524018.146070@n76g2000hsh.googlegroups.com> References: <1175807996.524018.146070@n76g2000hsh.googlegroups.com> Message-ID: <1175808803.379481.62290@l77g2000hsb.googlegroups.com> On Apr 5, 4:19 pm, "Henrik Lied" wrote: > Hi there! > > I'm trying to convert a video in a background process. > The scenario I'm after: > 1. The user uploads a video > 2. The video is saved in my media directory, and the database is > populated with the references > 3. The video gets converted to FLV - but the user shouldn't have to > wait around for this to happen > > So, I thought to myself that spawnv would be a good fit for this. The > problem is that it doesn't fire of the command. > > Here's my test script:http://dpaste.com/hold/7981/ > > Why won't this work? The while-loop is printed, but the os command > isn't executed. I've also tried to specify the whole path to mencoder > (/opt/local/bin/mencoder), but to no use. I don't know what the deal is. Maybe you should try the subprocess module since it replaces the os.spawn* modules and do a subprocess.Popen instead? Or don't assign the result to a variable since you told it not to wait. You may need to do a combination of the subprocess module and one of the Threading modules. Mike From metalzong at 163.com Mon Apr 16 22:59:44 2007 From: metalzong at 163.com (Tommy Zong) Date: Tue, 17 Apr 2007 10:59:44 +0800 Subject: question of easyExcel (<>) Message-ID: <46243BD2.0D637F.28583@m5-85.163.com> Hi, class easyExcel: def __init__(self, filename=None): self.xlApp = Dispatch('Excel.Application') if filename: self.filename = filename self.xlBook = self.xlApp.Workbooks.Open(filename) else: self.xlBook = self.xlApp.Workbooks.Add() self.filename = '' def save(self, newfilename=None): if newfilename: self.filename = newfilename self.xlBook.SaveAs(newfilename) else: self.xlBook.Save() def close(self): self.xlBook.Close(SaveChanges=0) del self.xlApp def getSheets(self): return self.xlBook.Worksheets def getCell(self, sheet, row, col): sht = self.xlBook.Worksheets(sheet) return sht.Cells(row, col).Value def setCell(self, sheet, row, col, value, noerr=True): sht = self.xlBook.Worksheets(sheet) sht.Cells(row, col).Value = value def cpSheet(self, before): shts = self.xlBook.Worksheets shts(1).Copy(None,shts(1)) def show(self, visible=True): self.xlApp.Visible = visible easyExcel comes from <>, it provides a easy way to process excel files. However, I found a problem today - it works fine in single thread version but can not work properly in multi-thread version - If I move excel file operations to sub-thread, it will complain 'CoInitialize has not been called'. I noticed the exception is thrown in "Lib\site-packages\win32com\client\dynamic.py", I tried to add "pythoncom.CoInitialize()" in line 78 and "pythoncom.CoUninitialize()" in line 330, it will be ok. I have following questions and hope someone can give me some comments. Thanks a lot. 1. After doing such modifications, the excel file will be opened as "read only" mode, how to avoid this? 2. Is it necessary to add these two lines? Is there any mistake I made? Below is information of my python: ActivePython 2.4.3 Build 12 (ActiveState Software Inc.) based on Python 2.4.3 (#69, Apr 11 2006, 15:32:42) [MSC v.1310 32 bit (Intel)] on win32 - Tommy -------------- next part -------------- An HTML attachment was scrubbed... URL: From jjl at pobox.com Sun Apr 1 11:48:20 2007 From: jjl at pobox.com (John J. Lee) Date: Sun, 01 Apr 2007 15:48:20 GMT 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> Message-ID: <87abxscczf.fsf@pobox.com> Richard Jones writes: [...] > 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. PyPI has "just worked" for me, so thanks for the work you've put into it. My theory is that if an open-source project is fairly new and unstable, you'll often get lots of people saying nice things about it hoping to get help. Then if it gets better, people shut up, since it just does its job. Then they get used to it just working, and start giving abuse instead of praise when it doesn't do everything they want. I still occasionally get praise for my open source stuff, so I figure I've got a long way to go ;-) John From usenet423.4.fms at neverbox.com Tue Apr 24 12:32:01 2007 From: usenet423.4.fms at neverbox.com (Frank Stajano) Date: Tue, 24 Apr 2007 17:32:01 +0100 Subject: q: how to output a unicode string? Message-ID: A simple unicode question. How do I print? Sample code: # -*- coding: utf-8 -*- s1 = u"h?ll? w?rld" print s1 # Gives UnicodeEncodeError: 'ascii' codec can't encode character # u'\xe9' in position 1: ordinal not in range(128) What I actually want to do is slightly more elaborate: read from a text file which is in utf-8, do some manipulations of the text and print the result on stdout. I understand I must open the file with f = codecs.open("input.txt", "r", "utf-8") but then I get stuck as above. I tried s2 = s1.encode("utf-8") print s2 but got h??ll?? w??rld Then, in the hope of being able to write the string to a file if not to stdout, I also tried import codecs f = codecs.open("out.txt", "w", "utf-8") f.write(s2) but got UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 1: ordinal not in range(128) So I seem to be stuck. I have checked several online python+unicode pages, including http://boodebr.org/main/python/all-about-python-and-unicode#WHYNOPRINT http://evanjones.ca/python-utf8.html http://www.reportlab.com/i18n/python_unicode_tutorial.html http://www.amk.ca/python/howto/unicode http://www.example-code.com/python/python-charset.asp http://docs.python.org/lib/csv-examples.html but none of them was sufficient to make me understand how to deal with this simple problem. I'm sure it's easy, maybe too easy to be worth explaining in a tutorial... Help gratefully received. From deets at nospam.web.de Mon Apr 23 05:42:33 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 23 Apr 2007 11:42:33 +0200 Subject: ctypes: how to make a structure pointer to point to a buffer References: <1177316640.305123.52040@y5g2000hsa.googlegroups.com> Message-ID: <593dc9F2j7kl9U1@mid.uni-berlin.de> ??????????????? wrote: > first, I'm try the POINTER to convesion the pointer type. but failed. > > class STUDENT(Structure): > _fields_ = [('name', c_int), > ('id', c_int), > ('addition', c_ubyte)] > > buffer = c_byte * 1024 > student_p = cast(buffer, POINTER(STUDENT)) > > The parameter of the POINTER must be ctypes type. > How could I attach the buffer pointer to the structure STUDENT ? I think it should work like this: from ctypes import * class STUDENT(Structure): _fields_ = [('name', c_int), ('id', c_int), ('addition', c_ubyte)] buffer = (c_byte * 1024)() buffer_p = pointer(buffer) student_p = cast(buffer_p, POINTER(STUDENT)) print student_p Diez From slm_guzel at hotmail.com Mon Apr 2 17:24:43 2007 From: slm_guzel at hotmail.com (gslm) Date: 2 Apr 2007 14:24:43 -0700 Subject: print the screen shot in python Message-ID: <1175549083.627721.315170@y80g2000hsf.googlegroups.com> Hi! I want to print an application view in python.I use labels and frames in my program.And ? want to know if it is possible to print all of the view of my program? Thanks a lot... From facundobatista at gmail.com Wed Apr 25 09:15:58 2007 From: facundobatista at gmail.com (Facundo Batista) Date: Wed, 25 Apr 2007 10:15:58 -0300 Subject: [python-advocacy] Would You Write Python Articles or Screencasts for Money? In-Reply-To: <000a01c78706$4d2e9340$03000080@hendrik> References: <462DCCE6.9060908@taupro.com> <462E0D93.3090705@holdenweb.com> <000a01c78706$4d2e9340$03000080@hendrik> Message-ID: 2007/4/25, Hendrik van Rooyen : > Most bugs fixed in the month for the developers? > (Watch them scrabbling for the easy ones - ) > > Most Patches reviewed and incorporated? These numbers are easy to acquire. Note, though, that the name of the developer in a top ten of these numbers in a public place (like python.org), and a mention in a weekly report in the main python mailing lists, will be enough prize most of the times... Regards, -- . Facundo Blog: http://www.taniquetil.com.ar/plog/ PyAr: http://www.python.org/ar/ From edfialk at gmail.com Mon Apr 23 16:28:11 2007 From: edfialk at gmail.com (edfialk) Date: 23 Apr 2007 13:28:11 -0700 Subject: script for seconds in given month? In-Reply-To: <1176796031.889407.323950@b75g2000hsg.googlegroups.com> References: <1176740556.859125.221980@l77g2000hsb.googlegroups.com> <1hwokmz.1ropcwj17pg55dN%aleax@mac.com> <1176796031.889407.323950@b75g2000hsg.googlegroups.com> Message-ID: <1177360091.516469.77830@l77g2000hsb.googlegroups.com> Alex, very nice. That should be good enough for me. The rest of you as well, thanks for all the help. I, unfortunately, failed to realize the actual platform the script is for is IronPython. When trying to import calendar in IronPython, I get: SyntaxError: future feature is not defined: with_statement (c: \Python25\Lib\calendar.py, line 8) so, incompatible. I have moved my question over to the IronPython group, but if anyone is familiar with IronPython and knows how to perform the same function, that's what I'm looking for now. :) Thanks again! -Ed From nagle at animats.com Sun Apr 29 20:08:23 2007 From: nagle at animats.com (John Nagle) Date: Sun, 29 Apr 2007 17:08:23 -0700 Subject: fastest way to find the intersection of n lists of sets In-Reply-To: <1177889667.450984.88970@p77g2000hsh.googlegroups.com> References: <1177883328.835058.138990@p77g2000hsh.googlegroups.com> <1177889667.450984.88970@p77g2000hsh.googlegroups.com> Message-ID: Prateek wrote: >> For the above example, it's worth sorting lists_of_sets by the >>length of the sets, and doing the short ones first. > > > Thanks. I thought so - I'm doing just that using a simple Decorate- > Sort-Undecorate idiom. > > >> How big are the sets? If they're small, but you have a lot of >>them, you may be better off with a bit-set representation, then >>using AND operations for intersection. If they're huge (tens of millions >>of entries), you might be better off doing sorts and merges on the >>sets. > > > I have either 2 or 3 sets (never more) which can be arbitrarily large. > Most of them are small (between 0 and few elements - say less that 5). > A few will be megamonstrous ( > 100,000 items) > > >> When you ask questions like this, it's helpful to give some >>background. We don't know whether this is a homework assignment, or >>some massive application that's slow and you need to fix it, even >>if it requires heavy implementation effort. >> > > Its definitely not a homework assignment - its part of a commercial > database query engine. Heavy implementation effort is no problem. > > Prateek If you're intersecting a set of 5 vs a set of 100,000, the intersection time won't be the problem. That's just five lookups. It's building a set of 100,000 items that may be time consuming. Does the big set stay around for a while, or do you have to pay that cost on each query? Those really aren't big data sets on modern machines. John Nagle From usenet at nicko.org Tue Apr 10 08:10:03 2007 From: usenet at nicko.org (Nicko) Date: 10 Apr 2007 05:10:03 -0700 Subject: Database in memory In-Reply-To: <1176124752.172926.129850@w1g2000hsg.googlegroups.com> References: <1176124752.172926.129850@w1g2000hsg.googlegroups.com> Message-ID: <1176207003.322736.114820@y5g2000hsa.googlegroups.com> Jim wrote: > I have an application that will maintain an in-memory database in the > form of a list of lists. Does anyone know of a way to search for and > retreive "records" from such a structure? The answer very much depends on the manner in which you want to do the look-up. If you only need to do exact-match look-up for items with unique keys (e.g. find the single record where SSN=1234567890) then using a dictionary is by far the best solution. It's fast and it's easy. If you expect to do exact-match look-up where the keys are not unique then build a dictionary containing 'set' objects which are the sets of records which have the given key. This lets you neatly find the intersection of selections on multiple criteria (e.g. matches = zipcode_index["94101"] & hometype_index["condo"] ). If you need to do range matching (e.g. 20000 <= salary < 50000) then your best bet is to keep a list of the records sorted in the ordering of the key, do a binary search to find where the lower and upper bounds lie within the sorted list and then take a slice. If you also have some index dictionaries containing sets then you can combine these two methods with something like 'matches = set(salary_index[lo_sal:hi_sal]) & zipcode_index["81435"] ' Having said all that, if you think that there is any possibility that you might ever want to expand the functionality of your program to require either (a) more complex and flexible searching and/or (b) putting the database somewhere else, then I would strongly suggest that you use PySQLite. SQLite is an efficient in-memory database with an SQL engine and the Python interface conforms to the DB-API spec, so you won't need to change your code (much) if you want to move the database to some MySQL, Oracle, Sybase or DB2 server at a later date. Furthermore SQLite is included in Python 2.5 as standard. From anton.vredegoor at gmail.com Thu Apr 19 18:37:46 2007 From: anton.vredegoor at gmail.com (Anton Vredegoor) Date: Fri, 20 Apr 2007 00:37:46 +0200 Subject: multirember&co In-Reply-To: References: <1176768854.720234.23320@w1g2000hsg.googlegroups.com> <1176790588.024371.119360@n76g2000hsh.googlegroups.com> <1176850352.999231.79260@n59g2000hsh.googlegroups.com> <1176921030.330467.76860@o5g2000hsb.googlegroups.com> <1176925857.535835.130010@b58g2000hsg.googlegroups.com> <1177010211.252779.83620@y5g2000hsa.googlegroups.com> Message-ID: Anton Vredegoor wrote: > Maybe this one is better? No, this one keeps generating output. But this one stops at least: from collections import deque from itertools import chain, repeat def xsplitter(seq, pred): Q = deque(),deque() sentinel = object() it = chain(seq,repeat(sentinel)) def gen(p): for x in it: if x is sentinel: while Q[p]: yield Q[p].popleft() break elif pred(x) == p: while Q[p]: yield Q[p].popleft() yield x else: Q[~p].append(x) for x in gen(p): yield x return gen(1),gen(0) def test(): L = 1, 2, 3, 'a', 'a' # L = 'a', 1, 2, 'a' # L = 1, 'a', 3, 'a', 4, 5, 6, 'a' it1, it2 = xsplitter(L, lambda x: x == 'a') print it1.next() print it2.next() print it1.next() print it2.next() if __name__=='__main__': test() Are there any other cases this doesn't cover? A. From http Sat Apr 7 20:16:29 2007 From: http (Paul Rubin) Date: 07 Apr 2007 17:16:29 -0700 Subject: itertools, functools, file enhancement ideas References: <7xveg7rhc7.fsf_-_@ruckus.brouhaha.com> <1hw7lfg.112hjgqyt48vN%aleax@mac.com> Message-ID: <7xzm5joh42.fsf@ruckus.brouhaha.com> aleax at mac.com (Alex Martelli) writes: > > for line in file_lines(filename): > > crunch(line) > > I'm +/-0 on this one vs the idioms: > with open(filename) as f: > for line in f: crunch(line) > Making two lines into one is a weak use case for a stdlib function. Well, the inspiration is being able to use the iterator in another genexp: for line in (ichain(file_lines(x) for x in all_filenames)): crunch(line) so it's making more than two lines into one, and just flows more naturally, like the perl idiom "while(<>) {...}". > > lsect and rsect allow making what Haskell calls "sections". Example: > > # sequence of all squares less than 100 > > from operator import lt > > s100 = takewhile(rsect(lt, 100), (x*x for x in count())) > > Looks like they'd be useful, but I'm not sure about limiting them to > working with 2-argument functions only. I'm not sure how to generalize them but if there's an obvious correct way to do it, that sounds great ;). Also forgot to include the obvious: def compose(f,g): return lambda(*args,**kw): f(g(*args,**kw)) From jimmyetouma at earthlink.net Sun Apr 8 23:18:15 2007 From: jimmyetouma at earthlink.net (Jimmy E Touma) Date: Mon, 09 Apr 2007 03:18:15 GMT Subject: Crypto Suggestion/Help Message-ID: Hi all, I need some advise on doing the following. I have a Linux application that allows users to access it via a code (password). At the end of the day, I gather a log of activities of the users and zip the file and would like to encrypt it so that the users can not access it or tamper with it. Only manager should. If I use a private/public key for doing so I have to store the private key on my computer. What is a good way to encrypt a file and have the key well hidden on the same computer? If you have any other way to do, like MD5 or similar, please let me know. Thanks, Jimmy From steve at REMOVE.THIS.cybersource.com.au Thu Apr 26 02:23:51 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Thu, 26 Apr 2007 16:23:51 +1000 Subject: My python annoyances so far References: <1177541453.471959.120830@c18g2000prb.googlegroups.com> Message-ID: On Wed, 25 Apr 2007 15:50:53 -0700, flifus wrote: > > Hi all. I'm learning python these days. I'm going to use this thread > to post, from time to time, my annoyances with python. I hope someone > will clarify things to me where I have misunderstood them. > > Annoyances: > > 1. Underscores! What's the deal with that? Especially those double > underscores. The best answer I read on this is that the double > underscores denotes special methods that the interpreter may > automatically use. For example, 4+4 get expanded by the interpreter to > 4.__add__(4). I know! It's such a trial, especially since my keyboard is broken and when I type an underscore I get a small electric shock. > 2. There are modules, there are functions, and there are classes- > methods! Wouldn't it have been easier had everything either been a > function or a class method? What really annoys me is the way function names use vowels _and_ *ow!* consonants. Some of them even use the letter Y, which sometimes is a vowel and sometimes is a consonant. That just makes me mad. -- Steven. From aleax at mac.com Thu Apr 26 22:36:09 2007 From: aleax at mac.com (Alex Martelli) Date: Thu, 26 Apr 2007 19:36:09 -0700 Subject: My python annoyances so far References: <1177541453.471959.120830@c18g2000prb.googlegroups.com> <59bf34F2k27v5U1@mid.individual.net> <1177603623.774892.230390@t38g2000prd.googlegroups.com> Message-ID: <1hx6zi2.1oz684ndspxdgN%aleax@mac.com> Steven D'Aprano wrote: ... > detail you shouldn't care about. Functions that cache the result of long > time-consuming complications are _good_. Not necessarily -- asserts the exactly opposite principle, "Don't save anything you can recalculate"... of course, the best approach is generally a compromise, but it's good to be aware of the potentially high costs of caching:-). Alex From seandavi at gmail.com Wed Apr 11 21:24:19 2007 From: seandavi at gmail.com (Sean Davis) Date: 11 Apr 2007 18:24:19 -0700 Subject: Deferred jobs server as backend for web application Message-ID: <1176341059.609525.140800@l77g2000hsb.googlegroups.com> In the past, I have put together web applications that process tasks serially, either with short algorithms to manipulate user-submitted data or to return database queries. However, now I am faced with the task of having a long-running process being started by a web submission. I want to process an uploaded file. One way to do this is to simply start a process each time someone submits a job and then email when complete. Instead, I would like to have a way of submitting the job to a persistent backend queue that can process the job and answer queries about the status of the job (if it is still running) or return results. I have looked at threadpool, which seems fine if I a want to submit jobs from a single process (such as a Qt application, etc), but it won't work directly for a web platform where I will likely have multiple threads/processes handling http requests. Any suggestions on how to go about this? Thanks, Sean From clajo04 at mac.com Wed Apr 11 07:36:24 2007 From: clajo04 at mac.com (John Clark) Date: Wed, 11 Apr 2007 07:36:24 -0400 Subject: ANN: Next NYC Python User Group meeting, Tues May 8th, 2007, 6:30 pm In-Reply-To: <00c301c776f1$d175e970$fefea8c0@haengma> References: <00c301c776f1$d175e970$fefea8c0@haengma> Message-ID: <003701c77c2d$a396a580$fefea8c0@haengma> My apologies for the comical timing of the below announcement - I actually sent the announcement on April 4th, but it obviously didn't clear the moderator's desk in time for the meeting mentioned below. In an attempt to avoid this same problem, let me announce next month's meeting now. The next New York City Python Users Group meeting is Tuesday, May 8th from 6:30-8:30pm at the Millenium Partners office at 666 Fifth Avenue (53rd St. and 5th Ave.) on the 8th Floor. We welcome all those in the NYC area who are interested in Python to attend. However, we need a list of first and last names to give to building security to make sure you can gain access to the building. RSVP to clajo04 at mac.com to add your name to the list. More information can be found on the yahoo group page: http://tech.groups.yahoo.com/group/nycpython Hope to see you there! -John _____ From: python-list-bounces+clajo04=mac.com at python.org [mailto:python-list-bounces+clajo04=mac.com at python.org] On Behalf Of John Clark Sent: Wednesday, April 04, 2007 3:46 PM To: python-list at python.org; python-announce at python.org; tutor at python.org Subject: New York City Python Users Group Meeting Greetings! The next New York City Python Users Group meeting is this Tuesday, April 10th, 6:30pm at at the Millennium Partners office at 666 Fifth Avenue (53rd St. and 5th Ave.) on the 8th Floor. We welcome all those in the NYC area who are interested in Python to attend. However, we need a list of first and last names to give to building security to make sure you can gain access to the building. RSVP to clajo04 at mac.com to add your name to the list. More information can be found on the yahoo group page: http://tech.groups.yahoo.com/group/nycpython/ Hope to see you there! -John -------------- next part -------------- An HTML attachment was scrubbed... URL: From attn.steven.kuo at gmail.com Tue Apr 17 02:16:28 2007 From: attn.steven.kuo at gmail.com (attn.steven.kuo at gmail.com) Date: 16 Apr 2007 23:16:28 -0700 Subject: multirember&co In-Reply-To: <1176768854.720234.23320@w1g2000hsg.googlegroups.com> References: <1176768854.720234.23320@w1g2000hsg.googlegroups.com> Message-ID: <1176790588.024371.119360@n76g2000hsh.googlegroups.com> On Apr 16, 5:14 pm, bearophileH... at lycos.com wrote: > Once in while I too have something to ask. This is a little problem > that comes from a Scheme Book (I have left this thread because this > post contains too much Python code for a Scheme newsgroup):http://groups.google.com/group/comp.lang.scheme/browse_thread/thread/... > (snipped) > > For fun I have tried to make it lazy, if may be useful if seq is a > very long iterable. So I've used tee: > > from itertools import ifilter, tee > > def multiremberandco4(el, iseq, fun): > iseq1, iseq2 = tee(iseq) > iterable1 = ifilter(lambda x: x == el, iseq1) > iterable2 = ifilter(lambda x: x != el, iseq2) > return fun(iterable1, iterable2) > > def leniter(seq): > count = 0 > for el in seq: > count += 1 > return count > > idata = iter(data) > print multiremberandco4('a', idata, lambda l1,l2: (leniter(l1), > leniter(l2))) > > But from the docs: >in general, if one iterator is going to use most > or all of the data before the other iterator, it is faster to use > list() instead of tee().< > > So I have tried to create two iterables for the fun function scanning > seq once only, but I haven't succed so far (to do it I have tried to > use two coroutines with the enhanced generators, sending el to one or > to the other according to the value of x == el, this time I don't show > my failed versions), do you have suggestions? Scan once, two iterables: class It(object): def __init__(self, iseq, fun, fun2): self.iseq = iseq self.wanted = fun self.queue = [] self.divert = fun2 def append(self, item): self.queue.append(item) def __iter__(self): while True: if self.queue: yield self.queue.pop(0) else: try: item = self.iseq.next() if self.wanted(item): yield item else: self.divert(item) except StopIteration: raise class TwoFromOne(object): def __init__(self, iseq, el): self.i1 = It(iseq, lambda x: x == el, lambda y: self.i2.append(y)) self.i2 = It(iseq, lambda x: x != e1, lambda y: self.i1.append(y)) def getiters(self): return self.i1, self.i2 def leniter(seq): count = 0 for el in seq: count += 1 return count data = [1, 'a', 3, 'a', 4, 5, 6, 'a'] lazy_eye = TwoFromOne(iter(data), 'a') it1, it2 = lazy_eye.getiters() print (lambda i1, i2: (leniter(i1), leniter(i2)))(it1, it2) -- Hope this helps, Steven From mvksagar at gmail.com Mon Apr 30 04:25:21 2007 From: mvksagar at gmail.com (sagar) Date: 30 Apr 2007 01:25:21 -0700 Subject: Reading From an Excel Sheet Message-ID: <1177921521.652523.35850@e65g2000hsc.googlegroups.com> Hi all, I want to write a python script which reads in data from the excel sheet .Can any one help out in this ...any help will be appreciated. Thanks in Advance Sagar Meesala From tom at finland.com Sat Apr 14 12:04:56 2007 From: tom at finland.com (tom at finland.com) Date: Sat, 14 Apr 2007 16:04:56 GMT Subject: Simple integer comparison problem In-Reply-To: References: Message-ID: Thanks for help! From robert.kern at gmail.com Fri Apr 13 16:12:41 2007 From: robert.kern at gmail.com (Robert Kern) Date: Fri, 13 Apr 2007 15:12:41 -0500 Subject: Problem with algorithm In-Reply-To: <1176482102.497485.108570@o5g2000hsb.googlegroups.com> References: <1176434160.047703.214600@q75g2000hsh.googlegroups.com> <1176434937.258002.162220@p77g2000hsh.googlegroups.com> <1176448576.047996.12930@d57g2000hsg.googlegroups.com> <1176473989.420067.190970@l77g2000hsb.googlegroups.com> <1176482102.497485.108570@o5g2000hsb.googlegroups.com> Message-ID: Paul McGuire wrote: > If I see farther, it is because I stand on the shoulders of an > infinite number of monkeys. If I ever get around to writing a book on numerical methods/computational science/whatever, this will be the chapter quote for my chapter on Monte Carlo algorithms. -- 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 jholg at gmx.de Thu Apr 5 11:05:29 2007 From: jholg at gmx.de (jholg at gmx.de) Date: Thu, 05 Apr 2007 17:05:29 +0200 Subject: [dateutil] bug(s) in dateutil.parser /dateutil.tz Message-ID: <20070405150529.147200@gmx.net> Hi all, I'm having some problems with python-datetutil (which is a very, very nice tool, btw). Anybody knows where to adress these other than here? I tried reaching the author but don't seem to get through. Anyhow: 1. There's a bug in dateutil.parser you run into when you try to use a custom parserinfo. This patch fixes it: *** /data/pydev/DOWNLOADS/python-dateutil-1.1/dateutil/parser.py.ORIG Mon Nov 6 15:39:26 2006 --- /data/pydev/DOWNLOADS/python-dateutil-1.1/dateutil/parser.py Mon Nov 6 15:39:46 2006 *************** *** 285,291 **** def __init__(self, info=parserinfo): if issubclass(info, parserinfo): ! self.info = parserinfo() elif isinstance(info, parserinfo): self.info = info else: --- 285,291 ---- def __init__(self, info=parserinfo): if issubclass(info, parserinfo): ! self.info = info() elif isinstance(info, parserinfo): self.info = info else: 2. There is another bug in dateutil.tz in the tzfile class. This is a section of the Solaris MET zoninfo file $ zdump -v MET|grep 1982 MET Sun Mar 28 00:59:59 1982 UTC = Sun Mar 28 01:59:59 1982 MET isdst=0 MET Sun Mar 28 01:00:00 1982 UTC = Sun Mar 28 03:00:00 1982 MEST isdst=1 MET Sun Sep 26 00:59:59 1982 UTC = Sun Sep 26 02:59:59 1982 MEST isdst=1 MET Sun Sep 26 01:00:00 1982 UTC = Sun Sep 26 02:00:00 1982 MET isdst=0 Using this with tz.tzfile: >>> from dateutil import tz >>> import datetime >>> tz.TZPATHS.insert(0, "/usr/share/lib/zoneinfo") >>> >>> datetime.datetime(1982, 9, 25, 22, 59, 0, tzinfo=tz.tzutc()).astimezone(tz.gettz()) datetime.datetime(1982, 9, 26, 0, 59, tzinfo=tzfile('/usr/share/lib/zoneinfo/MET')) >>> print datetime.datetime(1982, 9, 25, 22, 59, 0, tzinfo=tz.tzutc()).astimezone(tz.gettz()) 1982-09-26 00:59:00+02:00 >>> >>> datetime.datetime(1982, 9, 25, 23, 59, 0, tzinfo=tz.tzutc()).astimezone(tz.gettz()) datetime.datetime(1982, 9, 26, 2, 59, tzinfo=tzfile('/usr/share/lib/zoneinfo/MET')) >>> print datetime.datetime(1982, 9, 25, 22, 59, 0, tzinfo=tz.tzutc()).astimezone(tz.gettz()) 1982-09-26 00:59:00+02:00 >>> print datetime.datetime(1982, 9, 25, 23, 59, 0, tzinfo=tz.tzutc()).astimezone(tz.gettz()) 1982-09-26 02:59:00+01:00 >>> >>> datetime.datetime(1982, 9, 26, 0, 59, 0, tzinfo=tz.tzutc()).astimezone(tz.gettz()) datetime.datetime(1982, 9, 26, 3, 59, tzinfo=tzfile('/usr/share/lib/zoneinfo/MET')) >>> print datetime.datetime(1982, 9, 26, 0, 59, 0, tzinfo=tz.tzutc()).astimezone(tz.gettz()) 1982-09-26 03:59:00+01:00 >>> >>> datetime.datetime(1982, 9, 26, 1, 59, 0, tzinfo=tz.tzutc()).astimezone(tz.gettz()) datetime.datetime(1982, 9, 26, 4, 59, tzinfo=tzfile('/usr/share/lib/zoneinfo/MET')) >>> print datetime.datetime(1982, 9, 26, 1, 59, 0, tzinfo=tz.tzutc()).astimezone(tz.gettz()) 1982-09-26 04:59:00+01:00 >>> >>> datetime.datetime(1982, 9, 26, 2, 59, 0, tzinfo=tz.tzutc()).astimezone(tz.gettz()) datetime.datetime(1982, 9, 26, 3, 59, tzinfo=tzfile('/usr/share/lib/zoneinfo/MET')) >>> print datetime.datetime(1982, 9, 26, 2, 59, 0, tzinfo=tz.tzutc()).astimezone(tz.gettz()) 1982-09-26 03:59:00+01:00 >>> Note how the MET local time is wrong at 23:59UTC, 0:59UTC and 01:59UTC. I've looked at the code but currently don't really understand how the default tzfinfo.fromutc implementation, as quoted in the python datetime documentation, is supposed to work in the first place. Any ideas? Cheers, Holger -- "Feel free" - 10 GB Mailbox, 100 FreeSMS/Monat ... Jetzt GMX TopMail testen: http://www.gmx.net/de/go/topmail From Jon_Slaughter at Hotmail.com Tue Apr 24 17:19:52 2007 From: Jon_Slaughter at Hotmail.com (Jon Slaughter) Date: Tue, 24 Apr 2007 21:19:52 GMT Subject: *** Watch BOMBSHELL video of Senator John Kerry admitting 911 was in INSIDE JOB ??? References: <1177387965.127809.175390@l77g2000hsb.googlegroups.com> Message-ID: wrote in message news:1177387965.127809.175390 at l77g2000hsb.googlegroups.com... > http://www.911blogger.com/node/8053 > > Senator John Kerry was questioned concerning 9/11 during an appearance > at Book People in Austin, Texas. Members of Austin 9/11 Truth Now > asked Kerry about the officially unexplained collapse of WTC Building > 7." > > Kerry responded: > > "I do know that that wall, I remember, was in danger and I think > they made the decision based on the danger that it had in destroying > other things-- that they did it in a controlled fashion." > > http://www.jonesreport.com/articles/220407_kerry_wtc7.html > > Thanks to the dozen or so people who submitted this as a blog entry :) > > "Mr. Kerry?!?" > > "Just a follow-up or two... > > WHAT THE HELL|?| Are you saying that building was wired that day? Or > well in advance? 'Splain, please. > > Does your fellow Bonesman George Walker Bush appreciate you letting > the cat out of the bag on this? Is that your cell phone I hear > ringing? > > Why is your wife squirming like that? Stop it, Theresa! Stop it!" > So what your saying is that the democrates are behind 9/11? So they tried to frame Bush? Whats new? Doesn't this then mean that the democrates and alqaeda are working together? I always that pelosie looked like she had a little arabic in her(probably in more ways than one). From charles.hebert at gmail.com Mon Apr 16 06:09:52 2007 From: charles.hebert at gmail.com (charles.hebert at gmail.com) Date: 16 Apr 2007 03:09:52 -0700 Subject: How to generate a continuous string In-Reply-To: <1176717806.754728.9600@y80g2000hsf.googlegroups.com> References: <1176717806.754728.9600@y80g2000hsf.googlegroups.com> Message-ID: <1176718192.459470.79770@e65g2000hsc.googlegroups.com> On 16 avr, 12:03, "???????????????" wrote: > How to generate a continuous string, like this > "aaaaaaaaaaaaaaaaaaaaaaa" > the number of characters is dynamic. Is there a module or function > implement this string ? > such as: duplicate_string(char, num) >>> "a"*10 'aaaaaaaaaa' >>> "a"*20 'aaaaaaaaaaaaaaaaaaaa' From http Fri Apr 13 22:25:27 2007 From: http (Paul Rubin) Date: 13 Apr 2007 19:25:27 -0700 Subject: nonstandard XML character entities? Message-ID: <7xfy73ae08.fsf@ruckus.brouhaha.com> I'm new to xml mongering so forgive me if there's an obvious well-known answer to this. It's not real obvious from the library documentation I've looked at so far. Basically I have to munch of a bunch of xml files which contain character entities like ú which are apparently nonstandard. They appear in w3.org tables but xml.etree.cElementTree.ElementTree.parse barfs at them and xmllint barfs at them. Basically I want to know if there's a way to supply the regular parser (preferably xml.etree but I guess I can switch to another one if necessary) with some kind of entity table, and/or if the info is supposed to be found in the DTD or someplace like that. Right now I'm ignoring the DTD and simply figuring out the doc structure by eyeballing the xml files, maybe not a perfectly approved method but it seems to be what most people do. Thanks From gagsl-py2 at yahoo.com.ar Fri Apr 20 04:38:37 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 20 Apr 2007 05:38:37 -0300 Subject: Python Feature Request: Explicit variable declarations References: <1176546078.934340.253810@y5g2000hsa.googlegroups.com> <1hwu43c.dp5yo01rsqhjfN%aleax@mac.com> Message-ID: En Fri, 20 Apr 2007 00:41:04 -0300, Alex Martelli escribi?: > Jorgen Grahn wrote: > >> As a C and C++ programmer (not a C/C++ programmer), I have to say that > > Yeah, I wonder, what's C divided by C++ -- maybe about 0.731...? C/C++ == 1 most of the time (being C of any integer type, of course - for arbitrary instances, see the always missing documentation). -- Gabriel Genellina From sms767intro at gmail.com Mon Apr 23 02:59:58 2007 From: sms767intro at gmail.com (sms767) Date: 22 Apr 2007 23:59:58 -0700 Subject: send pictures to mobile phones - sms767 Message-ID: <1177311598.349112.229310@b75g2000hsg.googlegroups.com> Hi, Is there anyone interested in helping test a web service? Sending pictures to mobile phones: http://www.sms767.com Thanks, Steve From kyosohma at gmail.com Wed Apr 4 13:51:34 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: 4 Apr 2007 10:51:34 -0700 Subject: Windows service and pyc files In-Reply-To: References: Message-ID: <1175709094.352514.64920@y66g2000hsf.googlegroups.com> On Apr 4, 10:48 am, Laszlo Nagy wrote: > Hello, > > I have a win32 service written in Python that starts a plain > application, written in Python. > > The win32 service tries to launch the application in a while loop and > logs the return value of the os.system call. That's all. > > The application is a simple Python program that connects to an https > xml/rpc server, and works with the data retrieved from that server. It > is written as an application because it must be able to download updates > for itself. Here is how it works: > > a.) connect to server > b.) compare current version with the latest > c.) if there is a difference, then download all sources from the server, > delete all pyc files and exit; otherwise start processing > > I could not write a self-restarting server, and I did not want to > write/install two services for one problem. The win32 service is very > small and primitive so probably I will not need to update it. I think > the basic idea is good, but... > > When there is a client update available, my application updates itself > cleanly and exists. Then the service tries to restart the application, > but it cannot. os.system returns with OS error code -1. The pyc files > are NOT generated for the application. However, if I start the > application from the command line, then pyc files are created, and then > the service will also start the application immediatelly. The win32 > service is running as "Localsystem" so it is sure that it has write > permission on all files. > > I cannot log out the error from the application since it is not started. > The only error message I have is OSError -1, but it tells me nothing > about the nature of the error. > > Thanks, > > Laszlo Have you tried the subprocess module for this rather than os.system? You might be able to pipe errors to a file with it. You might be able to use the traceback module for more verbose error catching too. Mike From marcpp at gmail.com Sun Apr 15 16:24:22 2007 From: marcpp at gmail.com (Marcpp) Date: 15 Apr 2007 13:24:22 -0700 Subject: Qt4 in ubuntu Message-ID: <1176668662.770066.208350@n76g2000hsh.googlegroups.com> Is possible install Qt4 pyqt4 under kubuntu? Few times ago i tried to run pyqt in ubuntu (gnome) but i can't do it. From antroy at gmail.com Wed Apr 18 03:38:59 2007 From: antroy at gmail.com (Ant) Date: 18 Apr 2007 00:38:59 -0700 Subject: Win32com, and Excel issues. Message-ID: <1176881939.612038.278770@y5g2000hsa.googlegroups.com> Hi all, I'm doing some Excel automation work for a friend, and am developing on a machine running Office 2000. My friends machine is running Excel 2003. The code I've written works like a charm on my machine (in fact all three of my machines), but falls over early on on Excel 2003. The code snippet it falls over on is code to copy one worksheet after another: app = wincl.Dispatch("Excel.Application") app.Visible = True app.Workbooks.Open(self.filename) sheet = app.Worksheets(1) sheet.Copy(None, sheet) and this last line throws the following exception: pywintypes.com_error: (-2147417851, 'the server threw an exception.' , None, None) which isn't too helpful. I'm wondering if something has changed in the Excel API that doesn't allow a null parameter to Copy or some similar issue. I tried using the keyword argument format, but that simply refused to work. Other relevant information: * The program is packaged using py2exe, so I know that the same version of Python, and the same libraries are on each machine. * One of the test machines running Excel 2000 does not have Python installed. * The machines are all of a similar spec. Any ideas are welcome! From whentimeslows at yahoo.ca Wed Apr 25 13:19:45 2007 From: whentimeslows at yahoo.ca (skotjs) Date: 25 Apr 2007 10:19:45 -0700 Subject: Python Screen Scraper In-Reply-To: References: Message-ID: <1177521585.374460.149190@c18g2000prb.googlegroups.com> On Apr 24, 5:50 am, James Stroud wrote: > Hello, > > Does anyone know of an example, however modest, of a screenscraper > authored in python? I am using Firefox. > > Basically, I am answering problems via my browser and being scored for > each problem. I have a tendency to go past my peak for training > efficiency, so I would like to scrape the result page for each problem I > answer, compile statistics, and have a program alert me when I should > stop (based on score and accuracy--assuming training value is related to > changes in these metrics). > > I have no idea how to go about writing such a beast and I am hoping that > I could get some pointers or an example that could get me going in the > right direction. > > Parsing, etc, is not a problem, but I'm not exactly sure how I might > interface python with Firefox, forwarding scraped pages to my browser > (or forwarding from the browser to the scraper). > > Thanks in advance for any help or advice. > > James Hey James, This might be of interest to you: http://www.screen-scraper.com/support/docs/scripting_in_python.php Scott From josiah.carlson at gmail.com Sun Apr 22 00:11:57 2007 From: josiah.carlson at gmail.com (Josiah Carlson) Date: 21 Apr 2007 21:11:57 -0700 Subject: Python's handling of unicode surrogates In-Reply-To: <1177122874.524447.85130@p77g2000hsh.googlegroups.com> References: <4628532B.5060104@v.loewis.de> <1177051493.468698.176740@b75g2000hsg.googlegroups.com> <4629591a$0$13629$9b622d9e@news.freenet.de> <1177122874.524447.85130@p77g2000hsh.googlegroups.com> Message-ID: <1177215117.116510.158940@l77g2000hsb.googlegroups.com> On Apr 20, 7:34 pm, Rhamphoryncus wrote: > On Apr 20, 6:21 pm, "Martin v. L?wis" wrote: > > > > I don't believe this specific variant has been discussed. > > Now that you clarify it: no, it hasn't been discussed. I find that > > not surprising - this proposal is so strange and unnatural that > > probably nobody dared to suggest it. > > Difficult problems sometimes need unexpected solutions. > > Although Guido seems to be relenting slightly on the O(1) indexing > requirement, so maybe we'll end up with an O(log n) solution (where n > is the number of surrogates, not the length of the string). The last thing I heard with regards to string indexing was that Guido was very adamant about O(1) indexing. On the other hand, if one is willing to have O(log n) access time (where n is the number of surrogate pairs), it can be done in O(n/logn) space (again where n is the number of surrogate pairs). An early version of the structure can be found here: http://mail.python.org/pipermail/python-3000/2006-September/003937.html I can't seem to find my later post with an updated version (I do have the source somewhere). > If you pick an index at random you will get IndexError. If you > calculate the index using some combination of len, find, index, rfind, > rindex you will be unaffected by my change. You can even assume the > length of a character so long as you know it fits in 16 bits (ie any > '\uxxxx' escape). > > I'm unaware of any practical use cases that would be harmed by my > change, so that leaves only philosophical issues. Considering the > difficulty of the problem it seems like an okay trade-off to me. It is not ok for s[i] to fail for any index within the range of the length of the string. - Josiah From jon at ffconsultancy.com Thu Apr 5 10:24:59 2007 From: jon at ffconsultancy.com (Jon Harrop) Date: Thu, 05 Apr 2007 15:24:59 +0100 Subject: Requirements For A Visualization Software System For 2010 References: <1175628186.459945.290750@d57g2000hsg.googlegroups.com> Message-ID: <461507e1$0$8716$ed2619ec@ptn-nntp-reader02.plus.net> Xah Lee wrote: > In this essay, i give a list of requirements that i think is necessary > for a software system for creating scientific visualization for the > next decade (2007-2017). You may be interested in the F# programming language from Microsoft Research. This is a high-performance functional programming language with integrated Visual Studio support and an interactive mode (like a Mathematica notebook). The F# language is not distributed with any graphical tools except a couple of example programs. However, you can write a purely functional scene graph library and compiler in only 200 lines of code and then generate 2D and 3D graphics (spawned as separate visualizations from an interactive sessions) with the brevity of Mathematica and the robustness of ML. I have detailed exactly this functionality in the visualization chapter of my forthcoming book F# for Scientists: http://www.ffconsultancy.com/products/fsharp_for_scientists/ and I am so happy with the results that we are going to write another book specifically on the use of graphics from the F# language. Also, as .NET programs, F# programs can be executed on non-Windows platforms using tools like Mono. In the case of a DirectX-based visualization, you would probably need to write another back-end targetting OpenGL. -- Dr Jon D Harrop, Flying Frog Consultancy OCaml for Scientists http://www.ffconsultancy.com/products/ocaml_for_scientists/index.html?usenet From spamtrap at dot-app.org Sat Apr 14 17:58:30 2007 From: spamtrap at dot-app.org (Sherm Pendley) Date: Sat, 14 Apr 2007 17:58:30 -0400 Subject: Python Feature Request: Allow changing base of member indices to 1 References: <1176546465.632410.52630@w1g2000hsg.googlegroups.com> <1176579205.948684.171640@q75g2000hsh.googlegroups.com> <1176584444.335732.111740@n76g2000hsh.googlegroups.com> Message-ID: "Paddy" writes: > I don't think we should add it to Python > because it would make porting VB code easier. Great Cthulhu no! I chimed in because your first comment regarding Perl implied that it's commonplace for Perl programmers to fiddle with the index base. It can be done, for historical reasons, but it's far from common. I have to wonder, if the OP wants VB so badly, why is he using Python to begin with? sherm-- -- Web Hosting by West Virginians, for West Virginians: http://wv-www.net Cocoa programming in Perl: http://camelbones.sourceforge.net From gagsl-py2 at yahoo.com.ar Sat Apr 7 01:51:22 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: 6 Apr 2007 22:51:22 -0700 Subject: Extract zip file from email attachment In-Reply-To: <1175922270.358349.64630@b75g2000hsg.googlegroups.com> References: <1175815907.434721.274190@w1g2000hsg.googlegroups.com> <65fge4-j15.ln1@athlon.my> <1175821421.265541.120440@w1g2000hsg.googlegroups.com> <1175835107.288163.139050@b75g2000hsg.googlegroups.com> <1175869873.747758.278050@b75g2000hsg.googlegroups.com> <1175922270.358349.64630@b75g2000hsg.googlegroups.com> Message-ID: <1175925082.122250.69610@n59g2000hsh.googlegroups.com> Basilisk96 wrote: > > > > Could the file like object still be encoded in MIME or something? > > > > Yes it is. You don't need to seek(0). > Try this: > > decoded = email.base64mime.decode(part.get_payload()) > fileObj.write(decoded) Or better: decoded = part.get_payload(decode=True) fileObj.write(decoded) fileObj.seek(0) zip = zipfile.ZipFile(fileObj) zip.printdir() From jan.m.danielsson at gmail.com Sun Apr 1 10:41:43 2007 From: jan.m.danielsson at gmail.com (Jan Danielsson) Date: Sun, 01 Apr 2007 16:41:43 +0200 Subject: SimpleXMLRPCServer - client address Message-ID: <460fc4a8$1@griseus.its.uu.se> Hello all, I writing an application based on the SimpleXMLRPCServer class. I would like to know the IP address of the client performing the RPC. Is that possible, without having to abandon the SimpleXMLRPCServer class? -- Kind regards, Jan Danielsson From tejovathi.p at gmail.com Mon Apr 9 05:14:26 2007 From: tejovathi.p at gmail.com (Teja) Date: 9 Apr 2007 02:14:26 -0700 Subject: Kill thread Message-ID: <1176110066.940676.173020@e65g2000hsc.googlegroups.com> Hi all, Can any on help me out in killing a thread (i.e deleteing the reources like, stack ,memory etc) which is started with win32process.beginthreadex()??? Rite now, I am suspending the thread. But any pointers as to how to delete the thread permanently? Its pretty urgent... Please... Teja.P From __peter__ at web.de Mon Apr 2 08:03:02 2007 From: __peter__ at web.de (Peter Otten) Date: Mon, 02 Apr 2007 14:03:02 +0200 Subject: BUG?: Saving empty array in shelve References: <1175512459.614122.315290@b75g2000hsg.googlegroups.com> Message-ID: iwl wrote: > I've tryed to save some data containing empty arrays (array('f')) in a > shelve. > It looks like the shelve has some problems with empty arrays, get > allways: > TypeError: ("'NoneType' object is not iterable", , > ('f', None))- > Messages when dealing with the readed back shelve. > Seems like I have to avoid empty arrays in a shelve. That seems to be a bug in the underlying pickling mechanism: >>> from array import array >>> from cPickle import loads, dumps >>> loads(dumps(array("f", [1]))) array('f', [1.0]) >>> loads(dumps(array("f"))) Traceback (most recent call last): File "", line 1, in TypeError: ("'NoneType' object is not iterable", , ('f', None)) Please submit a bug report. Peter From steve at holdenweb.com Thu Apr 19 08:24:41 2007 From: steve at holdenweb.com (Steve Holden) Date: Thu, 19 Apr 2007 08:24:41 -0400 Subject: Do other Python GUI toolkits require this? In-Reply-To: References: <462697A6.6010007@codebykevin.com> <465B30B4-5BA0-459A-BE6F-1038874FA74B@jedimindworks.com> Message-ID: Antoon Pardon wrote: > On 2007-04-19, Steve Holden wrote: >> Michael Bentley wrote: >>> On Apr 19, 2007, at 4:11 AM, Antoon Pardon wrote: >>> >>>> On 2007-04-19, Michael Bentley wrote: >> [...] The >>>>> learning curve is rather steep IMO, but worth it. >>>> Just a throw in remark, that you may ignore if you wish, but a steep >>>> learning curve means that the subject is easily familiarized and that >>>> the learning period is short. >>>> >>>> You seem to use it as if it is the opposite. >>> Mathematical absurdities aside, it's the common usage -- but perhaps >>> you knew that. >>> >>> >> Perhaps in Belgium they prefer climbing mountains over walking up and >> down gentle hills? Or possibly they will simply pick any nit that is >> carelessly left within range? > > If it is just a nit, why don't you ignore my remark as I suggested? > Because I suffer from the quixotic urge to help stamp out obsessive compulsive behavior on c.l.py? This is self-defeating, of course, since it makes me appear obsessive compulsive in my own right ... > Now suppose I give you a graph that shows you how different people > are making progress. Would you prefer the rather flat curves instead > of the steep curves because the latter gives you the idea of someone > having to conquer huge obstacles or would you choose the steep curve > because they show you someone is getting results fast? > Suppose I should you a hill you have to climb? Would you rather don mountain boots and crampons to climb 3,000 feet up a vertical cliff or would you rather amble up, say, Ben Lomond with the other tourists? Clearly you have no wish to bow before common usage. be careful this doesn't put you in a universe with only one inhabitant. We all have to get along. obsessive-compulsive-ly y'rs - 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 mike.aldrich at gmail.com Wed Apr 11 16:15:48 2007 From: mike.aldrich at gmail.com (mike.aldrich at gmail.com) Date: 11 Apr 2007 13:15:48 -0700 Subject: Reading the first line of a file (in a zipfile) In-Reply-To: References: <1176318822.811661.115730@q75g2000hsh.googlegroups.com> Message-ID: <1176322548.710970.315610@d57g2000hsg.googlegroups.com> On Apr 11, 4:10 pm, "Gabriel Genellina" wrote: > En Wed, 11 Apr 2007 16:13:42 -0300, escribi?: > > > > > > > Hi folks, > > I am trying to read the first occurence of non-whitespace in a file, > > within a zipfile. Here is my code: > > > zipnames = glob.glob("*") > > for zipname in zipnames: > > z = zipfile.ZipFile(zipname, "r") > > for filename in z.namelist(): > > count = len(z.read(filename).split('\n')) > > if fnmatch.fnmatch(filename, "*AUDIT*"): > > test = filename.split(' ') > > print 'File:', test[0], > > bytes = z.read(filename) > > print 'has', len(bytes), 'bytes' > > print 'and', count, 'lines' > > > The first line in the file I am examining will be a number followed by > > more whitespace. Looks like I cannot split by whitespace? > > Your code does nothing with the first line on the file; you only split the > *filename* on whitespace. And you extract the file twice. > You don't even try to find "the first occurence of non-whitespace". Surely > an example of file contents and what output you really expect from it > would be adequate. > > -- > Gabriel Genellina- Hide quoted text - > > - Show quoted text - The file contents have leading whitespace, then a number: 123456 \n I expect to return '123456' From bj_666 at gmx.net Wed Apr 11 09:30:49 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Wed, 11 Apr 2007 15:30:49 +0200 Subject: tuples, index method, Python's design References: <1175867771.114540.61810@n76g2000hsh.googlegroups.com> <1175884427.779950.267220@y80g2000hsf.googlegroups.com> <1175953520.316208.241490@o5g2000hsb.googlegroups.com> <7xzm5igbrb.fsf@ruckus.brouhaha.com> <1176200361.260546.280510@n76g2000hsh.googlegroups.com> <1176214831.3430.49.camel@dot.uniqsys.com> Message-ID: In , Antoon Pardon wrote: > On 2007-04-11, Steven D'Aprano wrote: >> Lists are designed for sequences of homogeneous items, e.g.: >> >> L = [1, 2, 4, 8, 16, 32] >> while tuples are designed to be more like structs or records, with >> heterogeneous items, e.g.: >> >> T = ("Fred", 32, 12.789, {}, None, '\t') > > I think you are confused. Last time I heard this homogeneous items stuf, > it had nothing to do with the types being the same. They were homogeneous > because they somehow belonged together and heterogeneous because they > just happened to live together. Similarity of type played no part in > calling the data homogeneous or heterogeneous. Then you are confused. The typical use case for tuples are database records. The columns in the table can have completely different types but the values in a row, represented as a Python tuple, of course belong together. The homogeneous objects in lists must not be of the same type but share some behavior so it makes sense to apply some operation on all the elements. For example get the length of each item or sum them all up. Ciao, Marc 'BlackJack' Rintsch From bbxx789_05ss at yahoo.com Sat Apr 14 15:12:44 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: 14 Apr 2007 12:12:44 -0700 Subject: Python Feature Request: Add the "using" keyword which works like "with" in Visual Basic In-Reply-To: <1176577078.549674.293390@y80g2000hsf.googlegroups.com> References: <1176547372.584539.89170@q75g2000hsh.googlegroups.com> <1176577078.549674.293390@y80g2000hsf.googlegroups.com> Message-ID: <1176577964.834225.140740@w1g2000hsg.googlegroups.com> On Apr 14, 12:57 pm, "7stud" wrote: > On Apr 14, 4:42 am, samj... at gmail.com wrote: > > > This also is > > similar to the C++ "using" keyword which exposes the members of a > > namespace to access without specifying the namespace scope for each > > reference. For example after giving "using namespace std;" I can > > change all references to "std::cout" to "cout", which is similar to > > what I am proposing for Python now. > > ...which is a bad practice in C++. When you expose the members of a > namespace, you create the potential for name clashes with the names in > your program. Why would you want to infect Python with that problem? Oh. James Stroud's recommendation would fix that: > I would favor a convention with leading dots > to disambiguate from other variables. From half.italian at gmail.com Thu Apr 5 02:06:47 2007 From: half.italian at gmail.com (half.italian at gmail.com) Date: 4 Apr 2007 23:06:47 -0700 Subject: Prevent Modification of Script? In-Reply-To: References: <1175735097.856840.177510@e65g2000hsc.googlegroups.com> Message-ID: <1175753207.779307.63260@n59g2000hsh.googlegroups.com> Just throw out the .py files and let it run on the .pyc's alone. ~Sean On Apr 4, 8:03 pm, James Stroud wrote: > ts-dev wrote: > > The root of my question is verifying the integrity of the application > > and the scripts being run. > > Google "md5sum". Then google "birthday attack". > > James From kenneth.m.mcdonald at sbcglobal.net Wed Apr 11 03:50:30 2007 From: kenneth.m.mcdonald at sbcglobal.net (Kenneth McDonald) Date: Wed, 11 Apr 2007 02:50:30 -0500 Subject: Calling Python from Javascript? Message-ID: <461C9346.7010700@sbcglobal.net> I know that there's some work out there to let Python make use of Javascript (Spidermonkey) via (I assume) some sort of bridging C/C++ code. Anyone know of efforts to allow the reverse? I'd really like to make use of Python when doing Mozilla DOM programming, and I can never get a clear idea of when PyXPCOM might be available to those of us who don't know the ins and outs of compiling Mozilla, and its XPCOM structures. So if there was an easy way to simply and quickly pass even just strings back and forth between Python and Moz Javascript, that would make certain things a heck of a lot easier. Thanks, Ken From mail at microcorp.co.za Thu Apr 5 03:40:41 2007 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Thu, 5 Apr 2007 09:40:41 +0200 Subject: Why NOT only one class per file? References: <1175721799.714907.52770@o5g2000hsb.googlegroups.com> Message-ID: <01a401c77757$42292000$03000080@hendrik> "Terry Reedy" wrote: > Ask him why he does not wear a straightjacket all the time. > It is great for one's posture ;-) No it isn't - those funny arms give you round shoulders.. - Hendrik From stou.sandalski at gmail.com Thu Apr 19 03:37:36 2007 From: stou.sandalski at gmail.com (Stou Sandalski) Date: 19 Apr 2007 00:37:36 -0700 Subject: Boost.Python create extra functions not in wrapped object Message-ID: <1176968256.066230.238940@n59g2000hsh.googlegroups.com> Hi, I have a python library created by wrapping the C++ library using Boost.Python, the problem is that the wrappers are not very pythonic.... so I want to add some methods that do not exist in the C+ + implementation, that would create a better Python interface. For example to initialize the data in an object in the library one must iterate through every point, setting a value for each individually. That's the way it works in C++ but in python it would be nice to instead just have one call that can receive a numpy array or a tuple. I want to add a call like: setData(array) to the python object, a call that does not exist in the C++ implementation and then in the C++ wrappers actually use setData to iterate through the array and set the values using the normal C++ method, say setValue(index, value). Something along the lines of this (initData is not in the constructor on purpose) C++ object: class Foo { public: void initData(int size) { data = new float[size]; }; // Create the data array void setValue(int index, float value) // Set given value { data[index] = value; } private: float *data; }; In python however I want to do this: obj = foo() ar = array([1,2,3,4,5], dtype=float) foo.setData(ar) Or even better: ar = array([1,2,3,4,5], dtype=float) obj = foo(ar) And have it somehow call initData() and setValue() iteration inside the C++ code of the wrapper. I've only used SWIG and don't really know much about Boost, I am not even sure how to label what I am trying to do. Can this be done with Boost, without changing the C++ library? Regards, Stou From bronger at physik.rwth-aachen.de Tue Apr 10 13:08:12 2007 From: bronger at physik.rwth-aachen.de (Torsten Bronger) Date: Tue, 10 Apr 2007 19:08:12 +0200 Subject: Why is __getslice__ still implemented? References: <87irc4wpxp.fsf@wilson.homeunix.com> Message-ID: <87wt0kduo3.fsf@wilson.homeunix.com> Hall?chen! Steven Bethard writes: > Torsten Bronger wrote: > >> [...] >> >> [...] It forces people to implement a deprecated function after >> all. I think the docs should say that you still have to override >> __getslice__ when subclassing from a built-in type, unless I >> really don't understand the issue correctly. > > [...] If you have a specific suggestion for what doc should be > updated and how, that would be helpful. Please post it to: > > http://sourceforge.net/tracker/?group_id=5470&atid=105470 Done. Tsch?, Torsten. -- Torsten Bronger, aquisgrana, europa vetus Jabber ID: bronger at jabber.org (See http://ime.webhop.org for ICQ, MSN, etc.) From ptmcg at austin.rr.com Mon Apr 16 19:01:36 2007 From: ptmcg at austin.rr.com (Paul McGuire) Date: 16 Apr 2007 16:01:36 -0700 Subject: script for seconds in given month? In-Reply-To: <1176745773.092500.47600@w1g2000hsg.googlegroups.com> References: <1176740556.859125.221980@l77g2000hsb.googlegroups.com> <1176744505.863580.182390@e65g2000hsc.googlegroups.com> <1176745773.092500.47600@w1g2000hsg.googlegroups.com> Message-ID: <1176764496.221753.197580@w1g2000hsg.googlegroups.com> On Apr 16, 12:49 pm, "edfialk" wrote: > Jim: I need years too, basically from 1960-2000. Don't want to > hardcode all those days :) > > Matt: Thanks, I will try this out. > > Paul: I don't believe we need leap seconds. Leap days definitely. > > I'll let you know how Matt's code works. Any other suggestions feel > free to let me know. > > Thanks all! > -Ed I googled for "NIST leap second" and found this table online of leap seconds, if you do in fact need them: http://tf.nist.gov/pubs/bulletin/leapsecond.htm -- Paul From nyamatongwe+thunder at gmail.com Fri Apr 20 01:02:52 2007 From: nyamatongwe+thunder at gmail.com (Neil Hodgson) Date: Fri, 20 Apr 2007 05:02:52 GMT Subject: Python's handling of unicode surrogates In-Reply-To: References: Message-ID: <0QXVh.16735$M.14016@news-server.bigpond.net.au> Adam Olsen: > To solve this I propose Python's unicode type using UTF-16 should have > gaps in its index, allowing it to only expose complete unicode scalar > values. Iteration would produce surrogate pairs rather than > individual surrogates, indexing to the first half of a surrogate pair > would produce the entire pair (indexing to the second half would raise > IndexError), and slicing would be required to not separate a surrogate > pair (IndexError otherwise). I expect having sequences with inaccessible indices will prove overly surprising. They will behave quite similar to existing Python sequences except when code that works perfectly well against other sequences throws exceptions very rarely. > Reasons to treat surrogates as undivisible: > * \U escapes and repr() already do this > * unichr(0x10000) would work on all unicode scalar values unichr could return a 2 code unit string without forcing surrogate indivisibility. > * "There is no separate character type; a character is represented by > a string of one item." Could amend this to "a string of one or two items". > * iteration would be identical on all platforms There could be a secondary iterator that iterates over characters rather than code units. > * sorting would be identical on all platforms This should be fixable in the current scheme. > * UTF-8 or UTF-32 containing surrogates, or UTF-16 containing isolated > surrogates, are ill-formed[2]. It would be interesting to see how far specifying (and enforcing) UTF-16 over the current implementation would take us. That is for the 16 bit Unicode implementation raising an exception if an operation would produce an unpaired surrogate or other error. Single element indexing is a problem although it could yield a non-string type. > Reasons against such a change: > * Breaks code which does range(len(s)) or enumerate(s). This can be > worked around by using s = list(s) first. The code will work happily for the implementor and then break when exposed to a surrogate. > * "Nobody is forcing you to use characters above 0xFFFF". This is a > strawman. Unicode goes beyond 0xFFFF because real languages need it. > Software should not break just because the user speaks a different > language than the programmer. Characters over 0xFFFF are *very* rare. Most of the Supplementary Multilingual Plane is for historical languages and I don't think there are any surviving Phoenician speakers. Maybe the extra mathematical signs or musical symbols will prove useful one software and fonts are implemented for these ranges. The Supplementary Ideographic Plane is historic Chinese and may have more users. I think that effort would be better spent on an implementation that appears to be UTF-32 but uses UTF-16 internally. The vast majority of the time, no surrogates will be present, so operations can be simple and fast. When a string contains a surrogate, a flag is flipped and all operations go through more complex and slower code paths. This way, consumers of the type see a simple, consistent interface which will not report strange errors when used. BTW, I just implemented support for supplemental planes (surrogates, 4 byte UTF-8 sequences) for Scintilla, a text editing component. Neil From robert.kern at gmail.com Mon Apr 9 10:10:52 2007 From: robert.kern at gmail.com (Robert Kern) Date: Mon, 09 Apr 2007 09:10:52 -0500 Subject: python, wxpython and Mac OS X In-Reply-To: <1176092755.914088.5040@p77g2000hsh.googlegroups.com> References: <1176086130.330795.268590@n76g2000hsh.googlegroups.com> <1176092755.914088.5040@p77g2000hsh.googlegroups.com> Message-ID: 7stud wrote: > On Apr 8, 8:46 pm, Robert Kern wrote: >> Why 2.4.4 instead of the official 2.5 binary fromwww.python.org? >> >> http://www.python.org/download/ > > 1) On some download page that listed both python 2.5 and 2.4, it said > that python 2.4 had more packages/modules available for Macs than 2.5. That's probably still a fair statement. > 2) The wxPython website says that to use wxPython on a Mac, you need a > special "framework" build of python--like the one that comes > preinstalled. It says framework builds are available for python 2.4. The 2.5 binary on www.python.org is also a framework build. > Should I remove 2.4.4 and install 2.5 instead? No, it's okay. -- 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 laurent.pointal at wanadoo.fr Thu Apr 26 17:02:04 2007 From: laurent.pointal at wanadoo.fr (Laurent Pointal) Date: Thu, 26 Apr 2007 23:02:04 +0200 Subject: Store variable name in another variable References: <1177592072.498517.139260@b40g2000prd.googlegroups.com> Message-ID: <4631120a$0$27375$ba4acef3@news.orange.fr> Cameron Laird wrote: > In article , > Laurent Pointal wrote: >>loial a ?crit : >>> I need to store a list of variable names in a dictionary or list. I >>> then later need to retrieve the names of the variables and get the >>> values from the named variables. The named variables will already have >>> been created and given a value. >> >>"Named variables will already have been created"... in what namespace ? >> >>Store a list of names -> dict/list (see tutorial) >> >>Then, >>use namespace.name >>or getattr(namespace,"name") >>or locals()["name"] >>or globals()["name"] >> >> > > admin, I want to be sure you understand the advice you've been given. > Yes, it is possible to "double dereference" through named variables; > HOWEVER, it is essentially *never* advantageous to do so in application > programming with Python (nor is it in Perl and PHP, despite what many > senior people there teach). Use a dictionary, perhaps one with > multi-dimensional keys. Yes, I understand. I just reply to OP question not searching the reason why he wants to manage *variables* this way (he talk about dict, so I hope he know that they can be used to map names to values). So, this is not an advice, just technical ways related to the question as it was written. And yes, personnally i use dictionnaries for such purpose. A+ Laurent. From cam.ac.uk at mh391.invalid Fri Apr 27 12:48:27 2007 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Fri, 27 Apr 2007 17:48:27 +0100 Subject: My newbie annoyances so far In-Reply-To: <_9pYh.1787$uJ6.894@newssvr17.news.prodigy.net> References: <1177688082.758043.133920@r30g2000prh.googlegroups.com> <_9pYh.1787$uJ6.894@newssvr17.news.prodigy.net> Message-ID: John Nagle wrote: > (P.S. PEP 3117 is a joke, right?) Note date of creation. -- Michael Hoffman From bignose+hates-spam at benfinney.id.au Thu Apr 5 00:57:25 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Thu, 05 Apr 2007 14:57:25 +1000 Subject: Prevent Modification of Script? References: <1175735097.856840.177510@e65g2000hsc.googlegroups.com> <1175743177.489242.214700@w1g2000hsg.googlegroups.com> Message-ID: <87zm5nfmfe.fsf@benfinney.id.au> "ts-dev" writes: > If the scripts can be modified (very easily), how can the > application be trusted? This sounds far more that you don't trust the application *user*. If that's the case, don't deploy the application such that the user possesses it. Run it as a service on a machine controlled by people you *can* trust. That, or re-evaluate your reason for dealing with people you don't trust. -- \ "Timid men prefer the calm of despotism to the boisterous sea | `\ of liberty." -- Thomas Jefferson | _o__) | Ben Finney From shirishag75 at gmail.com Fri Apr 27 11:43:33 2007 From: shirishag75 at gmail.com (shirish) Date: 27 Apr 2007 08:43:33 -0700 Subject: use urllib library to have an upload status bar Message-ID: <1177688613.085156.116170@o40g2000prh.googlegroups.com> Hi all, Before I start, please know that I'm no developer, just a user. This is also a cross-post as I have tried to post the same at python- bugs mailing list, just don't know if it gets in or not. We have a bug-reporting system in ubuntu called apport. Apparently apport uses a python library called urllib. As of now, apport does a bouncing bar while uploading which doesn't give the user idea as to how much is being uploaded. Refer https://bugs.launchpad.net/ubuntu/+source/apport/+bug/91521 . I did try to see if this issue has been addressed or not but came nowhere. It would be nice to know if there are some solutions, or is there a roadmap where this feature would be integrated in the library. Looking forward to suggestions, additions, flames & constructive criticism of the same. Keep up the good work. Cheers! From kyosohma at gmail.com Wed Apr 18 15:03:40 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: 18 Apr 2007 12:03:40 -0700 Subject: Win32com, and Excel issues. In-Reply-To: <1176922705.587663.97940@y80g2000hsf.googlegroups.com> References: <1176881939.612038.278770@y5g2000hsa.googlegroups.com> <1176901606.433286.225770@q75g2000hsh.googlegroups.com> <1176922705.587663.97940@y80g2000hsf.googlegroups.com> Message-ID: <1176923020.453174.242430@d57g2000hsg.googlegroups.com> On Apr 18, 1:58 pm, Ant wrote: > Hi Mike, > > > I can't find anything about copying a worksheet, but I found a some > > fairly detailed information about COM objects and getting more > > information about Python's bindings to them here:http://www.oreilly.com/catalog/pythonwin32/chapter/ch12.htmlorhere:http://mathieu.fenniak.net/plotting-in-excel-through-pythoncom/ > > Thanks, I've already seen those pages (in fact I have the book) but no > luck. In fact it's worse - I've tested it out on a different machine > running Excel 2003, and it works fine :-( > > Which means that there's another variable at stake here... > > -- > Ant. Yeah. I have the book too. You might check to see if both PCs have the Office SP2 on them. It shouldn't make a difference, but they shouldn't change the way VBA behaves between versions either, and yet they do. Sorry I wasn't of more help. Mike From gagsl-py2 at yahoo.com.ar Fri Apr 20 16:13:48 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 20 Apr 2007 17:13:48 -0300 Subject: Do other Python GUI toolkits require this? References: <462697A6.6010007@codebykevin.com> <1177014799.004875.262060@y80g2000hsf.googlegroups.com> Message-ID: En Thu, 19 Apr 2007 17:33:19 -0300, sjdevnull at yahoo.com escribi?: > On Apr 19, 6:54 am, Antoon Pardon wrote: >> I don't know how you come to the conclusion that it is a mathematical >> absurdity but consider this: If you find that common usage propagates >> something that is incorrect, should we just shrug it off or should we >> attemp a correction? > > a) In English, "learning curve" is not restricted to a mathematical > plot--Webster's also defines it as "the course of progress made in > learning something". In that context, adding the adjective steep > ("extremely or excessively high...STEEP implies such sharpness of > pitch that ascent or descent is very difficult") makes sense. > > Trying to apply a mathematical definition to an English-language > phrase is prone to incorrect outcomes. I don't know if it's used in English, but my uncle says "open the light" and "close the light". From an electrician point of view, that's wrong: to turn the light on you have to close the circuit, and the light is off when the circuit is open. A biologyst won't aggree on the common usage of "crocodrile tears". Such expressions should not be understood technically (I think they're known as idioms). As English is not my native language, I sometimes got puzzled by some idioms. How much Python can be put in a nutshell? Almost nothing, so for me, the famous book starts diminished from the title. Or, I would not consider "sleepping tight" a good thing, I prefer big and comfortable beds... This is getting close to win the "longest off topic thread" award. -- Gabriel Genellina From larry.bates at websafe.com Tue Apr 17 17:43:19 2007 From: larry.bates at websafe.com (Larry Bates) Date: Tue, 17 Apr 2007 16:43:19 -0500 Subject: python - dll access (ctypes or swig) In-Reply-To: References: Message-ID: <46253F77.20409@websafe.com> Daniel Watrous wrote: > Hello, > > I am interested in using python to script access to some hardware for > which there are existing drivers in the form of DLLs. The DLLs each > have four exported functions and a host of COM Properties and COM > Methods. The four exported functions are as follows: > DllCanUnloadNow > DllGetClassObject > DllRegisterServer > DllUnregisterServer > > The COM methods and properties all begin with I, followed by a unique name. > > I am able to load the DLL using ctypes and it can access the exported > functions, but I'm not sure how to access the COM methods and > properties. I have read that ctypes once had support for COM but that > it has since been separated into its own project. I couldn't find any > information about how these work together. > > All help is appreciated. THANKS in advance... > > Daniel I recently learned that you can ship COM as either an .EXE or a .DLL (nobody has yet let me know why). You don't have a traditional .DLL that you would use ctypes to call methods in, you have a COM .DLL. COM methods need to be access with Win32com obj=win32com.client.Dispatch("typelib name"). You need to find out the COM dispatch typelib name and make sure the DLL is registered (regsvr32 your.dll). -Larry From eugene.vandenbulke at gmail.com Fri Apr 27 02:07:08 2007 From: eugene.vandenbulke at gmail.com (EuGeNe Van den Bulke) Date: Fri, 27 Apr 2007 08:07:08 +0200 Subject: EuroPython vs PyconUK References: <4630D480.7050308@gmail.com> <1177617449.064076.250150@t38g2000prd.googlegroups.com> <1hx76ez.k3b9p41gyek8dN%aleax@mac.com> Message-ID: Alex Martelli wrote: > I like the kudos, thanks!, but I'm not quite sure what you're saying > about my travel plans... just to clarify, once again I'll have to miss > EuroPython _and_ PythonUK, two events I attended most assiduously when I > was living in Europe (but then, for two years running I've also missed > PyCon, _despite_ living in the US, sigh). I was just using your possible travel plans as an example to express my "concerns" :P Re your effective travel plans, thanks God for Google Video then :D Cheers, EuGeNe -- http://www.3kwa.com From nate.finch at gmail.com Fri Apr 6 09:59:23 2007 From: nate.finch at gmail.com (Nate Finch) Date: 6 Apr 2007 06:59:23 -0700 Subject: "Plugin" architecture - how to do? In-Reply-To: <1175785055.668181.308140@b75g2000hsg.googlegroups.com> References: <1175785055.668181.308140@b75g2000hsg.googlegroups.com> Message-ID: <1175867963.727762.321170@l77g2000hsb.googlegroups.com> On Apr 5, 10:57 am, anglozax... at gmail.com wrote: > I'm making a program that consists of a main engine + plugins. Both > are in Python. My question is, how do I go about importing arbitrary > code and have it be able to use the engine's functions, classes, etc? For a true plugin architecture, you don't have the main engine calling methods on the plugin. What you do is have an API on your engine with methods the plugin can call and events it can hook into. The events are how the engine communicates state to any plugins, without having to know who they are or what they do. Your engine has a configuration that tells it what plugins to load (which the plugins presumably modified when they installed themselves) or otherwise has some standard way that the engine can figure out what plugins need to be loaded. Now granted, I don't specifically know how to do this via python.. but, maybe what I've said will send you in the right direction. -Nate From aleax at mac.com Thu Apr 12 23:15:05 2007 From: aleax at mac.com (Alex Martelli) Date: Thu, 12 Apr 2007 20:15:05 -0700 Subject: ulimit on open sockets ? In-Reply-To: References: <1hwbp5h.1fnai9snzd1vpN%aleax@mac.com> Message-ID: <82069913-B174-4701-8E81-7A82FAB7D040@mac.com> On Apr 12, 2007, at 1:17 PM, Maxim Veksler wrote: ... > Now, someone I work with suggested a simple work around "Pass the list > objects in groups of 1024 each time to the select.select structure". I > think it's acceptable and good advice, the thing is I don't know how > to implement this "the python way" (that is - with out it being ugly). I don't understand how you're going to make it work (I see no select calls in your code and I don't understand how you'd get one in there by polling), but I'm going to just explain how to get slices of 1024 items at a time from a long list. Simplest way: for i in xrange(0, len(longlist), 1024): shortlist = longlist[i:i+1024] # rest of the body goes here More elegant/reusable: def sliceby(longlist, N=1024): for i in xrange(0, len(longlist), 1024): yield longlist[i:i+1024] for shortlist in sliceby(longlist): # body goes here If you want to show off, itertools.groupby may be suitable for that: for _, g in itertools.groupby(enumerate(longlist), lambda (i, j): i// 1024): shortlist = list(a for b, a in g) # rest of the body goes here but I wouldn't recommend it in this case for other purposes. Alex From paul at boddie.org.uk Wed Apr 11 11:37:39 2007 From: paul at boddie.org.uk (Paul Boddie) Date: 11 Apr 2007 08:37:39 -0700 Subject: tuples, index method, Python's design In-Reply-To: References: <1176210960.3430.20.camel@dot.uniqsys.com> <740c3aec0704100810g5f962e8eu614fbaedecf3608e@mail.gmail.com> <1176219856.3430.76.camel@dot.uniqsys.com> <740c3aec0704101021i1fd79ef2l99eac4ced1e252d9@mail.gmail.com> <1176226682.3430.86.camel@dot.uniqsys.com> <4866bea60704101104r4600d281h135286b66378f4d4@mail.gmail.com> <740c3aec0704101534y3c65f5a7je382f97e1f6301b7@mail.gmail.com> Message-ID: <1176305859.581010.199600@n76g2000hsh.googlegroups.com> On 11 Apr, 16:14, "Chris Mellon" wrote: > > If you want a language that just adds whatever methods anyone thinks > of, along with whatever aliases for it any can think of, to every data > type, you know where to find Ruby. Nobody is asking for Ruby, as far as I can see. I even submitted a quick patch to provide tuple.index (a method that has already been thought of), given the triviality of the solution, but you won't find me asking for a bundle of different convenience methods with all their aliases on every object, regardless of whether you can monkey-patch them after the fact or not. For example: http://www.ruby-doc.org/core/classes/Array.html#M002235 There's a pretty big chasm between wanting to be able to apply existing functionality exactly to a type which for some reason never acquired it and embracing the method proliferation and other low- hanging fruit-picking seemingly popular in Ruby. In observing this, one can make objective decisions about things like this... http://wiki.python.org/moin/AbstractBaseClasses Note that, in that document, index and count are methods of MutableSequence. Quite why this should be from a conceptual perspective is baffling, but don't underestimate the legacy influence in such matters. Paul From bj_666 at gmx.net Fri Apr 13 06:09:46 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Fri, 13 Apr 2007 12:09:46 +0200 Subject: reading from sys.stdin References: <1176366058.261031.111870@p77g2000hsh.googlegroups.com> <1176387908.406115.270630@w1g2000hsg.googlegroups.com> <1176438754.995753.50190@d57g2000hsg.googlegroups.com> <1176454871.538968.176620@n76g2000hsh.googlegroups.com> <1176457007.589050.285400@d57g2000hsg.googlegroups.com> <1176457624.259636.197030@p77g2000hsh.googlegroups.com> Message-ID: In <1176457624.259636.197030 at p77g2000hsh.googlegroups.com>, 7stud wrote: > On Apr 13, 3:36 am, "7stud" wrote: >> >> > It is if the file is smaller than the buffer size. >> >> How is that relevant? >> > > If I put 100 lines of text in a file with each line having 50 > characters, and I run this code: > > import sys > > lst = [] > for line in open("aaa.txt"): > print "an iteration" > lst.append(line) > break > > print lst > > > The output is: > > $ python test1.py > > an iteration > ['helleo haljdfladj ahdflasdjf ds hdljfalsdjfdsljfds \n'] > > It seems clear to me that the whole file wasn't first read into a > buffer before the code started processing the data. How is that clear to you? Why do you think the file was not loaded completely into a buffer and only the first line from this buffer ends up in `lst`? Let's try this: def main(): test_file = open('test.txt', 'w') for i in xrange(100): test_file.write('%d %s\n' % (i, 'x' * 50)) test_file.close() test_file = open('test.txt', 'r') for line in test_file: print line break print '>%s<' % test_file.read(75) test_file.close() Output: 0 xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx >< You see the read after the loop doesn't read anything because the file content is in the buffer of the iterator. If the test file has more lines, I tested it with 1000, the output looks like this: 0 xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx >xx 151 xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx 152 xxxxxxxxxxxxx< Ciao, Marc 'BlackJack' Rintsch From duncan.booth at invalid.invalid Mon Apr 9 07:21:44 2007 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 9 Apr 2007 11:21:44 GMT Subject: how to use the string '\\.\' References: <1176117103.670611.291740@n59g2000hsh.googlegroups.com> Message-ID: "=?utf-8?B?5Lq66KiA6JC95pel5piv5aSp5rav77yM5pyb5p6B5aSp5rav5LiN6KeB5a62?=" wrote: > print r'\\.\' > > This line will cause error. I just want to print the > \\.\ > why the prefix character "r" isn't effective. Thanks! > > See the FAQ: http://www.python.org/doc/faq/general/#why-can-t-raw-strings-r-strings-end-with-a-backslash From sjmachin at lexicon.net Fri Apr 6 19:20:54 2007 From: sjmachin at lexicon.net (John Machin) Date: 6 Apr 2007 16:20:54 -0700 Subject: Database Timestamp conversion error In-Reply-To: <1175892527.110813.26570@n76g2000hsh.googlegroups.com> References: <1175892527.110813.26570@n76g2000hsh.googlegroups.com> Message-ID: <1175901654.390331.150420@e65g2000hsc.googlegroups.com> On Apr 7, 6:48 am, kyoso... at gmail.com wrote: > Hi, > > I am populating a mySQL database with data from the MS Access > database. I have successfully figured out how to extract the data from > Access, and I can insert the data successfully into mySQL with Python. > My problem is that I keep hitting screwy records with what appears to > be a malformed dbiDate object when I insert certain records. I get the > following traceback: Ummm ... I didn't start using Python on databases till after DB API 2.0 came out (1999) so please pardon my ignorance, but isn't dbiDate something that was in API 1.0 but vanished in API 2.0 [e.g. its mentioned only briefly in the history section of the current mxODBC docs]? If that's what you are still using: (a) I can't imagine how printing a dbiDate object would give such a garbled result -- try: print type(obj) print repr(obj) for both a "bad" obj and a "good" obj. (b) The API 1.0 docs give a clue: """ dbiDate(value) This function constructs a 'dbiDate' instance that holds a date value. The value should be specified as an integer number of seconds since the "epoch" (e.g. time.time()). """ and googling brought up a few hits mentioning that not handling dates earlier that the "epoch" (1970-01-01T00:00:00) was a limitation. So: if you are calling dbiDate yourself, you can inspect its input argument; presumably a date in the year 112 will show up as negative. > > Traceback (most recent call last): > File "\\someServer\Development\collectiveFleet.py", line 68, in - > toplevel- > mycursor.execute(sql) > TypeError: argument 1 must be string without null bytes, not str > > When I print the timestamp variable, I get this output: > > (I31 > (S'OK' > p1 > Nttp2 > . > > If I look in the MS Access database, I see the timestamp as "5/6/112". > Obviously some user didn't enter the correct date and the programmer > before me didn't give Access strict enough rules to block bad dates. > How do I test for a malformed date object so I can avoid this? > There > are thousands of records to transfer. > > I am using the odbc module for connection purposes with Python 2.4 on > Windows XP SP2. If this is the odbc module that comes in the win32all package: 1. There are much better options available on Windows e.g. mxODBC. 2. Doesn't document dbiDate objects AFAICT. If your SELECT from the Access db is returning you "seconds since the epoch" values, proceed as I suggested earlier. If it is returning you dbiDate objects directly, find out if the dbiDate obj has any useful attributes or methods e.g. obj.date_as_tuple() -> (2007, 4, 7, ...) or obj.year -> 2007 obj.month -> 4 etc How to find out: insert code like print dir(obj) in your script and inspect the output for likely attribute/method names. And if that doesn't help, abandon the odbc module and use e.g. mxODBC or Python adodb. Hope some of this helps, John From robert.kern at gmail.com Tue Apr 17 18:04:47 2007 From: robert.kern at gmail.com (Robert Kern) Date: Tue, 17 Apr 2007 17:04:47 -0500 Subject: scipy 0.52 det crashes python In-Reply-To: References: Message-ID: Peter Maas wrote: > I tried some scipy examples using scipy 0.52, numpy 1.02 and python 2.5 on > a WinXP SP2 machine. numpy.linalg.det() works but scipy.linalg.det() > crashes python. Has anybody experienced this and can point me to a solution? Most likely your build of scipy was built with an ATLAS library that uses SSE2 instructions (IIRC) while your processor doesn't support those instructions. The solution is to rebuild scipy with an ATLAS library built for your platform. You will want to ask more scipy questions on the scipy lists, though: http://www.scipy.org/Mailing_Lists -- 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 R.Brodie at rl.ac.uk Fri Apr 20 09:57:35 2007 From: R.Brodie at rl.ac.uk (Richard Brodie) Date: Fri, 20 Apr 2007 14:57:35 +0100 Subject: setDaemon problem. References: <1177057029.688992.160020@o5g2000hsb.googlegroups.com> <58rk68F2hof6mU1@mid.uni-berlin.de> <1177076608.110673.305970@d57g2000hsg.googlegroups.com> Message-ID: "Ramashish Baranwal" wrote in message news:1177076608.110673.305970 at d57g2000hsg.googlegroups.com... > I was also wondering about "daemonizing" a thread, but I interpreted > that it would daemonize the process which it didn't. I think setDaemon > should be renamed to setDetached or something similar. Neither is particularly intuitive; it just depends whether you are more familiar with the Posix terminology or the Java one. I personally prefer detached but there is little chance of a name change now. From aisaac at american.edu Wed Apr 18 19:05:05 2007 From: aisaac at american.edu (Alan G Isaac) Date: Wed, 18 Apr 2007 18:05:05 -0500 Subject: comparison with None Message-ID: <3IqdnfRnCNWPC7vbnZ2dnUVZ_jqdnZ2d@rcn.net> >>> None >= 0 False >>> None <= 0 True Explanation appreciated. Thanks, Alan Isaac From miki.tebeka at gmail.com Mon Apr 2 09:54:40 2007 From: miki.tebeka at gmail.com (Miki) Date: 2 Apr 2007 06:54:40 -0700 Subject: p2p chat framework In-Reply-To: References: Message-ID: <1175522080.125019.243030@o5g2000hsb.googlegroups.com> Hello Ghirai, > Are there any p2p chat/filetransfer frameworks/examples floating > around? http://divmod.org/projects/shtoom HTH, -- Miki http://pythonwise.blogspot.com From mansonmuni at alexandria.cc Tue Apr 17 01:42:08 2007 From: mansonmuni at alexandria.cc (Glen) Date: Tue, 17 Apr 2007 05:42:08 GMT Subject: Beginner: Simple Output to a Dialog PyQt4 Message-ID: Hello, I've written a script in python and put together a simple QFrame with a QTextBrowser with Designer. I've translated the C++ into python using puic4. The .py file is called outputWin.py. My Script and its functions are in cnt.py. Finally, my main is in pball.py which follows here: import sys from PyQt4 import Qt, QtCore from outputWin import * from cnt import * if __name__ == "__main__": app = Qt.QApplication(sys.argv) window = Qt.QDialog() ui = Ui_Dialog() ui.setupUi(window) window.show() app.exec_() I want to call my functions in cnt and have an output to my QDialog. Can somebody give me a clue as to how to proceed? I can't find good an easy tutorial for PyQt4 and I've never used Qt before. From dave.dean at xilinx.com Thu Apr 26 13:39:15 2007 From: dave.dean at xilinx.com (Dave Dean) Date: Thu, 26 Apr 2007 10:39:15 -0700 Subject: urlopen Message-ID: Hi all, I'm running into some trouble using urllib.urlopen to grab a page from our corporate intranet. The name of the internal site is simply http://web (no www or com). I can use urlopen to grab a site like http://www.google.com just fine. However, when I use urlopen to grab the internal site, I instead get data from http://www.web.com. This is the url returned by the geturl() function. There must be a way to stop Python, or whoever is doing it, from changing my url. Maybe urllib is not the correct approach. Does anyone know a solution to this? Thanks, Dave From thorsten at thorstenkampe.de Mon Apr 2 08:00:05 2007 From: thorsten at thorstenkampe.de (Thorsten Kampe) Date: Mon, 2 Apr 2007 13:00:05 +0100 Subject: I18n issue with optik References: <1175462657.413779.286590@l77g2000hsb.googlegroups.com> Message-ID: * Leo Kislov (1 Apr 2007 14:24:17 -0700) > On Apr 1, 8:47 am, Thorsten Kampe wrote: > > I guess the culprit is this snippet from optparse.py: > > > > # used by test suite > > def _get_encoding(self, file): > > encoding = getattr(file, "encoding", None) > > if not encoding: > > encoding = sys.getdefaultencoding() > > return encoding > > > > def print_help(self, file=None): > > """print_help(file : file = stdout) > > > > Print an extended help message, listing all options and any > > help text provided with them, to 'file' (default stdout). > > """ > > if file is None: > > file = sys.stdout > > encoding = self._get_encoding(file) > > file.write(self.format_help().encode(encoding, "replace")) > > > > So this means: when the encoding of sys.stdout is US-ASCII, Optparse > > sets the encoding to of the help text to ASCII, too. > > .encode() method doesn't set an encoding. It encodes unicode text into > bytes according to specified encoding. That means optparse needs ascii > or unicode (at least) for help text. In other words you'd better use > unicode throughout your program. > > > But that's > > nonsense because the Encoding is declared in the Po (localisation) > > file. > > For backward compatibility gettext is working with bytes by default, > so the PO file encoding is not even involved. You need to use unicode > gettext. You mean gettext.install('test', unicode = True) and description = _(u'THIS SOFTWARE COMES WITHOUT WARRANTY, LIABILITY OR SUPPORT!') ? If I modify my code like this, I don't get any traceback anymore, but the non-ascii umlauts are still displayed as question marks. Thorsten From gherzig at fmed.uba.ar Thu Apr 26 17:39:23 2007 From: gherzig at fmed.uba.ar (Gerardo Herzig) Date: Thu, 26 Apr 2007 18:39:23 -0300 Subject: I25 barcode generator? Message-ID: <46311C0B.10506@fmed.uba.ar> Hi. Im looking for an I25 barcode generator. I found a couple of nice EAN barcode generators, but this application needs an I25 barcode. Since this will be an web application, i need to do it in the server side. In python, off course :) Anybody knows one? Thanks! Gerardo From steve at REMOVE.THIS.cybersource.com.au Wed Apr 11 23:38:21 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Thu, 12 Apr 2007 13:38:21 +1000 Subject: Strange Behavior with Old-Style classes and implicit __contains__ References: <1176334655.677943.70030@q75g2000hsh.googlegroups.com> Message-ID: On Wed, 11 Apr 2007 16:37:35 -0700, rconradharris wrote: > A co-worker of mine came across some interesting behavior in the > Python interpreter today and I'm hoping someone more knowledgeable in > Python internals can explain this to me. > > First, we create an instance of an Old-Style class without defining a > __contains__ but instead define a __getitem__ method in which we raise > KeyError. Next we repeatedly use the 'in' operator to test to see > whether something, a string, an int, etc is an attribute of this new > instance. > > Here's the strange part: The first test will return False as if the > __getitem__ was never called. The next test will raise a KeyError as > we'd expect. The test after that will again return False. This goes on > ad infinitum. I can confirm that. It looks like __getitem__ is only being called every second time. class Parrot: def __getitem__(self, n): print "Checking index %s..." % n raise KeyError def tester(n): parrot = Parrot() results = [] for i in range(n): try: results.append(i in parrot) except KeyError: results.append("KeyError") return results Here are the results under Python 2.5: >>> tester(10) Checking index 0... Checking index 0... Checking index 0... Checking index 0... Checking index 0... [False, 'KeyError', False, 'KeyError', False, 'KeyError', False, 'KeyError', False, 'KeyError'] And here are the results under Python 2.4.3: >>> tester(10) Checking index 0... Checking index 0... Checking index 0... Checking index 0... Checking index 0... Checking index 0... Checking index 0... Checking index 0... Checking index 0... Checking index 0... ['KeyError', 'KeyError', 'KeyError', 'KeyError', 'KeyError', 'KeyError', 'KeyError', 'KeyError', 'KeyError', 'KeyError'] Looks like a bug to me. -- Steven. From facundo at taniquetil.com.ar Thu Apr 12 16:54:24 2007 From: facundo at taniquetil.com.ar (Facundo Batista) Date: Thu, 12 Apr 2007 20:54:24 +0000 (UTC) Subject: Inconsistent result from urllib.urlopen References: <1176402303.340868.165510@o5g2000hsb.googlegroups.com> Message-ID: junkdump2861 at hotmail.com wrote: > import urllib > f = urllib.urlopen('http://en.wikipedia.org/wiki/Cain') > data = f.read(9999999) > f.close() > f1 = open('junk.txt', 'w') > f1.write(data) > f1.close() Did you see the file "junk.txt"? It's an error page from Wikipedia, not the actual content page... Regards, -- . Facundo . Blog: http://www.taniquetil.com.ar/plog/ PyAr: http://www.python.org/ar/ From pelonpelon at gmail.com Tue Apr 3 01:32:26 2007 From: pelonpelon at gmail.com (pelon) Date: 2 Apr 2007 22:32:26 -0700 Subject: Testing functions via command line Message-ID: <1175578346.845789.119590@p15g2000hsd.googlegroups.com> There must be a couple of lines that will replace the following: >From the shell command line I wanted to send data to a specific function inside my module and execute that function in order to test it separately from the rest of the module. I know pdb will allow me to insert data into a running process, but this particular function requires several long steps beforehand. My command line: myprog.py --test removefromcue "myargs" ### removefromcue is my function inside myprog.py main() ... try: opts, args = getopt.getopt(sys.argv[1:], "t:", ["--test="]) except getopt.GetoptError: for o, a in opts: if o in "-t": myfunc = a myargs = args test(myfunc, myargs) sys.exit() My problem was that I send a string into the the test function. I needed to convert that string into the appropriate object. globals() provides a dictionary with string:object pairs in the global namespace. def test(myfunc, myargs): """ execute a given function """ for key,value in globals().items(): if myfunc in key: func = value break args = "" for i in myargs: args += i + "," func(args[:-1]) ### removefromcue("myitem") There's something very basic that I should know. From laurent.pointal at limsi.fr Thu Apr 26 05:41:11 2007 From: laurent.pointal at limsi.fr (Laurent Pointal) Date: Thu, 26 Apr 2007 11:41:11 +0200 Subject: simplest install procedure for Python + packages under winXP ? In-Reply-To: <617df$46306f26$83aef404$8949@news2.tudelft.nl> References: <617df$46306f26$83aef404$8949@news2.tudelft.nl> Message-ID: stef a ?crit : > hello, > > I'm still in the transition of going from MatLab to Scipy, > and installed previous week a SciPy on a PC twice, > through the new "Enstaller". > It's a pitty that there will be no old installer versions anymore > (although I can understand why). > > Although I succeeded, the behavior of the Enstaller was different both > times, and you can clearly see it's an alpha version. > (I already wrote my experiences with the first install, > the second install had the weird phenomena that none of the succesful > installed packages was detected). > > As a spoiled windows user, which by the way are most people in my > surrounding, I'm used to a "one-button-install", > so I wonder if it's possible to make a much simpler install procedure. > > I don't know anything about what's required for a good install, > what kind of things things should be stored in the windows registry, > but as Python is an interpretor, > I would expect there should be a very easy procedure: > - Install it on one machine, > - copy the complete subdirectory to another computer > Does this work for Python + Scipy ? > (If so, I can use Inno, which I'm familiar with) Maybe take a look at: http://www.portablepython.com/ http://www.voidspace.org.uk/python/movpy/ Dont know for scipy. From soren.skou.nielsen at gmail.com Wed Apr 25 17:00:02 2007 From: soren.skou.nielsen at gmail.com (Soren) Date: 25 Apr 2007 14:00:02 -0700 Subject: Embedding Matplotlib in wxpython wx.Panel problem Message-ID: <1177534801.938139.39220@r35g2000prh.googlegroups.com> Hi, I'm trying to create a small GUI program where I can do plots using Matplotlib. I've been trying to borrow code from the examples at the matplotlib website, but I can't get it to work. I want to be able to create a wx.Panel that contains an axis for plotting. Around it i want other panels containing various settings, buttons etc. to control the plot. So far I can't even get the program to actually show a plot in a panel. Does anyone here have experience in making a wxpython GUI with matplotlib? Any help would be appreciated! Thanks, Soren My code shows a frame, and I'm trying to set up two panels.. one with a plot and one with a button.. The plotpanel is just a little square in the corner when I run it.. ??? My code is as follows: import wx import pylab from matplotlib.numerix import arange, sin, cos, pi import matplotlib matplotlib.use('WXAgg') from matplotlib.backends.backend_wxagg import FigureCanvasWxAgg from matplotlib.backends.backend_wx import NavigationToolbar2Wx from matplotlib.figure import Figure matplotlib.interactive(False) class App(wx.App): def OnInit(self): self.frame = MainFrame("Autoplotter", (50,60), (700,700)) self.frame.Show() return True class MainFrame(wx.Frame): def __init__(self, title, pos, size): wx.Frame.__init__(self, None, -1, title, pos, size) pPanel = PlotPanel(self, -1) # Plot panel bPanel = ButtonPanel(self, 100,500, (200,100)) # button panel sizer = wx.BoxSizer(wx.VERTICAL) sizer.Add(pPanel,0) sizer.Add(bPanel,0) self.SetSizer(sizer) class ButtonPanel(wx.Panel): def __init__(self, Parent, xPos, yPos, insize): pos = (xPos, yPos) wx.Panel.__init__(self, Parent, -1, pos, style = wx.RAISED_BORDER, size = insize) button = wx.Button(self, -1, 'HELLO!!', (10,10), (150,50)) class NoRepaintCanvas(FigureCanvasWxAgg): """We subclass FigureCanvasWxAgg, overriding the _onPaint method, so that the draw method is only called for the first two paint events. After that, the canvas will only be redrawn when it is resized. """ def __init__(self, *args, **kwargs): FigureCanvasWxAgg.__init__(self, *args, **kwargs) self._drawn = 0 def _onPaint(self, evt): """ Called when wxPaintEvt is generated """ if not self._isRealized: self.realize() if self._drawn < 2: self.draw(repaint = False) self._drawn += 1 self.gui_repaint(drawDC=wx.PaintDC(self)) class PlotPanel(wx.Panel): def __init__(self, parent, id = -1, color = None,\ dpi = None, style = wx.NO_FULL_REPAINT_ON_RESIZE, **kwargs): wx.Panel.__init__(self, parent, id = id, style = style, **kwargs) self.figure = Figure(None, dpi) self.canvas = NoRepaintCanvas(self, -1, self.figure) self._resizeflag = True self.Bind(wx.EVT_IDLE, self._onIdle) self.Bind(wx.EVT_SIZE, self._onSize) self._SetSize() def draw(self): # just draw something! if not hasattr(self, 'subplot'): self.subplot = self.figure.add_subplot(111) theta = arange(0, 45*2*pi, 0.02) rad = (0.8*theta/(2*pi)+1) r = rad*(8 + sin(theta*7+rad/1.8)) x = r*cos(theta) y = r*sin(theta) #Now draw it self.subplot.plot(x,y, '-r') def _onSize(self, event): self._resizeflag = True def _onIdle(self, evt): if self._resizeflag: self._resizeflag = False self._SetSize() self.draw() def _SetSize(self, pixels = None): """ This method can be called to force the Plot to be a desired size, which defaults to the ClientSize of the panel """ if not pixels: pixels = self.GetClientSize() self.canvas.SetSize(pixels) self.figure.set_figsize_inches(pixels[0]/ self.figure.get_dpi(), pixels[1]/self.figure.get_dpi()) if __name__ == "__main__": app = App(0) app.MainLoop() From sjmachin at lexicon.net Thu Apr 12 17:14:00 2007 From: sjmachin at lexicon.net (John Machin) Date: 12 Apr 2007 14:14:00 -0700 Subject: Creating an EXE for XLRD + WIN32COM + wxWidgets application - Help request In-Reply-To: <461E3B06.5020809@websafe.com> References: <1176331416.703642.242690@y5g2000hsa.googlegroups.com> <461E3B06.5020809@websafe.com> Message-ID: <1176412440.617825.263880@o5g2000hsb.googlegroups.com> On Apr 12, 11:58 pm, Larry Bates wrote: > BrendanC wrote: > > I've started learninhg Python and have developed a small Python app > > that imports Excel data into an Access mdb/jet database. This > > application has dependencies on the following: > > > XLRD -http://cheeseshop.python.org/pypi/xlrd/0.5.2 - (to read Excel > > files) > > Python windows extensions -http://starship.python.net/crew/mhammond/win32/ > > - to use ADO > > wxPython GUI toolkit -http://www.wxpython.org/- for the GUI > > interface > > > Ideally I'd like to create a standalone app that I can deliver to a > > client who can will run this on a Windows system that has Access > > installed. (Python will not be installed on this system). > > > I'm planning to use P2YEXE for the build - however I'm not sure if it > > is possible to include all the required components for this in a > > package. I imagine there may be a few 'gotchas' with this. > > > Any suggestions on how to do this and are there some additional issues > > I might run into? > > > Thx in advance > > > BrendanC > > I can tell you that I've used py2exe to build quite a number of apps > that depended on many different pieces. I have not experience with XLRD > but the other pieces you use work just fine. xlrd [save wear and tear on the shift key!] up to version 0.6.1 at least is a pure-Python package with no dependencies on 3rd-party modules/packages and is very unlikely to cause grief with py2exe; I'd like to hear any evidence to the contrary PDQ. The OP is best advised to "just do it" :-) HTH, John From bj_666 at gmx.net Fri Apr 20 04:30:14 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Fri, 20 Apr 2007 10:30:14 +0200 Subject: Python Feature Request: Explicit variable declarations References: <1176546078.934340.253810@y5g2000hsa.googlegroups.com> <1hwu43c.dp5yo01rsqhjfN%aleax@mac.com> Message-ID: In <1hwu43c.dp5yo01rsqhjfN%aleax at mac.com>, Alex Martelli wrote: > Jorgen Grahn wrote: > >> As a C and C++ programmer (not a C/C++ programmer), I have to say that > > Yeah, I wonder, what's C divided by C++ -- maybe about 0.731...? Isn't it 1 unless `C` is 0? The increment happens after the division, right? :-) Ciao, Marc 'BlackJack' Rintsch From flyzone at technologist.com Thu Apr 12 05:30:01 2007 From: flyzone at technologist.com (flyzone at technologist.com) Date: 12 Apr 2007 02:30:01 -0700 Subject: parsing text in blocks and line too Message-ID: <1176370200.947603.314500@d57g2000hsg.googlegroups.com> Goodmorning people :) I have just started to learn this language and i have a logical problem. I need to write a program to parse various file of text. Here two sample: --------------- trial text bla bla bla bla error bla bla bla bla bla bla bla bla on more lines trial text bla bla bla bla warning bla bla bla more bla to be grouped with warning bla bla bla on more lines could be one two or ten lines also withouth the tab beginning again text text can contain also blank lines text no delimiters.... -------------- Apr 8 04:02:08 machine text on one line Apr 8 04:02:09 machine this is an error Apr 8 04:02:10 machine this is a warning -------------- parsing the file, I'll need to decide if the line/group is an error, warning or to skip. Mine problem if how logical do it: if i read line by line, I'll catch the error/warning on first and the second/third/more will be skipped by control. Reading a group of line i could lose the order on the output: my idea is to have an output in html with the line in the color of the check (yellow for warning, red for error). And i have also many rules to be followed so if i read one rule and then i search on the entire file, the check will be really slow. Hope someone could give me some tips. Thanks in advance From robert.kern at gmail.com Fri Apr 13 00:59:23 2007 From: robert.kern at gmail.com (Robert Kern) Date: Thu, 12 Apr 2007 23:59:23 -0500 Subject: UnicodeDecodeError when importing random? (running with -U) In-Reply-To: <1176437444.758338.292550@n76g2000hsh.googlegroups.com> References: <1176437444.758338.292550@n76g2000hsh.googlegroups.com> Message-ID: Ben wrote: > Is the following a known bug? > > [temp]$ python -U > Python 2.4.4 (#1, Oct 23 2006, 13:58:18) > [GCC 4.1.1 20061011 (Red Hat 4.1.1-30)] on linux2 > Type "help", "copyright", "credits" or "license" for more information. >>>> import random > Traceback (most recent call last): > File "", line 1, in ? > File "/usr/lib64/python2.4/random.py", line 834, in ? > _inst = Random() > File "/usr/lib64/python2.4/random.py", line 94, in __init__ > self.seed(x) > File "/usr/lib64/python2.4/random.py", line 108, in seed > a = long(_hexlify(_urandom(16)), 16) > File "/usr/lib64/python2.4/os.py", line 723, in urandom > bytes += read(_urandomfd, n - len(bytes)) > UnicodeDecodeError: 'ascii' codec can't decode byte 0x97 in position > 0: ordinal not in range(128) It's unsurprising, certainly. It's not a bug in 2.4, though. -U is for experimentation only, not for actual use. Python will change to only using Unicode strings in 3.0, but not before then. Python 3.0 will add a bytes type to replace non-text strings like those read from /dev/urandom in that piece of code. os.urandom() and the random module will have to be modified to use it instead of a string. Looking at the Python 3.0 branch, I see that this hasn't quite happened, yet. -- 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 antroy at gmail.com Wed Apr 25 17:15:39 2007 From: antroy at gmail.com (Ant) Date: 25 Apr 2007 14:15:39 -0700 Subject: Tutorial creates confusion about slices In-Reply-To: References: Message-ID: <1177535739.431386.77300@s33g2000prh.googlegroups.com> On Apr 23, 1:38 pm, Antoon Pardon wrote: > The following is part of the explanation on slices in the > tutorial: > > The best way to remember how slices work is ... > +---+---+---+---+---+ > | H | e | l | p | A | > +---+---+---+---+---+ > 0 1 2 3 4 5 > -5 -4 -3 -2 -1 > > This is all very well with a simple slice like: > > "HelpA"[2:4] => "lp" > > But it give the wrong idea when using the following extended slice: > > "HelpA"[4:2:-1] => "Ap" I think that the tutorial example is absolutely fine as it is. It gives the new python programmer (the target demographic of the tutorial) a visual tool to understand what simple slicing is. Extended slicing (in particular ones using negative indices) are beyond the scope of the tutorial, and thus are irrelevant as far as the example goes. Adding examples / memory aids to cover all the many varied and possibly degenerate ways you can slice a string would merely confuse the python newbie. By the time you actually *are* interested in the more advanced slicing capabilities, it's time to read the Library reference where the formula stating *exactly* how slicing works is stated. A tutorial has every reason to be simplistic, so as far as I'm concerned, -1 for changing the docs. Apologies if this turns out to be my third near identical post - I've tried sending variations on this message twice already today from Google Groups, and they seem to have got lost in the ether... From jura.grozni at gmail.com Fri Apr 13 15:59:59 2007 From: jura.grozni at gmail.com (azrael) Date: 13 Apr 2007 12:59:59 -0700 Subject: Problem with algorithm In-Reply-To: References: <1176434160.047703.214600@q75g2000hsh.googlegroups.com> <1176434937.258002.162220@p77g2000hsh.googlegroups.com> <1176448576.047996.12930@d57g2000hsg.googlegroups.com> <1176482771.267327.247940@e65g2000hsc.googlegroups.com> Message-ID: <1176494399.176891.129350@l77g2000hsb.googlegroups.com> Are you maybe trying to create a rainbow table, or a very big dictionary From b.r.willems at gmail.com Sun Apr 29 07:32:44 2007 From: b.r.willems at gmail.com (Bart Willems) Date: Sun, 29 Apr 2007 07:32:44 -0400 Subject: if __name__ == 'main': & passing an arg to a class object In-Reply-To: <1177708104.277756.245360@t38g2000prd.googlegroups.com> References: <1177708104.277756.245360@t38g2000prd.googlegroups.com> Message-ID: gtb wrote: > appear at the end of many examples I see. Is this to cause a .class > file to be generated? This might be obvious, but no one else mentioned it: the Python interpreter cannot execute code that it hasn't compiled yet, which is why the "if __name__ ..." code is always at the end of the module - to guarantee that the entire file is scanned first. From codecraig at gmail.com Thu Apr 12 14:11:30 2007 From: codecraig at gmail.com (abcd) Date: 12 Apr 2007 11:11:30 -0700 Subject: wrap_EncryptByteArray argument 1 must be string without null bytes, not str Message-ID: <1176401490.277552.318630@q75g2000hsh.googlegroups.com> Has anyone seen this error before: wrap_EncryptByteArray() argument 1 must be string without null bytes, not str I am having a hard time finding anything about it. From bignose+hates-spam at benfinney.id.au Sun Apr 22 22:54:27 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Mon, 23 Apr 2007 12:54:27 +1000 Subject: Dictionaries and dot notation References: <23087554.X5dcTmlj7P@beaureve.gmx.net> <462B6227.5070405@web.de> <5296241.Dh78hTc8ZZ@beaureve.gmx.net> Message-ID: <87tzv7iyvw.fsf@benfinney.id.au> Martin Drautzburg writes: > Okay let me rephrase my question: is there a way of using dot > notation without having to create a class? Dot notation, e.g. 'foo.bar', is parsed by the interpreter as "access the attribute named 'bar' of the object 'foo'". Objects have attributes either by virtue of the class having them, or the object getting them assigned after creation. Can you describe what you would change in the above, or can you re-word your request based on these facts? -- \ "Our products just aren't engineered for security." -- Brian | `\ Valentine, senior vice-president of Microsoft Windows | _o__) development | Ben Finney From michael at jedimindworks.com Thu Apr 19 07:11:03 2007 From: michael at jedimindworks.com (Michael Bentley) Date: Thu, 19 Apr 2007 06:11:03 -0500 Subject: Do other Python GUI toolkits require this? In-Reply-To: References: <462697A6.6010007@codebykevin.com> Message-ID: <7679ABD4-5EC6-4502-AFF7-4EEFEBB19740@jedimindworks.com> *plonk* From cam.ac.uk at mh391.invalid Fri Apr 20 08:19:30 2007 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Fri, 20 Apr 2007 13:19:30 +0100 Subject: Problems with os.rename In-Reply-To: <1177069093.003491.194840@b75g2000hsg.googlegroups.com> References: <1177069093.003491.194840@b75g2000hsg.googlegroups.com> Message-ID: loial wrote: > How can I get more info what the cause of the OSError exception is? For starters, post the traceback here. -- Michael Hoffman From bdesth.quelquechose at free.quelquepart.fr Tue Apr 10 17:53:57 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Tue, 10 Apr 2007 23:53:57 +0200 Subject: block scope? In-Reply-To: <7xmz1jsihq.fsf@ruckus.brouhaha.com> References: <7xr6qwal50.fsf@ruckus.brouhaha.com> <7xtzvseqzo.fsf@ruckus.brouhaha.com> <1hw72cg.115yokgarr9enN%aleax@mac.com> <1hw7kzo.1hepj3c1who5zhN%aleax@mac.com> <1hw7lxn.18itayl1fua6w0N%aleax@mac.com> <7xodlzofw2.fsf@ruckus.brouhaha.com> <1hw7rf0.1p2nwloex6vupN%aleax@mac.com> <7xmz1jsihq.fsf@ruckus.brouhaha.com> Message-ID: <461bfe5a$0$1162$426a74cc@news.free.fr> Paul Rubin a ?crit : > aleax at mac.com (Alex Martelli) writes: > >>>>>locals['x']=5 >> >>Traceback (most recent call last): >> File "", line 1, in >>TypeError: 'builtin_function_or_method' object does not support item >>assignment > > > > Whoops, yeah, meant "locals()['x'] = 5". > > >>I think that ideally there should be a runtime error when assigning an >>item of locals() with a key that's not a local variable name (possibly >>excepting functions containing exec, which are kind of screwy anyway). > > > I have no opinion of this, locals() has always seemed like a crazy > part of the language to me and I never use it. I'd be happy to see it > gone since it makes compiling a lot easier. I personally find locals() handy in few cases, like def output(): foo = 42 bar = baaz() quux = blah(foo, bar) return "the %(bar)s is %(foo)d and the %(quux)s shines" % locals() or: class Foo(object): @apply def bar(): def fget(self): return self._quux / 42 def fset(self, value): self._quux = value * 42 return property(**locals()) I'd be very unhappy to see it gone... From sjmachin at lexicon.net Thu Apr 19 17:15:27 2007 From: sjmachin at lexicon.net (John Machin) Date: 19 Apr 2007 14:15:27 -0700 Subject: Significance of "start" parameter to string method "endswith" In-Reply-To: References: <1177012694.726434.142660@q75g2000hsh.googlegroups.com> Message-ID: <1177017327.547115.67400@n76g2000hsh.googlegroups.com> On Apr 20, 6:08 am, Larry Bates wrote: > Boris Du?ek wrote: > > Hello, > > > what is the use-case of parameter "start" in string's "endswith" > > method? Consider the following minimal example: > > > a = "testing" > > suffix="ing" > > a.endswith(suffix, 2) > > > Significance of "end" is obvious. But not so for "start". > > > Let's assume the "end" parameter is not used - then the function > > should simple check that the last "len(suffix)" characters of "a" are > > equal to "ing", no matter where we start (the function does not *scan* > > the string from the "start", does it?) > > Only case where it would make difference is if we had start + > > len(suffix) < len(a) (excuse possible "of-by-one" error :-) > > Then the function would never return True. But is there a real use > > case when we would test for endswith like this? (knowing that it must > > return false?) Any or all of a, start and suffix can be variable. I can't see how we could know that it must return false (except of course in the trivial and useless case that they are all constant). IMHO it's much better in general to let a string method do checks for corner cases (very efficiently) than to waste brain cells trying to work out how to write correct (but relatively very slow) Python code to avoid calling the method. > > Seems like a convenience I've never used. > > >>> a="abcdef" > >>> a.endswith('cd',2,4) > True > >>> a[2:4].endswith('cd') > > True > It's not just a convenience, and not just with endswith. In general: astring[start:end].amethod(anarg) manifests the slice as a separate temporary object, whereas astring.amethod(anarg, start, stop) does not, and should be more efficient when one is looping over a long string Granted endswith's start arg is not wildly useful, but it's orthogonal -- IMHO all string-processing functions should have a pair of start/ end args as a matter of course, unless neither start nor end is useful. Cheers, John From deets at nospam.web.de Tue Apr 24 16:17:44 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 24 Apr 2007 22:17:44 +0200 Subject: Blank rows resulting from simple csv script In-Reply-To: <1177444717.188536.20340@r3g2000prh.googlegroups.com> References: <1177444717.188536.20340@r3g2000prh.googlegroups.com> Message-ID: <5976vbF2j160eU1@mid.uni-berlin.de> Drew schrieb: > Hi all - > > I've written a simple script to read a .csv file and then write out > rows to a new file only if the value in the 4th column is a 0. Here's > the code: > > import csv > > reader = csv.reader(open('table_export.csv','rb')) > > writer = csv.writer(open('new_jazz.csv','w')) > > for row in reader: > if row[3] == '0': > writer.writerow(row) > > This is writing out the correct rows, however it is writing a blank > row between each of the rows written out. Any ideas? The modes aren't compatible - either use rb, wb or r,w Diez From carsten at uniqsys.com Tue Apr 10 10:03:06 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Tue, 10 Apr 2007 10:03:06 -0400 Subject: tuples, index method, Python's design In-Reply-To: References: Message-ID: <1176213786.3430.37.camel@dot.uniqsys.com> On Tue, 2007-04-10 at 13:21 +0000, Antoon Pardon wrote: > > But if you are so eager to rewrite, how about the following: > > > > I am using the struct module to get binary data from a file. > > Sometimes I want to skip until I find a particular binary > > number. Somewhat simplified it looks like this: > > > > > > class Itemfile: > > def __init__(self, fn): > > self.fl = open(fn) > > self.ix = 80 > > > > def nextitem(self): > > if self.ix == 80: > > self.buf = struct.unpack("80i", self.fl.read(320)) > > self.ix = 0 > > result = self.buf[self.ix] > > self.ix += 1 > > return result > > > > def skipuntil(self, val): > > done = False > > while not done: > > try: > > self.ix = self.buf.index(val, self.ix) > > done = True > > except ValueError: > > self.ix = 0 > > self.buf = struct.unpack("80i", self.fl.read(320)) > > > > > > Now I'm sure you can rewrite this without the need of tuple.index. > > It just seems odd that I have to go through extra hoops here to > > get the effect of tuple.index because struct.unpack returns its result > > in a tuple and a tuple doesn't provide index. Your data is an array. Choosing a data structure that doesn't fit your data is always going to cause pain. Instead of using struct.unpack, you should use array.array, and voila!, you get an index method. -Carsten From kyosohma at gmail.com Fri Apr 20 15:15:33 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: 20 Apr 2007 12:15:33 -0700 Subject: Newbie question regarding string.split() In-Reply-To: <1177095062.826018.63590@n59g2000hsh.googlegroups.com> References: <1177095062.826018.63590@n59g2000hsh.googlegroups.com> Message-ID: <1177096533.564349.285930@q75g2000hsh.googlegroups.com> On Apr 20, 1:51 pm, kevinliu23 wrote: > Hey guys, > > So I have a question regarding the split() function in the string > module. Let's say I have an string... > > input = "2b 3 4bx 5b 2c 4a 5a 6" > projectOptions = (input.replace(" ", "")).split('2') > print projectOptions > > ['', 'b34bx5b', 'c4a5a6'] > > My question is, why is the first element of projectOptions an empty > string? What can I do so that the first element is not an empty > string? but the 'b34bx5b' string as I expected? > > Thanks so much guys. :) The reason you have an empty string at the beginning is because you are "splitting" on a character that happens to include the first character in your string. So what you are telling Python to do is to split the beginning from itself, or to insert a blank so that it is split. Also, you shouldn't use "input" as a variable name since it is a built- in variable. One hack to make it work is to add the following line right before you print "projectOptions": projectOptions.pop(0) # pop the first element out of the list Mike From adam at atlas.st Thu Apr 19 17:29:41 2007 From: adam at atlas.st (Adam Atlas) Date: 19 Apr 2007 14:29:41 -0700 Subject: Better dict of dicts In-Reply-To: References: Message-ID: <1177018181.493650.297900@e65g2000hsc.googlegroups.com> On Apr 19, 5:24 pm, Bill Jackson wrote: > I have a dictionary of dictionaries where the keys are typically very > long tuples and repeated in each inner dictionary. The dictionary > representation is nice because it handles sparseness well...and it is > nice to be able to look up values based on a string rather than a > number. However, since my keys are quite long, I worry that I am > wasting a lot of memory. I wouldn't worry about it. Try doing hash('string_2') in the interpreter -- the output thereof is what's really being used as the key. It doesn't use up any more memory than the integer 2. From adamgarstang at googlemail.com Sat Apr 7 14:22:41 2007 From: adamgarstang at googlemail.com (Adam) Date: 7 Apr 2007 11:22:41 -0700 Subject: How to tell when a file is opened In-Reply-To: References: <1175960486.759715.317140@y80g2000hsf.googlegroups.com> Message-ID: <1175970161.126550.257090@n59g2000hsh.googlegroups.com> On Apr 7, 5:09 pm, Tim Golden wrote: > Adam wrote: > > I want to know if it possible to tell when a file is opened. However I > > don't want it to be the last access time. I want to know how many > > times a file opened so I can generate statistics of file usage. > > > I will be wanting to watch all files on a server so this will be on > > quite a large scale. So checking a directory on a loop for accesses > > won't work. > > > Maybe some way to monitor the Open Files section of Computer > > Management? > > > I check through Tim Golden's site but nothing jumped out at me. > > Any pointers would be great. > > I take it from the fact that you mention my site (and > your reference to "Computer Management") that you're > looking at Win32? It's always best to be explicit when > you're asking for help; a lot of people on this list > will be using Linux or Mac where the answers are > probably very different. > > This is no small task you've set yourself! As far as I know, > you're going to have to go down to the level of change journals > for this kind of thing. (Search for "NTFS change journal"). > > Although you might think: the filesystem knows when files are > being accessed; can't I hook into that directly? I think the > answer is: no. But I could be wrong. > > TJG Sorry about not mentioning my platform. What you mention looks promising. Will look into it. Like I said knowing the last access time is not useful as I would have to be constantly looping through the directory looking for changes. Will look into NTFS change journals when I get some spare time. Thanks for the reply. Adam From robert.kern at gmail.com Fri Apr 20 15:49:27 2007 From: robert.kern at gmail.com (Robert Kern) Date: Fri, 20 Apr 2007 14:49:27 -0500 Subject: matplotlib basic question In-Reply-To: <76C22CF3-C355-4670-90AC-02054B0B9F8F@mac.com> References: <1177016327.543985.34500@o5g2000hsb.googlegroups.com> <1177092157.763869.77600@o5g2000hsb.googlegroups.com> <76C22CF3-C355-4670-90AC-02054B0B9F8F@mac.com> Message-ID: Tommy Grav wrote: > On Apr 20, 2007, at 2:44 PM, Robert Kern wrote: >> Colin J. Williams wrote: >> >>> I'm not sure that scipy has been updated to Python 2.5 >> ? scipy certainly works with 2.5. Are you referring to something >> else perhaps? > > A side question: Is there any plans of updating the scipy.org > Superpack bundle > for Mac OS X to work with 2.5? You would have to ask Chris Fonnesbeck. It's not an "official" binary inasmuch as scipy has official binaries. -- 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 bbxx789_05ss at yahoo.com Mon Apr 16 06:05:07 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: 16 Apr 2007 03:05:07 -0700 Subject: string methods of a str subclass In-Reply-To: References: Message-ID: <1176717907.294258.222800@n59g2000hsh.googlegroups.com> On Apr 16, 3:28 am, "Daniel Nogradi" wrote: > I would expect all methods operating on a string instance > and returning another string instance Ok, then this: class A(object): def __init__(self, s): self.s = s def strip(self): return self.s class mystr(A): pass x = mystr("x") print isinstance(x, mystr) print isinstance(x.strip(), mystr) "x" is a string, and that is what gets passed to the base class's __init__ method, and that is what strip() operates on. From fumanchu at amor.org Tue Apr 17 11:53:46 2007 From: fumanchu at amor.org (fumanchu) Date: 17 Apr 2007 08:53:46 -0700 Subject: The smallest and largest values of numeric types In-Reply-To: References: Message-ID: <1176825226.633555.85860@d57g2000hsg.googlegroups.com> On Apr 17, 7:12 am, t... at finland.com wrote: > How can I determine the smallest and largest values > of numeric types (for example int) possible in my > system? I think there exists a function for this task > but I don't know it. This should work for ints: import sys print sys.maxint For floats, just try until it fails. This is from http://projects.amor.org/geniusql/browser/trunk/geniusql/adapters.py#l41 # Determine max binary digits for float on this system. Crude but effective. maxfloat_digits = 2 while True: L = (2 ** (maxfloat_digits + 1)) - 1 if int(float(L)) != L: break maxfloat_digits += 1 Note this will get you the number of binary digits, which is not a simple matter to translate to maximum and minimum values, since floats are inexact numerics. IEEE 754 floats are stored with one bit for the sign, some bits for the exponent (which is biased) and some for the significand. See http://babbage.cs.qc.edu/IEEE-754/32bit.html for a visual example of how it works. Robert Brewer System Architect Amor Ministries fumanchu at amor.org From anton.vredegoor at gmail.com Wed Apr 25 07:12:36 2007 From: anton.vredegoor at gmail.com (Anton Vredegoor) Date: Wed, 25 Apr 2007 13:12:36 +0200 Subject: Would You Write Python Articles or Screencasts for Money? In-Reply-To: References: <462DCCE6.9060908@taupro.com> <1hx2dvj.10ek1v51noh1otN%aleax@mac.com> Message-ID: Anton Vredegoor wrote: > It's about as ridiculous as proving that a stiff parrot is dead by > grabbing it by the legs and repeatedly hitting it's head on the counter. Or to write "it's" where its is more appropriate. A. From steve at holdenweb.com Sat Apr 28 11:21:49 2007 From: steve at holdenweb.com (Steve Holden) Date: Sat, 28 Apr 2007 11:21:49 -0400 Subject: webbrowser.open works in IDLE and cmd shell but not from cygwin prompt In-Reply-To: <1177704571.370848.101970@r3g2000prh.googlegroups.com> References: <1177646975.285805.106920@b40g2000prd.googlegroups.com> <1177704571.370848.101970@r3g2000prh.googlegroups.com> Message-ID: Gregory Bloom wrote: > On Apr 27, 3:12 am, Michael Hoffman wrote: >>> And, more to the point, how can I use webbrowser from scripts launched under >> > cygwin? >> >> If you're using native Windows Python as you seem to be, try >> webbrowser.get("windows-default").open_new(url) >> >> If you want to use Cygwin Python instead, I submitted a patch more than >> 1.5 years ago to allow it, but it hasn't been reviewed: >> >> http://python.org/sf/1244861 >> -- >> Michael Hoffman > > > Awesome! That works perfectly. Thanks. > > Interestingly when I tried this under Cygwin I got the links browser displaying the material from the given URL. That's different enough that I might keep it like that.:-) regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden ------------------ Asciimercial --------------------- Get Python in your .sig and on the web. Blog and lens holdenweb.blogspot.com squidoo.com/pythonology tag items: del.icio.us/steve.holden/python All these services currently offer free registration! -------------- Thank You for Reading ---------------- From http Sun Apr 15 15:10:53 2007 From: http (Paul Rubin) Date: 15 Apr 2007 12:10:53 -0700 Subject: Calling private base methods References: <1176374675.347453.89340@n76g2000hsh.googlegroups.com> <1176404325.211501.26610@w1g2000hsg.googlegroups.com> <1176435087.708516.66470@o5g2000hsb.googlegroups.com> <1176650850.211487.294690@y80g2000hsf.googlegroups.com> Message-ID: <7x7isdwj0i.fsf@ruckus.brouhaha.com> Duncan Booth writes: > The problem is that when people design interfaces they don't (and > cannot) know all the situations in which the code is going to be used in > the future. Clearly separating the published interface from the > implementation details is a good thing, but physically preventing access to > those details is IMHO a bad thing. The idea is to make the implementation details independent from the calling program. For example, I'm using a library now that does something highly CPU intensive. To speed up the application, I may put the library on a completely separate computer, so that the published API exposed to the caller becomes a wrapper for a network client, and all those library implementation details are on the other machine. That's the ultimate in physical access prevention, there's good reason to do it, and it completely breaks if the calling program is using anything except the published API. From robert.rawlins at thinkbluemedia.co.uk Wed Apr 11 09:31:30 2007 From: robert.rawlins at thinkbluemedia.co.uk (Robert Rawlins - Think Blue) Date: Wed, 11 Apr 2007 14:31:30 +0100 Subject: SOAP Webservices and Python Message-ID: <005001c77c3d$b7887090$269951b0$@rawlins@thinkbluemedia.co.uk> Hello Chaps, I'm pretty new to the world of Python, but I'm slowly getting my head around things, and on today's agenda I'm looking at consuming SOAP web services. I've got an Adobe ColdFusion application which I've written that publishes the web service that I'm looking to consume, but I'm at a loss as to where to start. I'm running Python 2.4.4 on a Debian Linux distribution, in case that makes any difference. I thought I'd start with something very simple, just a service I pass an ID to and it'll return a Boolean value. Here is the web service link. http://www.yourblue.co.uk/webservicetester/ip.cfc?wsdl I'd be interested to hear any thoughts on the best way to go about this, or perhaps some working code examples of consuming this service. I will always have the WSDL file available to me by appending the ?wsdl to the URL, I've heard this makes life easier. like I say, I'm pretty new so it's perfectly ok for you guys to assume I'm an idiot and talk to me as if I were a small child :-D Thanks, Rob -------------- next part -------------- An HTML attachment was scrubbed... URL: From bdeck at user.sourceforge.com Thu Apr 19 21:32:43 2007 From: bdeck at user.sourceforge.com (caddit) Date: Fri, 20 Apr 2007 11:32:43 +1000 Subject: PythonD 2.4.2 for older Windows / DOS / DJGPP References: <46279af8$0$4610$61c65585@un-2park-reader-01.sydney.pipenetworks.com.au> Message-ID: <4628183d$0$4606$61c65585@un-2park-reader-01.sydney.pipenetworks.com.au> Steve Holden wrote: > caddit wrote: >> Hello. >> >> There has been some confusion as to the current version of the python >> programming language available for DOS. >> >> This is partially due to incorrect information kept on python.org, that >> says "python2.2.1 available for DOS". The actual version is currently >> 2.4.2. >> >> I am also happy to announce that a second release of PythonD. >> Additionally, there are many fine module libraries hat have been made >> available including Python-opengl and curses. >> >> The URL for PythonD has moved. >> It is now http://www.caddit.net/pythond >> >> not that this is NOT the same as http://www.caddit.net/pythond.php, which >> it was formerly. Please update your bookmarks. It would also be nice if >> someone else could raise a ticket to have python.org website updated. >> > Submitted as > > http://pydotorg.python.org/pydotorg/ticket/423 > > Please note: it would have been helpful if you'd given the URL of the > offending page! There is a "report website bug" link on each page of the > python.org web site, though at present you have to email someone to get > posting privileges (this is an anti-spam measure). > > regards > Steve Thanks for this Steve. I notice the ticket is already closed. When should I see the changes appear? Regards, Ben From steve at holdenweb.com Thu Apr 26 08:30:46 2007 From: steve at holdenweb.com (Steve Holden) Date: Thu, 26 Apr 2007 08:30:46 -0400 Subject: Scheduler Module Help In-Reply-To: <25547.4246260293$1177577452@news.gmane.org> References: <25547.4246260293$1177577452@news.gmane.org> Message-ID: Robert Rawlins - Think Blue wrote: > Hello Guys, > > > > I?m using the sched module to create a set of functions that run every > 10 or 20 minutes whilst the application is running, however it would > seem that the moment I run scheduler.run() it prevents any other > operations in my application from running, its sits dormant until it > runs the scheduled functions. > > > > Any ideas on what might be the root of this issue? > The fact that you are calling a routine that won't return until there is nothing left to schedule. You might want to think about using a threading.thread to run this part of your process, or making it some kind of background process. regards Steve -- Steve Holden +1 571 484 6266 +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 __peter__ at web.de Sun Apr 22 05:14:08 2007 From: __peter__ at web.de (Peter Otten) Date: Sun, 22 Apr 2007 11:14:08 +0200 Subject: Namespaces/introspection: collecting sql strings for validation References: <1921780.hifcbgjtIO@beaureve.gmx.net> Message-ID: Martin Drautzburg wrote: > I would like to validate sql strings, which are spread all over the > code, i.e. I run ("prepare") them against a database to see if it happy > with the statements. Spelling errors in sql have been a major pain for > me. > > The statements will not be assembled from smaller pieces, but they will > not neccessarily be defined at module level. I could live with class > level, but method level would be best. And I definitely don't want to > parse the source file, but I am willing to mark the strings so it is > easier to tell sql from non-sql. > > So the code will look like this > > class Foo:(...): > def aQuery(...): > stmt = """ > -- checkSql > select 1 from dual > """ > executeQuery() > > at the end of the file I would like to write something like > if (...): > validateSql() > > The validateSql() is the problem. It would be imported from elsewhere. > and has to do some serious magic. It would have to lookup its caller's > module, find all the classes (and methods, if we go that far) extract > the constants, check if any of them are an SQL statement and validate > it. > > The problem is the first part: how can I lookup the callers module and > the classobjs defined in there? Or finding any constant strings in the > caller's module would also be just fine. Or is there a completely > different way to do such a thing? Since all strings are constants you could just tokenize the source code: def strings(filename): with open(filename, "rU") as instream: for t in tokenize.generate_tokens(instream.readline): if t[0] == token.STRING: yield eval(t[1]) def validateSQL(filename=None): if filename is None: # by default operate on the calling module filename = sys._getframe(1).f_globals["__file__"] for s in strings(filename): print "validating", repr(s) Another option would be to mark SQL statements similar to gettext by enclosing them in a function call sql = SQL("select * from...") and then defining SQL() as either a no-op in production or an actual validation while you are debugging. Even simpler and safer would be to always validate once: def SQL(sql, checked=set()): if sql in checked: return True if not valid_sql(sql): raise ValueError checked.add(sql) return sql Peter From nobody at invalid.com Wed Apr 18 12:20:20 2007 From: nobody at invalid.com (Erik Johnson) Date: Wed, 18 Apr 2007 10:20:20 -0600 Subject: subprocess "handle is invalid" error References: <132cdrpqsmnvpa7@corp.supernews.com> Message-ID: <4626450b$1@nntp.zianet.com> "Grant Edwards" wrote in message news:132cdrpqsmnvpa7 at corp.supernews.com... > How does one troubleshoot errors that happen three layers deep > in the subprocess module? I think the problem is more likely in how your py2exe is getting bundled, rather than any real problem with the subprocess module. I have been on the py2exe email list but not really paying much attention... If I recall correctly, there are some special considerations when using gnuplot with py2exe? I would suggest digging through the py2exe email archives to see if you can locate emails on that subject (one copy of which I believe can be found at: http://sourceforge.net/mailarchive/forum.php?forum_name=py2exe-users), and if that doesn't work, to direct your question to the py2exe users list at: py2exe-users at lists.sourceforge.net (I believe the current home page of the py2exe project is at: http://sourceforge.net/projects/py2exe/) Hope that helps, -ej From steve at REMOVEME.cybersource.com.au Tue Apr 3 02:04:02 2007 From: steve at REMOVEME.cybersource.com.au (Steven D'Aprano) Date: Tue, 03 Apr 2007 16:04:02 +1000 Subject: Testing functions via command line References: <1175578346.845789.119590@p15g2000hsd.googlegroups.com> Message-ID: On Mon, 02 Apr 2007 22:32:26 -0700, pelon wrote: > There must be a couple of lines that will replace the following: Yes, because otherwise the terrorists will have won. *wink* > From the shell command line I wanted to send data to a specific > function inside my module and execute that function in order to test > it separately from the rest of the module. For manual testing, why don't you do your testing from the interactive Python shell? e.g. $ python Python 2.3.4 (#1, Oct 11 2006, 06:18:43) [GCC 3.4.6 20060404 (Red Hat 3.4.6-3)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> >>> import my_module >>> my_module.function('something') # test the function Am I missing something? Also, while your self-test code is very ingenious, perhaps you would be better off using standard testing modules. Perhaps you should use the doctest and/or unittest modules. -- Steven D'Aprano From bdesth.quelquechose at free.quelquepart.fr Thu Apr 5 19:41:45 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Fri, 06 Apr 2007 01:41:45 +0200 Subject: grandparent method with super In-Reply-To: <1175804992.189096.225300@d57g2000hsg.googlegroups.com> References: <20070405161939.694d51a1@localhost> <1175804992.189096.225300@d57g2000hsg.googlegroups.com> Message-ID: <46158043$0$7512$426a74cc@news.free.fr> kyosohma at gmail.com a ?crit : > On Apr 5, 3:19 pm, Martin Manns wrote: > >>Hi, >> >>I have a class structure as follows and I would like to invoke the >>method A.m() from D.m >> >>class A(object): >> def m(self): >>class B(A): >> def m(self): >>class C(A): >> def m(self): >>class D(B,C): >> def m(self): >> # Call A.m with super? >> (snip) > I'm not sure if this is what you want, but it's my best guess: > > class A(object): > def m(self): > print "I'm the original" > class B(A): > def m(self): > print 'B class here' > class C(A): > def m(self): > print 'C class here' > class D(B,C): > def m(self): > x = A() > x.m() Err... This will call A.m(x), not A.m(self). The correct thing to is: class D(B,C): def m(self): A.m(self) But this doesn't solve the OP's problem, which is to not hard-code the concrete base class to call (hence the question about how to do this using super) From joshua at eeinternet.com Mon Apr 2 20:18:56 2007 From: joshua at eeinternet.com (Joshua J. Kugler) Date: Mon, 02 Apr 2007 16:18:56 -0800 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> <1hvqae5.1alie2515sbssfN%aleax@mac.com> <460c01df$0$16410$88260bb3@free.teranews.com> <1hvr2it.jmrhe215gail1N%aleax@mac.com> Message-ID: <461190fe$0$16311$88260bb3@free.teranews.com> On Thursday 29 March 2007 17:58, Alex Martelli wrote: > Sure, pydoc (which help calls under the code) does that, with a nice mix > of inspect, os, and pkgutil.iter_modules calls. pkgutil.iter_modules > may in fact be most of what you need: > >>>> help(pkgutil.iter_modules) > Help on function iter_modules in module pkgutil: > > iter_modules(path=None, prefix='') > Yields (module_loader, name, ispkg) for all submodules on path, > or, if path is None, all top-level modules on sys.path. > > 'path' should be either None or a list of paths to look for > modules in. > > 'prefix' is a string to output on the front of every module name > on output. OK, that looks nice...but what version of Python is that? http://docs.python.org/lib/module-pkgutil.html only shows one function (and that's 2.5) and my python 2.4 installation is similarly lacking an iter_modules() function for the pkgutil module. Is this a 2.6 thing? Suppose I could just copy the code from here: http://mail.python.org/pipermail/python-checkins/2006-April/051452.html and add it to my module. :) Thanks for the pointer! 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 nospam at invalid.com Fri Apr 13 14:20:23 2007 From: nospam at invalid.com (Jack) Date: Fri, 13 Apr 2007 11:20:23 -0700 Subject: Python editor/IDE on Linux? Message-ID: I wonder what everybody uses for Python editor/IDE on Linux? I use PyScripter on Windows, which is very good. Not sure if there's something handy like that on Linux. I need to do some development work on Linux and the distro I am using is Xubuntu. From manuel.graune at koeln.de Fri Apr 6 03:23:53 2007 From: manuel.graune at koeln.de (Manuel Graune) Date: Fri, 06 Apr 2007 09:23:53 +0200 Subject: Objects, lists and assigning values References: Message-ID: Hello Gabriel, hello William, thanks to both of you for your answers. I seem to need a better book about python. Regards, Manuel "Gabriel Genellina" writes: > class new_class(object): > def __init__(self, internal_list=None): > if internal_list is None: > internal_list = [] > self.internal_list= internal_list > > See > http://effbot.org/pyfaq/why-are-default-values-shared-between-objects.htm > > -- > Gabriel Genellina > -- A hundred men did the rational thing. The sum of those rational choices was called panic. Neal Stephenson -- System of the world http://www.graune.org/GnuPG_pubkey.asc Key fingerprint = 1E44 9CBD DEE4 9E07 5E0A 5828 5476 7E92 2DB4 3C99 From soyouthinkimgonnalikethis at hotmail.com Sat Apr 7 14:13:19 2007 From: soyouthinkimgonnalikethis at hotmail.com (Eric Price) Date: Sat, 07 Apr 2007 13:13:19 -0500 Subject: Pass A Var To a Python Script? Message-ID: Hi; How do I pass a variable to a python script? Something like this (which doesn't work): ./test.py?var=hello_world TIA, Eric _________________________________________________________________ Mortgage refinance is Hot. *Terms. Get a 5.375%* fix rate. Check savings https://www2.nextag.com/goto.jsp?product=100000035&url=%2fst.jsp&tm=y&search=mortgage_text_links_88_h2bbb&disc=y&vers=925&s=4056&p=5117 From draghuram at gmail.com Thu Apr 12 10:45:01 2007 From: draghuram at gmail.com (draghuram at gmail.com) Date: 12 Apr 2007 07:45:01 -0700 Subject: reading from sys.stdin In-Reply-To: <1176366058.261031.111870@p77g2000hsh.googlegroups.com> References: <1176366058.261031.111870@p77g2000hsh.googlegroups.com> Message-ID: <1176389101.887799.106800@e65g2000hsc.googlegroups.com> On Apr 12, 4:20 am, "7stud" wrote: > I can't break out of the for loop in this example: > > ------ > import sys > > lst = [] > for line in sys.stdin: > lst.append(line) > break > > print lst > ----------- You may want to look at a related issue: http://www.python.org/sf/1633941 Thanks, Raghu. From collinstocks at gmail.com Thu Apr 5 14:26:36 2007 From: collinstocks at gmail.com (Collin Stocks) Date: Thu, 5 Apr 2007 14:26:36 -0400 Subject: Looping issues In-Reply-To: <1175797130.561115.147450@p77g2000hsh.googlegroups.com> References: <1175796069.501575.157410@w1g2000hsg.googlegroups.com> <1175797130.561115.147450@p77g2000hsh.googlegroups.com> Message-ID: <4c0048df0704051126y15cabaees21aa5bc4ec50ea6@mail.gmail.com> That *shouldn't* be the problem, since files are iterable On 5 Apr 2007 11:18:50 -0700, anglozaxxon wrote: > > On Apr 5, 2:01 pm, brochu... at gmail.com wrote: > > What I am trying to do is compare two files to each other. > > > > If the 2nd file contains the same line the first file contains, I want > > to print it. I wrote up the following code: > > > > correct_settings = open("C:\Python25\Scripts\Output > > \correct_settings.txt","r") > > current_settings = open("C:\Python25\Scripts\Output\output.txt","r") > > > > for line in correct_settings: > > for val in current_settings: > > if val == line: > > print line + " found." > > > > correct_settings.close() > > current_settings.close() > > > > For some reason this only looks at the first line of the > > correct_settings.txt file. Any ideas as to how i can loop through each > > line of the correct_settings file instead of just looking at the first? > > Instead of "for line in correct_settings", try "for line in > correct_settings.readlines()". > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From carsten at uniqsys.com Wed Apr 18 10:02:10 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Wed, 18 Apr 2007 10:02:10 -0400 Subject: looking for library to read ppt files In-Reply-To: <1176903051.777820.216750@n59g2000hsh.googlegroups.com> References: <1176747406.722209.126900@w1g2000hsg.googlegroups.com> <1176756401.108945.230880@y5g2000hsa.googlegroups.com> <1176903051.777820.216750@n59g2000hsh.googlegroups.com> Message-ID: <1176904930.3424.19.camel@dot.uniqsys.com> On Wed, 2007-04-18 at 06:30 -0700, Aljosa Mohorovic wrote: > > > Not really a Python question but Google turned up: > it is a python question. i'm not looking for a program, i'm looking > for a library. > my goal is to convert ppt to jpegs but later i wish to convert to swf > and maybe implement animations > > > I suppose you could also use the win32 module and the COM object to > > grab the info from the slide and then use the PIL module to create a > > jpeg. Sounds like a lot of head banging to me, but it might be an > > interesting project. > i can't use win32 because it should work on linux since it will be > used as server-side application. How about running a headless OpenOffice instance and remote-controlling it with pyuno: http://udk.openoffice.org/python/python-bridge.html -Carsten From jstroud at mbi.ucla.edu Tue Apr 24 00:00:21 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Mon, 23 Apr 2007 21:00:21 -0700 Subject: Python Widget to read in user input box in blog In-Reply-To: <1177379827.873957.47760@n76g2000hsh.googlegroups.com> References: <1177379827.873957.47760@n76g2000hsh.googlegroups.com> Message-ID: ecpbm765 at gmail.com wrote: > Hey, > > I am helping to develop a project that displays images based on user > input. One possible way of implementing this is via a widget that > when it is run, would read in the users input from an input text field > (probably from a blog), and replace it with the HTML that would > display those images. This is more a proof of concept, so really all > I am wondering is if there is a good way in Python to read in the text > the user has typed and change it before the user hits submit? > > Thanks > You can bind KeyRelease, etc. like such: #! /usr/bin/env python from Tkinter import * from ScrolledText import ScrolledText def format(t): return t.replace('.','!') def dobind(tin, tout): def doit(e=None): tout['state'] = NORMAL tout.delete('1.0', END) newtext = format(tin.get('1.0', END).strip()) tout.insert(END, newtext) tout['state'] = DISABLED return doit def main(): tk = Tk() textin = ScrolledText(tk) textin.pack(expand=NO, fill=X) textout = ScrolledText(tk) textout['state'] = DISABLED textout.pack(expand=NO, fill=BOTH) textin.bind('', dobind(textin, textout)) tk.mainloop() if __name__ == "__main__": main() Etc. includes copy and paste events with mouse. James From sgeiger at ncee.net Sun Apr 1 22:52:23 2007 From: sgeiger at ncee.net (Shane Geiger) Date: Sun, 01 Apr 2007 21:52:23 -0500 Subject: How can i compare a string which is non null and empty In-Reply-To: <1310puahjesd9b9@corp.supernews.com> References: <1175469766.979636.65020@e65g2000hsc.googlegroups.com> <1310puahjesd9b9@corp.supernews.com> Message-ID: <46106FE7.2000705@ncee.net> It is probably worth noting that the example is not executable code: str() is a function. sgeiger3 at nycsr0002:~$ python Python 2.4.4c0 (#2, Jul 30 2006, 15:43:58) [GCC 4.1.2 20060715 (prerelease) (Debian 4.1.1-9)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> if str: print "whoah, str is a function!" ... whoah, str is a function! >>> /me pines for the day when all examples are executable code Grant Edwards wrote: > On 2007-04-01, Plissken.s at gmail.com wrote: > > >> how can i compare a string which is non null and empty? >> > [...] > >> In java,I do this: >> if (str != null) && (!str.equals("")) .... >> >> how can i do that in python? >> > > If you want to litterally do that, it's > > if (str != None) and (str != ""): > > > However, the standard idiom for doing that in Python is > > if str: > > > > -- 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 steve at holdenweb.com Sat Apr 28 11:18:24 2007 From: steve at holdenweb.com (Steve Holden) Date: Sat, 28 Apr 2007 11:18:24 -0400 Subject: More urllib timeout issues. In-Reply-To: References: Message-ID: John Nagle wrote: > I thought I had all the timeout problems with urllib worked around, > but no. > > socket.setdefaulttimeout is useful, but not always effective. > I'm setting that to 15 seconds. > If the host end won't open the connection within 15 seconds, > urllib times out. But if the host end opens the connection, > then never sends anything, urllib waits for many minutes before > timing out. Any idea how to deal with this? And don't just > say "use urllib2" unless you KNOW it works better there and > can explain why. I finally have M2Crypto and urllib playing > well together, and don't want to mess with that. > > For some wierd reason, several UK academic sites have this > behavior, including "soton.ac.uk". If you try to open that > in a browser, the browser just sits there, and eventually, > after several minutes, displays "The site is taking too > long to respond". > > What's the current status in this area? Some patches to sockets > were proposed a while back. There's a long history of trouble > in this area, and some fixes, but nothing that just works. > The sockets module has two timeout settings (socket.setdefaulttimeout and > sock.settimeout, the M2Crypto module has two (sock.set_socket_read_timeout and > sock.set_socket_write_timeout), and none of them play well together > or with the urllib/urllib2/httplib level and the blocking/non blocking > socket distinction. > > What we really should have is something like this: > > Sockets should have > set_socket_connect_timeout > set_socket_read_timeout > set_socket_write_timeout > > which set an upper limit on how long a socket can go with a request for > a connect, read or write pending but without progress on the connection. > This needs to be independent of select poll timeouts, and these timeouts > should work on blocking sockets. > > The existing socket function > > settimeout > > should set all of the above, and > > socket.setdefaulttimeout > > should set the default value for settimeout to be used on new sockets. > > SSL and M2Crypto, which wrap socket functionality, > should understand all the above functions. > > HTTPlib, urllib, and urllib2 objects should understand > > settimeout > > Making the connect/read/write timeout distinction at that level > probably isn't worth the trouble. > > Then we'd have a reasonable network timeout system. > We have about half of the above now, but it's not consistent. > > Comments? > The only comments I'll make for now are 1) There is work afoot to build timeout arguments into network libraries for 2.6, and I know Facundo Batista has been involved, you might want to Google or email Facundo about that. 2) The main reason why socket.setdefaulttimeout is unsuitable for many purposes is its thread-unsafe property, so all threads must use the same default timeout or have it randomly change according to the whim of hte last thread to alter it. 3) This is important and sensible work and if properly followed through will likely lead to serious quality improvements in the network libraries. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden ------------------ Asciimercial --------------------- Get Python in your .sig and on the web. Blog and lens holdenweb.blogspot.com squidoo.com/pythonology tag items: del.icio.us/steve.holden/python All these services currently offer free registration! -------------- Thank You for Reading ---------------- From exarkun at divmod.com Tue Apr 10 10:57:04 2007 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Tue, 10 Apr 2007 10:57:04 -0400 Subject: Why is __getslice__ still implemented? In-Reply-To: Message-ID: <20070410145704.18920.759676670.divmod.quotient.10064@ohm> On Tue, 10 Apr 2007 08:35:56 -0600, Steven Bethard wrote: >Torsten Bronger wrote: >> Hall?chen! >> >> According to , >> __getslice__ is deprecated. At the moment, I derive an own class >> from unicode and want to implement my own slicing. I found that I >> have to override __getslice__ since __getitem__ isn't called when I >> have something like my_instance[a:b] in my code. >> >> According to >> , this may >> have efficiency reasons, however, I agree with >> news:1102645919.114898.139820 at f14g2000cwb.googlegroups.com that this >> is quite confusing. It forces people to implement a deprecated >> function after all. I think the docs should say that you still have >> to override __getslice__ when subclassing from a built-in type, >> unless I really don't understand the issue correctly. > >Yes, you do still need to implement __getslice__ if you're subclassing >a class (like unicode or list) which provides it. The __getslice__ >method can't be removed entirely for backwards compatibility reasons >(though it is being removed in Python 3000). If you have a specific >suggestion for what doc should be updated and how, that would be >helpful. Please post it to: Why does this mean that the unicode type has to implement __getslice__? Jean-Paul From bdesth.quelquechose at free.quelquepart.fr Thu Apr 5 15:56:49 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Thu, 05 Apr 2007 21:56:49 +0200 Subject: Why NOT only one class per file? In-Reply-To: <2O9Rh.24647$uo3.24013@newssvr14.news.prodigy.net> References: <1175721799.714907.52770@o5g2000hsb.googlegroups.com> <46142acc$0$7532$426a34cc@news.free.fr> <4614b40e$0$26843$426a74cc@news.free.fr> <1175778276.603838.86500@l77g2000hsb.googlegroups.com> <2O9Rh.24647$uo3.24013@newssvr14.news.prodigy.net> Message-ID: <46154b8c$0$14532$426a34cc@news.free.fr> John Nagle a ?crit : > Nate Finch wrote: > >> I think you're all going about this the wrong way. There's no reason >> to *always* have one class per file. However, there's also no reason >> to have 1600 lines of code and 50 classes in one file either. > > > It's really an operating system thing. We think of programs as > living in text files, manipulated by programs which are basically text > editors. Python has that implicit assumption. There have been > systems that didn't work that way, in which the program source was > manipulated within the language environment, in a more structured > fashion. Smalltalk, LISP, and (wierdly) Forth environments have been > built that way. But it never really caught on. > > The assumption that programs are text files is deeply embedded in > programming culture, so deeply that it's seldom questioned. Programs > are the last refuge of non-rich media. You can't even embed an image > in your program; it has to be in some completely separate file. Having source code as text files may not be such a bad thing. Diffing, grepping and versioning binary files is not that easy... > Interestingly, PHP breaks this model; PHP programs are web pages. Err... Actually, "web pages" *are* text files. And FWIW, in most php programs (at least the clean ones), the application logic is in separate files, and the 'rendering' code (views, templates, call them what you like) are seldom full html documents. From mensanator at aol.com Sun Apr 8 12:47:56 2007 From: mensanator at aol.com (mensanator at aol.com) Date: 8 Apr 2007 09:47:56 -0700 Subject: How do I get a slice of a string held in a tuple? In-Reply-To: <25ine4-rvt.ln1@Hedley.internal.thethurmans.com> References: <25ine4-rvt.ln1@Hedley.internal.thethurmans.com> Message-ID: <1176050876.835238.68560@d57g2000hsg.googlegroups.com> On Apr 8, 11:34?am, Lorenzo Thurman wrote: > I have tuple which hold a string in tup[0]. I want to get a slice of > that string. I thought I would do something like: > tup[0][start:end] > But this fails. No, it doesn't. >>> a = ('abcdefg','hijkl') >>> a[0] 'abcdefg' >>> a[0][1:2] 'b' > How do I go about it? Do it correctly. Post your actual example that fails and the related error message. Possibnly your indexes were out of range. > I googled this and found a couple > of references, but no solution. Well, there wouldn't be a solution to a non-existent problem, would there? > TIA From bcwhite at pobox.com Thu Apr 19 13:46:04 2007 From: bcwhite at pobox.com (bcwhite at pobox.com) Date: 19 Apr 2007 10:46:04 -0700 Subject: Future Python Gui? In-Reply-To: <46275BED.3050808@codebykevin.com> References: <1176859699.906386.326720@b75g2000hsg.googlegroups.com> <1176923448.998078.170760@e65g2000hsc.googlegroups.com> <46267C84.8040505@codebykevin.com> <1176941169.750013.216660@e65g2000hsc.googlegroups.com> <4caef$4626b6f4$4275d90a$19707@FUSE.NET> <1176952141.007295.272000@e65g2000hsc.googlegroups.com> <46275BED.3050808@codebykevin.com> Message-ID: <1177004764.222101.185880@l77g2000hsb.googlegroups.com> > It shouldn't change at all. I use Frame for Tkinter frames and > Tile.Frame for Tile frames, since a lot of the widgets have the same > names. Here's a sample: > > from Tkinter import * > import Tile Thanks for all the info. I'm a little confused about using both Tkinter and Tile at the same time. Do the calls to Tkinter now get themed? What is the benefit of calling similar widgets for both modules within the same code? Why wouldn't I call everything via Tile? (i.e. "from Tile import *" and not import Tkinter at all) Thanks! -- Brian From ptmcg at austin.rr.com Fri Apr 13 12:35:02 2007 From: ptmcg at austin.rr.com (Paul McGuire) Date: 13 Apr 2007 09:35:02 -0700 Subject: Problem with algorithm In-Reply-To: References: <1176434160.047703.214600@q75g2000hsh.googlegroups.com> <1176434937.258002.162220@p77g2000hsh.googlegroups.com> <1176448576.047996.12930@d57g2000hsg.googlegroups.com> <1176473989.420067.190970@l77g2000hsb.googlegroups.com> Message-ID: <1176482102.497485.108570@o5g2000hsb.googlegroups.com> On Apr 13, 10:49 am, Carsten Haese wrote: > On Fri, 2007-04-13 at 10:22 -0500, Michael Bentley wrote: > > On Apr 13, 2007, at 9:19 AM, Paul McGuire wrote: > > > > If you just expand the length to five million* or so, one of those > > > strings will contain all the works of Shakespeare. > > > Not likely, even with a tiny sampling of the works of Shakespeare: > > Actually, the OP seems to be interested in generating *all* strings of > length N. If you generate the set of *all* strings of 5 million > characters length, at least one of them will contain all works of > Shakespeare. That statement is utterly true and utterly impractical, > which is, of course, the point of Paul's joke. > > -Carsten But even random typing will *eventually* get there (where "eventually" = several gazillion times the age of the universe) - see http://en.wikipedia.org/wiki/Infinite_monkey_theorem. -- Paul If I see farther, it is because I stand on the shoulders of an infinite number of monkeys. From george.sakkis at gmail.com Sun Apr 22 18:56:43 2007 From: george.sakkis at gmail.com (George Sakkis) Date: 22 Apr 2007 15:56:43 -0700 Subject: Namespaces/introspection: collecting sql strings for validation In-Reply-To: <1921780.hifcbgjtIO@beaureve.gmx.net> References: <1921780.hifcbgjtIO@beaureve.gmx.net> Message-ID: <1177282603.660437.181440@e65g2000hsc.googlegroups.com> On Apr 21, 4:16 pm, Martin Drautzburg wrote: > I would like to validate sql strings, which are spread all over the > code, i.e. I run ("prepare") them against a database to see if it happy > with the statements. Spelling errors in sql have been a major pain for > me. > > The statements will not be assembled from smaller pieces, but they will > not neccessarily be defined at module level. I could live with class > level, but method level would be best. And I definitely don't want to > parse the source file, but I am willing to mark the strings so it is > easier to tell sql from non-sql. > > So the code will look like this > > class Foo:(...): > def aQuery(...): > stmt = """ > -- checkSql > select 1 from dual > """ > executeQuery() > > at the end of the file I would like to write something like > if (...): > validateSql() > > The validateSql() is the problem. It would be imported from elsewhere. > and has to do some serious magic. It would have to lookup its caller's > module, find all the classes (and methods, if we go that far) extract > the constants, check if any of them are an SQL statement and validate > it. > > The problem is the first part: how can I lookup the callers module and > the classobjs defined in there? Or finding any constant strings in the > caller's module would also be just fine. Or is there a completely > different way to do such a thing? Yes, there is: use an ORM to do the SQL generation for you. Check out SQLAlchemy, it will buy you much more than what you asked for. George From isaac.rodriguez at comcast.net Wed Apr 18 09:26:40 2007 From: isaac.rodriguez at comcast.net (Isaac Rodriguez) Date: 18 Apr 2007 06:26:40 -0700 Subject: What makes an iterator an iterator? In-Reply-To: References: Message-ID: <1176902800.461035.284490@q75g2000hsh.googlegroups.com> > > class Parrot(object): > def __iter__(self): > return self > def __init__(self): Typo right here!!!! > self.next = self._next() write: self.next = self._next no parenthesis. > def _next(self): > for word in "Norwegian Blue's have beautiful plumage!".split(): > yield word > See previous explanation. thanks, - Isaac. From michael at jedimindworks.com Sun Apr 15 20:57:36 2007 From: michael at jedimindworks.com (Michael Bentley) Date: Sun, 15 Apr 2007 19:57:36 -0500 Subject: how to strip the domain name in python? In-Reply-To: <1176672270.932679.283230@d57g2000hsg.googlegroups.com> References: <1176526155.679721.159870@l77g2000hsb.googlegroups.com> <1176564977.498635.171600@n59g2000hsh.googlegroups.com> <1176654669.737355.78300@y5g2000hsa.googlegroups.com> <1176672270.932679.283230@d57g2000hsg.googlegroups.com> Message-ID: <19C3B41E-B67E-4A9B-8FC2-1222EF25F1AD@jedimindworks.com> On Apr 15, 2007, at 4:24 PM, Marko.Cain.23 at gmail.com wrote: > On Apr 15, 11:57 am, Marc 'BlackJack' Rintsch wrote: >> In <1176654669.737355.78... at y5g2000hsa.googlegroups.com>, >> Marko.Cain.23 >> wrote: >> >> >> >>> On Apr 14, 10:36 am, Marko.Cain... at gmail.com wrote: >>>> On Apr 14, 12:02 am, Michael Bentley >>>> wrote: >> >>>>> On Apr 13, 2007, at 11:49 PM, Marko.Cain... at gmail.com wrote: >> >>>>>> Hi, >> >>>>>> I have a list of url names like this, and I am trying to strip >>>>>> out the >>>>>> domain name using the following code: >> >>>>>> http://www.cnn.com >>>>>> www.yahoo.com >>>>>> http://www.ebay.co.uk >> >>>>>> pattern = re.compile("http:\\\\(.*)\.(.*)", re.S) >>>>>> match = re.findall(pattern, line) >> >>>>>> if (match): >>>>>> s1, s2 = match[0] >> >>>>>> print s2 >> >>>>>> but none of the site matched, can you please tell me what am i >>>>>> missing? >> >>>>> change re.compile("http:\\\\(.*)\.(.*)", re.S) to re.compile >>>>> ("http:\/ >>>>> \/(.*)\.(.*)", re.S) >> >>>> Thanks. I try this: >> >>>> but when the 'line' ishttp://www.cnn.com, I get 's2' com, >>>> but i want 'cnn.com' (everything after the first '.'), how can I do >>>> that? >> >>>> pattern = re.compile("http:\/\/(.*)\.(.*)", re.S) >> >>>> match = re.findall(pattern, line) >> >>>> if (match): >> >>>> s1, s2 = match[0] >> >>>> print s2 >> >>> Can anyone please help me with my problem? I still can't solve it. >> >>> Basically, I want to strip out the text after the first '.' in url >>> address: >> >>> http://www.cnn.com-> cnn.com >> >> from urlparse import urlsplit >> >> def get_domain(url): >> net_location = urlsplit(url)[1] >> return '.'.join(net_location.rsplit('.', 2)[-2:]) >> >> def main(): >> print get_domain('http://www.cnn.com') >> >> Ciao, >> Marc 'BlackJack' Rintsch > > Thanks for your help. > > But if the input string is "http://www.ebay.co.uk/", I only get > "co.uk" > > how can I change it so that it works for both www.ebay.co.uk and > www.cnn.com? > from urlparse import urlsplit def get_domain(url): net_location = ( urlsplit(url)[1] and urlsplit(url)[1].split('.') or urlsplit(url)[2].split('.') ) # tricksy way to get long line into email if net_location[0].lower() == 'www': net_location = net_location[1:] return '.'.join(net_location) def main(): testItems = ['http://www.cnn.com', 'www.yahoo.com', 'http://www.ebay.co.uk'] for testItem in testItems: print get_domain(testItem) if __name__ == '__main__': main() From robert.rawlins at thinkbluemedia.co.uk Fri Apr 27 04:54:44 2007 From: robert.rawlins at thinkbluemedia.co.uk (Robert Rawlins - Think Blue) Date: Fri, 27 Apr 2007 09:54:44 +0100 Subject: Re-ocurring Events In-Reply-To: <4631B8FE.8000405@limsi.fr> References: <3891950377467154133@unknownmsgid> <003001c7889c$f1fb6a50$d5f23ef0$@rawlins@thinkbluemedia.co.uk> <4631B8FE.8000405@limsi.fr> Message-ID: <004901c788a9$b42c2130$1c846390$@rawlins@thinkbluemedia.co.uk> Thanks for getting back to me Laurent. I've now made some pretty tidy progress on this and -think- it's going to shape up nicely, I'm just working on converting my date strings from the XML into a date_struct and we should be good to go. I'll keep you all posted. Rob -----Original Message----- From: Laurent Pointal [mailto:laurent.pointal at limsi.fr] Sent: 27 April 2007 09:49 To: Robert Rawlins - Think Blue Subject: Re: Re-ocurring Events Robert Rawlins - Think Blue a ?crit : > Thank you guys for your suggestions. > > I've been having a look at that launchd stuff from apple but couldn?t really > see how that applies to my requirements. I was not thinking about launchd itself, but about its XML configuration files which manage timed events, as you need. > I've been putting some serious thought into how this should work as its > essentially the final part of the puzzle for my application, I'll have a > fully working model for my application. > > I've been thinking about the possibility of using a combination of xpath to > search the XML with some loops which change the date. As events won't ever > be set to start before 01-01-2007 I can set that as the ceiling for my loop. > So when I'm searching for weekly events, I 'simply' take today's date and > time and loop from now until 01-01-2007 decrementing the date by a week each > iteration of the loop and then search the XML for events in that date, make > sense? > > I know that's a fairly intensive way of doing it, but if it works it works. > > Now, the loop is where I'm really struggling, I've not done any looping with > dates, can anyone give me a hand with this? How can I loop back in time from > now to beginning of 07 a week at a time? Do we have some form of dateAdd() I > can use with a while loop? Perhaps. See datetime module, eventually third party mxDatetime. > Date = (now) > While date > 2007-01-01: > Date = dateAdd(date, -1, w) > > Something to that effect? Then I can quickly xpath for every iteration of > the loop. A+ Laurent. -- Laurent POINTAL CNRS-LIMSI d?pt. CHM, groupes AMI et PS Courriel: laurent.pointal at limsi.fr (prof) laurent.pointal at laposte.net (perso) Ouebe: http://www.limsi.fr/Individu/pointal/ T?l. 01 69 85 81 06 (prof) Fax. 01 69 85 80 88 From apardon at forel.vub.ac.be Wed Apr 25 03:08:47 2007 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 25 Apr 2007 07:08:47 GMT Subject: Tutorial creates confusion about slices References: Message-ID: On 2007-04-24, Michael Hoffman wrote: > Really only one person has argued that the docs do not need to be > changed. The other two people seemed to think you were asking for help > rather than discussing how to revise the docs. Understandable, since > that's why most people come to this group in my estimation. > > Your time is your own and it is good to spend your efforts on what you > think will be most fruitful. But if you are going to let the opposition > of one person stop you from doing anything, you will not accomplish very > much. sjdevnull at yahoo.com has brought a point that is worth considering. So I retreat now a bit to see if I can come with a proposal that bears in mind his point. -- Antoon Pardon From plutoinchina at gmail.com Wed Apr 4 06:49:48 2007 From: plutoinchina at gmail.com (autin) Date: 4 Apr 2007 03:49:48 -0700 Subject: bool value 'False' no memory address? In-Reply-To: <1175683317.458791.275270@d57g2000hsg.googlegroups.com> References: <1175682972.507206.29000@n76g2000hsh.googlegroups.com> <1175683317.458791.275270@d57g2000hsg.googlegroups.com> Message-ID: <1175683788.881443.116260@e65g2000hsc.googlegroups.com> and test on Python 2.3.5 2.4.32 debian is ok!maybe its bug for unstable debian version! From thorsten at thorstenkampe.de Sun Apr 1 11:47:04 2007 From: thorsten at thorstenkampe.de (Thorsten Kampe) Date: Sun, 1 Apr 2007 16:47:04 +0100 Subject: I18n issue with optik References: Message-ID: I guess the culprit is this snippet from optparse.py: # used by test suite def _get_encoding(self, file): encoding = getattr(file, "encoding", None) if not encoding: encoding = sys.getdefaultencoding() return encoding def print_help(self, file=None): """print_help(file : file = stdout) Print an extended help message, listing all options and any help text provided with them, to 'file' (default stdout). """ if file is None: file = sys.stdout encoding = self._get_encoding(file) file.write(self.format_help().encode(encoding, "replace")) So this means: when the encoding of sys.stdout is US-ASCII, Optparse sets the encoding to of the help text to ASCII, too. But that's nonsense because the Encoding is declared in the Po (localisation) file. How can I set the encoding of sys.stdout to another encoding? Of course this would be a terrible hack if the encoding of the localisation changes or different translators use different encodings... Thorsten From s_broscious at comcast.net Thu Apr 12 19:00:40 2007 From: s_broscious at comcast.net (Scott) Date: Thu, 12 Apr 2007 19:00:40 -0400 Subject: Question About Creating Lists References: <1176414392.977660.16610@o5g2000hsb.googlegroups.com> Message-ID: > Please forgo the psychological self analysis from your future posts. Unfortunately I can't, that's how I am, love it or leave it. But if your going to be condescending about it, please leave your future replies in your outbox. Now don't take that as I don't appreciate your reply. I just don't appreciate the tone of that statement. I wouldn't say something about your pseudonym possibly making up for some personal deficiency only because it wouldn't be right. Email etiquette is a beautiful thing. And I'm sorry if you didn't mean it that way, but that's the way it read. > I don't think your question has anything to do with lists. Maybe this > will help: there is a distinction between what are called "literals" > and "variables". My question was in fact about lists and their proper "syntax" (I'm guessing that's the right word). Basically all I was asking was if I had the idea down or not, which was meant to be implied when I wrote: Am I safe in assuming.... Maybe I didn't write it the exact way to get the response I needed, and if it read differently I'm sorry. But that's all I was asking. From steve at holdenweb.com Thu Apr 26 07:46:05 2007 From: steve at holdenweb.com (Steve Holden) Date: Thu, 26 Apr 2007 07:46:05 -0400 Subject: kwarg references In-Reply-To: References: Message-ID: Gabriel Genellina wrote: > En Tue, 24 Apr 2007 22:31:59 -0300, Calvin Spealman > escribi?: > >> In the internal API when a C function is called and passed a kwarg >> dictionary, is there any case where anything else has a reference to >> it? I checked with the following code and it looks like even if you >> explicitly pass a dictionary with **kwargs, it still copies the >> dictionary anyway. > > See the Python Reference Manual, 5.3.4 Calls > http://docs.python.org/ref/calls.html > > Unfortunately it does not explicitely *guarantee* it will be a new > dictionary. At least the way I read the docs, on a function call like this: > > def foo(**kwargs): pass > d = {'a':1, 'b':2) > foo(**d) > > Python could bind the existing d object to the formal parameter kwargs and > still comply with the documented behavior. Some of my own code would break > if that happened... :( > The point is, of course, that inside the function you don't know whether extra keyword arguments were provided as a part of a call with a **kwargs argument or individually provided as kw1=value1. In the latter case, obviously, there is no dict to choose whether to copy or not, so the interpreter has no choice but to create a new dictionary. On the one hand it would seem sensible to extend the definition of the semantics so it is clear beyond doubt that mutating a **kwargs parameter dictionary inside a function body does not change any dictionary that was provided as a **argument, /even in the case where there is a one-to-one correspondence between them/. On the other hand it would also seem sensible to realise that this latter case is so unusual that providing explicit semantics to support it would take much more implementation work than always making a copy of any **kw argument. On the third hand, even *I* seem sensible sometimes so you just never can tell :-) regards Steve -- Steve Holden +1 571 484 6266 +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 promagian at gmail.com Thu Apr 12 04:25:19 2007 From: promagian at gmail.com (bruce peng) Date: Thu, 12 Apr 2007 16:25:19 +0800 Subject: Newbie help with array handling References: <1176364734.439383.252930@o5g2000hsb.googlegroups.com> Message-ID: use dir with list nested for example: {key1 : [value1, value2, value3], key2 : [value1, value2, vlaue4]} "loial" wrote in message news:1176364734.439383.252930 at o5g2000hsb.googlegroups.com... >I am new to python and am converting an awk script to python > > I need to store some data in an array/table of some form > > keyvalue1, value1, value2, value3 > keyvalue2, value1,value2, value3 > keyvalue3, value1,value2,value3 > etc > > I will later need to sort in keyvalue order and also need to be able > to check if a key already exists > > It is not clear how to do this in python. All the examples I see have > just a key and a single value > From mail at timgolden.me.uk Mon Apr 30 04:47:31 2007 From: mail at timgolden.me.uk (Tim Golden) Date: Mon, 30 Apr 2007 09:47:31 +0100 Subject: Reading Data From an Excel Sheet In-Reply-To: <1177922130.251948.107740@p77g2000hsh.googlegroups.com> References: <1177922130.251948.107740@p77g2000hsh.googlegroups.com> Message-ID: <4635AD23.20300@timgolden.me.uk> sagar wrote: > Hi all, > I want a python script which takes in input an EXCEL sheet > and then reads the data in it. > Any code snippets will be fine and this i want this in windows > XP . Might I humbly suggest that, instead of posting several somewhat demanding requests for help with no evidence of any effort on your part, that you put your subject line into Google (or your search engine of choice), add the word Python and then look at the results? TJG From grante at visi.com Thu Apr 5 13:32:21 2007 From: grante at visi.com (Grant Edwards) Date: Thu, 05 Apr 2007 17:32:21 -0000 Subject: AW: Write to a binary file References: <131a2eeq2feuefe@corp.supernews.com> Message-ID: <131acl5mfsvp27d@corp.supernews.com> On 2007-04-05, Thinker wrote: >>> --- START --- >>> import os >>> >>> msg = chr(0x02) + chr(0x36) + chr(0x00) + chr(0x01) + chr(0x0a) + >>> chr(0xb0) + chr(0x77) >>> >>> f = os.open('/dev/pytest', os.O_RDWR) >>> os.write(f,msg) >>> os.close(f) >>> >>> f = file('/dev/pytest', 'wb') >>> f.write(msg) >>> f.close() >>> --- END --- I just ran that on my system (2.4.3), and both versions do a signle write. >>> The "pytest" device is a very simple device-driver which >>> prints out (using "printk()") the buffer delivered to the >>> write function in a hexadecimal format ("Pytest write> [buffer >>> in hex format]"). >>> >>> The output was: >>> --- Start --- >>> Pytest write> 02 36 00 01 0a b0 77 >>> Pytest write> 02 36 00 01 0a >>> Pytest write> b0 77 >>> --- END --- >>> >> >> I'm surprised that the normal file object's write method does >> that -- especially for a "binary" file. IMO, it's a bug when a >> binary file object treats 0x0a differently than other byte >> values. But, using the file object to read/write a device is >> probably not a good idea because of undefined behavior like >> that. File objects also do their own buffering, which I >> suspect isn't what you want. >> > Why not try to create a file object with bufsize = 0 ? > for ex: > --------- > fo = file('/dev/pytest', 'wb', 0) > fo.write(....) > fo.close() > -------- That's worth a try, but I can't get the normal method to fail... -- Grant Edwards grante Yow! I selected E5... but at I didn't hear "Sam the Sham visi.com and the Pharoahs"! From brencam at gmail.com Wed Apr 11 18:43:36 2007 From: brencam at gmail.com (BrendanC) Date: 11 Apr 2007 15:43:36 -0700 Subject: Creating an EXE for XLRD + WIN32COM + wxWidgets application - Help request Message-ID: <1176331416.703642.242690@y5g2000hsa.googlegroups.com> I've started learninhg Python and have developed a small Python app that imports Excel data into an Access mdb/jet database. This application has dependencies on the following: XLRD - http://cheeseshop.python.org/pypi/xlrd/0.5.2 - (to read Excel files) Python windows extensions - http://starship.python.net/crew/mhammond/win32/ - to use ADO wxPython GUI toolkit - http://www.wxpython.org/ - for the GUI interface Ideally I'd like to create a standalone app that I can deliver to a client who can will run this on a Windows system that has Access installed. (Python will not be installed on this system). I'm planning to use P2YEXE for the build - however I'm not sure if it is possible to include all the required components for this in a package. I imagine there may be a few 'gotchas' with this. Any suggestions on how to do this and are there some additional issues I might run into? Thx in advance BrendanC From xuxu_1009 at 163.com Fri Apr 13 22:37:22 2007 From: xuxu_1009 at 163.com (Ann) Date: 13 Apr 2007 19:37:22 -0700 Subject: Which is the best FREE forum? Message-ID: <1176518242.376467.258800@q75g2000hsh.googlegroups.com> Free Unlimited Storage Free Unlimited Bandwidth Free Free Subdomain Free More Skins Free No annoying pop-ups Free 99% Uptime Free Daily Backups Free Fast, Friendly Tech Support So,what's that? That's our free forum named http://www.forumgogo.com. We have the human_based management also provide you human_based forum service. You needn't,we won't ! This is a great site that is completely free, and can make some cool forums, here's an example of one, you can make your own topic, polls, and replies etc, and you can have an accout for every member. This next link is an example of a forum made from invisionfree. http://support.forumgogo.com From david at boddie.org.uk Fri Apr 20 20:54:26 2007 From: david at boddie.org.uk (David Boddie) Date: Sat, 21 Apr 2007 02:54:26 +0200 Subject: Beginner: Formatting text output (PyQt4) References: Message-ID: On Thursday 19 April 2007 00:50, Glen wrote: > What seems to be happening is that the font that pyqt is using is not > fixed width, so I did this: > qTxtFormat = QTextCharFormat() > qTxtFormat.setFontFixedPitch(True) > ui.textEdit.setCurrentCharFormat(qTxtFormat) It may be that the font you're using isn't actually a monospaced font. The result of this is that the font used to display the text won't be a fixed pitch font. To test this, try specifying a known monospaced font and see if you get the output you expect. David From gandalf at designaproduct.biz Thu Apr 5 13:32:11 2007 From: gandalf at designaproduct.biz (Laszlo Nagy) Date: Thu, 05 Apr 2007 19:32:11 +0200 Subject: Windows service and pyc files In-Reply-To: References: <1175709094.352514.64920@y66g2000hsf.googlegroups.com> <46151D34.50608@designaproduct.biz> <461528C8.9020707@designaproduct.biz> Message-ID: <4615329B.2050400@designaproduct.biz> >> 1. subprocess.Popen cannot redirect stderr and stdout when called from a >> win32 service. This is not documented, and makes debugging almost >> impossible. >> > > Without the patch menctioned in my previous message, you must redirect all > stdin, stdout AND stderr (because the child cannot inherit the handles > from the parent service, as a service has no standard handles assigned > usually) or none of them. > The truth is that subprocess.Popen raises an exception when I try to redirect stdin,stdout or stderr. If I do not redirect any of them, then everything works fine for me. (Well, of course standard output is lost.) >> interpreter = os.path.join( os.path.split(sys.executable),[0], >> os.sep,os.sep,os.sep,'Python.exe' ) >> > > I think you meant to write: os.path.join(os.path.split(sys.executable)[0], > os.pardir, os.pardir, os.pardir, 'python.exe') > Yes, sorry. > pythonservice.exe is so Windows-specific that using os.pardir only makes > the code harder to read. > Anyway I'd use os.path.join(sys.prefix, 'python.exe') (sys.prefix would be > C:\Python25 in your case) > Oh, I did not know about that variable. Thanks! :-) Best, Laszlo From Allerdyce.John at gmail.com Sun Apr 15 19:25:23 2007 From: Allerdyce.John at gmail.com (John) Date: 15 Apr 2007 16:25:23 -0700 Subject: how to check the 'content/type' using urlopen Message-ID: <1176679523.382142.309220@b75g2000hsg.googlegroups.com> i have the following code to open a URL address, but can you please tell me how can I check the content type of the url response? Thank you. try: req = Request(url, txdata, txheaders) handle = urlopen(req) except IOError, e: print e print 'Failed to open %s' % url return 0; else: data = handle.read() From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Mon Apr 2 10:29:35 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Mon, 02 Apr 2007 16:29:35 +0200 Subject: Problem with global variables References: <1311u48bqkehk24@corp.supernews.com> Message-ID: <57ciafF2cf6qdU1@mid.individual.net> Laurent Pointal wrote: > And so the solution to add "global foo" before using it. Didn't you read his final question? | All of a sudden, tiny() can see the global variable "foo". Very | confusing! Why is it that tiny() sometimes can, and sometimes | can't, see the global variable "foo"? I have no explanation for this, but I'm interested in one, too. Regards, Bj?rn -- BOFH excuse #422: Someone else stole your IP address, call the Internet detectives! From flifus at gmail.com Fri Apr 27 08:40:53 2007 From: flifus at gmail.com (flifus at gmail.com) Date: 27 Apr 2007 05:40:53 -0700 Subject: My python annoyances so far In-Reply-To: <59chkcF2e6106U1@mid.individual.net> References: <1177541453.471959.120830@c18g2000prb.googlegroups.com> <59bf34F2k27v5U1@mid.individual.net> <1177603623.774892.230390@t38g2000prd.googlegroups.com> <59chkcF2e6106U1@mid.individual.net> Message-ID: <1177677653.374768.170010@n35g2000prd.googlegroups.com> On 26 Apr, 21:50, Bjoern Schliessmann wrote: > > like perhaps ruby. > > If I were rude, I would ask now why you don't use ruby. But I bet > ruby has some annoyances ready for you too. > > Regards, > > Bj?rn > Well, I'd use ruby but python is everywhere, and ruby isn't. All the applications that interest me are scriptable in python, not ruby. From b.r.willems at gmail.com Sat Apr 14 16:03:03 2007 From: b.r.willems at gmail.com (Bart Willems) Date: Sat, 14 Apr 2007 16:03:03 -0400 Subject: That might be the case for more complex objects... In-Reply-To: References: <1176546078.934340.253810@y5g2000hsa.googlegroups.com> <1176557734.456820.275780@p77g2000hsh.googlegroups.com> Message-ID: <7saUh.37$4S1.2@newsfe12.lga> Dennis Lee Bieber wrote: > On 14 Apr 2007 06:35:34 -0700, "jamadagni" declaimed > the following in comp.lang.python: > In Python, the "variable" NAME does NOT define storage; unlike most > other classical languages where the "variable name" is a storage > address, and the value of the RHS is COPIED to that address. Python does > not do such copying. Names are references to the RHS object itself. > > a = 5 > > means that somewhere in memory is an integer object with the value "5"; > the name "a" is now "pasted onto" that integer object. > > b = a > > finds the object that has the name "a" stuck to it, and sticks a second > name "b" onto the same object. There is still only one "5" in memory. I can try this in interactive mode: >>> a = 5 >>> b = a >>> a += 1 >>> print b 5 So, if /a/ and /b/ where pointing to the *same* "5" in memory, then I would expect b to be increased, just as a. But after increasing a, b is still 5... Lists behave as described above, integers and floats don't. By the way, a classic language like C has features like this too; they're called pointers. From pak_lun at hotmail.com Thu Apr 19 00:47:18 2007 From: pak_lun at hotmail.com (EMC ROY) Date: 18 Apr 2007 21:47:18 -0700 Subject: Text Suffix to Prefix Conversion Message-ID: <1176958038.116780.104660@n59g2000hsh.googlegroups.com> Dear all, I'm a postgraduate student in Hong Kong, studying english language. I wanna seek help from all of you about some plain text manipulation. I have already add part-of-speech (POS) tags with angle bracket by software tagger, right after every word in my file, as attribute. How could I change the tag suffix to tag prefix? Original Sentence: An apple for you. Present: An apple for you .<.> Desire: An apple for you <.>. My file includes several hundred thousands of words. Manual editing is not possible. All suggestion are welcome!! EMC ROY 19/04/2007 From scott.daniels at acm.org Fri Apr 20 22:03:06 2007 From: scott.daniels at acm.org (Scott David Daniels) Date: Fri, 20 Apr 2007 19:03:06 -0700 Subject: I need a string/list/generator/comprehension incantation. In-Reply-To: References: Message-ID: <132is5bgadkh1f0@corp.supernews.com> Steven W. Orr wrote: > I really tried. I give up. > > I got this one last time (for which I'm very grateful). > ... Now I want something that's going to give me a string whose value is the > set of all of the first letters of months. Order is not important. > > And for extra credit, I need the string whose value is the set of all of > the letters of months minus the first letter. Boy am I sorry we did your homework for you. If you have no idea where to go, and you can't even show your work, you need to see a TA or instructor. You are already in over your head; back up and learn to swim. -- --Scott David Daniels scott.daniels at acm.org From rpw3 at rpw3.org Mon Apr 16 03:22:33 2007 From: rpw3 at rpw3.org (Rob Warnock) Date: Mon, 16 Apr 2007 02:22:33 -0500 Subject: is laziness a programer's virtue? References: <1176654319.273907.167280@q75g2000hsh.googlegroups.com> <1176663615.592055.45720@l77g2000hsb.googlegroups.com> Message-ID: Daniel Gee wrote: +--------------- | You fail to understand the difference between passive laziness and | active laziness. Passive laziness is what most people have. It's | active laziness that is the virtue. It's the desire to go out and / | make sure/ that you can be lazy in the future by spending just a | little time writing a script now. It's thinking about time | economically and acting on it. +--------------- Indeed. See Robert A. Heinlein's short story (well, actually just a short section of his novel "Time Enough For Love: The Lives of Lazarus Long") entitled "The Tale of the Man Who Was Too Lazy To Fail". It's about a man who hated work so much that he worked very, *very* hard so he wouldn't have to do any (and succeeded). -Rob ----- Rob Warnock 627 26th Avenue San Mateo, CA 94403 (650)572-2607 From jowr.pi at gmail.com Sat Apr 28 13:15:30 2007 From: jowr.pi at gmail.com (Eric Gisse) Date: 28 Apr 2007 10:15:30 -0700 Subject: Video: Professor of Physics Phd at Cal Tech says: 911 Inside Job In-Reply-To: <1177467203.719625.93920@u32g2000prd.googlegroups.com> References: <1177467203.719625.93920@u32g2000prd.googlegroups.com> Message-ID: <1177780530.539758.275660@c35g2000hsg.googlegroups.com> On Apr 24, 6:13 pm, stj... at rock.com wrote: > Cal Tech is the ELITE of ELITE in physics. "INN World Report interviewed Dr. Crockett Grabbe - professor of physics at the University of Iowa - regarding his thoughts on the 'collapses' of WTC1, WTC2, & WTC7. In this interview he lists numerous reasons to suspect controlled demolition and expresses support for alternative theories." A common mistake - I frequently confuse CalTech and U of Iowa. http://scholar.google.com/scholar?hl=en&lr=&safe=off&client=firefox-a&q=crockett+grabbe+author%3Ac-grabbe+iowa&btnG=Search That's interesting, no publications on any engineering topic. A professor of physics, not engineering, who claims that explosives were planted in not only WTC7, but WTC 1 and 2 which were trigged by the planes impacting the building. Why is anyone listening to this loon? > > If Feynman were alive, he would point his finger straight at the 911 > criminal operators, the yank bastards themselves ....... I don't recall Feynman ever advocating nutcase positions. > > http://www.911blogger.com/node/8101 > > No self-respecting scientist should keep his mouth shut. Its a > fundamental challenge to the method of science, a detective work most > demanding of INTELLECTUAL HONESTY. I love how folks like you ask for intellectual honesty when every effort is made to ignore evidence that doesn't agree with your presupposed findings. From bj_666 at gmx.net Thu Apr 5 09:58:05 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Thu, 05 Apr 2007 15:58:05 +0200 Subject: Storing of folder structure in SQL DB References: <1175774302.652656.285260@d57g2000hsg.googlegroups.com> <1360b7230704050522h6dd82fedseef04ccd43c68adc@mail.gmail.com> Message-ID: In , Amit Khemka wrote: > On 4/5/07, Amit Khemka wrote: >> On 5 Apr 2007 04:58:22 -0700, Sergei Minayev wrote: > >> An Example: >> >> import os >> root='/my/root/directory' >> id =0 >> tree={root:(-1, id)} >> id+=1 >> for path, dirs, files in os.walk(root): >> for dir in dirs: >> if not tree.has_key(path+'/'+dir): >> tree[path+'/'+dir]=(tree[path][1], id) >> id+=1 >> >> [?] > > use os.sep instead of '/' ! Or even better `os.path.join()` instead of building the strings with ``+``. Ciao, Marc 'BlackJack' Rintsch From steven.bethard at gmail.com Wed Apr 11 23:27:42 2007 From: steven.bethard at gmail.com (Steven Bethard) Date: Wed, 11 Apr 2007 21:27:42 -0600 Subject: Code Explaination: Spelling correction code In-Reply-To: <1176345676.300560.78020@n59g2000hsh.googlegroups.com> References: <1176345676.300560.78020@n59g2000hsh.googlegroups.com> Message-ID: <_tqdnfpprqGxOoDbnZ2dnUVZ_uTinZ2d@comcast.com> Drew wrote: > I recently saw this website: http://www.norvig.com/spell-correct.html > > All the code makes sense to me save one line: > > def known_edits2(word): > return set(e2 for e1 in edits1(word) for e2 in edits1(e1) if e2 in > NWORDS) This is the same as: result = set() for e1 in edits1(word): for e2 in edits1(e1): if e2 in NWORDS: result.add(e2) return result The thing between the ``set(`` and ``)`` is called a generator comprehension if you'd like to look into it further. STeVe From larry.bates at websafe.com Mon Apr 16 14:42:07 2007 From: larry.bates at websafe.com (Larry Bates) Date: Mon, 16 Apr 2007 13:42:07 -0500 Subject: looking for library to read ppt files In-Reply-To: <1176747406.722209.126900@w1g2000hsg.googlegroups.com> References: <1176747406.722209.126900@w1g2000hsg.googlegroups.com> Message-ID: Aljosa Mohorovic wrote: > i'm looking for a way to read ppt (powerpoint) files using python and > to convert slides into jpeg files. > any links or tips how to do this? > Not really a Python question but Google turned up: http://www.sharewareconnection.com/ppt-to-jpeg-jpg-tiff-bmps-converter.htm http://www.print-driver.com/howto/converting/convert_microsoft_powerpoint_presentation_to_jpeg.htm -Larry From bbxx789_05ss at yahoo.com Wed Apr 4 04:45:43 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: 4 Apr 2007 01:45:43 -0700 Subject: heap doesn't appear to work as described In-Reply-To: References: <1175641694.226975.258820@n76g2000hsh.googlegroups.com> <17938.58082.317522.331513@montanaro.dyndns.org> Message-ID: <1175676343.513378.205790@y80g2000hsf.googlegroups.com> On Apr 3, 10:30 pm, "Terry Reedy" wrote: > wrote in message > > news:17938.58082.317522.331513 at montanaro.dyndns.org... > | > | >> My book says that in a heap, a value at position i will be smaller > | >> than the values at positions 2*i and 2*i + 1. > > I am sure your book either uses 1-based arrays or a 0-based arrays with the > first not used. The need to keep these alternatives in mind is an > unfortunate fact of programming life. > My book uses lists. From robert.kern at gmail.com Tue Apr 17 15:36:41 2007 From: robert.kern at gmail.com (Robert Kern) Date: Tue, 17 Apr 2007 14:36:41 -0500 Subject: Numpy problem: Arrays in a list of dictionaries In-Reply-To: <1176837810.276473.55020@e65g2000hsc.googlegroups.com> References: <1176837810.276473.55020@e65g2000hsc.googlegroups.com> Message-ID: ZMY wrote: > I am new to Numpy/Pylab, and I am trying to construct a list of > dictionaries with arrays as the items, for example: > >>>> dict = {1: array([2, 3, 4]), 2: ''} >>>> list1 = [] >>>> for i in range(3): list1.append(dict.copy()) > ... >>>> list1 > [{1: array([2, 3, 4]), 2: ''}, {1: array([2, 3, 4]), 2: ''}, {1: > array([2, 3, 4]), 2: ''}] >>>> list1[0][1][1]=100 >>>> list1 > [{1: array([ 2, 100, 4]), 2: ''}, {1: array([ 2, 100, 4]), 2: > ''}, {1: array([ 2, 100, 4]), 2: ''}] > >>>> list1[0][2]='Jack' >>>> list1 > [{1: array([ 2, 100, 4]), 2: 'Jack'}, {1: array([ 2, 100, 4]), > 2: ''}, {1: array([ 2, 100, 4]), 2: ''}] > > So the strings can be assigned seperately but arrays can not. What is > the problem here? When you call dict.copy(), all it does is make a copy of the dictionary; each copy of the dictionary still refers to the same objects. list1[i][1] refers to the same array for all i, so when you modify it in-place like you did, you will see the modifications in every reference to that object. list[i][2] also referred to the same string for all i until you *replaced* the entry in the 0'th dictionary. -- 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 tjreedy at udel.edu Fri Apr 13 20:13:16 2007 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 13 Apr 2007 20:13:16 -0400 Subject: vocab question References: Message-ID: "Alan G Isaac" wrote in message news:sYWdnQwcu9EhW4LbnZ2dnUVZ_gOdnZ2d at rcn.net... | Pardon the vocab question; | I'm not a computer science type. | According to the Reference Manual, | a class defintion has the structure:: | | classdef ::= "class" classname [inheritance] ":" suite | | What is the entire part before the suite called? | (Just pointing to a reference is fine & helpful, | as long as its not an entire course on BNF.) I call it the header for the compound statement. Same with def f(pars): tjr From salmonegg at sbcglobal.net Sat Apr 28 15:06:21 2007 From: salmonegg at sbcglobal.net (Salmon Egg) Date: Sat, 28 Apr 2007 19:06:21 GMT Subject: Video: Professor of Physics Phd at Cal Tech says: 911 Inside Job References: <1177467203.719625.93920@u32g2000prd.googlegroups.com> <1177778685.506101.201540@h2g2000hsg.googlegroups.com> Message-ID: On 4/28/07 9:44 AM, in article 1177778685.506101.201540 at h2g2000hsg.googlegroups.com, "War Office" <911falseflag at gmail.com> wrote: > Why can't any of you just discuss the fact that free-fall collapse of > this building contradicts the laws of physics? > > Why do you all have to avoid the topic and rather go on a character > assassination which is totally abhorent to scientific method? Sometimes, when I pee into the toilet, a few droplets rise to heights that defy god's laws. Do I have magic urine? -- If there is such a thing as intelligent design, please explain hemorrhoids. From steve at holdenweb.com Mon Apr 2 18:50:42 2007 From: steve at holdenweb.com (Steve Holden) Date: Mon, 02 Apr 2007 18:50:42 -0400 Subject: Submit patches for documentation In-Reply-To: References: Message-ID: Kevin Walzer wrote: > What's the best way to submit patches for Python documentation at the > SourceForge patch tracker if you are not writing LaTeX? I would like to > submit some simple text updates. However, if I do this, I'm not clear > what files I should run a diff against. > > Or is simply submitting the updates as a text file, with a note > indicating which documentation files they replace, sufficient? > The doc authors would much rather have plain English text than nothing, and are willing to do the markup themselves to incorporate wothwhile changes. 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 Mon Apr 30 01:00:49 2007 From: aleax at mac.com (Alex Martelli) Date: Sun, 29 Apr 2007 22:00:49 -0700 Subject: Master's Thesis Help Needed References: <1177898031.790447.253360@n76g2000hsh.googlegroups.com> Message-ID: <1hxcqfn.11m7qp91766nc4N%aleax@mac.com> RobJ wrote: > http://pyschool.robj.webfactional.com/ Things start on a pretty bad note when I'm asked to select my OS: Ubuntu Linux Windows XP I'm running MacOSX. What now? Why is there no choice "none of the above"...?! Alex From KDawg44 at gmail.com Wed Apr 11 13:00:42 2007 From: KDawg44 at gmail.com (KDawg44) Date: 11 Apr 2007 10:00:42 -0700 Subject: Parsing log in SQL DB to change IPs to hostnames In-Reply-To: References: <1176219463.407804.315560@y80g2000hsf.googlegroups.com> <1176221494.813800.78580@y80g2000hsf.googlegroups.com> <1176231258.626137.228220@d57g2000hsg.googlegroups.com> <92%Sh.21541$tD2.14028@newsread1.news.pas.earthlink.net> <1176295161.448113.253650@w1g2000hsg.googlegroups.com> Message-ID: <1176310842.511437.241560@l77g2000hsb.googlegroups.com> On Apr 11, 11:58 am, Dennis Lee Bieber wrote: > On 11 Apr 2007 05:39:21 -0700, "KDawg44" declaimed > the following in comp.lang.python: > > > ohhh okay. thanks so much. I knew that it came out as strings, i > > guess it makes sense that I would have to send it back IN as a > > string. Changed that and now it works! THanks so much. > > I'd be interested in the schema definition -- my experience has been > that numeric fields come out of MySQLdb as numerics... > > >>> import MySQLdb > >>> cn = MySQLdb.connect(host="localhost", user="BestiariaCP", db="bestiaria") > >>> cr = cn.cursor() > >>> cr.execute("select * from comics where banner is not Null") > 35L > >>> cr.fetchone() > > (2L, 'Anxiety Cafe', 'Anxiety Cafe', > 'http://rockerbot.artistrealm.org/', 'images/ronandrockerbutton.jpg', > 234L, 60L, 'Platitudes from a platypus.', 'On hiatus - site rebuild', > 'N', 'Y') > > > > Note the first field there -- a Python long integer (the schema > defines that as an integer auto_increment field). Also the "234L, 60L," > (image width/height) -- all returned as numeric. > > If your data is coming out as a string, I'd suspect the schema > defined it as a character type. > > >>> cr.description > > (('ID', 3, 2, 11, 11, 0, 0), ('name', 253, 33, 100, 100, 0, 0), > ('sortname', 253, 33, 100, 100, 0, 0), ('URL', 253, 56, 75, 75, 0, 0), > ('banner', 253, 29, 75, 75, 0, 1), ('width', 3, 3, 11, 11, 0, 1), > ('height', 3, 3, 11, 11, 0, 1), ('description', 252, 170, 65535, 65535, > 0, 0), ('occurs', 253, 58, 125, 125, 0, 1), ('isactive', 254, 1, 1, 1, > 0, 0), ('isonline', 254, 1, 1, 1, 0, 0)) > > > > CREATE TABLE `comics` ( > `ID` int(11) NOT NULL auto_increment, > `name` varchar(100) NOT NULL default '', > `sortname` varchar(100) NOT NULL default '', > `URL` varchar(75) NOT NULL default '', > `banner` varchar(75) default NULL, > `width` int(11) default NULL, > `height` int(11) default NULL, > `description` text NOT NULL, > `occurs` varchar(125) default NULL, > `isactive` enum('N','Y') NOT NULL default 'Y', > `isonline` enum('N','Y') NOT NULL default 'Y', > PRIMARY KEY (`ID`), > KEY `namesort` (`sortname`) > ) ENGINE=MyISAM AUTO_INCREMENT=92 DEFAULT CHARSET=latin1; > -- > 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/ I see your point. Somewhere in my head I must have mixed them up. It goes in as a string but comes out as whatever data type. Thanks. From steven.bethard at gmail.com Tue Apr 3 18:05:19 2007 From: steven.bethard at gmail.com (Steven Bethard) Date: Tue, 03 Apr 2007 16:05:19 -0600 Subject: how to remove multiple occurrences of a string within a list? In-Reply-To: <1175637133.938883.224570@q75g2000hsh.googlegroups.com> References: <1175624433.206953.214290@n59g2000hsh.googlegroups.com> <1175625098.269660.184790@o5g2000hsb.googlegroups.com> <1175627593.307674.11280@w1g2000hsg.googlegroups.com> <1175637133.938883.224570@q75g2000hsh.googlegroups.com> Message-ID: bahoo wrote: > The larger problem is, I have a list of strings that I want to remove > from another list of strings. If you don't care about the resulting order:: >>> items = ['foo', 'bar', 'baz', 'bar', 'foo', 'frobble'] >>> to_remove = ['foo', 'bar'] >>> set(items) - set(to_remove) set(['frobble', 'baz']) If you do care about the resulting order:: >>> to_remove = set(to_remove) >>> [item for item in items if item not in to_remove] ['baz', 'frobble'] STeVe From bbxx789_05ss at yahoo.com Fri Apr 13 14:29:52 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: 13 Apr 2007 11:29:52 -0700 Subject: mac IDLE problems In-Reply-To: <461FAF55.9090109@codebykevin.com> References: <1176441305.802719.105520@q75g2000hsh.googlegroups.com> <461FAF55.9090109@codebykevin.com> Message-ID: <1176488992.439341.226340@q75g2000hsh.googlegroups.com> On Apr 13, 10:27?am, Kevin Walzer wrote: > 7stud wrote: > > Hi, > > > In the IDLE, I can't get most shortcut keys that are listed next to > > the menu items to work. ?For instance, under the Format menu item only > > the shortcuts for "indent region" and "undent region" work. ? If I > > highlight some text and use Shift+3 to comment out the region I > > highlighted, the code is erased and I get the # symbol. ? When I use > > the option(alt key) and type a character, I get things like this: > > > ?,?,?,? > > > I looked under Options/Configure IDLE/Keys and tried the various built > > in key sets, and none seem to work. > > > I also can't use my mouse to copy(or cut) and paste. ?When I highlight > > something and right click(in an attempt to bring up the context menu > > that has copy, cut, paste, etc.), the text that is highlighted is > > doubled when I right click, e.g.: > > > ? ? ?some text > > > becomes: > > > ? ? ?some textsome text > > > And, sometimes when I try to highlight a line, the line 7 lines below > > the cursor gets highlighted. > > > intel mac, os 10.4.7, python 2.4.4 > > IDLE under 2.5 has been much improved on the Mac; all the standard Mac > keyboard shortcuts are supported, and in general it's more stable. With > 2.5, IDLE replaces the old PythonIDE that used to ship with MacPython. > Can you update to 2.5? > > -- > Kevin Walzer > Code by Kevinhttp://www.codebykevin.com Thanks for the info. I just updated to 2.4.4 because the download said there were more packages for the mac than with 2.5. I think I'll probably just stick to vim for an editor. From martin at v.loewis.de Sun Apr 22 15:58:39 2007 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sun, 22 Apr 2007 21:58:39 +0200 Subject: python style guide inconsistencies In-Reply-To: References: Message-ID: <462BBE6F.9000007@v.loewis.de> Darren Dale schrieb: > I was just searching for some guidance on how to name packages and modules, > and discovered some inconsistencies on the www.python.org. > http://www.python.org/doc/essays/styleguide.html says "Module names can be > either MixedCase or lowercase." That page also refers to PEP 8 at > http://www.python.org/dev/peps/pep-0008/, which says "Modules should have > short, all-lowercase names. ... Python packages should also have short, > all-lowercase names ...". > > Which is most up to date? Is this the right place to point out that one of > those pages needs to be updated? No - this is better discussed on python-dev. In any case, there isn't technically a contradiction. Module names MUST be either MixedCase or lowercase; they SHOULD be lowercase. So unfortunately, for tradition, some module names are mixed case (such as ConfigParser or StringIO). I can personally accept that as a necessary evil, although I would prefer if all modules were lower case. Martin From ziade.tarek at gmail.com Fri Apr 20 09:32:00 2007 From: ziade.tarek at gmail.com (=?ISO-8859-1?Q?Tarek_Ziad=E9?=) Date: Fri, 20 Apr 2007 15:32:00 +0200 Subject: International Python user groups events calendar In-Reply-To: <1177033403.119317.66840@n59g2000hsh.googlegroups.com> References: <1177033403.119317.66840@n59g2000hsh.googlegroups.com> Message-ID: <94bdd2610704200632r1878f401j7aab0ef0b105b086@mail.gmail.com> Hi, we have one to add: the french speaking python days http://journees.afpy.org/ 2/3 June - Paris - France Regards On 19 Apr 2007 18:43:23 -0700, TechVenue Eventmaster wrote: > > FYI All, > > International Python user groups events calendar: > > http://TechVenue.com/Calendars/Python/ > > Enjoy! > > TechVenue.com Eventmasters > > -- > http://mail.python.org/mailman/listinfo/python-announce-list > > Support the Python Software Foundation: > http://www.python.org/psf/donations.html > -- Tarek Ziad? | Association AfPy | www.afpy.org Blog FR | http://programmation-python.org Blog EN | http://tarekziade.wordpress.com/ -------------- next part -------------- An HTML attachment was scrubbed... URL: From peter.maas at somewhere.com Sat Apr 21 08:02:36 2007 From: peter.maas at somewhere.com (Peter Maas) Date: Sat, 21 Apr 2007 14:02:36 +0200 Subject: is laziness a programer's virtue? In-Reply-To: <1176667091.415819.152890@n76g2000hsh.googlegroups.com> References: <1176654319.273907.167280@q75g2000hsh.googlegroups.com> <1176667091.415819.152890@n76g2000hsh.googlegroups.com> Message-ID: Xah Lee wrote: > For those reading this, i also want to mention, that although i think > Perl is a motherfucking language on earth, and its leader and > ?inventor? Larry Wall has done massive damage to the computing world, > but Perl the community is in fact very tolerant in general (which is > to Larry's credit), when compared to the motherfucking Pythoners (who > knew SHIT) as well as many of the self-appointed lisp bigwig > characters. Be careful not to damage the English language by making "motherfucking" a compliment :) -- Regards/Gruesse, Peter Maas, Aachen E-mail 'cGV0ZXIubWFhc0B1dGlsb2cuZGU=\n'.decode('base64') From mensanator at aol.com Sun Apr 8 14:29:08 2007 From: mensanator at aol.com (mensanator at aol.com) Date: 8 Apr 2007 11:29:08 -0700 Subject: How do I get a slice of a string held in a tuple? In-Reply-To: References: <25ine4-rvt.ln1@Hedley.internal.thethurmans.com> <1176050876.835238.68560@d57g2000hsg.googlegroups.com> Message-ID: <1176056948.721586.48460@o5g2000hsb.googlegroups.com> On Apr 8, 12:29???pm, Lorenzo wrote: > In article <1176050876.835238.68... at d57g2000hsg.googlegroups.com>, > > > > > > ?"mensana... at aol.com" wrote: > > On Apr 8, 11:34?am, Lorenzo Thurman > > wrote: > > > I have tuple which hold a string in tup[0]. I want to get a slice of > > > that string. I thought I would do something like: > > > tup[0][start:end] > > > But this fails. > > > No, it doesn't. > > > >>> a = ('abcdefg','hijkl') > > >>> a[0] > > 'abcdefg' > > >>> a[0][1:2] > > 'b' > > > > How do I go about it? > > > Do it correctly. Post your actual example that fails > > and the related error message. Possibnly your indexes > > were out of range. > > > > I googled this and found a couple > > > of references, but no solution. > > > Well, there wouldn't be ?a solution to a non-existent > > problem, would there? > > > > TIA > > Here's the code: > > ?elapsedTime = mydata[1] > ?index = elapsedTime.find("real") > ?# the index will have a value 0f 110 > ?totaltime = elapsedTime[index:] > ?# instead of this returning a shortened html string, i only > ?# get the left angle bracket '<' This implies that '<' is the 111th character (counting from 0) and that it is the last character since you used [index:]. Print out the entire string elapsedTime, count from 0 to the characters you want and see if you have the correct index numbers (verify them). > > -- > "My Break-Dancing days are over, but there's always the Funky Chicken" > --The Full Monty From stefan.behnel-n05pAM at web.de Sun Apr 15 05:58:42 2007 From: stefan.behnel-n05pAM at web.de (Stefan Behnel) Date: Sun, 15 Apr 2007 11:58:42 +0200 Subject: Standardizing XML In-Reply-To: <1176625793.392269.24060@n59g2000hsh.googlegroups.com> References: <1176625793.392269.24060@n59g2000hsh.googlegroups.com> Message-ID: <4621F752.2030902@web.de> ZeeGeek wrote: > Is there a module for python to standardize XML? Since MSN Live Space > doesn't use standard XML in the posts, I want to standardize them so > that I can use them elsewhere. Could you give a hint what you mean with "standardize"? What's non standardized XML for you? Stefan From bj_666 at gmx.net Mon Apr 2 13:47:43 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Mon, 02 Apr 2007 19:47:43 +0200 Subject: Clean "Durty" strings References: <1175463083.135907.128480@y80g2000hsf.googlegroups.com> <57bt02F2c9fpuU2@mid.uni-berlin.de> <57cddlF2bsqdbU2@mid.uni-berlin.de> <1175530649.060784.147900@d57g2000hsg.googlegroups.com> Message-ID: In <1175530649.060784.147900 at d57g2000hsg.googlegroups.com>, irstas wrote: > I'd like to see how this transformation can be done with > BeautifulSoup. Well, the last two regexps can be replaced with this: > > unicode(BeautifulStoneSoup(s,convertEntities=BeautifulStoneSoup.HTML_ENTITIES).contents[0]) Completely without regular expressions: def main(): soup = BeautifulSoup(source, convertEntities=BeautifulSoup.HTML_ENTITIES) print ' '.join(''.join(soup(text=True)).split()) Ciao, Marc 'BlackJack' Rintsch From gagsl-py2 at yahoo.com.ar Fri Apr 6 01:03:16 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: 5 Apr 2007 22:03:16 -0700 Subject: Problems with os.spawnv In-Reply-To: <1175811935.298942.150620@d57g2000hsg.googlegroups.com> References: <1175807996.524018.146070@n76g2000hsh.googlegroups.com> <1175809984.762401.11020@n59g2000hsh.googlegroups.com> <1175811935.298942.150620@d57g2000hsg.googlegroups.com> Message-ID: <1175835796.705278.258740@q75g2000hsh.googlegroups.com> Henrik Lied wrote: > > Does the command work OK from the console? > > Try from the python interpreter, using P_WAIT, and inspect the returned > > value. > That's what I've done. P_WAIT returned a the PID 127 - but there's > still no sign of the FLV-file, I'm afraid. This does not look like a Python issue then; you'll have to find the problem elsewhere. Perhaps the spawned process is blocked waiting for user input, by example? -- Gabriel Genellina From bj_666 at gmx.net Mon Apr 9 10:27:13 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Mon, 09 Apr 2007 16:27:13 +0200 Subject: Database in memory References: <1176124752.172926.129850@w1g2000hsg.googlegroups.com> Message-ID: In <1176124752.172926.129850 at w1g2000hsg.googlegroups.com>, Jim wrote: > I have an application that will maintain an in-memory database in the > form of a list of lists. Does anyone know of a way to search for and > retreive "records" from such a structure? Scan the list of lists with a ``for`` loop. Or build indexes with dictionaries. Ciao, Marc 'BlackJack' Rintsch From claird at lairds.us Tue Apr 24 16:45:41 2007 From: claird at lairds.us (Cameron Laird) Date: Tue, 24 Apr 2007 20:45:41 +0000 Subject: Generate report containing pdf or ps figures? References: <132pnp6r4qg0lc2@corp.supernews.com> <132sdmde3vg6kf3@corp.supernews.com> <132sn8eh1iphnf0@corp.supernews.com> Message-ID: In article <132sn8eh1iphnf0 at corp.supernews.com>, Grant Edwards wrote: >>> >>> In fairness to ReportLab I'd like to say that their *commercial* >>> products can do everything the OP asks for and more besides, but >>> unfortunately they are mostly targeted at the "enterprise" (read: big >>> money) market. >> >> This is just a smallish app for internal use by 1-2 people, so >> I probably can't justify spending much cash. I'll check on >> the ReportLab pricing. > >I can't even find any mention of a commercial version of >ReportLab on the web site. The FAQ says ReportLib is available >under the BSD license. Period. > >There are some other "projects" listed, but they don't appear >to be relevent. . . . From Leisure.208 at gmail.com Sun Apr 29 20:51:31 2007 From: Leisure.208 at gmail.com (Leisure.208 at gmail.com) Date: 29 Apr 2007 17:51:31 -0700 Subject: Get Mac OS X google Desktop 5 Free Message-ID: <1177894291.908867.303320@u30g2000hsc.googlegroups.com> http://macosxdesktop.blogspot.com/ - Mac OS X now compatible with google desktop 5. From mik3l3374 at gmail.com Sat Apr 14 06:51:06 2007 From: mik3l3374 at gmail.com (mik3l3374 at gmail.com) Date: 14 Apr 2007 03:51:06 -0700 Subject: list comparison help? In-Reply-To: References: Message-ID: <1176547866.855316.294540@e65g2000hsc.googlegroups.com> On Apr 14, 5:36 pm, "Dropkick Punt" wrote: > Hi. I have a list of common prefixes: > > >>> prefixes = [ "the", "this", "that", "da", "d", "is", "are", "r", "you", "u"] > > And I have a string, that I split() into a list. > > >>> sentence = "what the blazes is this" > >>> sentence = sentence.split() > > Now I want to strip the sentence of all words in the prefix list. > > I tried this method: > > >>> for x in prefixes: > > ... if sentence.index(x): > ... del sentence[sentence.index(x)] > > This raises, the error: > > Traceback (most recent call last): > File "", line 3, in ? > ValueError: list.index(x): x not in list > > This puzzles me, because if x isn't in the list, the subroutine shouldn't attempt to delete it > from the list, so I'm not sure why it's complaining. > > Can anybody explain this to me, &/or show me a better way to do it? >>> prefixes = [ "the", "this", "that", "da", "d", "is", "are", "r", "you", "u"] >>> sentence = "what the blazes is this" >>> sentence = sentence.split() >>> sentence ['what', 'the', 'blazes', 'is', 'this'] >>> set(sentence).difference(prefixes) set(['what', 'blazes']) From gagsl-py2 at yahoo.com.ar Sat Apr 7 15:46:49 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: 7 Apr 2007 12:46:49 -0700 Subject: Unicode problem In-Reply-To: References: Message-ID: <1175975209.261304.183220@p77g2000hsh.googlegroups.com> Rehceb Rotkiv wrote: > #!/usr/bin/python > import sys > import codecs > fileHandle = codecs.open(sys.argv[1], 'r', 'utf-8') > fileString = fileHandle.read() > print fileString > > if I call it from a Bash shell like this > > $ ./test.py testfile.utf8.txt > > it works just fine, but when I try to pipe the output to another process > ("|") or into a file (">"), e.g. like this > > $ ./test.py testfile.utf8.txt | cat > > I get an error: > > Traceback (most recent call last): > File "./test.py", line 6, in ? > print fileString > UnicodeEncodeError: 'ascii' codec can't encode character u'\xe4' in > position 538: ordinal not in range(128) > > I absolutely don't know what's the problem here, can you help? Using codecs.open, when you read the file you get Unicode. When you print the Unicode object, it is encoded using your terminal default encoding (utf8 I presume?) But when you redirect the output, it's no more connected to your terminal so no encoding can be assumed, and the default encoding is used. Try this line at the top: print "stdout:",sys.stdout.encoding,"default:",sys.getdefaultencoding() I get stdout: ANSI_X3.4-1968 default: ascii normally and stdout: None default: ascii when redirected. You have to encode the Unicode object explicitely: print fileString.encode("utf-8") (or any other suitable one; I said utf-8 just because you read the input file using that) -- Gabriel Genellina From basilisk96 at gmail.com Wed Apr 18 00:00:17 2007 From: basilisk96 at gmail.com (Basilisk96) Date: 17 Apr 2007 21:00:17 -0700 Subject: Getting started with python In-Reply-To: <1176598011.463543.96990@q75g2000hsh.googlegroups.com> References: <1176598011.463543.96990@q75g2000hsh.googlegroups.com> Message-ID: <1176868817.675179.231110@q75g2000hsh.googlegroups.com> On Apr 14, 8:46 pm, "Eric" wrote: > Hello, after reading some of the book Programming Python it seems that > python is something I would like to delve deeper into. The only thing > is, I have no idea what I should try and write. So I was hoping that > someone here could help point me to a group/project that would be a > good starting place for a person with limited python knowledge, but > that is willing to learn whatever is necessary. I'm hoping that with a > goal I can start to learn python instead of just playing around with > it. Thanks. Eric, You will certainly appreciate how concise and easy Python is. I am also relatively new to Python (started about a year ago), and I'd rather not go back to any other language! Why would I want to torment my not-so-quick typing fingers?? :) I'm a self-learner. I learn by reading, by example, and by doing. Here is a list of suggestions. Start with simple things, grow confident, and move on to more interesting stuff as you progress: At the Python command line, type "import this" to see the basic ideas behind Python development. It begins with "Beautiful is better than ugly." - a nice thought. 1. First of all, read the publication "How to Think Like a Computer Scientist: Learning with Python" by Allen B. Downey et al. I have found this little gem to be very, very useful when I first got interested in Python and thought to myself, "how do I go about learning this, where do I start??". Highly recommended. I read it from start to finish in a couple of days and started making useful scripts right after that. The author actually implements a simple card game toward the end of the book, using all the knowledge from the previous chapters. The text is available at: http://www.ibiblio.org/obp/thinkCSpy/ 2. Play with Python from the command line first, using PyShell, PyCrust, or any of its other siblings that come with the wxPython package (a GUI toolkit - see #8 below). You will find the code completion feature and the syntax helper quite useful. 3. Tinker around with the builtin modules. There's a lot of built-in functionality in Python right out of the box. Try the "os" and "sys" modules to experiment with filesystem handling. Try reading and writing text files, as this is quite a common task with a variety of applications. Try the "struct" module for binary file processing. Try the "urllib" and "urllib2" modules for loading and processing Web pages... I could go on, but you get the idea. 4. If you have a text processing background, dip your hand in regular expressions with the "re" module. Maybe you have a need for extracting some statistical data from a financial report, and this might be one way to do it. 5. If you have a mathematical background, download and install the NumPy or SciPy package and do some wild matrix math! 6. I have recently tinkered with the Pymedia package, perhaps you want to try it later on. It is a nice tool for dealing with audio - for recording, encoding, decoding, spectrum analysis, etc. In just a few hours, I came up with a nice voice-activated MP3 sound recorder application. 7. If you feel brave and want to work with Windows COM client/server stuff (assuming Windows is your platform), get the PythonWin package, also known as "win32com" and try to read/write Excel, Word files, etc., or whatever 8. Last but certainly not least, once you feel comfortable with basic Python, try GUI development. Several gui toolkits are out there. wxPython is a good one to start with, though you may find some others to your liking. 9. If you have previous programming experience, try taking an application you've developed before and port it to Python. See how much your code base shrinks compared to its C++ or Java counterpart :) But really, do it just to understand Python on a deeper level. Instead of thinking in the old way, try to think in the Pythonic way. A nice example of this is iteration. Where an iteration counter variable is required in most other languages, Python inherently supports iteration in sequence objects like lists, strings, and dictionary keys; so the syntax is simpler in most cases. -Basilisk96 From steve at REMOVE.THIS.cybersource.com.au Sat Apr 28 04:22:47 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Sat, 28 Apr 2007 18:22:47 +1000 Subject: Memory addressing References: <1177702902.156596.52510@n35g2000prd.googlegroups.com> <1177703803.179501.95300@n35g2000prd.googlegroups.com> <1177715277.592511.296990@h2g2000hsg.googlegroups.com> Message-ID: On Fri, 27 Apr 2007 16:07:57 -0700, castironpi wrote: > That's what we need: a CopyMemory() routine. What we _really_ need are Poke() and Peek() routines. -- Steven. From apardon at forel.vub.ac.be Thu Apr 12 10:10:12 2007 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 12 Apr 2007 14:10:12 GMT Subject: tuples, index method, Python's design References: <1175953520.316208.241490@o5g2000hsb.googlegroups.com> <7xzm5igbrb.fsf@ruckus.brouhaha.com> <1176200361.260546.280510@n76g2000hsh.googlegroups.com> <740c3aec0704100824m132c45fbi5c4c3ec0c0fa3a67@mail.gmail.com> Message-ID: On 2007-04-12, Steve Holden wrote: > Antoon Pardon wrote: >> On 2007-04-11, Terry Reedy wrote: >>> "BJrn Lindqvist" wrote in message >>> news:740c3aec0704100824m132c45fbi5c4c3ec0c0fa3a67 at mail.gmail.com... >>> On 4/10/07, Steve Holden wrote: >>>> One might perversely allow extension to lists and tuples to allow >>>> >>>> [3, 4] in [1, 2, 3, 4, 5, 6] >>>> >>>> to succeed, but that's forcing the use case beyond normal limits. >>> I'd love to have that! There are at least one million use cases for >>> finding a sequence in a sequence and implementing it yourself is >>> non-trivial. Plus then both list and tuple's index methods would work >>> *exactly* like string's. It would be easier to document and more >>> useful. A big win. >>> >>> ======================= >>> It would be ambiguous: [3,4] in [[1,2], [3,4], [5,6]] is True now. >>> >>> Strings are special in that s[i] can only be a (sub)string of length 1. >>> 'b' in 'abc' is True. This makes looking for longer substrings easy. >>> >>> However, [2] in [1,2,3] is False. IE, list[i] is not normally a list. So >>> looking for sublists is different from looking for items. >> >> Well I think this illustrates nicely what can happen if you design by >> use cases. >> >> Let us assume for a moment that finding out if one list is a sublist of >> a second list gets considered something usefull enough to be included >> in Python. Now the in operator can't be used for this because it >> would create ambiguities. So it would become either a new operator >> or a new method. But whatever the solution it would be different >> from the string solution. >> > That's because strings are different from other sequences. See below. > >> Now if someone would have thought about how "st1 in st2" would >> generalize to other sequemce if st1 contained more than one >> character they probably would have found the possible inconsistency >> that could create and though about using an other way than using >> the in-operator for this with strings. A way that wouldn't create >> ambiguities when it was considered to be extended to other sequences. >> > The fact is that strings are the only sequences composed of subsequences > of length 1 - in other words the only sequences where type(s) == > type(s[0:1]) is an invariant condition. Yes this allows you to do some things for strings in a way that would be impossible or ambiguous should you want to do the same things for other kind of sequences. The question is: should you? if you want to provide new functionality for strings and you have the choice between doing it 1) in a way, that will make it easy to extend this functionality in a consistent way to other sequences 2) in a way that will make it impossible to extend this functionality in a consistent way to other sequences. then I think that unless you have very good arguments you should pick (1). Because if you pick (2) even if this functionality is never extened in the language itself, you make it more difficult for programmers to add this functionality in a consistent way to a subclass of list themselves. People are always defending duck-typing in this news group and now python has chosen to choose the option that makes duck-typing more difficult. > This was discussed (at my instigation, IIRC) on python-dev when Python > (2.4?) adopted the enhanced semantics for "in" on strings - formerly > only tests for single characters were allowed - but wasn't thought > significant enough to deny what was felt to be a "natural" usage for > strings only. Which I consider a pity. -- Antoon Pardon From tiarno at sas.com Tue Apr 17 11:48:47 2007 From: tiarno at sas.com (Tim Arnold) Date: Tue, 17 Apr 2007 11:48:47 -0400 Subject: subprocess confusion References: Message-ID: "Nick Craig-Wood" wrote in message news:slrnf29k6m.c97.nick at irishsea.home.craig-wood.com... > Tim Arnold wrote: >> Should I just put the remsh in the actual command instead of >> preexec_fn? > > Yes. > > The preexec_fn is run after the fork() but before the exec(). Ie a > new process has been made, but it hasn't started your task yet. > > For example a classic use of preexec_fn is > > preexec_fn=os.setsid > > You seem to be thinking it is pre-pending something to your command > line which isn't how it works. > > -- > Nick Craig-Wood -- http://www.craig-wood.com/nick Thanks much to you and Michael H. for the great explanations. Now everything is working fine, and I understand subprocess a little better! --Tim Arnold From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Fri Apr 27 10:01:56 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Fri, 27 Apr 2007 16:01:56 +0200 Subject: My python annoyances so far References: <1177541453.471959.120830@c18g2000prb.googlegroups.com> <59bf34F2k27v5U1@mid.individual.net> <1177603623.774892.230390@t38g2000prd.googlegroups.com> <59chkcF2e6106U1@mid.individual.net> <1177677653.374768.170010@n35g2000prd.googlegroups.com> Message-ID: <59ee2kF2kdcb0U1@mid.individual.net> flifus at gmail.com wrote: > Well, I'd use ruby but python is everywhere, and ruby isn't. All > the applications that interest me are scriptable in python, not > ruby. Pity that you don't comment core topics. Regards, Bj?rn -- BOFH excuse #289: Interference between the keyboard and the chair. From arabzwaj4 at gmail.com Sat Apr 14 14:43:01 2007 From: arabzwaj4 at gmail.com (=?windows-1256?B?2tHIINLmx8w=?=) Date: 14 Apr 2007 11:43:01 -0700 Subject: =?windows-1256?B?dGhlIGJlc3Qgd2ViIHNpdGUgZm9ybWFycmlnZSBhbmQgZnJpbmRzaGlwIHd3dy5hcmFiendhai5jb23H3dbhIOPm3tog48zH5O0g4eHK2sfR3SDmIOHh0ubHzA==?= Message-ID: <1176576181.531188.199230@o5g2000hsb.googlegroups.com> ??? ???? ?????? ?????? ???? ?????? ????? ????? ??????? ????? ?? ?? ??? ?????? ???? ??? ???? ?? ?????? ??????? ????? ???? ???? ??????? ??? ????? ?? ?????? ??????? ?? ?? ??? ?????? www.arabzwaj.com ????? ?? ?? ??? ?????? ???? ????? ????? ????? ???????? ??? ????? ????? ????? ???? ???? ???? 5000 ????? ???? ????? ???? ???? ???????? ????? ???? ??? ?????? ????? http://www.arabzwaj.com/welcome/viewtopic.php?t=1952&sid=15f0596ebc9c205da75f65eb723025a2 ???? ???? ??????? ??? ????? ?? ?????? ??????? ?? ?? ??? ?????? www.arabzwaj.com ???? ????? ??????? ??????? ????? ??? ????? ?????? ????? ????? ?? ?? ??? ?????? www.arabzwaj.com for marrige and friend ship???? ????? ??? ?????? ??????? ???? ???? ????? www.arabzwaj.com www.arabzwaj.com ???? ???? ????? ??????? ? ?????? ?????? www.arabzwaj.com ???? ????? ????? ????? ????? the best web site formarrige and frindship www.arabzwaj.com???? ???? ????? ??????? ? ?????? From mad.vijay at gmail.com Thu Apr 12 07:57:26 2007 From: mad.vijay at gmail.com (SamG) Date: 12 Apr 2007 04:57:26 -0700 Subject: redirecting stdout to a file as well as screen In-Reply-To: References: <1176362072.527678.201150@l77g2000hsb.googlegroups.com> <1176368478.301318.35210@q75g2000hsh.googlegroups.com> <1176373423.576445.123220@y5g2000hsa.googlegroups.com> Message-ID: <1176379046.049098.253920@n76g2000hsh.googlegroups.com> On Apr 12, 3:42 pm, "Gabriel Genellina" wrote: > En Thu, 12 Apr 2007 07:23:43 -0300, SamG escribi?: > > > > >> >> > How could i make, from inside the program, to have the stdout and > >> >> > stderr to be printed both to a file as well the terminal(as usual). > > >> >> class Tee(file): > >> >> others = () > > >> >> def write(self, data): > >> >> file.write(self, data) > >> >> for f in others: > >> >> f.write(data) > > >> > This is only creating an out.log file and all the stdout and stderr > >> > are logged there. > > >> Sorry, `for f in others:` should read `for f in self.others:` > > > Does not make difference, does this work for you? Im working on linux. > > But this code looks portable except for the file path :) > > Yes. And it's rather similar to your other example... Omit sys.stderr as > Antoon Pardon suggested. > > -- > Gabriel Genellina Thanks people i have got it working now... with this program! #END import sys class multicaster(object): def __init__(self, filelist): self.filelist = filelist def write(self, str): for f in self.filelist: f.write(str) log_file=open('out.log','w') mc = multicaster([sys.stderr, log_file]) sys.stdout = mc sys.stderr = mc sys.stdout.write( "Mojozoox\n") sys.stderr.write( "Hello\n") #END works perfect for my needs. From paul at boddie.org.uk Tue Apr 3 06:13:55 2007 From: paul at boddie.org.uk (Paul Boddie) Date: 3 Apr 2007 03:13:55 -0700 Subject: Standard Library Structure (was Re: Shed Skin Python-to-C++ Compiler 0.0.21, Help needed) In-Reply-To: <1175537817.989894.125020@b75g2000hsg.googlegroups.com> References: <576vhbF2ca1guU1@mid.individual.net> <1175376373.241744.6220@y80g2000hsf.googlegroups.com> <1175413310.295953.230840@e65g2000hsc.googlegroups.com> <1175455529.936887.249170@e65g2000hsc.googlegroups.com> <1175496721.899984.193690@n76g2000hsh.googlegroups.com> <1175509861.292455.226280@b75g2000hsg.googlegroups.com> <1175511923.323321.30220@n76g2000hsh.googlegroups.com> <1175513253.595204.220110@o5g2000hsb.googlegroups.com> <1175537817.989894.125020@b75g2000hsg.googlegroups.com> Message-ID: <1175595235.102878.225260@n59g2000hsh.googlegroups.com> On 2 Apr, 20:17, "Kay Schluehr" wrote: > > Note that the conflict of putting modules on top level or better > within separate packages is not an either-or decision from a > programmers point of view who just wants to access those modules. A > top level module like lib or std can be pretty virtual since you can > create modules at runtime whenever you try to import them. Or, if the subpackages/submodules are small enough, just import them and make their contents available at higher levels in the hierarchy. > I used this strategy for a project where editing objects in separate files leaded > to a better overview compared to one large file containing all > definitions. However I created one module at runtime that served as a > common access point for all these particular definitions that were > tedious to import separately and would have required file system > lookups quite often. This might even allow multiple classifications > but I haven't experimented with them yet. Yes, I tend to make aliases available quite a bit. It seems to me that introducing a hierarchy into the standard library has a fairly limited cost: you need to occupy some more top-level names, some unfortunately being potentially common, but any growth in the library isn't as likely to introduce more naming conflicts - something that anyone with their own calendar.py, new.py or xml.py programs might find desirable. ;-) One problem I've become more aware of, however, is the role of C-based modules in the library. I think there was an unresolved issue about such modules living at non-root locations in the library hierarchy, but aside from that, the work required to clean up any abstractions eventually requires people to roll up their sleeves and look at non- Python code. Paul From martin at v.loewis.de Sat Apr 14 01:49:03 2007 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sat, 14 Apr 2007 07:49:03 +0200 Subject: Portably generating infinity and NaN In-Reply-To: <17952.3072.690960.419104@montanaro.dyndns.org> References: <462008d1$0$11763$9b622d9e@news.freenet.de> <17952.3072.690960.419104@montanaro.dyndns.org> Message-ID: <46206B4F.1040105@v.loewis.de> > I don't know. On I was just asking. On unixoid systems I sort of assume > you could add tests to the configure script to detect what worked. If > converting the strings works you're done. If not, maybe Robert Kern's numpy > code could be run in the configure script to generate constants for NaN and > Inf that could be used in floatmodule.c. Windows would probably have to be > hard-coded, but except for 32-bit and 64-bit differences it should be the > same all over, yes? I cannot imagine what the constants would look like. For +/-inf, it might be possible to write down an expression that causes an overflow. For NaN, I cannot think of such an expression (also, there are many possible values that are all not-a-number - which of them should be denoted by float("NaN")?). Even if you determine at configure time whether or not the C library already supports strtod("inf") and even if you then special-case Windows - what do you do with platforms where neither approach works? In short, I cannot think of a way to do that portably on all platforms in C. If there was such a way, it probably would have been implemented long ago. Regards, Martin From maxime.p at gmail.com Sun Apr 1 08:13:55 2007 From: maxime.p at gmail.com (Ulysse) Date: 1 Apr 2007 05:13:55 -0700 Subject: Extract information from HTML table Message-ID: <1175429635.278697.92690@b75g2000hsg.googlegroups.com> Hello, I'm trying to extract the data from HTML table. Here is the part of the HTML source : """ Sat, 31.03.2007 - 20:24:00
Vous avez tendu une embuscade ? votre victime ! Sat, 31.03.2007 - 20:14:35 Vous avez tendu une embuscade ? votre victime ! Sat, 31.03.2007 - 20:11:39 Vous avez bien accompli votre t?che de Gardien de Cimeti?re et vous vous voyez remis votre salaire comme r?compense. Vous recevez 320 Or et collectez 3 d'exp?rience ! """ I would like to transform this in following thing : Date : Sat, 31.03.2007 - 20:24:00 ContainType : Link LinkText : Vous avez tendu une embuscade ? votre victime ! LinkURL : http://s2.bitefight.fr/bite/bericht.php?q=01bf0ba7258ad976d890379f987d444e&beid=2628033 Date : Sat, 31.03.2007 - 20:14:35 ContainType : Link LinkText : Vous avez tendu une embuscade ? votre victime ! LinkURL : http://s2.bitefight.fr/bite/bericht.php?q=01bf0ba7258ad976d890379f987d444e&beid=2628007 Date : Sat, 31.03.2007 - 20:14:35 ContainType : Text Contain : Vous avez bien accompli votre t?che de Gardien de Cimeti?re et vous vous voyez remis votre salaire comme r?compense. Vous recevez 320 et collectez 3 d'exp?rience ! .... Do you know the way to do it ? Thanks From a.schmolck at gmail.com Fri Apr 27 04:16:01 2007 From: a.schmolck at gmail.com (Alexander Schmolck) Date: Fri, 27 Apr 2007 09:16:01 +0100 Subject: List objects are un-hashable References: <1177660237.470851.170200@s33g2000prh.googlegroups.com> Message-ID: Andy writes: > Hi, I'm trying to search and print any no# of Python keywords present > in a text file (say - foo.txt), and getting the above error. Sad for > not being able to decipher such a simple problem (I can come up with Without looking at the docs, it seems save to assume keywords.iskeyword would expect a string. You pass it a list. > other ways - but want to fix this one FFS). Any help is appreciated. > Thanks!! > > import keyword, re, sys, string > inp = open("foo.txt", "r") words = sum(1 for line in inp for w in line.split() if keyword.iskeyword(w)) 'as From stargaming at gmail.com Mon Apr 2 14:52:04 2007 From: stargaming at gmail.com (Stargaming) Date: Mon, 02 Apr 2007 20:52:04 +0200 Subject: Error when trying to pass list into function. In-Reply-To: <1175539402.046635.196310@b75g2000hsg.googlegroups.com> References: <1175539402.046635.196310@b75g2000hsg.googlegroups.com> Message-ID: erikcw schrieb: > Hi, > > I'm getting the following error when I try to pass a list into a > function. > > My List: crea =[(u'218124172', u'536', u'32394'), (u'218320282', > u'1323', u'77931')] > > Traceback (most recent call last): > File "wa.py", line 118, in ? > curHandler.walkData() > File "wa.py", line 49, in walkData > self.results[parent][child]['results'] = self.calculate(crea) > #pass in list of tuples > TypeError: calculate() takes exactly 1 argument (2 given) > > def calculate(dta): > #stub > > How can I make this work? > > Thanks! > Erik > The first argument to a method (a function bound to an instance) is always the instance itself. (I assume you *have* a method here because you call self.calculate(crea), what will itself call SomeClass.calculate(self, crea).) For further information, consult the python tutorial http://docs.python.org/tut/node11.html#SECTION0011400000000000000000. HTH, Stargaming From 12cc104 at gmail.com Fri Apr 27 10:10:18 2007 From: 12cc104 at gmail.com (proctor) Date: 27 Apr 2007 07:10:18 -0700 Subject: regex question In-Reply-To: <1177659238.159411.40640@c18g2000prb.googlegroups.com> References: <1177655637.717863.93920@o40g2000prh.googlegroups.com> <1177659238.159411.40640@c18g2000prb.googlegroups.com> Message-ID: <1177683018.566343.105620@c18g2000prb.googlegroups.com> On Apr 27, 1:33 am, Paul McGuire wrote: > On Apr 27, 1:33 am, proctor <12cc... at gmail.com> wrote: > > > > > hello, > > > i have a regex: rx_test = re.compile('/x([^x])*x/') > > > which is part of this test program: > > > ============ > > > import re > > > rx_test = re.compile('/x([^x])*x/') > > > s = '/xabcx/' > > > if rx_test.findall(s): > > print rx_test.findall(s) > > > ============ > > > i expect the output to be ['abc'] however it gives me only the last > > single character in the group: ['c'] > > > C:\test>python retest.py > > ['c'] > > > can anyone point out why this is occurring? i can capture the entire > > group by doing this: > > > rx_test = re.compile('/x([^x]+)*x/') > > but why isn't the 'star' grabbing the whole group? and why isn't each > > letter 'a', 'b', and 'c' present, either individually, or as a group > > (group is expected)? > > > any clarification is appreciated! > > > sincerely, > > proctor > > As Josiah already pointed out, the * needs to be inside the grouping > parens. > > Since re's do lookahead/backtracking, you can also write: > > rx_test = re.compile('/x(.*?)x/') > > The '?' is there to make sure the .* repetition stops at the first > occurrence of x/. > > -- Paul i am working through an example from the oreilly book mastering regular expressions (2nd edition) by jeffrey friedl. my post was a snippet from a regex to match C comments. every 'x' in the regex represents a 'star' in actual usage, so that backslash escaping is not needed in the example (on page 275). it looks like this: =========== /x([^x]|x+[^/x])*x+/ it is supposed to match '/x', the opening delimiter, then ( either anything that is 'not x', or, 'x' one or more times, 'not followed by a slash or an x' ) any number of times (the 'star') followed finally by the closing delimiter. =========== this does not seem to work in python the way i understand it should from the book, and i simplified the example in my first post to concentrate on just one part of the alternation that i felt was not acting as expected. so my question remains, why doesn't the star quantifier seem to grab all the data. isn't findall() intended to return all matches? i would expect either 'abc' or 'a', 'b', 'c' or at least just 'a' (because that would be the first match). why does it give only one letter, and at that, the /last/ letter in the sequence?? thanks again for replying! sincerely, proctor From daraburke78 at gmail.com Wed Apr 18 20:52:04 2007 From: daraburke78 at gmail.com (dbee) Date: 18 Apr 2007 17:52:04 -0700 Subject: Third party script debugging on remote server ... In-Reply-To: <1176939110.773939.83160@p77g2000hsh.googlegroups.com> References: <1176938153.119084.214700@d57g2000hsg.googlegroups.com> <1176939110.773939.83160@p77g2000hsh.googlegroups.com> Message-ID: <1176943924.267007.182270@q75g2000hsh.googlegroups.com> On Apr 19, 12:31 am, Graham Dumpleton wrote: > After calling whatever it is that is writing to standard output/error, > do: > > import sys > sys.stdout.flush() > sys.stderr.flush() > > This should cause any buffered data to be immediately flushed to the > main Apache error log, ie., don't look in any virtual host logs, check > the main one. > > Graham > > On Apr 19, 9:15 am, dbee wrote: > > > Right. I've got a really, really annoying/difficult/time consuming > > problem with my development environment. I'm using django to build a > > web app with paypal integration. My server is hosted remotely, and it > > is receiving IPN (payment notifications) POST requests from Paypal. > > I've checked on google and irc and this is my last shot at solving > > this before I go mad ... :-( > > > The problem is that I can't debug those POST requests. Browser > > debugging is out of the question obviously cause I'm not at the > > computer, ( and it doesn't have X ). > > > I've tried cgitb but that doesn't seem to work at all ... > > > import cgitb; cgitb.enable(display=0,logdir='/tmp/',format='plain') > > import cgitb; cgitb.enable() > > > ... neither of those commands have any effect. Although I do log other > > parts of the script to /tmp, so I know that it's reachable... > > > mod_pythonabsolutely refuses to error_log to the apache error_log. I > > have restarted it and it still won't flush whatever error buffer it > > may ( or may not ) have stored. > > > I can re-constitute the requests in my browser using a GET request. > > But frankly, that's kinda messy - there are lots of paypal IPN > > combinations and I may have to integrate other applications with > > paypal. So ideally speaking I'm looking for a proper debugging > > environment for this kind of thing ... > > > Basically, I either wantmod_pythonto start error_logging properly, > > or I want some type of working traceback environment to be available. > > Help ! > > > Server version: Apache/2.0.52 > > Server built: Aug 13 2006 03:29:43 > > CentOS4.x: (RedHat Clone)mod_python.i386 3.1.3-5.1 > > installed > > > # httpd.conf > > > > > > ServerName mydomain.biz > > ServerAliaswww.mydomain.biz > > SetHandlermod_python > > PythonPath "['/home/babo/django'] + sys.path" > > PythonHandler django.core.handlers.modpython > > SetEnv DJANGO_SETTINGS_MODULE mydomain.settings > > > > > SetHandler None > > Options None > > > > > > > > My python.conf: ( seems pretty normal ) > > > # > > #Mod_pythonis a module that embeds the Python language interpreter > > # within the server, allowing Apache handlers to be written in Python. > > # > > > LoadModule python_module modules/mod_python.so > > > # Override type-map handler for /var/www/manual > > > > > > SetHandler default-handler > > > > > > > # This will cause files beneath /var/www/html with the extension .spam > > # to be handled by the Python script /var/www/html/eggs.py > > # > > # > > # AddHandler python-program .spam > > # PythonHandler eggs > > # > > > # This will cause all requests to the /python heirachy of your > > # webserver to be handled by the python script /path/to/myhandler.py > > # > > # > > # SetHandler python-program > > # PythonPath "sys.path + ['/path/to']" > > # PythonHandler myhandler > > # > > > # This will cause all requests to the /python heirachy of your > > # webserver to be handled bymod_python'sPublisher handler > > # (seehttp://localhost/manual/mod/mod_python/hand-pub.html) > > # > > # This will cause the output of all requests to files beneath > > # /var/www/html with the extension .flt to be filtered through > > # the Python script /var/www/html/filter.py > > # > > # > > # PythonOutputFilter filter MYFILTER > > # AddOutputFilter MYFILTER .flt > > # Hi Graeme, Thanks for the suggestion. Unluckily for me, it doesn't seem to be working though ... I've tried it a number of different ways. I guess if I put the code after an exception, then the code won't be called. So I ran an error in the python script and then I called the sys.stderr.flush() from the python shell. No luck though. I called on it's own, still no luck, Then I tried ... try: raise Exception('Please log this error') except: import sys sys.stderr.flush() sys.stdout.flush() The error log still has no error info in it :-( .... Is this problem unique to me ? This is startup message that gets posted to error_log on apache restart ... (The IIS string is a mod_sec Security Signature) [Wed Apr 18 19:58:25 2007] [notice] mod_python: (Re)importing module 'django.core.handlers.modpython' [Wed Apr 18 19:58:32 2007] [notice] mod_python: (Re)importing module 'django.core.handlers.modpython' DEBUG: InitPostgres DEBUG: InitPostgres [Wed Apr 18 19:59:56 2007] [notice] caught SIGTERM, shutting down [Wed Apr 18 19:59:57 2007] [notice] suEXEC mechanism enabled (wrapper: /usr/sbin/suexec) [Wed Apr 18 19:59:57 2007] [notice] mod_security/1.9.4 configured - Apache/2.0.52 (CentOS) [Wed Apr 18 19:59:58 2007] [notice] Digest: generating secret for digest authentication ... [Wed Apr 18 19:59:58 2007] [notice] Digest: done [Wed Apr 18 19:59:58 2007] [notice] LDAP: Built with OpenLDAP LDAP SDK [Wed Apr 18 19:59:58 2007] [notice] LDAP: SSL support unavailable [Wed Apr 18 19:59:58 2007] [notice] mod_python: Creating 4 session mutexes based on 256 max processes and 0 max threads. [Wed Apr 18 19:59:58 2007] [notice] Microsoft-IIS/5.0 configured -- resuming normal operations There are no python debug messages ... Also, I've reinstalled mod_python, but it makes no difference. And put this into my VirtualHost, just in case ... PythonDebug On Is there any answer for my problem ? From eight02645999 at yahoo.com Fri Apr 13 03:57:58 2007 From: eight02645999 at yahoo.com (eight02645999 at yahoo.com) Date: 13 Apr 2007 00:57:58 -0700 Subject: which version libpcap Message-ID: <1176451078.244945.45290@y5g2000hsa.googlegroups.com> hi from the web, i found 2 kinds of wrappers for libpcap, one is pylibpcap, the other is pcapy. may i know which is more popularly used? thanks From cam.ac.uk at mh391.invalid Mon Apr 2 15:08:40 2007 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Mon, 02 Apr 2007 20:08:40 +0100 Subject: Clean "Durty" strings In-Reply-To: <1175530649.060784.147900@d57g2000hsg.googlegroups.com> References: <1175463083.135907.128480@y80g2000hsf.googlegroups.com> <57bt02F2c9fpuU2@mid.uni-berlin.de> <57cddlF2bsqdbU2@mid.uni-berlin.de> <1175530649.060784.147900@d57g2000hsg.googlegroups.com> Message-ID: irstas at gmail.com wrote: > But it could be that he just wants all HTML tags to disappear, like in > his example. A code like this might be sufficient then: re.sub(r'<[^>] > +>', '', s). Won't work for, say, this: <text> -- Michael Hoffman From mail at timgolden.me.uk Sun Apr 8 03:07:52 2007 From: mail at timgolden.me.uk (Tim Golden) Date: Sun, 08 Apr 2007 08:07:52 +0100 Subject: How to tell when a file is opened In-Reply-To: <1175998621.538446.177880@y80g2000hsf.googlegroups.com> References: <1175960486.759715.317140@y80g2000hsf.googlegroups.com> <1175970161.126550.257090@n59g2000hsh.googlegroups.com> <1175998621.538446.177880@y80g2000hsf.googlegroups.com> Message-ID: <461894C8.3030109@timgolden.me.uk> momobear wrote: >> Will look into NTFS change journals when I get some spare time. > How can we get NTFS change journals? Is there any API for this purpose > or we could implement our own? > there're an api in windows help us montior file changes. > win32file.ReadDirectoryChangesW Don't know what the API is but whatever it ends up being, there's always ctypes. This article: http://www.codeproject.com/useritems/Eyes_on_NTFS.asp points to DeviceIOControl and CreateFile, both in the win32file module. The problem with win32file.ReadDirectoryChangesW, which the OP probably saw when he looked at my site (though he doesn't actually say so) is that you're trying to monitor *an entire hard disk*, maybe more. And you'll almost certainly run into buffer shortfalls or even performance issues. But I don't really have access to a big enough or used enough disk to carry out a meaningful test. TJG From steve at holdenweb.com Wed Apr 25 09:42:17 2007 From: steve at holdenweb.com (Steve Holden) Date: Wed, 25 Apr 2007 09:42:17 -0400 Subject: When are immutable tuples *essential*? Why can't you just use lists *everywhere* instead? In-Reply-To: References: <1177088796.622928.224890@d57g2000hsg.googlegroups.com> <1177089206.550423.288670@q75g2000hsh.googlegroups.com> <58sf33F2b1q8tU1@mid.individual.net> <1177103370.022138.110320@n59g2000hsh.googlegroups.com> <1177108560.660288.171890@n76g2000hsh.googlegroups.com> <1177451173.176235.216270@t38g2000prd.googlegroups.com> Message-ID: Neil Cerutti wrote: > On 2007-04-24, Thomas Nelson wrote: >> On Apr 23, 10:38 pm, Mel Wilson wrote: >>> Even with a balanced tree, if a key in a node changes value, >>> you may have to re-balance the tree. Nothing in a Python list >>> says that a dictionary tree would have to be re-balanced if >>> you changed that particular list. >> You don't have to look at any implementation. A dictionary >> maps every key to exactly one object. If the objects were >> mutable, you could change one key to another key, and then >> which item would the dictionary pull? >> (Imaginary code) >> d = {[1,2,3]: 'hat', [1,2,4]: 'sock' } >> for key in d: >> key.pop() >> print d[[1,2]] #does this print hat or sock? > > That would be documented as undefined behavior, and users > exhorted not to do such things. > > Python's dictionaries are a proven winner--I'm definitely not an > advocate for changing them. But the general requirement for a > mapping container *isn't* that keys be immutable, but that you > either don't mutate keys, or don't do so without also reording > (rehashing?) the mapping. > And which API do you use to "reord(er?) (rehash) the mapping"? regards Steve -- Steve Holden +1 571 484 6266 +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 holdenweb.com Wed Apr 18 16:30:17 2007 From: steve at holdenweb.com (Steve Holden) Date: Wed, 18 Apr 2007 16:30:17 -0400 Subject: Help Understanding mx.ODBC Error In-Reply-To: <10065545.post@talk.nabble.com> References: <10063746.post@talk.nabble.com> <10065545.post@talk.nabble.com> Message-ID: Greg Corradini wrote: [actually, her wrote it here but I moved it to the bottom] > Steve Holden wrote: >> Greg Corradini wrote: >>> Hello All, >>> A few weeks ago, I wrote two scripts using mx.ODBC on an Access DB. Among >>> other things, both scripts create new tables, perform a query and then >>> populate the tables with data in a dictionary that I've uploaded from >>> elsewhere. These scripts have run hundreds of times in the last few weeks >>> with no problems. >>> >>> But recently they continue to bail on the mycursor.execute('An SQL >>> Statement') after the table has been created. I get the following error >>> message: >>> Traceback (most recent call last): >>> File "C:\Documents and Settings\marv1shi\Desktop\Workspace\Existence >>> Script\DBF Checker\Access_SQL.py", line 35, in ? >>> curse.execute(sql) >>> ProgrammingError: ('07001', -3010, '[Microsoft][ODBC Microsoft Access >>> Driver] Too few parameters. Expected 4.', 4612) >>> >>> The real stinker, however, is that after it bails I can manually call >>> mycursor.execute('An SQL Statement'), then call my insert statement in >>> the >>> Python Shell and it works fine. >>> >>> I just can't figure out how to reconcile this problem. Has anybody run >>> into >>> this before? >>> >>> Thanks >>> Greg Corradini >> I suspect what's happening here is that you are presenting statements >> you have made up programmatically, and the values you are trying to >> insert include apostrophes that break the syntax of your SQL. However >> there isn't really enough evidence to decide unless you are prepared to >> show us the error traceback, possibly with a dump of the SQL statement >> you are actually trying to execute. >> >> I apologize in advance if you are using parameterized queries (as you >> should to avoid SQL injection vulnerabilities among other major >> problems) but this message is typical of Access when it sees words it >> can't parse. >> > Steve, > As always, thanks for your consistent help on matters big and small. > I've managed to solve the problem, although I'm scared b/c the bug is still > elusive. > I dumped and deleted my separate Access DBs, created new ones and tried > running the scripts on old data (that these scripts were able to digest > successfully before) and new data (that they errored on to begin with). > Everything works without me changing any code around. Hmm? > > I don't know much about Access or the JetEngine. Is it possible that .mdbs > can go corrupt if overused? This seems unlikely, but I'm dumbfounded. Greg: No, there are no known cases of a database getting "tired" :-) It sounds like a data dependency of some sort, but if the error has "gone away" then I guess we no longer have anything to work with. This is somewhat annoying, as I hate to see an error go untraced. Take it from me, it does look like a SQL error - *are* you building your statements in the program, or are you using proper parameterization with "?" in your statements where a parameter would go? 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 mwilson at the-wire.com Thu Apr 19 23:27:00 2007 From: mwilson at the-wire.com (Mel Wilson) Date: Thu, 19 Apr 2007 23:27:00 -0400 Subject: List of Objects In-Reply-To: <1177037915.042476.153190@n76g2000hsh.googlegroups.com> References: <1177037915.042476.153190@n76g2000hsh.googlegroups.com> Message-ID: datamonkey.ryan at gmail.com wrote: > Howdy, a (possibly) quick question for anyone willing to listen. > I have a question regarding lists and Classes; I have a class called > "gazelle" with several attributes (color, position, etc.) and I need > to create a herd of them. I want to simulate motion of individual > gazelles, but I don't want to have to go through and manually update > the position for every gazelle (there could be upwards of 50). I was > planning to create an array of these gazelle classes, and I was going > to iterate through it to adjust the position of each gazelle. That's > how I'd do it in C, anyway. However, Python doesn't support pointers > and I'm not quite sure how to go about this. Any help you can provide > would be greatly appreciated. > Thanks a lot! You don't want a herd of the Platonic type of gazelle, you want a herd of individual instances of the class of gazelle. No problem. Something like class Gazelle(object): def __init__ (self, color, position) self.color = color self.position = position # ... herdsize = 30 herd = [] for i in xrange (herdsize) color, position = function_to_supply_a_gazelle's_attributes() herd.append (Gazelle (color, position) # ... while true: for gazelle in herd: do_something_to (gazelle) > > -Ryan > From victor.lebrun at gmail.com Sat Apr 28 16:32:37 2007 From: victor.lebrun at gmail.com (vml) Date: 28 Apr 2007 13:32:37 -0700 Subject: python and activeX control Message-ID: <1177792357.047096.18480@q75g2000hsh.googlegroups.com> I have an application that I want to automatised trough a COM layer or (DCOM)... I can access to all the method of the COM objects with python and win32com when this application is running.... If the application is not running, I can not access to all the method of the object. Usually to overcome this problem , One can use an activeX control which is just a bitmap in a form in VB(6)... and then the code is : Dim module As Automation.IModule Dim myBlock as Automation.IBlock2 Dim myDatabase As Automation.IDatabase Set module = ActiveXModuleLoader1.module myDatabase = module.Database("C:/Data/myproj") I can have active X ModuleLoader._DActiveXModuleLoader running under python without a GUI but when you call the .module method of this object it crashes.... : Traceback (most recent call last): File "", line 1, in File "D:\soft\python25\lib\site-packages\win32com\client \__init__.py", line 458, in __getattr__ return self._ApplyTypes_(*args) File "D:\soft\python25\lib\site-packages\win32com\client \__init__.py", line 451, in _ApplyTypes_ dispid, 0, wFlags, retType, argTypes, *args), com_error: (-2147418113, 'Catastrophic failure', None, None) my questions : - Do you have ideas to do translate the vb code into python ? -In a module genrated by makepy : what can I call as object : coclass or Dipatch base class ?\ -Do you know how to integrate an activeX control in a python GUI ( wxpython ) ? WOuld it solve my problems ? - Why I can not access all the method of an object when the application is not running ? Is there a way to do it ? - can I create a Ghost of such an application to be able to have all the method on all the objects ? - Can I create a vb code which contains all the code for the com objects and then try to use python with scipy to do some mathematical operations on the data? I would like to do every thing in python but I am a newbie .... Thanks in advance ! From kelvin.you at gmail.com Mon Apr 23 05:53:54 2007 From: kelvin.you at gmail.com (=?utf-8?B?5Lq66KiA6JC95pel5piv5aSp5rav77yM5pyb5p6B5aSp5rav5LiN6KeB5a62?=) Date: 23 Apr 2007 02:53:54 -0700 Subject: ctypes: how to make a structure pointer to point to a buffer In-Reply-To: <593dc9F2j7kl9U1@mid.uni-berlin.de> References: <1177316640.305123.52040@y5g2000hsa.googlegroups.com> <593dc9F2j7kl9U1@mid.uni-berlin.de> Message-ID: <1177322034.304531.302620@q75g2000hsh.googlegroups.com> On Apr 23, 5:42?pm, "Diez B. Roggisch" wrote: > ??????????????? wrote: > > first, I'm try the POINTER to convesion the pointer type. but failed. > > > class STUDENT(Structure): > > ? ? _fields_ = [('name', ?c_int), > > ? ? ? ? ? ? ? ? ? ? ('id', ? c_int), > > ? ? ? ? ? ? ? ? ? ? ('addition', ? ?c_ubyte)] > > > buffer = c_byte * 1024 > > student_p = cast(buffer, POINTER(STUDENT)) > > > The parameter of the POINTER must be ctypes type. > > How could I attach the buffer pointer to the structure STUDENT ? > > I think it should work like this: > > from ctypes import * > > class STUDENT(Structure): > ? ? _fields_ = [('name', ?c_int), > ? ? ? ? ? ? ? ? ? ? ('id', ? c_int), > ? ? ? ? ? ? ? ? ? ? ('addition', ? ?c_ubyte)] > > buffer = (c_byte * 1024)() > buffer_p = pointer(buffer) > student_p = cast(buffer_p, POINTER(STUDENT)) > > print student_p > > Diez yes, it should add the bracket buffer = (c_byte * 1024)() Thank you ! From nagle at animats.com Sat Apr 7 00:30:05 2007 From: nagle at animats.com (John Nagle) Date: Sat, 07 Apr 2007 04:30:05 GMT Subject: block scope? In-Reply-To: <7xr6qwal50.fsf@ruckus.brouhaha.com> References: <7xr6qwal50.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > James Stroud writes: > >>Probably, with good code, block scope would be overkill, except that I >>would welcome list comprehensions to have a new scope: > > > Block scope is a win because it gets rid of the uncertainty of whether > the variable is used outside the block or not. In a language with few declarations, it's probably best not to have too many different nested scopes. Python has a reasonable compromise in this area. Functions and classes have a scope, but "if" and "for" do not. That works adequately. Javascript got it wrong. They have declarations, but the default, in the absence of a declaration, is global, not local or an error. Bad design. It's a result of retrofitting declarations to a language, which usually has painful aftereffects. John Nagle From steve at holdenweb.com Sat Apr 28 14:27:36 2007 From: steve at holdenweb.com (Steve Holden) Date: Sat, 28 Apr 2007 14:27:36 -0400 Subject: Cgi File Upload without Form In-Reply-To: <1177708242.553577.226530@n15g2000prd.googlegroups.com> References: <1177708242.553577.226530@n15g2000prd.googlegroups.com> Message-ID: <46339218.6090108@holdenweb.com> Karsten.G.Weinert at googlemail.com wrote: > Hello, > > what is the simplest way to upload a file (or a long string) to a > server using cgi/python? > > Since I want to upload the data programmatically, a form based > solution is not good. I am not experienced with SOAP/WSDL and I > believe that would be more difficult than necessary. The client > program I have to use does not support FTP. > A "form-based" solution is actually just what you want - you write a Python program that does just what the user's browser would do after they filled in a form. You can do this with urllib fairly easily. If you get stuck then look for a library called mechanise. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden ------------------ Asciimercial --------------------- Get Python in your .sig and on the web. Blog and lens holdenweb.blogspot.com squidoo.com/pythonology tag items: del.icio.us/steve.holden/python All these services currently offer free registration! -------------- Thank You for Reading ---------------- From Eric_Dexter at msn.com Wed Apr 18 04:07:55 2007 From: Eric_Dexter at msn.com (Eric_Dexter at msn.com) Date: 18 Apr 2007 01:07:55 -0700 Subject: (python papers on tape) anyone wan't audio tutorial w thier software Message-ID: <1176883675.323737.31300@e65g2000hsc.googlegroups.com> http://www.lulu.tv/?p=7841 issue 1 http://www.lulu.tv/?p=7897 issue 2 I am playing around with audio blogs and realised that help tutorials can be distributed as links to an audio file hosted on the internet.. The robot voice isn't the way I would do it though.... anyone intrested??? From jstroud at mbi.ucla.edu Fri Apr 27 19:26:10 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Fri, 27 Apr 2007 16:26:10 -0700 Subject: Portable SciPy v0.1 released In-Reply-To: <1177714703.751242.61090@e65g2000hsc.googlegroups.com> References: <2418d$463275ce$d443bb3a$25239@news.speedlinq.nl> <1177714703.751242.61090@e65g2000hsc.googlegroups.com> Message-ID: Beliavsky wrote: > On Apr 27, 6:17 pm, Stef Mientki > wrote: > >>Portable SciPy, is an easy installer of SciPy for M$ windows users. > > > If you have an announcement for Windows users, I suggest that you not > needlessly turn them off by abbreviating Microsoft as M$ . You don't > like Windows, but many of us Windows users don't like the anti-Windows > snobs. There is nothing wrong with making money by selling software. > Yes, dollar signs are very derogatory. Please do not use them in the future, either as prefixes to variables, or especially as suffixes to abbreviations. This is a *python* list for crying out loud! James From aleax at mac.com Sun Apr 29 20:18:17 2007 From: aleax at mac.com (Alex Martelli) Date: Sun, 29 Apr 2007 17:18:17 -0700 Subject: Numbers and truth values References: <1hxa95b.13zrrmv1wucw71N%aleax@mac.com> <1177854961.385898.221410@n59g2000hsh.googlegroups.com> Message-ID: <1hxbxil.1ps4bb71p1vo1dN%aleax@mac.com> Beliavsky wrote: ... > > If this has changed in the Fortran 1990 standard or later, then I can > > only say I'm happy I stopped using Fortran heavily before such standards > > became widespread in commonly available compilers -- by the late '90s, > > when I was still using _some_Fortran, it was Fortran '77, as that was > > the version that was widely available and well optimized. > > I don't think the official status of such has changed -- it's still > illegal to change a constant and the compiler is still not required to > catch the error Oh good -- I'm happy to hear that the original spirit IS still around. > -- but compilers may be more likely to reject > such code as before, helping programmers spot errors. IMO that's a > good thing. In general, as an engineer, I think that making tools more complicated so that a single tool can serve multiple purposes is not necessarily a win. I do not want one pair of shoes that are designed to be excellent for running AND for dancing AND for mountain hiking: I'd much rather have three specialized pairs of shoes instead, one pair for running, one for dancing, one for hiking. Similarly, I'd rather have one tool to take presumably-correct sources and generate great machine code from them, and separate tools to nitpick the bejeezus out of the sources to make really sure they ARE indeed perfectly correct from all viewpoints. Two (or more) simple, fully specialized tools make for a better toolbox than one complex, multi-purpose one. Few except engineers seem to understand this. > When is no longer using a language, one has the luxury of thinking > about it in an ideological rather than practical manner. I thought about Fortran in exactly the same way when I was doing most of my coding in it, and also using it to teach "numerical computing" in university. Most errors came (and still come) from people who just don't understand the underlying mathematical nature and realities of floating point (and numerical computations more generally), and I never expected a compiler to magically start warning the user about "you're using a very badly conditioned algorithm for this computation":-), the one thing that would have really saved me a lot of time in my advisory and teaching roles. Exactly the same problems keep surfacing in programs in Python and any other language too, barely veiled by today's growing propensity for double-precision and wider-yet floats; offering a rich library of functions is NOT a viable replacement for understanding and approaching computation correctly (users will just call extremely general library functions, rather than understand their problem's specific "geometries" and address them appropriately). (Let me offer one more plug for my favorite "book about programming without a single line of code in it", Foreman Acton's "Real computing made real", now out in a wonderfully cheap Dover edition: Acton makes this case better than I've ever seen it made elsewhere, and offers many excellent examples of how numerical computation SHOULD be done). Alex From ruiligc at earthlink.net Mon Apr 30 19:02:15 2007 From: ruiligc at earthlink.net (Ray) Date: Mon, 30 Apr 2007 23:02:15 GMT Subject: python TK scrollbar problem Message-ID: Hi, would someone tell me how to make scrollbar work under grid? I think I'm missing something to connect scrollbar with the grid. following is some sample code. it shows the scrollbar, but it do not work. Thanks a lot for the help! Ray #####code begin######## from Tkinter import * def mygrid(text,M = []): while M: x = M.pop() x.destroy() rows = [] count=int(text) yscroll = Scrollbar(frame_grid, orient='vertical') yscroll.grid(rowspan=count, column=5, sticky=NS) M.append(yscroll) for i in range(count): cols = [] for j in range(4): e = Entry(frame_grid, relief=RIDGE) M.append(e) e.grid(row=i, column=j, sticky=NSEW) e.insert(END, '%d.%d' % (i, j)) cols.append(e) rows.append(cols) root=Tk() frame_entry=Frame(root, width=550, height=100) frame_entry.pack() text=Entry(frame_entry) text.pack(side=LEFT) button=Button(frame_entry, text='generate grid', command=(lambda:mygrid(text.get()))) button.pack() frame_space=Frame(root, width=550, height=100) frame_space.pack() frame_grid=Frame(root, width=550, height=300, relief=GROOVE) frame_grid.pack() frame_exit=Frame(root, width=550, height=100) frame_exit.pack() button2=Button(frame_exit, text='exit', command=root.quit) button2.pack() root.mainloop() From kirkjobsluder at gmail.com Wed Apr 18 16:47:57 2007 From: kirkjobsluder at gmail.com (kirkjobsluder) Date: 18 Apr 2007 13:47:57 -0700 Subject: Future Python Gui? In-Reply-To: <1176909848.455264.174730@e65g2000hsc.googlegroups.com> References: <1176859699.906386.326720@b75g2000hsg.googlegroups.com> <1176863948.526051.186210@n76g2000hsh.googlegroups.com> <1176909848.455264.174730@e65g2000hsc.googlegroups.com> Message-ID: <1176929277.779449.270810@q75g2000hsh.googlegroups.com> On Apr 18, 11:24 am, "bcwh... at pobox.com" wrote: > > I'd say that the best bet is to learn swig and similar > > bridging, expanding, and embedding mechanisms. > > Python GUI programming is likely to involve either > > python hooking into frameworks like Cocoa, Qt, or > > wxWidgets, python embedded in frameworks > > like Java or .NET, or flavors of python used > > as domain-specific languages in applications such as > > emacs, vim, and OpenOffice.org. > > If this were just a tool for me, it wouldn't matter. My concern is > distribution. If anybody who wants to run my software then they also > have to go through all the trouble to install these extensions, none > of which seem to have decent instructions. I'm an old-time hack and I > have trouble getting them to work. A simple user won't have a chance! Deployment has improved a lot in recent years, PyObjC is a simple double-click on a package. Most windows libraries work the same way. On the FOSS Unix world, you would add to a package system which will install dependencies automatically. When I used a FOSS Unix, I really only got burned when I decided to live on the bleeding edge. And as someone else pointed out, package tools should take much of the work out of delivery. Meanwhile, things could work the other way around. If Apple extends their support to PyObjC for example, python developers would know that every new OS X system would be able to run their PyObjC. > If Python doesn't declare an official Gui system, then it'll be > fragmented, inconsistent, and unsupportable. I don't see that as the case because many other languages don't have an "official" GUI system including C, C++, Ruby, lisp, Basic and perl. All of these have their active areas of deployment. For that matter, Java has three "official" GUI systems with most development on the server side. And didn't comp.long.python have this same argument in regards to MySQL support which was dropped from php? In addition to license issues, the php core library just wasn't used, and lagged behind the MySQL library. My personal opinion is that GUI development is such a moving target that toolkits are a poor choice for inclusion into the core standard libraries. There does not appear to be a standards process involved, and toolkits are expanding or changing parts of their API every few years. Anything that could be added, is going to be obsolete by the time it is incorporated into the standard. My feeling is that python is better served by encouraging GUI developers to include python- friendly bindings. > I wouldn't mind using just Tkinter, despite it's primative look, > except that it doesn't support more advanced widgets like "notebook". I wouldn't mind seeing tkgrid and tkhtml added to the standard library. But Tk is probably "good enough" for most simple interfaces. > > -- Brian From larry.bates at websafe.com Wed Apr 4 19:14:37 2007 From: larry.bates at websafe.com (Larry Bates) Date: Wed, 04 Apr 2007 18:14:37 -0500 Subject: How to open a txt file from the same folder as my module (w/out changing the working dir) In-Reply-To: References: Message-ID: Sergio Correia wrote: > I have a program in 'C:\Python25\Lib\site-packages\spam\spam.py' > > Importing and everything works fine: >>>> from spam import spam > > But the program calls a file located on the same folder (that is: > C:\Python25\Lib\site-packages\spam\). > > How do i do that? > >>>> spam.eggs() > > Traceback (most recent call last): > File "", line 1, in > datita = spam.eggs() > File "C:\Python25\lib\site-packages\spam\spam.py", line 149, in JustDoIt > config = open("configuration.txt", "rb").read().split('\r\n') > IOError: [Errno 2] No such file or directory: 'configuration.txt' > > My last resort is to hard code the path for that file, but it's ugly, > and I want to know if I'm missing something. Am I? > > Thanks a lot, > Sergio The problem is that C:\Python25\Lib\site-packages\spam is not the current working directory when you run the program. If it were, and if configuration.txt is in that directory it WILL find it. If you are running this from a shortcut make the working directory C:\Python25\Lib\site-packages\spam -Larry From malkarouri at gmail.com Wed Apr 11 11:36:40 2007 From: malkarouri at gmail.com (malkarouri at gmail.com) Date: 11 Apr 2007 08:36:40 -0700 Subject: run function in separate process In-Reply-To: <1hweao8.1t99a5vdqygvbN%aleax@mac.com> References: <1176301427.183706.321920@n76g2000hsh.googlegroups.com> <1hweao8.1t99a5vdqygvbN%aleax@mac.com> Message-ID: <1176305800.824643.28810@e65g2000hsc.googlegroups.com> On Apr 11, 3:58 pm, a... at mac.com (Alex Martelli) wrote: [...] > That's my favorite way to ensure that all resources get reclaimed: let > the operating system do the job. Thanks a lot, Alex, for confirming the basic idea. I will be playing with your function later today, and will give more feedback. I think I avoided the pipe on the mistaken belief that pipes cannot be binary. I know, I should've tested. And I avoided pickle at the time because I had a structure that was unpicklable (grown by me using a mixture of python, C, ctypes and pyrex at the time). The structure is improved now, and I will go for the more standard approach.. Regards, Muhammad From robert.rawlins at thinkbluemedia.co.uk Mon Apr 16 07:07:41 2007 From: robert.rawlins at thinkbluemedia.co.uk (Robert Rawlins - Think Blue) Date: Mon, 16 Apr 2007 12:07:41 +0100 Subject: Import From SubFolder Message-ID: <001501c78017$740dc0d0$5c294270$@rawlins@thinkbluemedia.co.uk> Chaps, Is it possible to import a module from a subdirectory in my application? I can only seem to get it to import from a single directory, but keeping all my files and classes in the same directory becomes a little sloppy. Thanks, Rob -------------- next part -------------- An HTML attachment was scrubbed... URL: From oliver at obeattie.com Tue Apr 3 10:51:50 2007 From: oliver at obeattie.com (oliver at obeattie.com) Date: 3 Apr 2007 07:51:50 -0700 Subject: raw_input just continues anyway? In-Reply-To: <57f489F2c787iU1@mid.individual.net> References: <1175606844.249364.290060@o5g2000hsb.googlegroups.com> <57f489F2c787iU1@mid.individual.net> Message-ID: <1175611910.685578.246780@w1g2000hsg.googlegroups.com> Hi There, Here's the full code, if it helps: """ Takes a list of filenames via standard input and uploads them to Amazon S3. Requires S3.py: http://developer.amazonwebservices.com/connect/entry.jspa?externalID=134&categoryID=47 Usage: cd /directory/with/media/files/ find | grep -v ".svn" | python /path/to/update_s3.py Before you use this, change the aws_access_key_id, aws_secret_key and bucket_name variables at the top of the file. You can run this multiple times on the same files -- it'll just override the files that were in your S3 account previously. """ import mimetypes import os import settings import os.path import sys os.environ['DJANGO_SETTINGS_MODULE'] = 'settings' from custom_filters import filename_slugify import S3 import settings aws_access_key_id = settings.AWS_ACCESS_KEY_ID aws_secret_key = settings.AWS_SECRET_KEY def update_s3(bucket_name=bucket_name): conn = S3.AWSAuthConnection(aws_access_key_id, aws_secret_key) for line in sys.stdin: filename = os.path.normpath(line[:-1]) if ((filename == '.' or not os.path.isfile(filename)) or (filename.find('ds_store') >= 0)): continue # Skip this, because it's not a file. print "Uploading %s" % filename_slugify(filename) filedata = open(filename, 'rb').read() content_type = mimetypes.guess_type(filename)[0] if not content_type: content_type = 'text/plain' conn.put(bucket_name, filename_slugify(filename), S3.S3Object(filedata), {'x-amz-acl': 'private', 'Content-Type': content_type}) if __name__ == "__main__": bucket_name = raw_input('Name of the bucket you wish the files to be placed into? ') update_s3() Basically I pipe some files into the script - so would this cause a linebreak? From larry.bates at websafe.com Tue Apr 17 17:43:19 2007 From: larry.bates at websafe.com (Larry Bates) Date: Tue, 17 Apr 2007 16:43:19 -0500 Subject: python - dll access (ctypes or swig) In-Reply-To: References: Message-ID: <46253F77.20409@websafe.com> Daniel Watrous wrote: > Hello, > > I am interested in using python to script access to some hardware for > which there are existing drivers in the form of DLLs. The DLLs each > have four exported functions and a host of COM Properties and COM > Methods. The four exported functions are as follows: > DllCanUnloadNow > DllGetClassObject > DllRegisterServer > DllUnregisterServer > > The COM methods and properties all begin with I, followed by a unique name. > > I am able to load the DLL using ctypes and it can access the exported > functions, but I'm not sure how to access the COM methods and > properties. I have read that ctypes once had support for COM but that > it has since been separated into its own project. I couldn't find any > information about how these work together. > > All help is appreciated. THANKS in advance... > > Daniel I recently learned that you can ship COM as either an .EXE or a .DLL (nobody has yet let me know why). You don't have a traditional .DLL that you would use ctypes to call methods in, you have a COM .DLL. COM methods need to be access with Win32com obj=win32com.client.Dispatch("typelib name"). You need to find out the COM dispatch typelib name and make sure the DLL is registered (regsvr32 your.dll). -Larry From ptmcg at austin.rr.com Sat Apr 21 20:57:10 2007 From: ptmcg at austin.rr.com (Paul McGuire) Date: 21 Apr 2007 17:57:10 -0700 Subject: '\\' in regex affects the following parenthesis? In-Reply-To: <1177199796.111430.300790@l77g2000hsb.googlegroups.com> References: <1177199796.111430.300790@l77g2000hsb.googlegroups.com> Message-ID: <1177203430.830415.109110@l77g2000hsb.googlegroups.com> On Apr 21, 6:56 pm, vox... at gmail.com wrote: > Could someone tell me why: > > >>> import re > >>> p = re.compile('\\.*\\(.*)') > > Fails with message: > > Traceback (most recent call last): > File "", line 1, in > re.compile('\\dir\\(file)') > File "C:\Python25\lib\re.py", line 180, in compile > return _compile(pattern, flags) > File "C:\Python25\lib\re.py", line 233, in _compile > raise error, v # invalid expression > error: unbalanced parenthesis > > I thought '\\' should just be interpreted as a single '\' and not > affect anything afterwards... > > The script 'redemo.py' shipped with Python by default is just fine > about this regex however. You are getting overlap between the Python string literal \\ escaping and re's \\ escaping. In a Python string literal '\\' gets collapsed down to '\', so to get your desired result, you would need to double- double every '\', as in: p = re.compile('\\\\.*\\\\(.*)') Ugly, no? Fortunately, Python has a special form for string literals, called "raw" which suppresses Python's processing of \'s for escaping - I think this was done expressly to help simplify entering re strings. To use raw format for a string literal, just precede the opening quotation mark with an r. Here is your original string, using a raw literal: p = re.compile(r'\\.*\\(.*)') This will compile ok. (Sometimes these literals are referred to as "raw strings" - I think this is confusing because new users think this is a special type of string type, different from str. This creates the EXACT SAME type of str; the r just tells the compiler/interpreter to handle the quoted literal a little differently. So I prefer to call them "raw literals".) -- Paul From see_below_no_spam at yahoo.es Mon Apr 16 04:15:19 2007 From: see_below_no_spam at yahoo.es (Javier Bezos) Date: Mon, 16 Apr 2007 10:15:19 +0200 Subject: Python Feature Request: Allow changing base of member indices to 1 References: <1176546465.632410.52630@w1g2000hsg.googlegroups.com> <1176579205.948684.171640@q75g2000hsh.googlegroups.com> <1176668873.556584.237410@p77g2000hsh.googlegroups.com> Message-ID: Paddy, >> Dijkstra's argument is obsolete, as it is based on >> how array length was computed many years ago -- if >> we have an array a = b..e, then the lenght of a >> is e-b (half open range). Good at low level >> programming. >> >> But a quarter of a century after we know concepts >> are much better than low level programming and >> explicit computations -- if we have an array >> a = b..e, then the length of a should be a.length() >> (or a.length(b,e)), and it is independent of > Hi Javier, > You seem to have missed out array *indexing* > in your argument, or is array indexing obsolete? Of course, it isn't, but it has evolved over the past 25 years. When Djikstra wrote that, many people (including me) was using a Spectrum--- Now we have OO programming to deal with concepts and a more generic programming. So, to me it's clear his _argument_ is very outdated and cannot be applied directly and withot reservations to modern languages like Python. Javier ----------------------------- http://www.texytipografia.com From steve at holdenweb.com Sun Apr 15 12:59:24 2007 From: steve at holdenweb.com (Steve Holden) Date: Sun, 15 Apr 2007 12:59:24 -0400 Subject: reading from sys.stdin In-Reply-To: <1176577574.338733.325790@n59g2000hsh.googlegroups.com> References: <1176366058.261031.111870@p77g2000hsh.googlegroups.com> <1176387908.406115.270630@w1g2000hsg.googlegroups.com> <1176438754.995753.50190@d57g2000hsg.googlegroups.com> <1176454871.538968.176620@n76g2000hsh.googlegroups.com> <1176457007.589050.285400@d57g2000hsg.googlegroups.com> <1176538930.891355.230880@n59g2000hsh.googlegroups.com> <1176577574.338733.325790@n59g2000hsh.googlegroups.com> Message-ID: 7stud wrote: > On Apr 14, 7:43 am, Steve Holden wrote: >> 7stud wrote: >>> On Apr 13, 6:20 am, Michael Hoffman wrote: >> [...] >> >>> But if you hit return on a blank line, there is no error. In other >>> words, will stop on a blank line and not return EOFError. >>> Anyway, it seems everyone is saying that when you iterate over a file, >>> the whole file is first read into memory. Therefore iterating over >>> sys.stdin is consistent: you have to type Ctrl+D to signal EOF before >>> the iteration can start. Is that about right? >> No. The file content is usually buffered, but the buffering doesn't >> necessarily include the whole content of the file. >> >> If you are iterating over the file the correct way to access the next >> line is to call the file's .next() method, as I indicated before. >> >> If you are reading lines the appropriate way is to use readline(). >> >> And, as you have already seen an error message telling you, mixing the >> two types is unlikely to give you usable results. >> > Does iterating over stdin work the same way? If one were to type in > enough lines to fill the buffer would iteration begin before entering > EOF with Ctrl+D? > Why don't you try it and tell me? That's what the interactive interpreter is for. 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 kyosohma at gmail.com Wed Apr 4 13:46:21 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: 4 Apr 2007 10:46:21 -0700 Subject: try... except SyntaxError: unexpected EOF while parsing In-Reply-To: <1175708304.034078.139020@e65g2000hsc.googlegroups.com> References: <1175708304.034078.139020@e65g2000hsc.googlegroups.com> Message-ID: <1175708780.966185.218190@n59g2000hsh.googlegroups.com> On Apr 4, 12:38 pm, "oscartheduck" wrote: > I have a small script for doing some ssh stuff for me. I could have > written it as shell script, but wanted to improve my python skills > some. > > RIght now, I'm not catching a syntax error as I'd like to. > > Here's my code: > > #!/usr/bin/env python > import sys > import os > > port = input("Please enter a port to connect on. If you're unsure or > just want the default of port 2024 just hit enter -- ") > > try: > if port > 65535: > print "That's not a valid port number, sorry. Between 0 and 65535 > is cool." > sys.exit() > else: > cmd = 'su root -c "/usr/sbin/sshd -p %s"' % port > except SyntaxError: > cmd = 'su root -c "/usr/sbin/sshd -p 2024;exit"' > > os.system(cmd) > > I'm under the impression that the except should catch the syntax error > and execute the "default" command, but hitting enter at the input > value doesn't lead to that. Any ideas what's going wrong? Try sticking your port = input("Please enter a port to connect on. If you're unsure or just want the default of port 2024 just hit enter -- ") inside your "try" block instead. Or switch to using the "raw_input" builtin instead of "input". Mike From nospam at invalid.com Thu Apr 12 18:02:53 2007 From: nospam at invalid.com (Jack) Date: Thu, 12 Apr 2007 15:02:53 -0700 Subject: Custom Python Runtime References: <2NudnVn5jsm2QIvbnZ2dnUVZ_vqpnZ2d@comcast.com> Message-ID: It seems that pywintypes24.dll and pythoncom24.dll have to be in C:\Windows\System32 directory. Otherwise I get an error. Any way to get around that? >> 3. Some files go to the Windows\system32 directory, including some >> win32all >> files. Can they be in the current directory as python.exe? > > .dll files? Sure. From szhorvat at gmail.com Sat Apr 28 17:54:01 2007 From: szhorvat at gmail.com (Szabolcs) Date: Sat, 28 Apr 2007 23:54:01 +0200 Subject: Numbers and truth values In-Reply-To: <1hxa95b.13zrrmv1wucw71N%aleax@mac.com> References: <1hxa95b.13zrrmv1wucw71N%aleax@mac.com> Message-ID: Alex Martelli wrote: > Maybe somebody assigning a value to True or False is a > common error, but much of my livelihood over the last 10 years has been > about mentoring/coaching programmers in Python, and that's one error I > have *NEVER* observed, so I'd need a lot of empirical evidence to > convince me it's worth adding two more reserved words to Python's > reasonably short list (I feel much the same way about None, by the way). > pychecker, pylint, and friends, are a much better way to detect and warn > about all sort of anomalies of this kind. Yes, I admit that it was a very stupid mistake. (Though I'm not even sure that this is what happened. Next time I should probably sleep on it, and try it again the next day, to avoid posting such a stupid question again.) But note that I was using Python interactively (just experimenting with it). It is very unlikely that someone would write things like True == 2 without any additional context in a real program. (Actually it is unlikely that someone would write this in any circumstance in a real program.) But I still think that it is an inconsistency to allow to redefine a _value_ like True or False (not a built-in function that may have been missing in earlier versions). Saying True = 2 is just like saying 3 = 2. Learning about pylint was very useful (thanks for the advice!) -- it helps in catching those kinds of errors that surface only at runtime in Python programs, but are easily caught at compile time in compiled languages. From kyosohma at gmail.com Fri Apr 20 10:08:24 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: 20 Apr 2007 07:08:24 -0700 Subject: wxPython and how to return text entry to main program? In-Reply-To: References: <1177011490.435609.155870@o5g2000hsb.googlegroups.com> <1177030290.529322.56210@p77g2000hsh.googlegroups.com> Message-ID: <1177078099.337536.79490@q75g2000hsh.googlegroups.com> On Apr 19, 9:05 pm, Steve Holden wrote: > 7stud wrote: > > On Apr 19, 1:38 pm, Tyler wrote: > > [after quoting umpteen lines of code] > > > > > > > You can do this: > > > --- > > class MyFrame(wx.Frame): > > > .. > > .. > > .. > > def OnSubmit(self, event): > > globals()["userInput"] = self.txtCtrlName.GetValue() > > self.Close() > > > app = MyApp() > > app.MainLoop() > > > print userInput > > ----- > > Please try to limit your quoting to what's relevant. > > 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 Steve, I think Tyler is opening a custom dialog from his main GUI application. He should have used "ShowModal" if he was using one of wxPython's standard dialog boxes, but since he was creating his own custom one he didn't need to, which is why I told him to use the self.Close(True) method to destroy the dialog. Then again, maybe I am being "wrong-headed" about the whole thing. I was trying to come up with the "instance variable" way of storing the variables, but I could not think of how to implement it last night. Here are some other threads on the topic that I thought were interesting: http://mail.python.org/pipermail/tutor/2005-May/038648.html http://lists.wxwidgets.org/archive/wxPython-users/msg06482.html http://www.daniweb.com/techtalkforums/thread60439.html Mike From spradml at gmail.com Thu Apr 26 11:49:43 2007 From: spradml at gmail.com (Pradnyesh Sawant) Date: Thu, 26 Apr 2007 21:19:43 +0530 Subject: passing tuple with pyqt4 signal/slot mechanism Message-ID: <80628d680704260849n6c8da864i5cfc8bf4cbab5f6d@mail.gmail.com> Thanks for the reply Phil. Actually, as mentioned earlier, the code that i sent was stripped; while stripping, i missed some things (class D should have a run method). Also, i tried your suggestion of connecting before emitting the signal, but am still getting the same output (in the original code). the modified code is given below: class D(QtCore.QThread): def __init__(self): QtCore.QThread.__init__(self) def run(self): tpl = ("Primary", "priSec") print "tpl:", tpl self.emit(QtCore.SIGNAL("setLabel"), tpl) class Gui(QtGui.QDialog): def __init__(self, parent = None): QtGui.QDialog.__init__(self, parent) def setLabel(self, tpl): print "####tpl:", tpl print "**********tpl:", str(tpl) if __name__ == "__main__": app = QtGui.QApplication(sys.argv) dialog = Gui() d = D() QtCore.QObject.connect(d, QtCore.SIGNAL("setLabel"), dialog.setLabel, QtCore.Qt.QueuedConnection) d.start() sys.exit(dialog.exec_()) Also, in the modified code, why aint the method setLabel getting called? > > The output i'm getting is as follows: > > > > tpl: ('Primary', 'priSec') > > ####tpl: (,) > > **********tpl: ((((((((,),),),),),),),) > > > Works for me in that the setLabel() isn't executed at all - but then you are > emitting the signal before connecting it. Also my crystal ball isn't telling > me what versions you are using or what platform you are on. > > Phil > > -- warm regards, Pradnyesh Sawant -- Be yourself, everyone else is taken. --Anon From steven.bethard at gmail.com Wed Apr 4 23:39:33 2007 From: steven.bethard at gmail.com (Steven Bethard) Date: Wed, 04 Apr 2007 21:39:33 -0600 Subject: function for counting items in a sequence Message-ID: <46146F75.9050904@gmail.com> Alex Martelli wrote: > If we had a "turn sequence into bag" function somewhere > (and it might be worth having it for other reasons): > > def bagit(seq): > import collections > d = collections.defaultdict(int) > for x in seq: d[x] += 1 > return d I use this function all the time -- I call it dicttools.count(). I'd love to see this appear in the collections module or somewhere else in the stdlib. STeVe From jzgoda at o2.usun.pl Fri Apr 13 16:10:56 2007 From: jzgoda at o2.usun.pl (Jarek Zgoda) Date: Fri, 13 Apr 2007 22:10:56 +0200 Subject: Python editor/IDE on Linux? In-Reply-To: References: <1176494048.627760.323630@p77g2000hsh.googlegroups.com> Message-ID: Greg Donald napisa?(a): >> try wing ide. i tried it and i love it. it's available for windows as >> well for linux > > Good thing those are the only two operating system out there.. err.. > I meant, good thing there's Emacs. Thanks God, there's no "PIDA for Emacs". -- Jarek Zgoda http://jpa.berlios.de/ From mik3l3374 at gmail.com Fri Apr 13 05:14:41 2007 From: mik3l3374 at gmail.com (mik3l3374 at gmail.com) Date: 13 Apr 2007 02:14:41 -0700 Subject: split and regexp on textfile In-Reply-To: <1176454505.336514.90910@p77g2000hsh.googlegroups.com> References: <1176451192.364949.8260@w1g2000hsg.googlegroups.com> <1176453634.577706.326170@y80g2000hsf.googlegroups.com> <1176454505.336514.90910@p77g2000hsh.googlegroups.com> Message-ID: <1176455681.424814.223830@q75g2000hsh.googlegroups.com> On Apr 13, 4:55 pm, "Flyzone" wrote: > On 13 Apr, 10:40, mik3l3... at gmail.com wrote: > > > you trying to match the date part right? if re is what you desire, > > here's one example: > > Amm..not! I need to get the text-block between the two data, not the > data! :) change to pat.split(data) then. I get this: ['', '\ntext\ntext\n', '\ntext\ntext '] From syedamjad_a at yahoo.com Tue Apr 24 12:18:11 2007 From: syedamjad_a at yahoo.com (CSUIDL PROGRAMMEr) Date: 24 Apr 2007 09:18:11 -0700 Subject: RPM error Message-ID: <1177431491.757683.138350@r35g2000prh.googlegroups.com> Hi folks I am new to python I am trying to write a program that will install rpm using rpm -ivh xxx.rpm I want to know if python has in-built exceptions to catch no- dependencies error. If not how can i build them thanks From jzgoda at o2.usun.pl Mon Apr 2 11:52:34 2007 From: jzgoda at o2.usun.pl (Jarek Zgoda) Date: Mon, 02 Apr 2007 17:52:34 +0200 Subject: I18n issue with optik In-Reply-To: References: Message-ID: Thorsten Kampe napisa?(a): > I can't see the "solution" here. Is the optparse "print_help" function > wrong? Why should there even be errors if I use "unicode = True" with > gettext.install? > > I have ISO-8859-15 gettext translations and I want optparse to display > them correctly. What do I have to do? Please, see gettext module documentation on this topic. The solution is: always install your translation with unicode=True setting. This assures usage of ugettext() instead of gettext() and works properly with character sets other than ASCII. Your messages are internally decoded to unicode objects and passed to output. Then the displayed output will be limited only by the encoding of your terminal, but it will not crash your program on any inconsistency, you would see question marks. -- Jarek Zgoda "We read Knuth so you don't have to." From steve at holdenweb.com Fri Apr 13 11:17:33 2007 From: steve at holdenweb.com (Steve Holden) Date: Fri, 13 Apr 2007 11:17:33 -0400 Subject: tuples, index method, Python's design In-Reply-To: References: <1175953520.316208.241490@o5g2000hsb.googlegroups.com> <7xzm5igbrb.fsf@ruckus.brouhaha.com> <1176200361.260546.280510@n76g2000hsh.googlegroups.com> <740c3aec0704100824m132c45fbi5c4c3ec0c0fa3a67@mail.gmail.com> Message-ID: Antoon Pardon wrote: > On 2007-04-13, Steve Holden wrote: >> Antoon Pardon wrote: >>> On 2007-04-12, Carsten Haese wrote: >>>> On Thu, 2007-04-12 at 14:10 +0000, Antoon Pardon wrote: >>>>> People are always defending duck-typing in this news group and now python >>>>> has chosen to choose the option that makes duck-typing more difficult. >>>> Au contraire! The "inconsistent" behavior of "in" is precisely what >>>> duck-typing is all about: Making the operator behave in a way that makes >>>> sense in its context. >>> No it isn't. Ducktyping is about similar objects using a similar >>> interface to invoke similar behaviour and getting similar result. >>> >>> So that if you write a function you don't concern yourself with >>> the type of the arguments but depend on the similar behaviour. >>> >> Please note that "similar" does not mean "exact". > > That is because I don't want to get down in an argument about > whether tp[:3] and ls[:3] is similar behaviour or exact the > same behaviour when tp is a tuple and ls is a list. > >> The behavior of str.__contains__ and list.__contains__ is similar. > > That would depend on how much you find things may differ and > still call them similar. IMO they are not similar enough > since "12" in "123" doesn't behave like [1,2] in [1,2,3] > And it never will, because of the property of strings I mentioned previously. Unless you want to introduce a character type into Python there is no way that you are ever going to be be satisfied. >> Duck-typing allows natural access to polymorphism. You appear to be >> making semantic distinctions merely for the sake of continuing this >> rather fatuous thread. > > I gave an argument that showed that the specific way the in > functionality was extended in strings makes duck-typing (and > by extention natural access to polymorphism) more difficult. > although it may do so in a way that is not significant to > you and the other developers. > I am not "a developer". > Now if you don't agree with the argument presented that > is fine with me. If you think the problem is not big > enough to bother with, that is fine with me too. > But the argument doesn't disappear simply because you > think ill of my intentions. > Apparently. > And consider that each small inconsistency in itself > may be not important enough to remove. But if you > have enough of them remembering all these special > cases can become tedious. > But not as tedious as this eternal discussion of already-decided issues. >>> Suppose someone writes a function that acts on a sequence. >>> The algorithm used depending on the following invariant. >>> >>> i = s.index(e) => s[i] = e >>> >>> Then this algorithm is no longer guaranteed to work with strings. >>> >> Because strings have different properties than other sequences. I can't >> help pointing out that your invariant is invalid for tuples also, >> because tuples don't have a .index() method. > > Strings have some properties that are different and some > properties that are similar with other sequences. My argument > is that if you want to facilitate duck typing and natural access to > polymorphism in peoples functions that work with sequences in general > you'd better take care that the sequence api of strings resembles > the sequence api of other sequences as good as possible. > This is just a bald restatement of the same argument you feel makes it desirable to add an index() method to tuples. If taken to its logical (and ridiculous) extreme there should only be one sequence type in Python. > You on the other hand seem to argue that since strings have > properties where they differ from other sequences it no longer > is so important that the sequence api of strings resembles those > of other sequences. > Well, of course. Programming languages are for human users, and they should do what human users find most natural. Since humans can disagree the developers (amongst who I do not count myself, although I *am* concerned about the development of Python) have to try and go by consensus, which by and large they do reasonably successfully. So what I suppose I *am* saying is that your opinions would seem to differ from the consensus. While you are not in a minority of one you are in a minority, and it would be nice if we could proceed without having to continually revisit each small design decision on a continuous basis. 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 goodTweetieBird at hotmail.com Thu Apr 26 14:49:39 2007 From: goodTweetieBird at hotmail.com (gtb) Date: 26 Apr 2007 11:49:39 -0700 Subject: Python keywords In-Reply-To: <4630C25D.9010309@websafe.com> References: <1177599386.204340.65680@r35g2000prh.googlegroups.com> <4630C25D.9010309@websafe.com> Message-ID: <1177613379.115009.23430@r3g2000prh.googlegroups.com> On Apr 26, 10:16 am, Larry Bates wrote: > gtb wrote: > > Have done some searching but have not found a place where I can look > > up python keywords. I was looking at a script that contained the > > following line: > > > assert self.getResponseCode() in (200, 304, 302) > > > I can infer the usage here but previously I had thought that "in" was > > only used with '"for". I looked thru 'the Python Reference Manual and > > found "in" is a keyword but in skimming thru I found it only with > > "for". The reference manual seems good but seems not to be setup for > > searching. Or maybe I just missed something. > > > Thanks, > > > gtb > > http://docs.python.org/ref/keywords.html > > in keyword is a general one and can be used for many objects. > > x in 'xyz' > > y in ['a','b','c','y','z''] > > z in ('a','b','c','y','z'] > > key in {'key1':1, 'key2': 2} > > The in you see with a for isn't associated with the for loop > but rather the sequence you are iterating over > > for i in range(10): > > -Larry Thanks Larry. I saw that page you referenced above and that is how I knew it was a keyword. But I still have found nodocumentation that supports the examples you provided. Thanks again, john From lobais at gmail.com Tue Apr 10 14:07:51 2007 From: lobais at gmail.com (lobais at gmail.com) Date: 10 Apr 2007 11:07:51 -0700 Subject: Kill thread or at least socket.getaddrinfo In-Reply-To: <1174925296.683942.279070@b75g2000hsg.googlegroups.com> References: <1174925296.683942.279070@b75g2000hsg.googlegroups.com> Message-ID: <1176228471.940919.272470@l77g2000hsb.googlegroups.com> On 26 Mar., 18:08, kyoso... at gmail.com wrote: > you know the pid, you can kill it, but that's not always a > clean way of accomplishing the task. So I have to open the connection in a new process... Sigh.. How I hate this part of Python. From nagle at animats.com Sat Apr 14 13:56:32 2007 From: nagle at animats.com (John Nagle) Date: Sat, 14 Apr 2007 17:56:32 GMT Subject: "HTTP error -1" from urllib2 In-Reply-To: References: Message-ID: The crash is a known bug, and is fixed in the Subversion repository, but not in any released version. The problem is that if the server returns an blank line, instead of "HTTP 1", httplib goes off into some old HTTP 0.9 code that's broken. John Nagle John Nagle wrote: > I'm getting a wierd error from urllib2 when opening certain > URLs. The code works for most sites, but not all of them. > Here's the traceback: > > [Thread-2] InfoSitePage EXCEPTION while processing page > "http://www.fourmilab.ch": Problem with page "http://www.fourmilab.ch": > HTTP > error -1 - .. > Traceback (most recent call last): > File "D:\projects\sitetruth\InfoSitePage.py", line 318, in httpfetch > fd = url_opener.open(self.requestedurl) # open file by url > File "D:\projects\sitetruth\miscutils.py", line 149, in open > result = urllib.FancyURLopener.open(self, url, *args) > File "D:\python24\lib\urllib.py", line 190, in open > return getattr(self, name)(url) > File "D:\python24\lib\urllib.py", line 322, in open_http > return self.http_error(url, fp, errcode, errmsg, headers) > File "D:\python24\lib\urllib.py", line 339, in http_error > return self.http_error_default(url, fp, errcode, errmsg, headers) > File "D:\projects\sitetruth\miscutils.py", line 144, in > http_error_default > raise InfoException.InfoException(self.url, 'HTTP error %s - %s.' % > (errcode, errmsg)) > InfoException: Problem with page "http://www.fourmilab.ch": HTTP error > -1 - .. > > This fails identically using Python 2.4 on a Windows desktop and on > Python 2.5 > on a Linux server. > > The site being accessed reads fine in a browser. It's not a redirect, > and it doesn't insist on cookies. > > See "http://mail.python.org/pipermail/python-list/2005-March/314301.html" > for another problem involving "HTTP error -1". > > John Nagle From jakub.stolarski at gmail.com Sat Apr 14 11:26:26 2007 From: jakub.stolarski at gmail.com (Jakub Stolarski) Date: 14 Apr 2007 08:26:26 -0700 Subject: Simple integer comparison problem In-Reply-To: References: Message-ID: <1176564386.352452.145330@n59g2000hsh.googlegroups.com> On Apr 14, 5:19 pm, t... at finland.com wrote: > Hi! > I ran in problem with simple exercise. I'm trying to get program to > return grade when given points but no matter what, I always get F. > > def grader(): > print "Insert points: " > points = raw_input('> ') > int(points) > > if points > 89 and points <= 100: > return "A" > elif points > 89 and points <= 89: > return "B" > elif points > 69 and points <= 79: > return "C" > elif points > 59 and points <= 69: > return "D" > else: > return "F" > > grade = grader() > print grade You should write: points = int(points) int returns value, not change in place. If I can suggest you can use simpler if-statement: if 89 < points <= 100: From anglozaxxon at gmail.com Thu Apr 5 14:18:50 2007 From: anglozaxxon at gmail.com (anglozaxxon) Date: 5 Apr 2007 11:18:50 -0700 Subject: Looping issues In-Reply-To: <1175796069.501575.157410@w1g2000hsg.googlegroups.com> References: <1175796069.501575.157410@w1g2000hsg.googlegroups.com> Message-ID: <1175797130.561115.147450@p77g2000hsh.googlegroups.com> On Apr 5, 2:01 pm, brochu... at gmail.com wrote: > What I am trying to do is compare two files to each other. > > If the 2nd file contains the same line the first file contains, I want > to print it. I wrote up the following code: > > correct_settings = open("C:\Python25\Scripts\Output > \correct_settings.txt","r") > current_settings = open("C:\Python25\Scripts\Output\output.txt","r") > > for line in correct_settings: > for val in current_settings: > if val == line: > print line + " found." > > correct_settings.close() > current_settings.close() > > For some reason this only looks at the first line of the > correct_settings.txt file. Any ideas as to how i can loop through each > line of the correct_settings file instead of just looking at the first? Instead of "for line in correct_settings", try "for line in correct_settings.readlines()". From bbxx789_05ss at yahoo.com Fri Apr 6 14:33:47 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: 6 Apr 2007 11:33:47 -0700 Subject: tuples, index method, Python's design In-Reply-To: <1175867771.114540.61810@n76g2000hsh.googlegroups.com> References: <1175867771.114540.61810@n76g2000hsh.googlegroups.com> Message-ID: <1175884427.779950.267220@y80g2000hsf.googlegroups.com> On Apr 6, 7:56 am, "Paul Boddie" wrote: > The problem with 7stud's quote from GvR is that it's out of date: I would argue that it shows the very guy who invented the language stated publicly there was no good reason for tuples not to have an index method---except for consistency; tuples had no other methods. Now that tuples have other methods, the only justification he stated no longer exists. From gregturn at mindspring.com Wed Apr 4 12:47:34 2007 From: gregturn at mindspring.com (Goldfish) Date: 4 Apr 2007 09:47:34 -0700 Subject: Newbie - needs help In-Reply-To: <1175635684.420398.101540@n59g2000hsh.googlegroups.com> References: <1175632937.838422.236850@y66g2000hsf.googlegroups.com> <1175635684.420398.101540@n59g2000hsh.googlegroups.com> Message-ID: <1175705254.779919.325360@o5g2000hsb.googlegroups.com> Nothing beats http://diveintopython.org/toc/index.html for getting into the basics of Python. This guy's writing is great! From carsten at uniqsys.com Sun Apr 8 00:18:16 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Sat, 7 Apr 2007 23:18:16 -0500 Subject: Why does not my wx.html.HtmlWindow work? In-Reply-To: <1176003505.794328.62170@n76g2000hsh.googlegroups.com> References: <1176003505.794328.62170@n76g2000hsh.googlegroups.com> Message-ID: <20070408041527.M16419@uniqsys.com> On 7 Apr 2007 20:38:25 -0700, liqfemail at gmail.com wrote > Below are my source code: > [snip > html.LoadPage(" > http://www.pythonthreads.com/articles/python/incorporating-into- > wxpython-part-1.html") > [snip] Have you tried loading a simpler page, something like http://www.google.com? -Carsten From cam.ac.uk at mh391.invalid Tue Apr 17 16:20:14 2007 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Tue, 17 Apr 2007 21:20:14 +0100 Subject: Binary file output using python In-Reply-To: References: Message-ID: Michael Hoffman wrote: > Chi Yin Cheung wrote: >> Hi, >> Is there a way in python to output binary files? I need to python to >> write out a stream of 5 million floating point numbers, separated by >> some separator, but it seems that all python supports natively is >> string information output, which is extremely space inefficient. > > I recommend using PyTables for this sort of thing. It also allows you to > choose from several compression algorithms. I'm using it to store files > with 22000 x (2000, 12) datasets, or 528 million Float64s. Addendum: it should also deal with endianness issues I wouldn't want to handle myself, so your code will also be portable. -- Michael Hoffman From 12cc104 at gmail.com Sun Apr 22 20:06:18 2007 From: 12cc104 at gmail.com (proctor) Date: 22 Apr 2007 17:06:18 -0700 Subject: recursion depth problem In-Reply-To: References: <1177267774.416169.276780@e65g2000hsc.googlegroups.com> <1177275314.846022.249000@e65g2000hsc.googlegroups.com> <1177276111.720137.315710@b75g2000hsg.googlegroups.com> Message-ID: <1177286778.918119.7490@e65g2000hsc.googlegroups.com> On Apr 22, 5:51 pm, Dennis Lee Bieber wrote: > On Sun, 22 Apr 2007 17:37:05 -0500, Michael Bentley > declaimed the following in comp.lang.python: > > > Anything that can be done with recursion can be done without > > recursion. If you really wanted to mimic a binary counter, why not > > write a function that converts a number to binary? > > > Then you could just count up from 0, printing the return from your > > binary conversion function... > > > And the binary converter would be pretty easy too: just think of it > > as making change -- for a given number you just divide the number by > > each of [2 ** x for x in range(len(sys.argv[1]), 0, -1)] and append > > the string representations of the answers to a list and if the answer > > is 1, subtract that much from the number... > > Or a simple lookup dictionary to convert from hex to binary, and use > string interpolation to produce the hex... > > Might also make it more natural -- the original recursive loop is > producing output with LSB on the left, most folks expect the MSB on the > left (where, in this case, B is "bit"). > > Of course, if I were to be masochistic, I'd write a binary adder() > composed of bit adders with carry... Such as {I hope this was just a > personal learning experience and not a homework project}... > > -=-=-=-=-=-=- > """ > masochistic exercise in generating a binary adder > """ > import sys > > def badd(b1, b2, c=0): > """ > badd(b1, b2, c) => (carry, sum) > """ > if b1 and b2: > # 1 + 1 + c => carry out, and 0/1 from carry in > return (1, c) > elif (b1 and c) or (b2 and c): > # either b1 or b2 is set, and carry in is set > return (1, 0) > else: > # only one of carry in, b1, or b2 is set > return (0, b1 + b2 + c) > > def adder(w1, w2): > """ > adder(w1, w2) => w3 > where w1, w2, w3 are lists of 0s and 1s > """ > #equalize list lengths > if len(w1) > len(w2): > w2 = [0] * (len(w1) - len(w2)) + w2 > elif len(w1) < len(w2): > w1 = [0] * (len(w2) - len(w1)) + w1 > > w3 = [0] * len(w1) > > carry = 0 #initialize > end = len(w3) - 1 > for i in range(end + 1): > (carry, w3[end-i]) = badd(w1[end-i], w2[end-i], carry) > > if carry: > return "OVERFLOW" #should be an exception > > return w3 > > if __name__ == "__main__": > #sloppy conversion from character to binary > binary = [ {True:1, False:0}[c == "1"] for c in sys.argv[1] ] > > #simple counter > > while binary != "OVERFLOW": > print "".join(["%1s" % b for b in binary]) > binary = adder(binary, [ 1 ]) #need to supply a list > > print "Overflow must have occurred" > > binary1 = [ {True:1, False:0}[c == "1"] for c in sys.argv[2] ] > binary2 = [ {True:1, False:0}[c == "1"] for c in sys.argv[3] ] > > print "".join(["%1s" % b for b in adder(binary1, binary2)]) > > -=-=-=-=-=- (watch out for line wrap on the command line > E:\UserData\Dennis Lee Bieber\My Documents\Python Progs>python binadd.py > 0000 0010 111 > > 0000 > 0001 > 0010 > 0011 > 0100 > 0101 > 0110 > 0111 > 1000 > 1001 > 1010 > 1011 > 1100 > 1101 > 1110 > 1111 > Overflow must have occurred > 1001 > > E:\UserData\Dennis Lee Bieber\My Documents\Python Progs> > E:\UserData\Dennis Lee Bieber\My Documents\Python Progs>python binadd.py > 010 001 011111111 > > 010 > 011 > 100 > 101 > 110 > 111 > Overflow must have occurred > 100000000 > > E:\UserData\Dennis Lee Bieber\My Documents\Python Progs> > E:\UserData\Dennis Lee Bieber\My Documents\Python Progs>python binadd.py > 00 1 111111111 > > 00 > 01 > 10 > 11 > Overflow must have occurred > OVERFLOW > > E:\UserData\Dennis Lee Bieber\My Documents\Python Progs> > > -- > 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/ thank you. you guys are keeping me busy! ps. no, i'm not in school. not in the traditional sense anyway :-) just books, practice, and forums like this. From kyosohma at gmail.com Fri Apr 6 16:48:47 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: 6 Apr 2007 13:48:47 -0700 Subject: Database Timestamp conversion error Message-ID: <1175892527.110813.26570@n76g2000hsh.googlegroups.com> Hi, I am populating a mySQL database with data from the MS Access database. I have successfully figured out how to extract the data from Access, and I can insert the data successfully into mySQL with Python. My problem is that I keep hitting screwy records with what appears to be a malformed dbiDate object when I insert certain records. I get the following traceback: Traceback (most recent call last): File "\\someServer\Development\collectiveFleet.py", line 68, in - toplevel- mycursor.execute(sql) TypeError: argument 1 must be string without null bytes, not str When I print the timestamp variable, I get this output: (I31 (S'OK' p1 Nttp2 . If I look in the MS Access database, I see the timestamp as "5/6/112". Obviously some user didn't enter the correct date and the programmer before me didn't give Access strict enough rules to block bad dates. How do I test for a malformed date object so I can avoid this? There are thousands of records to transfer. I am using the odbc module for connection purposes with Python 2.4 on Windows XP SP2. Thanks a lot! Mike From hlubenow2 at gmx.net Sat Apr 7 10:53:14 2007 From: hlubenow2 at gmx.net (hlubenow) Date: Sat, 07 Apr 2007 16:53:14 +0200 Subject: Hide the python-script from user References: <8ktie4-0i9.ln1@athlon.my> <1175898877.869321.112310@w1g2000hsg.googlegroups.com> <7ovie4-nfa.ln1@athlon.my> Message-ID: hlubenow wrote: > hlubenow wrote: > >> ts-dev wrote: >> >>> On Apr 6, 3:19 pm, hlubenow wrote: >>>> recently there was a thread about hiding the python-script from the >>>> user. The OP could use >>> >>> Interesting - thanks >> >> Well, testing it, it doesn't seem to work very well ... >> >> It seems, Python-code is rather difficult to obfuscate, probably because >> of its clear syntax and indentations. Here's yet another approach: >> >> > http://pythonhacker.is-a-geek.net/my_programs/pyfuscate/pyfuscate-0.1.zip/view >> >> H. > > That didn't work very well either :(. > > Ok, but now I can offer a real secure solution: > > You can have real encryption in Python using this modules: > > > http://www.amk.ca/files/python/crypto/pycrypto-2.0.1.tar.gz > > and > > http://sourceforge.net/projects/yawpycrypto > > Below I post a code-example that I've written some time ago. With it, > encrypting text is rather easy. > > Then you have to program a start-script, that reads in your script and the > decryption-key. The decryption-key must be encrypted too. Such a encrypted > key can be generated by the modules if you don't pass a password to my > function "doEncrypt(). The decryption-key must then be hidden somewhere > within the encrypted program-script. That's because, if the user knows > where to find the key, he can decrypt the program-script. > > If your start-script is written, everything should work automatically, one > shouldn't nearly notice the decryption-process. > > Ok, here's my example code, how to encrypt and decrypt some text with the > modules: > > ---------------------------------------------------------------------------- > > #!/usr/bin/env python > > import os > import sys > import base64 > > from yawPyCrypto.Cipher import DecryptCipher, EncryptCipher > from yawPyCrypto.Cipher import ZipDecryptCipher, ZipEncryptCipher > from yawPyCrypto.Constants import CIPHER_BLOWFISH, MODE_CBC > > > def doEncrypt(text, passw = None): > > e = EncryptCipher(passw, CIPHER_BLOWFISH, MODE_CBC) > e.feed(text) > e.finish() > encryptedtext = e.data > > if passw != None: > passwr = passw > else: > passwr = e.password > > a = (encryptedtext, passwr) > return a > > > def doDecrypt(encryptedtext, passw): > d = DecryptCipher(passw) > d.feed(encryptedtext) > d.finish() > decoded = (d.data) > return decoded > > > # Calling the encryption routine. > # If you just pass the text to encrypt, a password is generated: > > a = doEncrypt("For your eyes only !", "Melina") > > > # Just trying to clean the screen: > > if sys.platform == "win32": > os.system("cls") > else: > os.system("clear") > > print > print "Hello !" > print > print "I just encrypted some text. It looks like this now:" > print > > print base64.b64encode(a[0]) > > print > print 'Please notice, that I just encoded the text once more using "base64.b64encode()" to make it printable.' > print > print "The password for decryption is: " > print > print base64.b64encode(a[1]) > print > print "Let's decrypt again (the original password must be passed without b64encoding):" > print > print doDecrypt(a[0], a[1]) > print > > ---------------------------------------------------------------------------- > > See you > > H. This still has a problem: The start-script has to know how to decrypt the main-script and the start-script is visible, so the user can see how it does it. Perhaps one could obfuscate the start-script or write a C extension, that does decrypting instead of the start-script. This is getting rather complicated ... H. From ptmcg at austin.rr.com Sat Apr 21 21:09:01 2007 From: ptmcg at austin.rr.com (Paul McGuire) Date: 21 Apr 2007 18:09:01 -0700 Subject: Handy short cut for formatting elapsed time in floating point seconds Message-ID: <1177204141.785661.203320@n59g2000hsh.googlegroups.com> I am doing some simple timing of some elements of Python scripts, and the simplest is to just call time.time() before and after key elements of the script: t1 = time.time() # do lengthy operation t2 = time.time() print "That took %f seconds" % (t2-t1) Unfortunately, this gives very ugly timing output, as just a floating point number of seconds. After several iterations of writing a formatter (strftime is not straightforward to use - it omits milliseconds for one thing), I came up with this: def secondsToStr(t): rediv = lambda ll,b : list(divmod(ll[0],b)) + ll[1:] return "%d:%02d:%02d.%03d" % tuple(reduce(rediv,[[t*1000,], 1000,60,60])) Now I can write: print "That took", secondsToStr(t2-t1),"seconds" and get nicely-formatted 0:00:12.345 style output. (I also posted this to the Python Cookbook.) -- Paul From jstroud at mbi.ucla.edu Fri Apr 6 06:22:42 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Fri, 06 Apr 2007 10:22:42 GMT Subject: tkinter canvas mvc In-Reply-To: References: Message-ID: Gigs_ wrote: > Hi all! > > I have just finished my tkinter text editor, learning tkinter purpose. > > Now I want to learn canvas so I want to make my paint program, I think > that this will be the best to do over model-view-controler pattern which > I need to learn also. > > Is there any good tutorial for mvc in python or can someone explain me > little bit about mvc? > or maybe some code snippet in mvc, that will be nice. > > Thanks in advance! > MVC in a nutshell. 1. You need a model. 2. You need a view. 3. You need a controller. Lets see how they work together, using dictionary-like interfaces: class Model(dict): pass class View(object): def __init__(self, controller, keys): self.controller = controller self.widgets = {} for k in keys: w = make_a_widget(k) def _callback(w=w): v = w.get_value() self.controller[k] = v w.bind(SomeEvent, _callback) self.widgets[k] = w self.controller.register_view(self) def __setitem__(self, k, v): self.widgets[k].set_value(v) def __contains__(self, k): return k in self.widgets class Controller(object): def __init__(self, model): self.views = [] self.data = model def register_view(self, aview): self.views.append(aview) def __setitem__(self, k, v): self.data[k] = v for aview in self.views: if k in aview: aview[k] = v def __getitem__(self, k): return self.data[k] def update(self, adict): self.data.update(adict) for k,v in adict.items(): for aview in self.views: if k in aview: aview[k] = v James From hlubenow2 at gmx.net Wed Apr 18 15:09:58 2007 From: hlubenow2 at gmx.net (hlubenow) Date: Wed, 18 Apr 2007 21:09:58 +0200 Subject: Future Python Gui? References: <1176859699.906386.326720@b75g2000hsg.googlegroups.com> <1176863948.526051.186210@n76g2000hsh.googlegroups.com> <1176909848.455264.174730@e65g2000hsc.googlegroups.com> Message-ID: <617if4-qe5.ln1@athlon.my> bcwhite at pobox.com wrote: > If this were just a tool for me, it wouldn't matter. My concern is > distribution. If anybody who wants to run my software then they also > have to go through all the trouble to install these extensions, none > of which seem to have decent instructions. I'm an old-time hack and I > have trouble getting them to work. A simple user won't have a chance! > > If Python doesn't declare an official Gui system, then it'll be > fragmented, inconsistent, and unsupportable. I guess that's why Tkinter, despite its primitive look, has made its way into the Python-distribution and I think, for the same reason it will stay there, until it can be replaced by something similar consistent. H. From bbxx789_05ss at yahoo.com Sun Apr 1 22:50:31 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: 1 Apr 2007 19:50:31 -0700 Subject: can a method access/set another's variables? In-Reply-To: <1175478965.803665.15040@o5g2000hsb.googlegroups.com> References: <1175477764.549115.159410@n59g2000hsh.googlegroups.com> <1175478965.803665.15040@o5g2000hsb.googlegroups.com> Message-ID: <1175482231.818833.324180@b75g2000hsg.googlegroups.com> On Apr 1, 7:56 pm, "wswilson" wrote: > On Apr 1, 9:43 pm, Michael Hoffman wrote: > > > > > asdf1234234 wrote: > > > -a.py- > > > import b > > > > class A: > > > def __init__(self): > > > pass > > > def my_method(self): > > > var = 1 > > > self.var = 2 > > > b.set_var(self) > > > print var > > > print self.var > > > > my_a = A() > > > my_a.my_method() > > > > -b.py- > > > def set_var(self): > > > var = 2 > > > self.var = 2 > > > > I want both var and self.var to be 2 at the end. Is there anything I > > > can pass to set_var() that will give it access to the variables in > > > my_method() like I can use self for the variables in the class A? > > > I hope there isn't a way to do this that simply. :) Why do you want to > > do this, or is it idle curiosity? There is almost surely a better way to > > solve your underlying problem. > > > You can *read* your caller's local variables (either pass locals() as an > > argument or use inspect to get the frame locals), but writing to this > > dictionary has undefined behavior. > > -- > > Michael Hoffman > > I am parsing a document which contains some lines with code I want to > eval or exec. However, due to the complexity of the parsing, I am > splitting it among different methods. So, if I eval something in one > method, it won't be there if I try to access its value a few lines > later since I happen to be in a different method in the parser. Thanks > for the help! class Parser(object): def early_parse(self): self.result1 = eval("10 + 5") def later_parse(self): self.result2 = self.result1 + eval("20 * 2") p = Parser() p.early_parse() p.later_parse() print p.result1 print p.result2 From jorgen.maillist at gmail.com Thu Apr 12 04:47:57 2007 From: jorgen.maillist at gmail.com (Jorgen Bodde) Date: Thu, 12 Apr 2007 10:47:57 +0200 Subject: Calling private base methods Message-ID: <11e49df10704120147x5d5df991r93d2b266a67e64ea@mail.gmail.com> Hi All, Now that I am really diving into Python, I encounter a lot of things that us newbies find difficult to get right. I thought I understood how super() worked, but with 'private' members it does not seem to work. For example; >>> class A(object): ... def __baseMethod(self): ... print 'Test' Deriving from A, and doing; >>> class D(A): ... def someMethod(self): ... super(A, self).__baseMethod() ... print 'test3' Will not work; >>> p = D() >>> p.someMethod() Traceback (most recent call last): File "", line 1, in File "", line 3, in someMethod AttributeError: 'super' object has no attribute '_D__baseMethod' Is it possible to call a private base method? I come from a C++ background, and I liked this construction as my base class has helper methods so that I do not have to duplicate code. When I do; >>> class E(object): ... def someMethod(self): ... print 'Hello' ... >>> class F(E): ... def otherMethod(self): ... super(F, self).someMethod() ... print 'There' ... >>> p = F() >>> p.otherMethod() Hello There >>> This seems to work. Thanks in advance, - Jorgen From thorsten at thorstenkampe.de Mon Apr 2 08:07:17 2007 From: thorsten at thorstenkampe.de (Thorsten Kampe) Date: Mon, 2 Apr 2007 13:07:17 +0100 Subject: I18n issue with optik References: Message-ID: * Jarek Zgoda (Sun, 01 Apr 2007 22:02:15 +0200) > Thorsten Kampe napisa?(a): > > >>> Under Windows I get " File "G:\program files\python\lib\encodings > >>> \cp1252.py", line 12, in encode > >>> return codecs.charmap_encode(input,errors,encoding_table)" > >> I'm not very experienced with internationalization, but if you change:: > >> > >> gettext.install('test') > >> > >> to:: > >> > >> gettext.install('test', unicode=True) > >> > >> what happens? > > > > No traceback anymore from optparse but the non-ascii umlauts are > > displayed as question marks ("?"). > > And this is expected behaviour of encode() with errors set to 'replace'. > I think this is the solution to your problem. I was a bit surprised I > never saw this error, but I always use the unicode=True setting to > gettext.install()... I can't see the "solution" here. Is the optparse "print_help" function wrong? Why should there even be errors if I use "unicode = True" with gettext.install? I have ISO-8859-15 gettext translations and I want optparse to display them correctly. What do I have to do? Thorsten From flifus at gmail.com Wed Apr 25 21:22:14 2007 From: flifus at gmail.com (flifus at gmail.com) Date: 25 Apr 2007 18:22:14 -0700 Subject: Where did my post go? Message-ID: <1177550534.197992.263190@u32g2000prd.googlegroups.com> I posted to this newsgroup earlier about my annoyances with python and now I can't find the post. What did you do with it? From irstas at gmail.com Mon Apr 2 12:17:29 2007 From: irstas at gmail.com (irstas at gmail.com) Date: 2 Apr 2007 09:17:29 -0700 Subject: Clean "Durty" strings In-Reply-To: <57cddlF2bsqdbU2@mid.uni-berlin.de> References: <1175463083.135907.128480@y80g2000hsf.googlegroups.com> <57bt02F2c9fpuU2@mid.uni-berlin.de> <57cddlF2bsqdbU2@mid.uni-berlin.de> Message-ID: <1175530649.060784.147900@d57g2000hsg.googlegroups.com> On Apr 2, 4:05 pm, "Diez B. Roggisch" wrote: > > If the OP is constrained to standard libraries, then it may be a > > question of defining what should be done more clearly. The extraneous > > spaces can be removed by tokenizing the string and rejoining the > > tokens. Replacing portions of a string with equivalents is standard > > stuff. It might be preferable to create a function that will accept > > lists of from and to strings and translate the entire string by > > successively applying the replacements. From what I've seen so far, > > that would be all the OP needs for this task. It might take a half- > > dozen lines of code, plus the from/to table definition. > > The OP had
-tags in his text. Which is _more_ than a half dozen lines of > code to clean up. Because your simple replacement-approach won't help here: > >
foo
bar
> > Which is perfectly legal HTML, but nasty to parse. > > Diez But it could be that he just wants all HTML tags to disappear, like in his example. A code like this might be sufficient then: re.sub(r'<[^>] +>', '', s). For whitespace, re.sub(r'\s+', ' ', s). For XML characters like é, re.sub(r'&(\w+);', lambda mo: unichr(htmlentitydefs.name2codepoint[mo.group(1)]), s) and re.sub(r'&#(\d+);', lambda mo: unichr(int(mo.group(1))), s). That's it pretty much. I'd like to see how this transformation can be done with BeautifulSoup. Well, the last two regexps can be replaced with this: unicode(BeautifulStoneSoup(s,convertEntities=BeautifulStoneSoup.HTML_ENTITIES).contents[0]) From shadroth at gmail.com Mon Apr 2 05:23:47 2007 From: shadroth at gmail.com (Ben) Date: Mon, 02 Apr 2007 19:23:47 +1000 Subject: Web App Framework with PostgreSQL + fast + easy Message-ID: I'm looking for a web application framework with a good interface to PostgreSQL. The app I'm developing is relatively simple, but I'm new to coding, so it needs to be easy. What I'm making is a wiki-like system that could be thought of as similar to MediaWiki, but with each word editable separately - ie. edit locks would be one word at a time. Features I need: * works well with PostgreSQL - fast and powerful with support/awareness of MVCC * easy to use * fast Features I want: * flexible options for user accounts, with some reasonable non HTTPS security * support for internationalisation. I am a happy Plone user, but I'm concerned it or even Zope on its own wouldn't be fast enough as they have a whole lot of functionality I really don't need and aren't built for a RDBMS. Ben From steve at REMOVE.THIS.cybersource.com.au Thu Apr 19 19:19:17 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Fri, 20 Apr 2007 09:19:17 +1000 Subject: Better dict of dicts References: <1177018181.493650.297900@e65g2000hsc.googlegroups.com> <-cudnX2k8KPLfLrbnZ2dnUVZ_uvinZ2d@ptd.net> Message-ID: On Thu, 19 Apr 2007 17:40:27 -0400, John Bauman wrote: > Adam Atlas wrote: >> On Apr 19, 5:24 pm, Bill Jackson wrote: >>> I have a dictionary of dictionaries where the keys are typically very >>> long tuples and repeated in each inner dictionary. The dictionary >>> representation is nice because it handles sparseness well...and it is >>> nice to be able to look up values based on a string rather than a >>> number. However, since my keys are quite long, I worry that I am >>> wasting a lot of memory. >> >> I wouldn't worry about it. Try doing hash('string_2') in the >> interpreter -- the output thereof is what's really being used as the >> key. It doesn't use up any more memory than the integer 2. >> > Are you sure about that? Most dictionaries need to store the actual key, > in case of a collision, so when you lookup a key they can tell which > you're really looking for. The key is already stored, so long as the string 'string_2' exists. And it will continue to exist so long as the dictionary includes it as a key. An extra copy isn't made (unless you make an extra copy yourself). In other words, the dictionary stores a reference to the string, not a copy of it: >>> s = "this is a long string" >>> d = {s: 1} >>> id(s) -1209073840 >>> id(d.keys()[0]) -1209073840 -- Steven. From tjreedy at udel.edu Wed Apr 25 17:18:11 2007 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 25 Apr 2007 17:18:11 -0400 Subject: Another Python Game Programming Challenge concludes References: <462F7688.2020300@vpcit.ru> Message-ID: "???? ???" wrote in message news:462F7688.2020300 at vpcit.ru... | The fourth Python Game Programming Challenge (PyWeek) has now concluded | with | judges (PyWeek being peer-judged) declaring the winners: | | Individual: Which way is up? by Hectigo | http://www.pyweek.org/e/Hectic/ | | Team: Bubble Kong by The Olde Battleaxe | http://www.pyweek.org/e/toba4/ 404 Not found Ditto for links on rating page. | | and the scores here: | http://media.pyweek.org/static/pyweek4_ratings.html tjr From erikwickstrom at gmail.com Sat Apr 14 21:56:00 2007 From: erikwickstrom at gmail.com (erikcw) Date: 14 Apr 2007 18:56:00 -0700 Subject: Traceback when trying to run script from cron? Message-ID: <1176602160.043372.225190@q75g2000hsh.googlegroups.com> Hi all, When trying to run this python script from cron, I get the following error: Traceback (most recent call last): File "/home/lybp/public_html/wa/wa.py", line 14, in ? import MySQLdb ImportError: No module named MySQLdb The cron command is python /home/lybp/public_html/wa/wa.py Any idea why MySQLdb wouldn't like this? Thanks! Erik From Bulkan at gmail.com Sun Apr 1 08:50:23 2007 From: Bulkan at gmail.com (placid) Date: 1 Apr 2007 05:50:23 -0700 Subject: Extract information from HTML table In-Reply-To: <1175429635.278697.92690@b75g2000hsg.googlegroups.com> References: <1175429635.278697.92690@b75g2000hsg.googlegroups.com> Message-ID: <1175431823.606062.13090@d57g2000hsg.googlegroups.com> On Apr 1, 10:13 pm, "Ulysse" wrote: > Hello, > > I'm trying to extract the data from HTML table. Here is the part of > the HTML source : > """ > > > type="checkbox"> > > Sat, 31.03.2007 - 20:24:00 > > Vous > avez tendu une embuscade ? votre victime ! > > > > type="checkbox"> > > Sat, 31.03.2007 - 20:14:35 > > Vous > avez tendu une embuscade ? votre victime ! > > > > type="checkbox"> > > Sat, 31.03.2007 - 20:11:39 > Vous avez bien accompli votre > t?che de Gardien de Cimeti?re et vous vous > voyez remis votre salaire comme r?compense. > Vous recevez 320 > alt="Or" align="absmiddle" border="0"> > et collectez 3 d'exp?rience ! > > """ > > I would like to transform this in following thing : > > Date : Sat, 31.03.2007 - 20:24:00 > ContainType : Link > LinkText : Vous avez tendu une embuscade ? votre victime ! > LinkURL :http://s2.bitefight.fr/bite/bericht.php?q=01bf0ba7258ad976d890379f987... > > Date : Sat, 31.03.2007 - 20:14:35 > ContainType : Link > LinkText : Vous avez tendu une embuscade ? votre victime ! > LinkURL :http://s2.bitefight.fr/bite/bericht.php?q=01bf0ba7258ad976d890379f987... > > Date : Sat, 31.03.2007 - 20:14:35 > ContainType : Text > Contain : Vous avez bien accompli votre t?che de Gardien de Cimeti?re > et vous vous > voyez remis votre salaire comme r?compense. > Vous recevez 320 et collectez 3 d'exp?rience ! > > .... > > Do you know the way to do it ? You can use Beautiful Soup http://www.crummy.com/software/BeautifulSoup/ see this page to see how you can search for tags, then retrieve the contents http://www.crummy.com/software/BeautifulSoup/documentation.html#Searching%20Within%20the%20Parse%20Tree Cheers From anbeyon at btinternet.com Tue Apr 3 16:42:17 2007 From: anbeyon at btinternet.com (Anbeyon) Date: 3 Apr 2007 13:42:17 -0700 Subject: Newbie - needs help Message-ID: <1175632937.838422.236850@y66g2000hsf.googlegroups.com> Hi I have not yet programmed in Python but am experienced in a number o other languages. I'd like to start to use Python to develop cross platform applications but havin kust started to investigate tols, libraries etc I feel a little overwhelmed. I'm hoping someone might be able to point me in the right direction. What I'd like to achieve is the abilty to develop applications for both Windows and Linux (Desktop and embedded). I'd also like to be able to develop applications that make use of TCP/IP and things like 'Widget' libraries. In an ideal would like to be able to pull together Python apps with GUI front ends in a nice IDE with a debugger. Does such a toolset exisit ? Perhaps some people can sully me some links ? Thanks in advance. Anbeyon From jstroud at mbi.ucla.edu Tue Apr 17 03:14:26 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Tue, 17 Apr 2007 07:14:26 GMT Subject: Getting started with python In-Reply-To: <1176706996.848574.196660@y5g2000hsa.googlegroups.com> References: <1176598011.463543.96990@q75g2000hsh.googlegroups.com> <1176608302.928513.274400@y5g2000hsa.googlegroups.com> <%LyUh.10121$YL5.5753@newssvr29.news.prodigy.net> <1176706996.848574.196660@y5g2000hsa.googlegroups.com> Message-ID: 7stud wrote: > On Apr 15, 9:49 pm, James Stroud wrote: >> py> t = timeit.Timer(stmt=s) >> py> print "%.2f usec/pass" % (1000000 * t.timeit(number=100000)/100000) >> 40.88 usec/pass >> > > What does this accomplish: > > 1000000 * t.timeit(number=100000)/100000 > > that the following doesn't accomplish: > > 10 * t.timeit(number=100000) > I have no idea--copy and pasted from timeit documentation. James From ah at hatzis.de Sat Apr 28 08:34:23 2007 From: ah at hatzis.de (Anastasios Hatzis) Date: Sat, 28 Apr 2007 14:34:23 +0200 Subject: Which are your favorite UML tools? In-Reply-To: References: <463265f0$0$19018$426a34cc@news.free.fr> Message-ID: <200704281434.23575.ah@hatzis.de> On Saturday 28 April 2007 00:26, Russell E. Owen wrote: > In article <463265f0$0$19018$426a34cc at news.free.fr>, > > Bruno Desthuilliers wrote: > > Anastasios Hatzis a ?crit : > > > Hello, > > > > > > I'm working on the light-weight MDA tool pyswarm, > > > http://pyswarm.sourceforge.net/ (it is about a code-generator for > > > Python/PostgreSQL-based software. I plan to add support of UML CASE > > > tools other than the one supported currently. > > > > > > I would like to learn which UML tools you use (if any), > > > > Any piece of paper and anything that can be used to write on it. > > > > > preferrably if it > > > comes to modeling a Python application. > > > > I stll wait for UML to be able to describe common hi-level dynamic > > languages idioms and patterns without requiring more space and time than > > source code. > > I am inclined to agree, though my experience is limited. I work on a > project that is trying to model all its software using Enterprise > Architect. EA has some nice features, but overall I find it clumsy and > frustrating. > > Some problems are intrinsic to UML (for instance it has no concept of > linking use case information to other elements). And I don't know of any > way to model functions (only classes). > > Others are EA's fault. For instance it is very slow and clumsy to add or > edit lists of items (such as class methods or database fields). Also, > shared development is a pain because there is no concurrent version > control (it uses CVS to keep track of revisions, but not in a concurrent > way; checking out a package locks out everybody else). Version control of UML models is a tough issue, given the dependencies between models and thinking of visualization of differences between two models. So far my tool only uses one model in one single XMI file, but I have to change this especially since I want to ease the re-use of components between projects. > > I tried using a competing product but the interporability was terrible. > Which brings up another point: it is likely the original poster would > need to do a lot of work for each CASE tool supported. Unfortunetaly you are too right! :)) Interoperability via XMI is a nightmare I don't want to dream anymore. For example, in the recent years it would have been much easier to use MagicDraw's OpenAPI with Jython to access models instead of importing its XMI files. The one thing is that MOF, UML and XMI are developing way too fast, so there are many tools but chance is little that they are based on the same standard versions. Additionally I don't know one tool which fully implements the corresponding standard specifications. Not a big surprise since the specifications are really complex and extensive. So, supporting one specific XMI format of one UML tool is not that complicated (especially since not all features are needed). But I have still a hard time thinking about an appropriate mapping between all these different standard versions and the differences how they are implemented in the tools. Especially since I want to keep these differences away from the normal tool user. Maybe it will be possible, at least as some compromise. The future will show. Best regards, Anastasios From bbxx789_05ss at yahoo.com Tue Apr 10 02:35:35 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: 9 Apr 2007 23:35:35 -0700 Subject: setup() and C extensions In-Reply-To: <1176184942.119878.230850@p77g2000hsh.googlegroups.com> References: <1176184942.119878.230850@p77g2000hsh.googlegroups.com> Message-ID: <1176186934.996315.142040@w1g2000hsg.googlegroups.com> Also: 1) When you create a C array to map python names to the C functions that you defined: static PyMethodDef MyFunctions[] = { {"my_calc", (PyCFunction)my_func, METH_VARARGS, "my very speedy c function"}, {NULL, NULL, 0, NULL} }; Why do you need to cast my_func to PyCFunction? 2) When returning None, why use the idiom: Py_INCREF(Py_None); return Py_None; instead of: return Py_BuildValue(""); From mail at timgolden.me.uk Mon Apr 30 05:21:19 2007 From: mail at timgolden.me.uk (Tim Golden) Date: Mon, 30 Apr 2007 10:21:19 +0100 Subject: Importing a csv file In-Reply-To: <1177923524.747364.182460@h2g2000hsg.googlegroups.com> References: <1177923524.747364.182460@h2g2000hsg.googlegroups.com> Message-ID: <4635B50F.1020306@timgolden.me.uk> sagar wrote: > Hi all , > I want to read data in a csv file using the python scripts. > when i gave the following code : > import csv > reader = csv.reader(open("some.csv", "rb")) > for row in reader: > print row > > it is showing : > > Traceback (most recent call last): > File "csv.py", line 1, in > import csv > File "C:\Documents and Settings\meesa02\csv.py", line 2, in > reader = csv.reader(open("some.csv", "rb")) > AttributeError: 'module' object has no attribute 'reader' You almost certainly have a file called "csv.py" in the current directory. (Maybe even the one that's running this script?). Rename it to "mycsv.py" or whatever and try again. TJG From ericcoetzee at gmail.com Sun Apr 1 18:42:25 2007 From: ericcoetzee at gmail.com (eC) Date: 1 Apr 2007 15:42:25 -0700 Subject: Is this a wxPython 2.8.0 bug with GetItemText method of wxTreeCtrl? Message-ID: <1175467345.135261.290050@d57g2000hsg.googlegroups.com> I use a tree control in my application and was hoping to use use the GetItemText method to read the new label of the tree item after the user has edited it. So in the EVT_TREE_END_LABEL_EDIT event handler, i call this method but the old label (previous value before the edti) is returned. Is there something else i have to do or is this a bug? From david at boddie.org.uk Mon Apr 16 18:13:15 2007 From: david at boddie.org.uk (David Boddie) Date: Tue, 17 Apr 2007 00:13:15 +0200 Subject: Pyqt calling a custom dialog and returning the vars References: <1176753980.142797.268800@e65g2000hsc.googlegroups.com> Message-ID: <9a677$4623f4fc$54d1d767$25878@news.chello.no> On Monday 16 April 2007 22:06, Marcpp wrote: > I call a dialog from a principal program but cannot return the value > of the > variables (text box's). Here is a example... [...] > class ag (Agenda): > ... > ... > def _slotAddClicked(self): > d=dialogo1() > d.exec_() > d.connect(d.buttonOk,SIGNAL("clicked()"),self._procesadialog1) > > def _procesadialog1(): > d=dialogo1() > drempresa = d.dempresa.text() > print drempresa # Without seeing more of what you've done, it's difficult to tell, but you are just creating a new dialog in _procesadialog1() and reading the default text in its "dempresa" attribute which I presume is a QLineEdit widget. Assuming everything else is working correctly, I think you should remove the second method and rewrite the first one in the following way: class ag (Agenda): ... ... def _slotAddClicked(self): d=dialogo1() if d.exec_() == QDialog.Accepted: drempresa = d.dempresa.text() print drempresa # David From paddy3118 at googlemail.com Sat Apr 14 23:20:42 2007 From: paddy3118 at googlemail.com (Paddy) Date: 14 Apr 2007 20:20:42 -0700 Subject: function with list argument defaulting to [] - what's going on here??? In-Reply-To: References: <46217e8f$0$19437$4c368faf@roadrunner.com> Message-ID: <1176607242.441196.140310@n76g2000hsh.googlegroups.com> On Apr 15, 3:58 am, Steven D'Aprano wrote: > On Sat, 14 Apr 2007 17:33:11 -0800, Troy Melhase wrote: > > On 4/14/07, Mike wrote: > >> While trying to write a recursive function involving lists, I came > >> across some (to me) odd behavior which I don't quite understand. Here's > >> a trivial function showing the problem. > > > fromhttp://docs.python.org/ref/function.html: > > > Default parameter values are evaluated when the function definition is > > executed. This means that the expression is evaluated once, when the > > function is defined, and that that same ``pre-computed'' value is used > > for each call. This is especially important to understand when a > > default parameter is a mutable object, such as a list or a dictionary: > > if the function modifies the object (e.g. by appending an item to a > > list), the default value is in effect modified. > > This comes up so often that I wonder whether Python should issue a warning > when it sees [] or {} as a default argument. > > What do people think? A misuse or good use of warnings? > > -- > Steven. I wonder if it is a check done by Pylint or PyChecker? - Paddy. From stargaming at gmail.com Sun Apr 22 04:02:27 2007 From: stargaming at gmail.com (Stargaming) Date: Sun, 22 Apr 2007 10:02:27 +0200 Subject: Suggestion: str.itersplit() In-Reply-To: <1177166092.614602.81530@n59g2000hsh.googlegroups.com> References: <1177160280.784224.53460@b58g2000hsg.googlegroups.com> <1177166092.614602.81530@n59g2000hsh.googlegroups.com> Message-ID: subscriber123 schrieb: > On Apr 21, 8:58 am, Dustan wrote: > >>>From my searches here, there is no equivalent to java's >> >>StringTokenizer in python, which seems like a real shame to me. >> >>However, str.split() works just as well, except for the fact that it >>creates it all at one go. I suggest an itersplit be introduced for >>lazy evaluation, if you don't want to take up recourses, and it could >>be used just like java's StringTokenizer. >> >>Comments? > > > That would be good, because then you could iterate over strings the > same way that you iterate over files: > > for line in string.itersplit("\n"): > ## for block ## > > >>> block = """Hello world. ... This is a comment. ... With a few more lines.""" >>> for line in block.split("\n"): ... print line ... Hello world. This is a comment. With a few more lines. >>> for line in block.splitlines(): # could even use this one here ... print line ... Hello world. This is a comment. With a few more lines. Iterators would just speed up the whole thing and be more pythonic (since development goes straight into the direction of converting all and everything into iterators). From oliver at obeattie.com Tue Apr 3 14:12:59 2007 From: oliver at obeattie.com (oliver at obeattie.com) Date: 3 Apr 2007 11:12:59 -0700 Subject: raw_input just continues anyway? In-Reply-To: References: <1175606844.249364.290060@o5g2000hsb.googlegroups.com> <57f489F2c787iU1@mid.individual.net> <1175611910.685578.246780@w1g2000hsg.googlegroups.com> Message-ID: <1175623979.629946.184530@b75g2000hsg.googlegroups.com> How could I resolve this? Many thanks, O From kw at codebykevin.com Sat Apr 14 13:00:04 2007 From: kw at codebykevin.com (Kevin Walzer) Date: Sat, 14 Apr 2007 13:00:04 -0400 Subject: Python editor/IDE on Linux? In-Reply-To: References: Message-ID: Jack wrote: > I wonder what everybody uses for Python editor/IDE on Linux? > I use PyScripter on Windows, which is very good. Not sure if > there's something handy like that on Linux. I need to do some > development work on Linux and the distro I am using is Xubuntu. > > Why not IDLE? -- Kevin Walzer Code by Kevin http://www.codebykevin.com From jstroud at mbi.ucla.edu Wed Apr 25 20:06:53 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Wed, 25 Apr 2007 17:06:53 -0700 Subject: My python annoyances so far In-Reply-To: <1177541453.471959.120830@c18g2000prb.googlegroups.com> References: <1177541453.471959.120830@c18g2000prb.googlegroups.com> Message-ID: flifus at gmail.com wrote: > Hi all. I'm learning python these days. I'm going to use this thread > to post, from time to time, my annoyances with python. Please start a new thread for each annoyance. Overuse of a single thread is an annoyance to a great many people. > I hope someone > will clarify things to me where I have misunderstood them. Perhaps substitute "annoyance" with "misunderstanding" to garner the friendliness of your python peers. > Annoyances: You mean "Misunderstandings:" > 1. Underscores! What's the deal with that? Especially those double > underscores. The best answer I read on this is that the double > underscores denotes special methods that the interpreter may > automatically use. For example, 4+4 get expanded by the interpreter to > 4.__add__(4). The double underscores are probably not the most aesthetic feature of the language. By the time you know how and when to use them, they will not bother you at all and so you will be scratching #1 off your list. > 2. There are modules, there are functions, and there are classes- > methods! Wouldn't it have been easier had everything either been a > function or a class method? > Do you mean "unbound methods" or "class methods"? They are essentially the same as functions unless you get into the internals of python, which means you are going out of your way to look for annoyances. Such behavior will lead to frustration and, eventually, abject ennui. So you should strike your latter point off your list of annoyances...misunderstandings. For example: py> class Thing(object): ... doit = classmethod(doit) ... py> Thing.doit(88) Param is "param". py> Thing.doit(object()) Param is "param". py> def doit(athing, param): ... print 'Param is "%s".' % param ... py> class Thing(object): ... doit = doit ... py> t = Thing() py> t.doit(4) Param is "4". If your latter misunderstanding is about the lack of actual class methods, then consider: py> class Thing(object): ... doit = classmethod(doit) ... py> Thing.doit(4) Param is "4". James From bdelmee at advalvas._REMOVEME_.be Wed Apr 11 04:17:35 2007 From: bdelmee at advalvas._REMOVEME_.be (=?ISO-8859-1?Q?Bernard_Delm=E9e?=) Date: Wed, 11 Apr 2007 10:17:35 +0200 Subject: No zlib in Python 2.4.4 In-Reply-To: <1176278576.196716.104760@p77g2000hsh.googlegroups.com> References: <1176278576.196716.104760@p77g2000hsh.googlegroups.com> Message-ID: <461c99cc$0$13855$ba620e4c@news.skynet.be> > I need Python to be compiled with Zlib so that I can compile and use > Zope. I am guessing you need zlib_dev.rpm (or somesuch) installed for the python build process to find the relevant headers. Sorry I cannot be more specific not being a SuSE user myself (anymore)... Bernard. From dandolls at yahoo.co.in Wed Apr 11 05:09:09 2007 From: dandolls at yahoo.co.in (Amit K Saha) Date: Wed, 11 Apr 2007 14:39:09 +0530 Subject: Python-list Digest, Vol 43, Issue 155 In-Reply-To: References: Message-ID: <1176282550.4952.4.camel@ubuntu-desktop> Hi mike! > > I've played with the win32 module's text-to-speech abilities a little. > > You may be able to get ideas from that. Here's a link to more info: > > http://surguy.net/articles/speechrecognition.xml > > > > http://www.cs.unc.edu/~parente/tech/tr02.shtml > > I forgot to mention that I am actually targeting the GNOME desktop for my application. So the win32 solution wont work for me. Thanks for the help anyways > > This isn't pure Python, but it may be helpful as well: > > http > > ://sourceforge.net/projects/VoiceCode/ This link is a nice one! Send instant messages to your online friends http://in.messenger.yahoo.com From mike.aldrich at gmail.com Wed Apr 11 15:13:42 2007 From: mike.aldrich at gmail.com (mike.aldrich at gmail.com) Date: 11 Apr 2007 12:13:42 -0700 Subject: Reading the first line of a file (in a zipfile) Message-ID: <1176318822.811661.115730@q75g2000hsh.googlegroups.com> Hi folks, I am trying to read the first occurence of non-whitespace in a file, within a zipfile. Here is my code: zipnames = glob.glob("*") for zipname in zipnames: z = zipfile.ZipFile(zipname, "r") for filename in z.namelist(): count = len(z.read(filename).split('\n')) if fnmatch.fnmatch(filename, "*AUDIT*"): test = filename.split(' ') print 'File:', test[0], bytes = z.read(filename) print 'has', len(bytes), 'bytes' print 'and', count, 'lines' The first line in the file I am examining will be a number followed by more whitespace. Looks like I cannot split by whitespace? From grante at visi.com Mon Apr 23 15:43:20 2007 From: grante at visi.com (Grant Edwards) Date: Mon, 23 Apr 2007 19:43:20 -0000 Subject: Generate report containing pdf or ps figures? References: <132pnp6r4qg0lc2@corp.supernews.com> <1177355647.569658.69580@b58g2000hsg.googlegroups.com> Message-ID: <132q32o9uv794ec@corp.supernews.com> On 2007-04-23, half.italian at gmail.com wrote: >> I've looked at ReportLab's documentation, but although it >> appears to be able to use bitmap images (e.g jpeg) it doesn't >> appear to be able to use vector images (EPS/PDF/SVG). >> >> Is there a PDF generation library that can place EPS or >> PDF figures on a page? > > On a Mac... > > http://developer.apple.com/graphicsimaging/pythonandquartz.html Something that's easy to do and builtin to MacOS that's painful or difficult to do under Windows? Nah, couldn't be... -- Grant Edwards grante Yow! Kids, don't gross me at off ... "Adventures with visi.com MENTAL HYGIENE" can be carried too FAR! From peter.maas at nospam.de Wed Apr 18 15:31:17 2007 From: peter.maas at nospam.de (Peter Maas) Date: Wed, 18 Apr 2007 21:31:17 +0200 Subject: scipy 0.52 det crashes python In-Reply-To: References: Message-ID: Robert Kern schrieb: > Most likely your build of scipy was built with an ATLAS library that uses SSE2 > instructions (IIRC) while your processor doesn't support those instructions. The > solution is to rebuild scipy with an ATLAS library built for your platform. Thanks, Robert. -- Peter Maas, Aachen From rehceb at no.spam.plz Sun Apr 8 17:13:55 2007 From: rehceb at no.spam.plz (Rehceb Rotkiv) Date: Sun, 08 Apr 2007 16:13:55 -0500 Subject: Unicode problem References: <1175975209.261304.183220@p77g2000hsh.googlegroups.com> Message-ID: On Sat, 07 Apr 2007 12:46:49 -0700, Gabriel Genellina wrote: > You have to encode the Unicode object explicitely: print > fileString.encode("utf-8") > (or any other suitable one; I said utf-8 just because you read the input > file using that) Thanks! That's a nice little stumbling block for a newbie like me ;) Is there a way to make utf-8 the default encoding for every string, so that I do not have to encode each string explicitly? From martin at v.loewis.de Sun Apr 1 02:17:16 2007 From: martin at v.loewis.de (=?UTF-8?B?Ik1hcnRpbiB2LiBMw7Z3aXMi?=) Date: Sun, 01 Apr 2007 08:17:16 +0200 Subject: CRC CCITT UPDATE in Python In-Reply-To: <1175393727.233247.254500@n76g2000hsh.googlegroups.com> References: <1175393727.233247.254500@n76g2000hsh.googlegroups.com> Message-ID: <460F4E6C.9050308@v.loewis.de> > Please, is there here some good soul that understand this > functions hi8 and lo8 (from GCC AVR) and can help me to port it to > Python? > > uint16_t > crc_ccitt_update (uint16_t crc, uint8_t data) > { > data ?= lo8 (crc); > data ?= data << 4; > return ((((uint16_t)data << 8) | hi8 (crc)) ? (uint8_t)(data >> 4) > ? ((uint16_t)data << 3)); > } Most likely, lo8(crc) == crc & 0xFF, and hi8(crc) == (crc >> 8) & 0xFF (the last bit masking might be redundant, as crc should not occupy more than 16 bits, anyway). HTH, Martin From carsten at uniqsys.com Sat Apr 28 10:41:14 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Sat, 28 Apr 2007 10:41:14 -0400 Subject: Program runs in all directories, except one.. In-Reply-To: References: Message-ID: <1177771274.3319.9.camel@localhost.localdomain> On Sat, 2007-04-28 at 13:50 +0200, Theo v. Werkhoven wrote: > Goodday, > > Something strange going on here. > A piece of code I wrote bombs out in one of de directories under $HOME, > but not in others. This usually means that the directory where your script doesn't work contains some .py file that has the same name as a standard library module that you need. Since the only import in your code snippet is "from array import array", and calling array() raises the exception that a list object is not callable, I am guessing that the culprit is a file named array.py that defines a list called array. Rename that file. -Carsten From danmcleran at yahoo.com Tue Apr 3 15:00:13 2007 From: danmcleran at yahoo.com (danmcleran at yahoo.com) Date: 3 Apr 2007 12:00:13 -0700 Subject: os.popen--which one to use? In-Reply-To: References: Message-ID: <1175626813.785146.326220@n59g2000hsh.googlegroups.com> On Apr 3, 12:53 pm, Kevin Walzer wrote: > I'm confused by the number of variations on "popen" that Python offers. > > I'm using os.popen in my programs without difficulty. Is this wrong? > Should I be using popen 2, popen3, etc.? I'm not clear on what the > advantages of popen2, 3 etc. are: they seem a lot more complicated. > > -- > Kevin Walzer > Code by Kevinhttp://www.codebykevin.com Check out subprocess. It's meant to be a replacement for all of the above. From michael at jedimindworks.com Sat Apr 14 01:02:40 2007 From: michael at jedimindworks.com (Michael Bentley) Date: Sat, 14 Apr 2007 00:02:40 -0500 Subject: how to strip the domain name in python? In-Reply-To: <1176526155.679721.159870@l77g2000hsb.googlegroups.com> References: <1176526155.679721.159870@l77g2000hsb.googlegroups.com> Message-ID: <1D26AE51-7CDC-491E-8729-BB8D152C16E4@jedimindworks.com> On Apr 13, 2007, at 11:49 PM, Marko.Cain.23 at gmail.com wrote: > Hi, > > I have a list of url names like this, and I am trying to strip out the > domain name using the following code: > > http://www.cnn.com > www.yahoo.com > http://www.ebay.co.uk > > pattern = re.compile("http:\\\\(.*)\.(.*)", re.S) > match = re.findall(pattern, line) > > if (match): > s1, s2 = match[0] > > print s2 > > but none of the site matched, can you please tell me what am i > missing? change re.compile("http:\\\\(.*)\.(.*)", re.S) to re.compile("http:\/ \/(.*)\.(.*)", re.S) From ziga.seilnacht at gmail.com Wed Apr 4 14:27:26 2007 From: ziga.seilnacht at gmail.com (Ziga Seilnacht) Date: 4 Apr 2007 11:27:26 -0700 Subject: operator overloading In-Reply-To: <1175679412.741899.45990@l77g2000hsb.googlegroups.com> References: <1175679412.741899.45990@l77g2000hsb.googlegroups.com> Message-ID: <1175711246.488717.262560@e65g2000hsc.googlegroups.com> looping wrote: > Hi, > for the fun I try operator overloading experiences and I didn't > exactly understand how it works. > > Here is my try: > >>> class myint(int): > > def __pow__(self, value): > return self.__add__(value) > > >>> a = myint(3) > >>> a ** 3 > > 6 > > OK, it works. Now I try different way to achieve the same result but > without much luck: > > >>> class myint(int): > pass > >>> myint.__pow__ = myint.__add__ > > or: > > >>> class myint(int): > > __pow__ = int.__add__ > > or: > > >>> class myint(int): > pass > >>> a.__pow__ = a.__add__ > > but for every try the result was the same:>>> a = myint(3) > >>> a ** 3 > 27 > > Why it doesn't works ? This looks like a bug in Python. It works for all the other operators: >>> class MyInt(int): ... __sub__ = int.__add__ ... __mul__ = int.__add__ ... __div__ = int.__add__ ... __truediv__ = int.__add__ ... __floordiv__ = int.__add__ ... __mod__ = int.__add__ ... __lshift__ = int.__add__ ... __rshift__ = int.__add__ ... __and__ = int.__add__ ... __xor__ = int.__add__ ... __or__ = int.__add__ ... __pow__ = int.__add__ ... >>> i = MyInt(42) >>> i + 3 45 >>> i - 3 45 >>> i * 3 45 >>> i / 3 45 >>> i // 3 45 >>> i % 3 45 >>> i << 3 45 >>> i >> 3 45 >>> i & 3 45 >>> i ^ 3 45 >>> i | 3 45 >>> i ** 3 74088 You should submit a bug report to the bug tracker: http://sourceforge.net/bugs/?group_id=5470 Ziga From steven.bethard at gmail.com Sun Apr 22 23:22:33 2007 From: steven.bethard at gmail.com (Steven Bethard) Date: Sun, 22 Apr 2007 21:22:33 -0600 Subject: recursion depth problem In-Reply-To: <1hwzkey.19hmuyn1tebhe7N%aleax@mac.com> References: <1177267774.416169.276780@e65g2000hsc.googlegroups.com> <1177271382.859369.104790@q75g2000hsh.googlegroups.com> <1177278499.378120.246560@o5g2000hsb.googlegroups.com> <1hwzkey.19hmuyn1tebhe7N%aleax@mac.com> Message-ID: Alex Martelli wrote: > Steven Bethard wrote: > ... >>>>>>> import sys >>>>>>> def ch4(item, n=0): >>>>>>> if n < len(item): >>>>>>> if item[n] == '0': >>>>>>> item[n] = '1' >>>>>>> print ''.join(item) >>>>>>> ch4(item) >>>>>>> elif item[n] == '1': >>>>>>> item[n] = '0' >>>>>>> ch4(item, n+1) >>>>>>> ch4(list(sys.argv[1])) > ... >>> for interest sake: is my method unredeemable? >> Let's just say that I don't currently see an obvious way of redeeming >> it. ;-) > > Change the outer if into a while, and the recursive calls into proper > assignments to n. They're both tail-recursive calls, so this won't > change the semantics, as it happens. Thanks! >>> def f(chars): ... n = 0 ... while n < len(chars): ... if chars[n] == '0': ... chars[n] = '1' ... n = 0 ... print ''.join(chars) ... elif chars[n] == '1': ... chars[n] = '0' ... n += 1 ... >>> f(list('00000000')) 10000000 01000000 11000000 ... 10111111 01111111 11111111 Looks good. STeVe From gagsl-py2 at yahoo.com.ar Wed Apr 11 22:50:13 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 11 Apr 2007 23:50:13 -0300 Subject: recec & Bastion ? References: <461d6064$1@nntp.zianet.com> Message-ID: En Wed, 11 Apr 2007 19:26:27 -0300, Erik Johnson escribi?: > The documentation for these two modules says that they were disabled > in > Python 2.3 due to security holes not easily fixable. I have not worked > with > them, but I can still import them under Python 2.4, so I'm not clear on > whether the security problems were fixed in Python itself, or whether the > modules remain deprecated (disabled?)? How are/were they actually > disabled? > Any place that documents what the problems are? Any alternatives? They were unsecure in 2003, and still are. This example still works (you have to re-enable Bastion.py and rexec.py to test, removing the explicit RuntimeError raise) http://mail.python.org/pipermail/python-dev/2003-January/031851.html With new-style classes you can create new instances using type(), by example; this way you can bypass the read-only restriction on files. The language has grown plenty of new attributes, they're very handy, but provide a lot of security holes; like __subclasses__ by example. As far as I know, Python can't secure itself by now. I think you have to go outside Python, using a chroot jail by example. -- Gabriel Genellina From trevis.crane at gmail.com Thu Apr 19 16:58:47 2007 From: trevis.crane at gmail.com (orangeDinosaur) Date: 19 Apr 2007 13:58:47 -0700 Subject: matplotlib basic question Message-ID: <1177016327.543985.34500@o5g2000hsb.googlegroups.com> Hi, I am exploring the possibility of using python as a replacement of MATLAB when I leave school. So, I've been playing with matplotlib and have run into some weird behavior after recently installing python 2.5.1 and matplotlib 0.90 on my Windows XP machine. Here's an example of what I see: >>>from matplotlib.pylab import * >>>x=arange(-2*pi,2*pi,pi/24) >>>y=sin(x) >>>plot(x,y) [] >>> show() So, first off, what's up with the [] line that shows up after my plot command? And second, when I call show(), a new figure pops up with my sin wave -- seems all right, yes? But I'm not given another >>> prompt in IDLE until or unless I close the figure that popped up with the show() call. So, after closing the figure I type this: >>>show() >>>plot(x,y) >>> and this time another figure pops up with my sine wave again and I get a prompt as well. But now, the figure window is completely unresponsive -- I can't even close it without getting the "your program is not repsonding" business. What am I missing? This behavior so far seems pretty unintuitive. Any clarification is appreciated! trevis From michael at jedimindworks.com Sat Apr 21 11:29:13 2007 From: michael at jedimindworks.com (Michael Bentley) Date: Sat, 21 Apr 2007 10:29:13 -0500 Subject: Styled Output In-Reply-To: <001b01c783ee$090d2520$1b276f60$@rawlins@thinkbluemedia.co.uk> References: <001b01c783ee$090d2520$1b276f60$@rawlins@thinkbluemedia.co.uk> Message-ID: <718EA79C-D66F-43AC-8015-AE0CC5DBBC68@jedimindworks.com> On Apr 21, 2007, at 3:21 AM, Robert Rawlins - Think Blue wrote: > Chaps, > > > > Hope you?re all having a good weekend, I?m sure it?ll only be the > more ?hard core? of you reading this, anyone with any sanity would > be out in the sunshine right now. > > > > I?m running a program of mine from Linux bash script and it > currently outputs status messages to the command prompt, but they > all look a little boring to say the least, it?ll be like this. > > > > Application Started > > Sucess > > Application Configured > > Failed > > Retry > > Application Configured > > Success > > > > What I?d ideally like to do it give it a little bit of format, so > it perhaps looks something like this. > > > > Application > Started > [Success] > > Application > Configured > [Success] > > > > And perhaps have the word ?success? in green, or red for ?failed? > and things like that, just to make it a little more presentable to > the user. > > > > Any ideas on the best way to achieve this? > > He, he -- umm yeah (and who said all that time with THEDRAW as a kid would never pay off) ;-) Try this: #! /usr/bin/env python def statusMessage(msg, status, msgWidth=60): if status.lower() == 'success': status = '\033[32m[%s]\033[00m' % status elif status.lower() == 'failed': status = '\033[31m[%s]\033[00m' % status else: status = '\033[33m[%s]\033[00m' % status msg = msg + ' ' * (msgWidth - len(msg)) print '%s%s' % (msg, status) if __name__ == '__main__': statusMessage('Application Started', 'Success') statusMessage('Application Configured', 'Failed') statusMessage('', 'Retry') statusMessage('Application Configured', 'Success') From cam.ac.uk at mh391.invalid Tue Apr 24 06:47:20 2007 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Tue, 24 Apr 2007 11:47:20 +0100 Subject: Would You Write Python Articles or Screencasts for Money? In-Reply-To: References: Message-ID: Jeff Rush wrote: > There is discussion by the Python Software Foundation of offering cash > bounties or perhaps periodic awards to the "best of" for magazine articles, > video/screencast clips and such. > > If YOU would be swayed to get involved in producing content in exchange for > cash, please speak up on the advocacy mailing list and also drop an email to > Steve Holden , current champion of this idea and looking > for encouragement. The very next thread I see after this one in this newsgroup is "work at home from internet.and earn 4000USD every month." So you'll have to do better than that for an adequate incentive. ;) Seems like a good idea, although I don't have any constructive suggestions at this point. -- Michael Hoffman From psdasilvaX at esotericaX.ptX Tue Apr 10 14:59:56 2007 From: psdasilvaX at esotericaX.ptX (Paulo da Silva) Date: Tue, 10 Apr 2007 19:59:56 +0100 Subject: NLTK, Random Sentence Generators? In-Reply-To: <1176224912.373928.326030@e65g2000hsc.googlegroups.com> References: <87slb8d3uj.fsf@localhost.localdomain> <1176224912.373928.326030@e65g2000hsc.googlegroups.com> Message-ID: <1176231570.124706@jubilee.claranet.pt> gene tani escreveu: > On Apr 10, 1:36 am, Passer By wrote: >> Has any created or not of examples of random sentence generators using >> n-gram models (or other models might be interesting). >> >> I know of one example from a course at MIT, but besides that nothing. >> >> Any help would be great. > > Markov chains e.g. > http://rubyquiz.com/quiz74.html > Seems interesting ... Is there anybody who masters both python and ruby to "translate" the code into python? From mcPas.De.Spam at mclaveauPas.De.Spam.com Mon Apr 9 05:25:36 2007 From: mcPas.De.Spam at mclaveauPas.De.Spam.com (Michel Claveau) Date: Mon, 09 Apr 2007 11:25:36 +0200 Subject: pluie documentation in english References: <1176109628.413745.285120@n76g2000hsh.googlegroups.com> Message-ID: Hi! Bonjour ! Thanks very well for translation. Merci beaucoup pour la traduction. I add a link on the index page of the site. J'ai ajout? un lien vers le document, dans la page d'accueil. Site: http://www.ponx.org/ponx/guie.htm But... I hope complete the (french) doc in next days. Mais... J'esp?re pouvoir compl?ter la documentation dans les jours qui viennent. -- @-salutations Michel Claveau From sjmachin at lexicon.net Tue Apr 24 23:47:11 2007 From: sjmachin at lexicon.net (John Machin) Date: Wed, 25 Apr 2007 13:47:11 +1000 Subject: Where's the source code for __builtin__? In-Reply-To: <87lkghgp72.fsf@benfinney.id.au> References: <1177457545.075398.204990@r3g2000prh.googlegroups.com> <462EA63C.6080805@lexicon.net> <87lkghgp72.fsf@benfinney.id.au> Message-ID: <462ecf43$1@news.eftel.com.au> On 25/04/2007 12:31 PM, Ben Finney wrote: > John Machin writes: > >> On 25/04/2007 9:32 AM, Dustan wrote: >>> I've been paging through the source code for various C modules in >>> python, and wanted to find the source of some of the builtin >>> functions. You snipped the 2nd sentence of what the OP wrote: """ I searched through the Modules, Objects, Python, and Parser folder, searched docs.python.org, searched the archived messages of this group, searched the web, and got absolutely nowhere in finding a __builtin__.c, or anything that contains the builtin source code. """ He's looking through the *SOURCE* distribution. >> What's the 2nd file (in alphabetical order) in the Python folder? > > What is "the Python folder"? > > Assuming you mean "the folder for the Python standard library > modules": Wrong assumption. You're expecting the source for builtin functions to be written in Python? > > $ ls -1 /usr/lib/python2.4/ | head -n 10 > aifc.py [snip] > atexit.pyc > > There are no files in that folder with 'builtin' in their name. And when you get to /Python, you'll find that that's still the case :-) > I'm > don't know what point you're driving at. Astonishment that the OP missed it in his serial scan of file names, even though the name wouldn't be picked up by glob.glob('*builtin*') BTW there's this ancient gadget called 'grep' that can be used to find patterns in files, like 'nameofabuiltinfunction('; any semi-usable editor or IDE would have similar functionality. Cheers, John From gagsl-py2 at yahoo.com.ar Mon Apr 9 15:22:40 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 09 Apr 2007 16:22:40 -0300 Subject: [offtopic?] problem with UDP broadcast on Windows XP References: <461a271c$0$323$e4fe514c@news.xs4all.nl> <461a6523$0$327$e4fe514c@news.xs4all.nl> Message-ID: En Mon, 09 Apr 2007 13:08:03 -0300, Irmen de Jong escribi?: > Gabriel Genellina wrote: > >> Try running the service impersonating another user (not LOCAL_SERVICE, >> the default). >> You can change that from the service control panel. > > Alas, that didn't change anything. > I made it run as a user account that has admin privileges even, > and it still doesn't respond to the broadcasts. :-( Ouch, no more ideas from me. You'll surely get more answers from a Windows networking group - this appears not to be related to Python anyway. -- Gabriel Genellina From robert.kern at gmail.com Tue Apr 3 13:51:23 2007 From: robert.kern at gmail.com (Robert Kern) Date: Tue, 03 Apr 2007 12:51:23 -0500 Subject: Numeric compiling problem under QNX 4.25 In-Reply-To: <1175622049.939184.28670@d57g2000hsg.googlegroups.com> References: <1175578324.426293.21970@y80g2000hsf.googlegroups.com> <1175622049.939184.28670@d57g2000hsg.googlegroups.com> Message-ID: ZMY wrote: > Is "ld" part of make command? I am not familiar with compiling with > make in general. No, it's the linker. I takes the object files (.o) which are generated by the compiler (cc, I imagine) and links them together into the shared library (.so). make is a program that can automate builds given instructions, but Numeric doesn't use it, nor do most other Python packages. > Most other extensions (including math, os, struct, cPickle) from > Python 2.2 works when I install python on QNX. No, I was wondering if you could build any other third-party extension modules. Did you install Python from source? When building extension modules, Python uses whatever linker was used to build itself. -- 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 mailmaverick666 at gmail.com Fri Apr 20 02:26:57 2007 From: mailmaverick666 at gmail.com (rishi pathak) Date: Fri, 20 Apr 2007 11:56:57 +0530 Subject: Can I place a question on the mailing list In-Reply-To: <337251.8564.qm@web51711.mail.re2.yahoo.com> References: <337251.8564.qm@web51711.mail.re2.yahoo.com> Message-ID: <180b672e0704192326u7bb6524fhb21f6db8a2f88c9f@mail.gmail.com> Any one can post if it's regarding python On 4/20/07, chachou martel juvet wrote: > > Good Morning Dear Sir , > I will like you allowing me to place question on > the web. > > Kind Regards: > Martel. > > ------------------------------ > *All new Yahoo! Mail - * > ------------------------------ > Get a sneak peak at messages with a handy reading pane. > > > -- > 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 Mon Apr 30 20:22:40 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 30 Apr 2007 21:22:40 -0300 Subject: socket module - recv() method References: <1177942942.996962.122680@n76g2000hsh.googlegroups.com> Message-ID: En Mon, 30 Apr 2007 11:22:23 -0300, escribi?: > All of the client apps on which this technique is employed are very > predictable in the sense that the client apps always know in advance > the value of endOfMessageText. > > Questions: > 1) is it theoretically possible that a client app will want to send a > request and receive a response where the response message does not > have something that unambigusously marks its end? Theoretically, yes, but such protocol would be hard to implement and unreliable. The message should contain enough information to determine when it's complete: apart from your example of known terminator, you could have a header stating the message size; or the number of elements of known size; or the number of elements, each one stating its size; or several elements, each one telling its size, ending with an empty element; or all messages being of fixed size; or all messages having a "type" field, where the message size is known for each type. All of them have been used and have drawbacks and advantages. The best choice depends on how data is better described, the desired robustness/expansibility/reliability/simplicity, and how much logic can you put on the sender side or the receiver side. If the message itself does *not* allow to determine when it's complete (not a good thing), you have to rely on external signals (connection closing, by example) but that's not very reliable. > 2) if so, are there any best-practices techniques for constructing the > code such that the client app knows that there is nothing else in the > response message? If you are free to design the protocol, choose from the above suggestions or other suitable ways. A fixed terminator is easy to implement (but you have to guarantee that it cannot happen inside the message, or replace it someway) -- Gabriel Genellina From marcpp at gmail.com Thu Apr 12 09:56:32 2007 From: marcpp at gmail.com (Marcpp) Date: 12 Apr 2007 06:56:32 -0700 Subject: Any Pythonistas in Mexico? In-Reply-To: References: Message-ID: <1176386191.990363.112350@y80g2000hsf.googlegroups.com> On 12 abr, 09:41, Hugo Gonz?lez Monteverde wrote: > Hola, > > Le? este mail viej?simo en una lista. Yo uso Python y tambi?n quer?a > saber qui?n pythoneaba en M?xico. Todav?a est?s por ah?? > > Saludos, > > Hugo G. Yo vivo en Espa?a. Usas el pyqt? From martin at v.loewis.de Sat Apr 14 13:16:35 2007 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sat, 14 Apr 2007 19:16:35 +0200 Subject: compiling modules with VS 2008 for python 2.4 prepared with Visual Studio 2003 In-Reply-To: References: <1hw2ak4.1cxnvt81nzd971N%aleax@mac.com> <461f1a5a$0$996$9b622d9e@news.freenet.de> Message-ID: <46210c73$0$15280$9b622d9e@news.freenet.de> > complier is just a compiler. perhaps final linking could be somehow > tweaked to include msvcrt71 instad of 80. Not easily. VS 2005 is not just a complier, it is also a rinkel, and ships with improt librareis. The import library for msvcrt.lib it ships with automatically links with msvcr8.dll. You either would have to create a import library for mscvr71.dll by hand, or you have to copy one from VS 2003 (breaking its license). Regards, Martin P.S. Why does the subject say "VS 2008", anyway? That product has not been released yet, and Microsoft is still hoping that it will be called VS 2007. From mansonmuni at alexandria.cc Thu Apr 26 10:36:37 2007 From: mansonmuni at alexandria.cc (Glen) Date: Thu, 26 Apr 2007 14:36:37 GMT Subject: lowercase class names, eg., qtgui ? (PyQt4) References: <6smdnRrvLvilza3bRVnzvQA@telenor.com> Message-ID: On Thu, 26 Apr 2007 09:09:44 +0200, Tina I wrote: Hi Tina, Thanks for the reply. Of course, by now I've run pyuic4 again on my .ui file and things are back to normal. Believe it or not, my example was a copy/paste directly from my .py file. Some strange anomoly, I guess. Everything's ok now. Maybe vim was just displaying the text wrong for a minute. Had me going though. Thanks again. Glen > Are you sure? That's strange. I have never seen that. Here is a snippet > of one of my typical .py files generated by 'pyuic4': > > self.gridlayout = QtGui.QGridLayout(self.centralwidget) > self.gridlayout.setMargin(9) > self.gridlayout.setSpacing(6) > self.gridlayout.setObjectName("gridlayout") > > self.hboxlayout = QtGui.QHBoxLayout() self.hboxlayout.setMargin(0) > self.hboxlayout.setSpacing(6) > self.hboxlayout.setObjectName("hboxlayout") > > self.hboxlayout1 = QtGui.QHBoxLayout() self.hboxlayout1.setMargin(0) > self.hboxlayout1.setSpacing(6) > self.hboxlayout1.setObjectName("hboxlayout1") > > Upper case all the way... > > Tina From kyosohma at gmail.com Tue Apr 17 14:07:38 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: 17 Apr 2007 11:07:38 -0700 Subject: Binary file output using python In-Reply-To: References: Message-ID: <1176833258.851804.63740@p77g2000hsh.googlegroups.com> On Apr 17, 12:41 pm, Chi Yin Cheung wrote: > Hi, > Is there a way in python to output binary files? I need to python to > write out a stream of 5 million floating point numbers, separated by > some separator, but it seems that all python supports natively is string > information output, which is extremely space inefficient. > > I'd tried using the pickle module, but it crashed whenever I tried using > it due to the large amount of data involved. > > Thanks for your help! You can create a binary file by doing something like this: f = open(r'filename, 'b') f.write('1,2,3,4,5,6') f.close() See also: http://www.devshed.com/c/a/Python/File-Management-in-Python/ Have fun! Mike From wahab-mail at gmx.de Tue Apr 17 06:52:34 2007 From: wahab-mail at gmx.de (Mirco Wahab) Date: Tue, 17 Apr 2007 12:52:34 +0200 Subject: is laziness a programer's virtue? In-Reply-To: References: <1176757271.282365.319740@n76g2000hsh.googlegroups.com> <1176797558.403629.53140@b75g2000hsg.googlegroups.com> Message-ID: Markus E Leypold wrote: > Trying to correct Xah's behaviour is probably impossible. People who > publish pictures of themselves as he does on the WWW probably don't > have any sense of embarrasment left ... you think of stuff like this www DOT m-e-leypold DOT de SLASH leypold-small.jpg ;-) > -- and I consider that a necessary > part in the feedback loop which makes people change: "Look what you > did! Do you really want to look like a dolt in public?" "Umpf. No. God > that was embarrasing" such a situation again>. The reason why I answered your posting at all (besides seeing your x-post going into 5 ng's) is your mentioning of 'God'. According to christian tradition (which is somehow on topic in a Perl group) it is exactly the case of Jesus (imho), who was (in his context) the "/Do you really want to look like a dolt in public/" man par excellance. Socrates also comes into the mind ;-) AFAIK - both were symptoms of the decline of their societies at the time ... Regards & sorry for scnr'ing Mirco remember - f'up to: comp.lang.perl.misc From rw at smsnet.pl Thu Apr 12 04:06:52 2007 From: rw at smsnet.pl (Rob Wolfe) Date: 12 Apr 2007 01:06:52 -0700 Subject: sqlite3 question In-Reply-To: References: Message-ID: <1176365212.588475.48440@n59g2000hsh.googlegroups.com> Jorgen Bodde wrote: > All I can think of is a 'crappy' construction where I use the iterator > to see if there was something in there, but surely, there must be a > better way to know? > > >>> r = c.execute('select * from song where id = 2') > >>> notfound = True > >>> for s in r: > ... notfound = False > ... print s > >>> if notfound: > ... print 'No rows' > > I am pretty new with Python, maybe there are some properties of an > iterator / sqlite3 I am not aware of that can tell me how many rows > are there? What about this: if not c.fetchone(): print "No rows" or print "rowcount=", len(cur.fetchall()) -- HTH, Rob From mccredie at gmail.com Mon Apr 2 13:42:32 2007 From: mccredie at gmail.com (Matimus) Date: 2 Apr 2007 10:42:32 -0700 Subject: Parallel ping problems python puzzler In-Reply-To: <1175509753.092714.281990@n76g2000hsh.googlegroups.com> References: <1175509753.092714.281990@n76g2000hsh.googlegroups.com> Message-ID: <1175535751.973390.159850@l77g2000hsb.googlegroups.com> I wouldn't use threads for system calls. Checkout the subprocess module instead. You can run multiple pipes at the same time (subprocess.Popen). The python documentation for subprocess is pretty good. There are a few examples. Actually, you don't even _need_ the subprocess module, you can use os.popen for similar functionality. From cjw at sympatico.ca Fri Apr 20 14:39:11 2007 From: cjw at sympatico.ca (Colin J. Williams) Date: Fri, 20 Apr 2007 14:39:11 -0400 Subject: matplotlib basic question In-Reply-To: <1177092157.763869.77600@o5g2000hsb.googlegroups.com> References: <1177016327.543985.34500@o5g2000hsb.googlegroups.com> <1177092157.763869.77600@o5g2000hsb.googlegroups.com> Message-ID: orangeDinosaur wrote: > OK, I'll go with the enthought installation. This seems to be the > path of least resistance. For those of you who have been in my > position, is there a reason NOT to go with the enthought installation > and do things piecemeal instead? > > thanks, > trevis > > On Apr 20, 11:36 am, Pete Forman wrote: >> orangeDinosaur writes: >> >> > [...] But now, the figure window is completely unresponsive -- I >> > can't even close it without getting the "your program is not >> > repsonding" business. What am I missing? This behavior so far >> > seems pretty unintuitive. >> >> The best way out of this is to use IPython. It also needs a backend >> which remains responsive, WxAgg works but Tk did not last time I >> tried. IPython 0.8.1 is a release candidate which fixes some Windows >> issues in 0.8.0. If you want a stable package that has all the parts >> present out of the box then look at Enthought. >> -- >> Pete Forman -./\.- Disclaimer: This post is originated >> WesternGeco -./\.- by myself and does not represent >> pete.for... at westerngeco.com -./\.- the opinion of Schlumberger orhttp://petef.port5.com -./\.- WesternGeco. > > It's rather heavy and may include stuff you don't need. I'm not sure that scipy has been updated to Python 2.5 Colin W. From aleax at mac.com Tue Apr 17 00:54:37 2007 From: aleax at mac.com (Alex Martelli) Date: Mon, 16 Apr 2007 21:54:37 -0700 Subject: Python Feature Request: Add the "using" keyword which works like "with" in Visual Basic References: <1176547372.584539.89170@q75g2000hsh.googlegroups.com> <1176739901.946900.132680@p77g2000hsh.googlegroups.com> Message-ID: <1hwona7.1chfz951v60n9iN%aleax@mac.com> Paul Boddie wrote: > > Now I hear that the word "with" is being discussed for a different > > purpose in Py 3 as a result of a PEP and I don't want to conflict with > > that. > > The "with" keyword appears in 2.5 onwards. ...but needs a "from __future__ import with_statement" in 2.5 itself. Alex From elventear at gmail.com Wed Apr 18 13:28:19 2007 From: elventear at gmail.com (elventear) Date: 18 Apr 2007 10:28:19 -0700 Subject: Martel Package from Biopython Message-ID: <1176917299.700081.138420@n76g2000hsh.googlegroups.com> Hello, I know this is not the best place to ask this but I haven't had luck in the Biopython forums with my questions, so I'll just try here. I want to use the Martel package to do some parsing. I've found it to be very powerful and convenient. Yet the documentation avaialble is less than complete. I have a few questions on how to use it, if you know the answers to my questions: - How does Bio.Std.record affect the parsing of a Martel expression. - How does Bio.RecordReader work? How does it interact with Martel.HeaderFooter? - Many of the matching objects (ie. Martel.Digits) have an attrs argument. How does it work? Thanks! From gizmo1 at gmail.com Fri Apr 6 12:40:20 2007 From: gizmo1 at gmail.com (Gizmo) Date: Fri, 6 Apr 2007 09:40:20 -0700 Subject: Basic Serialization - a design decision question Message-ID: <5d2e4d280704060940s3fa1defdl874c8c4e7fa92266@mail.gmail.com> Hello I am a relative newcomer to Python, and I am studying it to understand its design. It intrigues me. I recently studied Serialization of classes via the pickle/cPickle library, and I have a question. Why is Serialization handled by a separate library (ie, pickle). Is it possible, by design, to have serialization "internally" implemented via an implicit ___serialize___ method? Ofcourse, you have to make this method not overrideable (sp?). For example, the __repr__ method gives us the string representation of a class... similarly, the __serialize__ method would give us the "serial norm" representation of the class. This would allow me to do something like this, conn.send(serial(myClass)); // or something like that? Thoughts? -------------- next part -------------- An HTML attachment was scrubbed... URL: From billhabr at sbcglobal.net Wed Apr 25 20:33:19 2007 From: billhabr at sbcglobal.net (Bill Habr) Date: Thu, 26 Apr 2007 00:33:19 GMT Subject: Video: Professor of Physics Phd at Cal Tech says: 911 Inside Job References: <1177467203.719625.93920@u32g2000prd.googlegroups.com> Message-ID: wrote in message news:1177467203.719625.93920 at u32g2000prd.googlegroups.com... > Cal Tech is the ELITE of ELITE in physics. > > If Feynman were alive, he would point his finger straight at the 911 > criminal operators, the yank bastards themselves ....... > > http://www.911blogger.com/node/8101 > > No self-respecting scientist should keep his mouth shut. Its a > fundamental challenge to the method of science, a detective work most > demanding of INTELLECTUAL HONESTY. > Isn't this the guy who has more conspiracy theories than Carter has pills? Whitewater, Vince Foster, moon landing hoax one week - we found a UFO on the moon the next, Oklahoma City bombing, a new conspiracy every day ad nauseum? From michael at jedimindworks.com Tue Apr 24 13:37:19 2007 From: michael at jedimindworks.com (Michael Bentley) Date: Tue, 24 Apr 2007 12:37:19 -0500 Subject: If Dict Contains a particular key In-Reply-To: <000001c78695$ed321540$c7963fc0$@rawlins@thinkbluemedia.co.uk> References: <000001c78695$ed321540$c7963fc0$@rawlins@thinkbluemedia.co.uk> Message-ID: On Apr 24, 2007, at 12:28 PM, Robert Rawlins - Think Blue wrote: > Hello Guys, > > > > I?m Looking to build a quick if/else statement that checks a > dictionary for a key like follows. > > > > If myDict contains ThisKey: > > Do this... > > Else > > Do that... > > > > Thats the best way of doing this? if ThisKey in myDict: pass # do this else: pass # do that -------------- next part -------------- An HTML attachment was scrubbed... URL: From rNOSPAMon at flownet.com Sun Apr 22 18:46:32 2007 From: rNOSPAMon at flownet.com (Ron Garret) Date: Sun, 22 Apr 2007 15:46:32 -0700 Subject: Bug in select References: <1aGdndBf1ON7UrbbnZ2dnUVZ_hjinZ2d@speakeasy.net> Message-ID: In article , Erik Max Francis wrote: > Ron Garret wrote: > > > Geez you people are picky. Since I ran this several times I ran into > > the TIM_WAIT problem. Here's the actual transcript: > > It's not about being picky, it's about making it clear what your problem > is. You're now describing an entirely different problem, Nope, it's been the same problem all along. If you don't think so then you have misunderstood something. rg From M.Waack at gmx.de Wed Apr 4 08:25:06 2007 From: M.Waack at gmx.de (Mathias Waack) Date: Wed, 04 Apr 2007 12:25:06 GMT Subject: optparse option prefix References: <57he53F2cm33sU1@mid.uni-berlin.de> Message-ID: Diez B. Roggisch wrote: >> (3) Create a filter module that reads sys.argv, replaces leading "+" >> signs with "-" signs, and then stuffs it back into sys.argv before >> optparse gets to see it. > > That's not even necessary, the optparser will work on a passed argument > list. No need to alter sys.argv. Sounds nice, I'll do so. Thanks! Mathias From claird at lairds.us Mon Apr 2 15:28:45 2007 From: claird at lairds.us (Cameron Laird) Date: Mon, 2 Apr 2007 19:28:45 +0000 Subject: Extract information from HTML table References: <1175429635.278697.92690@b75g2000hsg.googlegroups.com> <1175439364.515873.142340@p15g2000hsd.googlegroups.com> <1175503135.234560.51730@n59g2000hsh.googlegroups.com> Message-ID: In article <1175503135.234560.51730 at n59g2000hsh.googlegroups.com>, anjesh wrote: >On Apr 2, 12:54 am, "Dotan Cohen" wrote: >> On 1 Apr 2007 07:56:04 -0700, Ulysse wrote: >> >> > I have seen the Beautiful Soup online help and tried to apply that to >> > my problem. But it seems to be a little bit hard. I will rather try to >> > do this with regular expressions... >> >> If you think that Beautiful Soup is difficult than wait till you try >> to do this with regexes. Granted you know the exact format of the HTML >> you are scraping will help, if you ever need to parse HTML from an >> unknown source than Beautiful Soup is the only way to go. Not all HTML >> authors close their td and tr tags, and sometimes there are attributes >> to those tags. If you plan on ever reusing the code or the format of >> the HTML may change, then you are best off sticking with Beautiful >> Soup. >> >> Dotan Cohen >> >> http://lyricslist.com/http://what-is-what.com/ > > >Have you tried HTMLParser. It can do the task you want to perform >http://docs.python.org/lib/module-HTMLParser.html > >-anjesh > Yes, except that these last two follow-ups UNDERstate the difficulty--in fact, the impossibility--of achieving adequate results on this problem with regular expressions. We'll help with the documentation for HTMLParser and BeautifulSoup. REs are an invitation to madness. might amuse those who want to think more about REs. From hlubenow2 at gmx.net Mon Apr 2 13:45:23 2007 From: hlubenow2 at gmx.net (hlubenow) Date: Mon, 02 Apr 2007 19:45:23 +0200 Subject: Pygame Q (linux) beginner References: <460F28F2.D91DB67A@braindead.com> <46105382.58F3B2DE@braindead.com> Message-ID: enquiring mind wrote: > Thank you very much. A buddy installed SUSE 10 in Dec. for me so I > shall ask him to look for rpm which I understand from your post includes > pygame. You have no idea how much I appreciate your information. My pleasure. By the way: It would be quite easy to install it yourself, too. Here's how: If you use KDE, click on the start-menu-button and go to System/ControlCenter(YaST) there. You're asked for your root-password. Enter it and YaST2 appears (it is SuSE's graphical installation tool). Click on Software/Software installation. After a while a search-field appears. Enter "python-pygame" there and click on "search". It should be shown in the right window. Click on the rectangle left of it and press "keep changes" (or "ok" or so) in the right corner at the bottom. You should be asked to insert some CD/DVD then. Do it, wait a while and pygame should have been installed. It is really not much more difficult than on Windows. See you H. From dandolls at yahoo.co.in Tue Apr 10 15:15:51 2007 From: dandolls at yahoo.co.in (Amit K Saha) Date: Wed, 11 Apr 2007 00:45:51 +0530 Subject: Python Speech tools Message-ID: <1176232552.4941.7.camel@ubuntu-desktop> Hi list I intend to design a Speech Recognition system.Can I have some pointers to the available Python speech tools? Till date I am aware of only Python bindings for a speech tool called Snack (http://www.speech.kth.se/snack/) Any help will be appreciated. -- Amit K Saha Send instant messages to your online friends http://in.messenger.yahoo.com From adamgarstang at googlemail.com Sat Apr 7 11:41:26 2007 From: adamgarstang at googlemail.com (Adam) Date: 7 Apr 2007 08:41:26 -0700 Subject: How to tell when a file is opened Message-ID: <1175960486.759715.317140@y80g2000hsf.googlegroups.com> Hello, I want to know if it possible to tell when a file is opened. However I don't want it to be the last access time. I want to know how many times a file opened so I can generate statistics of file usage. I will be wanting to watch all files on a server so this will be on quite a large scale. So checking a directory on a loop for accesses won't work. Maybe some way to monitor the Open Files section of Computer Management? I check through Tim Golden's site but nothing jumped out at me. Any pointers would be great. Thanks, Adam From steve at REMOVE.THIS.cybersource.com.au Sat Apr 28 04:55:05 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Sat, 28 Apr 2007 18:55:05 +1000 Subject: My newbie annoyances so far References: <1177688082.758043.133920@r30g2000prh.googlegroups.com> <59f5btF2k70baU2@mid.individual.net> Message-ID: On Sat, 28 Apr 2007 06:57:54 +0000, Dennis Lee Bieber wrote: > On Fri, 27 Apr 2007 22:39:25 +0200, Bjoern Schliessmann > declaimed the following > in comp.lang.python: > >> Dennis Lee Bieber wrote: >> >> > And I'll probably ignore those expressions whenever I do get >> > around to 2.5+... That syntax, in my mind, just... stinks... >> > >> > HP RPL made more sense: b if c [else d] end >> >> Please explain. >> >> HP RPL: b if c [else d] end >> Python: b if c else d >> >> What's the "more sense" here? >> > You didn't take account of what b, c, and d were... > > RPL: if else end > Python: if else > > (RPL is a somewhat common reference to the stack based language of the > later calculators -- HP48, for instance) I believe RPL is the official name of the language used for the HP-28 and -48 series calculators, although it doesn't appear to be in their reference manuals. The syntax as given above is actually incorrect. That appears more like Forth -- an easy mistake to make. In RPL, it is: IF THEN END IF THEN ELSE END Note that despite being a stack-based language, the Reverse Polish notation of RPL is loosened slightly for conditional and looping commands. The syntax above is a little misleading... in fact, IF doesn't actually do anything (but is required!), as it is the THEN that pops a flag off the stack. So long as there is a value on the stack for the THEN to pop off, it doesn't matter if it gets there before or after the IF. Hence many people preferred to write: IF THEN ELSE END instead. Note also that each <*-clause> can be a block of code, and is only executed if needed. Either true-clause or false-clause can be empty. -- Steven. From cam.ac.uk at mh391.invalid Sun Apr 15 19:01:37 2007 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Mon, 16 Apr 2007 00:01:37 +0100 Subject: optparse -- anyway to find if the user entered an option? In-Reply-To: References: <1176594561.971801.211710@y80g2000hsf.googlegroups.com> Message-ID: James Stroud wrote: > Karthik Gurusamy wrote: >> Hi, >> >> I see that I can provide a default value for an option. But I couldn't >> find out any way if the user really entered the option or the option >> took that value because of default. A simple check for value with >> default may not always work as the user might have manually >> entered the same default value. >> >> Let's assume I want to take in the ip-address using -i . >> If user didn't give it explicitly, I am going to use socket interface >> to figure out this host's IP address. >> >> ip_addr_default = '100.100.100.100' >> >> parser.add_option("-i", "--ip-address", dest="ip", >> default=ip_addr_default, >> metavar="IP-ADDRESS", help="IP address. default:" + >> ip_addr_default + "e.g. --i=1.1.1.1" >> ) >> >> (options, args) = parser.parse_args() >> >> Now if options.ip == ip_addr_default, I still can't be 100% sure that >> the user did not type -i 100.100.100.100. >> Any way to figure out from options that the user typed it or not? >> >> (The reason I want to know this is if user did not mention -i, I can >> compute IP later >> using socket module) >> >> I could think of a hack of using None as default and since no user can >> ever >> enter a None value, I can be sure that the user didn't provide -i. >> I'm wondering if there is a cleaner approach -- something like >> parser.opt_seen("-i") >> >> Thanks, >> Karthik >> > > Using None wouldn't be a hack, it would rather be a common and > straightforward python idiom. I agree. Also, remember that in optparse the default default (if you will) is None. -- Michael Hoffman From steve at REMOVE.THIS.cybersource.com.au Sat Apr 28 09:24:43 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Sat, 28 Apr 2007 23:24:43 +1000 Subject: Numbers and truth values References: Message-ID: On Sat, 28 Apr 2007 14:33:23 +0200, Szabolcs wrote: > Newbie question: > > Why is 1 == True and 2 == True (even though 1 != 2), > but 'x' != True (even though if 'x': works)? Everything in Python has a truth-value. So you can always do this: if some_object: print "if clause is true" else: print "else clause" no matter what some_object is. The constants True and False are a pair of values of a special type bool. The bool type is in fact a sub-class of int: >>> issubclass(bool, int) True >>> 7 + False 7 >>> 7 + True 8 Can you guess what values True and False are "under the hood"? >>> 1 == True True >>> 0 == False True >>> 2 == True False >>> if 2: ... print "2 is considered true" ... 2 is considered true If you are getting different results, the chances are that you have accidentally reassigned that names True or False: >>> True = 2 # DON'T DO THIS!!! >>> 2 == True True -- Steven. From pydecker at gmail.com Wed Apr 4 21:43:20 2007 From: pydecker at gmail.com (Peter Decker) Date: Wed, 4 Apr 2007 21:43:20 -0400 Subject: Resume of Steve Snow : Database SQL Applications Programmer In-Reply-To: References: Message-ID: On 4/4/07, stevesnow wrote: > ---------------------------------------------- > > Please forward this work experience & skills summary > to your Database & software development, MIS/IT/Software Department for review. > > ---------------------------------------------- > > Here is my full resume in Microsoft Word format. You forgot to include your spamming experience. -- # p.d. From isaac.rodriguez at comcast.net Wed Apr 18 09:17:25 2007 From: isaac.rodriguez at comcast.net (Isaac Rodriguez) Date: 18 Apr 2007 06:17:25 -0700 Subject: Calling private base methods In-Reply-To: <1hwmmq4.n76p2d1k88mz5N%aleax@mac.com> References: <1176374675.347453.89340@n76g2000hsh.googlegroups.com> <1176404325.211501.26610@w1g2000hsg.googlegroups.com> <1176435087.708516.66470@o5g2000hsb.googlegroups.com> <1176650850.211487.294690@y80g2000hsf.googlegroups.com> <1hwmmq4.n76p2d1k88mz5N%aleax@mac.com> Message-ID: <1176902245.845880.308870@b75g2000hsg.googlegroups.com> > > C++'s and Java's approaches are vitiated by an unspoken assumption that > the library's designer is some kind of demigod, while the writer of code > that uses the library is presumably still struggling with the challenge > of opposable thumbs. That might be your point of view. To me, the library designer is the one that has done the homework and should know better how to simplify things for others not a God. No one uses a high level library if implementing the low-level your self is easier. Libraries provide functionality that allow the application programmer to concentrate in what he is being paid for, making the application. An application programmer will have to define what the correct interface for the application is (for example, what UI to provide). There will be users that will say, I wish this application had a way of doing this, but unless they were technically savy and wanted to spend the necessary time to understand how the application works, they would not write the feature themselves; they will request that feature to the programmer. > In real life, the skills of the two people in > question are likely to be much closer, and since designing libraries for > use in all kinds of applications is a really hard task, it's likelier > than the library designer will make an error in designing his or her > library, rather than the application programmer in using that library. Those are called defects or "bugs". When I find a bug in a library or an application, I submit a bug report. I might have to work around it for a little bit, but I don't just work around it and call it goods. Library designers are normal programmers that work under a set of requirements like any other programmer (application programmers included), but when I find a bug in an application, I report it and try to work around it until it gets fixed; I don't hack the application or re-write my own just because a found a bug. > > Purely-advisory encapsulation approaches, like Python's, even the odds. > Actually, I'd argue that even double-leading-underscores are overkill > more often than not (and single-leading-underscores the compromise that > is generally prefereable). You see it as an intelligence challenge, where I see it as making things easier for everybody. Thanks, - Isaac. From bbxx789_05ss at yahoo.com Thu Apr 5 05:40:13 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: 5 Apr 2007 02:40:13 -0700 Subject: Can we make a local variable in a function as global variable??? In-Reply-To: <1175764774.260576.286420@y66g2000hsf.googlegroups.com> References: <1175764774.260576.286420@y66g2000hsf.googlegroups.com> Message-ID: <1175766013.789804.217740@b75g2000hsg.googlegroups.com> On Apr 5, 3:19 am, "sairam" wrote: > I have some local variables defined in one method and Can I make those > variables as global variables? If so , can any one explain me how can > I do that > > Thanks, > Sairam ----------- num = None def f1(): global num num = 30 def f2(): print num f1() f2() ----------- You can read from a global variable, but to assign to one, you have to declare its name in a global statement on the first line of the function. A better way: ------------ def f1(): num = 30 return num def f2(x): print x result = f1() f2(result) ----------- From bruno.42.desthuilliers at wtf.websiteburo.oops.com Fri Apr 27 07:19:04 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Fri, 27 Apr 2007 13:19:04 +0200 Subject: what python technology for my app? In-Reply-To: References: Message-ID: <4631dc06$0$15457$426a74cc@news.free.fr> Chris a ?crit : > I have an database containing lots of numerical data. I want to write a > browser based interface that will allow selection of various key > parameters and yield tables, plots and/or printouts of the data > according to the selections. Ultimately I want this to run on an > intranet so that others can get access via their browsers. > > The application is for in-house use only and not likely to have more > than a few users at any one time. I've managed to hack out enough > understanding of sql and sqlAlchemy over the last couple of days to > create and access an sqlite3 based database for my data. This seems to > suit my purposes for now. Now for a front end and some simple > distribution over a network. > > I have written some small Wxpython & matplotlib apps for data analysis > and display but I'm not sure how these would work in a browser based > world, or even if they are appropriate. wxPython being a GUI toolkit, it's of course not really appropriate for a web-based solution (and yes, this is an understatement). I don't have any experience with matplotlib, but according to the project's FAQ, this shouldn't be a problem: http://matplotlib.sourceforge.net/faq.html#BATCHMODE > > Any advice on what technologies I should be looking at for this? Python > based naturally, and hopefully simple and lightweight. I'm not a > programmer by trade and that's not what I really get paid for but I've > learned to love python and its myriad of modules for all the data > analysis work I need to do. If I can throw something moderately > functional together in a week or two (along with all the learning that > entails) If you don't have any experience with web programming, it might take a bit more time. > I'll be happy. Pylons (http://pylonshq.com) and turbogears are two great web frameworks. Both support SQLAlchemy. My own favourite is Pylons, but you should try both and choose the one that better fits your brain. > btw - Platform needs to be windows because that's what on my desk. Python is mostly platform independant. HTH From irmen.NOSPAM at xs4all.nl Sat Apr 28 09:05:17 2007 From: irmen.NOSPAM at xs4all.nl (Irmen de Jong) Date: Sat, 28 Apr 2007 15:05:17 +0200 Subject: Numbers and truth values In-Reply-To: References: Message-ID: <4633468e$0$339$e4fe514c@news.xs4all.nl> Szabolcs wrote: > Newbie question: > > Why is 1 == True and 2 == True (even though 1 != 2), > but 'x' != True (even though if 'x': works)? Please check before you post: [E:\Projects]python Python 2.5.1 (r251:54863, Apr 18 2007, 08:51:08) [MSC v.1310 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> 2==True False >>> Anyway, it helps to think about value domains (in your examples, numbers and strings) as having a single "null" value, and non-null values. The null value is considered False. The non-null values are considered True. The null value for numbers is 0 obviously, and for strings it is '' (the empty string). Non-zero numbers and non-empty strings are considered "True" when used in a boolean expression. --Irmen From szhorvat at gmail.com Mon Apr 23 05:24:28 2007 From: szhorvat at gmail.com (Szabolcs) Date: 23 Apr 2007 02:24:28 -0700 Subject: Two syntax questions (newbie) In-Reply-To: References: <1177316126.432039.232300@o5g2000hsb.googlegroups.com> Message-ID: <1177320268.228495.186590@y5g2000hsa.googlegroups.com> Thanks for the reply! On Apr 23, 10:55 am, "Gabriel Genellina" wrote: > > or define a > > function composition operator for functions that take a single > > argument? > > You could use this: > > def chain(*args): > """Compose functions (assoc right). > last argument (args[-1]): argument to last function > args[0] .. args[-2]: functions taking a single argument > Returns args[0](args[1](...(args[-2]))(args[-1]) > """ > args = list(args) > data = args.pop(-1) > while args: > fn = args.pop(-1) > data = fn(data) > return data > > import random > items = [random.randrange(100) for _ in range(20)] > print chain(list, reversed, sorted, items) This is already better. Is it possible to define function composition as an operator and have something like (list at reversed@sorted)(items) or (list*reversed*sorted)(items) ? > I almost never use backslashes for line continuation. If you have an open > (,[,{ continuation is implicit. If not, usually adding a heading ( is > enough. > That is, instead of > > x = a + b + \ > c - d > > I'd use: > > x = (a + b + > c - d) Thanks! This is very useful. Szabolcs From jstroud at mbi.ucla.edu Fri Apr 27 21:09:44 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Fri, 27 Apr 2007 18:09:44 -0700 Subject: Memory addressing In-Reply-To: <1177703803.179501.95300@n35g2000prd.googlegroups.com> References: <1177702902.156596.52510@n35g2000prd.googlegroups.com> <1177703803.179501.95300@n35g2000prd.googlegroups.com> Message-ID: Simon Berube wrote: > On Apr 27, 3:52 pm, Carsten Haese wrote: > >>On Fri, 2007-04-27 at 12:41 -0700, Simon Berube wrote: >> >>>Hi, >> >>> I have a rather simple question for which I couldn't find an >>>answer. I noticed how a significant number of objects in Python return >>>a __repr__() string along the lines of : >> >>>< Object at 0xXXXXXX> >> >>> I find this notation quite convenient to avoid out of control >>>strings when using large arrays but I was wondering how you can use >>>the memory address for assigning a new object. >> >>You can't. >> >> >>>In c, one could simple have a pointer to that memory address and >>>voila, you have a new object you can analyze however it seems like >>>python is allergic to direct memory manipulation. >> >>For good reason. Python is not C. >> >> >>>Hence, I was wondering what is the correct way to go about obtaining >>>objects returned in such a fashion? What am I going wrong or what am I >>>not getting? >> >>What is the actual problem you're trying to solve? >> >>-Carsten > > > First of all, thanks for your reply. I am not trying to solve a > problem in particular, I know that my way of thinking of very wrong in > a python sense and I am simply trying to find the equivalent accepted > practice. > > When you call certain objects __repr__() strings in python you often > get the : happen. I am simply trying to > understand how that information can be used to recreate a certain > object that failed as per the given purpose of the __repr__() > functions. > > In short, how do I used strings to recreate > a an object. > > I hope this is clearer. > > I typed this before I realized it was essentially what everyone else has said. I'm posting it to make myself feel better than if I were to simply delete it. If you can call __repr__() on an object, then you already have a reference to it. If you have a reference to an object, then, in principle, you can create a copy of that object from the reference, rendering __repr__() unnecessary. It makes no senese to pass around a __repr__() of an object and attempt to create it from the __repr__(). This is because, in actuality, you would be passing around a reference to the returned value from __repr__() and so you might as well be passing a reference to the actual object. Obviously, you can not simply store the __repr__() output and hope to re-create the object later, say between invocations of the interpreter. You would either need the contents of the object stored or you would need to know those contents via a reference (in the same invocation). In short, you propose to do accounting that you should otherwise allow the interpreter to do for you. James From nospam at nospam.com Sun Apr 22 17:28:23 2007 From: nospam at nospam.com (Gilles Ganault) Date: Sun, 22 Apr 2007 23:28:23 +0200 Subject: [re.finditer] Getting all occurences in one go? Message-ID: Hello I'd like to make sure there isn't an easier way to extract all the occurences found with re.finditer: ======================= req = urllib2.Request(url, None, headers) response = urllib2.urlopen(req).read() matches = re.compile("(\d+).html").finditer(response) # ----------- BEGIN for match in matches: if mytable[item]=="": mytable[item]= match.group(1) else: mytable[item]= mytable[item] + "," + match.group(1) # ----------- END ======================= Can the lines between BEGIN/END be simplified so I can copy all the items into the mytable[] dictionary in one go, instead of getting each one in a row, and append them with a comma, eg. # I want this : mytable[123] = 6548,8457,etc." # DOESN' T WORK # mytable[item] = matches.group(0) mytable[item] = matches.getall() Thank you. From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Mon Apr 9 21:39:37 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Tue, 10 Apr 2007 03:39:37 +0200 Subject: ulimit on open sockets ? References: Message-ID: <58086qF2dlcviU1@mid.individual.net> Maxim Veksler wrote: > I've written this code, the general idea was to listen on all > 65535 port of tcp for connection. Please excuse the question: Why would anyone want to do such a manic thing (instead of, e. g., using raw sockets)? Regards, Bj?rn -- BOFH excuse #326: We need a licensed electrician to replace the light bulbs in the computer room. From gandalf at designaproduct.biz Thu Apr 12 14:41:06 2007 From: gandalf at designaproduct.biz (Laszlo Nagy) Date: Thu, 12 Apr 2007 20:41:06 +0200 Subject: Inconsistent result from urllib.urlopen In-Reply-To: <1176402303.340868.165510@o5g2000hsb.googlegroups.com> References: <1176402303.340868.165510@o5g2000hsb.googlegroups.com> Message-ID: <461E7D42.6030309@designaproduct.biz> > Any ideas why I don't get the same result from the python script as I > do from a web browser? This problem seems to be a recent > development. The scripts I wrote like this worked fine for a while > and then stopped working within the past couple of weeks. > Maybe it has to do something with your user agent string. The server side can decide to return a different content when your user agent is not 'mozilla', 'internet explorer' or 'opera' etc. Do you want to know how to change your user agent string? Google for it.... :-) Laszlo From http Fri Apr 13 22:29:39 2007 From: http (Paul Rubin) Date: 13 Apr 2007 19:29:39 -0700 Subject: tuples, index method, Python's design References: <1175953520.316208.241490@o5g2000hsb.googlegroups.com> <7xzm5igbrb.fsf@ruckus.brouhaha.com> <1176200361.260546.280510@n76g2000hsh.googlegroups.com> <740c3aec0704100824m132c45fbi5c4c3ec0c0fa3a67@mail.gmail.com> Message-ID: <7xbqhradt8.fsf@ruckus.brouhaha.com> Steve Holden writes: > This is just a bald restatement of the same argument you feel makes it > desirable to add an index() method to tuples. If taken to its logical > (and ridiculous) extreme there should only be one sequence type in > Python. That doesn't sound ridiculous given type/class unification. There could be a single sequence class that implements functions like index. Subclasses like strings, tuples, lists, etc. would inherit from it. Some of them might have optimized or customized implementations of those standard operations, others might not. From sberub at gmail.com Fri Apr 27 15:41:42 2007 From: sberub at gmail.com (Simon Berube) Date: 27 Apr 2007 12:41:42 -0700 Subject: Memory addressing Message-ID: <1177702902.156596.52510@n35g2000prd.googlegroups.com> Hi, I have a rather simple question for which I couldn't find an answer. I noticed how a significant number of objects in Python return a __repr__() string along the lines of : < Object at 0xXXXXXX> I find this notation quite convenient to avoid out of control strings when using large arrays but I was wondering how you can use the memory address for assigning a new object. In c, one could simple have a pointer to that memory address and voila, you have a new object you can analyze however it seems like python is allergic to direct memory manipulation. Hence, I was wondering what is the correct way to go about obtaining objects returned in such a fashion? What am I going wrong or what am I not getting? Regards, From steve at holdenweb.com Tue Apr 3 11:54:29 2007 From: steve at holdenweb.com (Steve Holden) Date: Tue, 03 Apr 2007 11:54:29 -0400 Subject: low level networking in python In-Reply-To: <1175615037.137052.70980@w1g2000hsg.googlegroups.com> References: <1175615037.137052.70980@w1g2000hsg.googlegroups.com> Message-ID: kyosohma at gmail.com wrote: > On Apr 3, 10:29 am, "Maxim Veksler" wrote: >> Hello, >> >> I wish to do some low level network stuff using python. >> >> I've googled somewhat and came up with pylibpcap[1], trouble is I >> can't compile it on my Ubuntu 6.10 workstation. Can someone please >> suggest a way to read some bits from random ports? I'm looking to >> write a simple pen-testing tool that would try from one side >> connecting to ports and from the other side sniff traffic to see on >> what ports traffic is coming. >> >> For pylibpcap I'm getting: >> >> """ >> hq4ever at lucky:~/development/personal/pylibpcap/pylibpcap-0.5.1$ python >> setup.py build >> running build >> running build_ext >> building '_pcapmodule' extension >> swig -python -shadow -ISWIG -o pcap.c pcap.i >> pcap.i:72: Warning(124): Specifying the language name in %typemap is >> deprecated - use #ifdef SWIG instead. >> pcap.i:77: Warning(124): Specifying the language name in %typemap is >> deprecated - use #ifdef SWIG instead. >> pcap.i:82: Warning(124): Specifying the language name in %typemap is >> deprecated - use #ifdef SWIG instead. >> /usr/bin/python ./build-tools/docify.py pcap.c >> /usr/bin/python ./build-tools/docify-shadow.py pcap.py >> Traceback (most recent call last): >> File "./build-tools/docify-shadow.py", line 30, in ? >> raise 'source file doesn\'t look like swigged shadow class code' >> source file doesn't look like swigged shadow class code >> error: command '/usr/bin/python' failed with exit status 1 >> """ >> >> [1]http://pylibpcap.sourceforge.net/ >> [2]http://py.vaults.ca/apyllo.py/126307487 >> >> -- >> Cheers, >> Maxim Veksler >> >> "Free as in Freedom" - Do u GNU ? > > I would assume you could use the socket module. This post details > someone else who opened ports with Python: > > http://www.thescripts.com/forum/thread44280.html > > Here's another resource using some python servers: > > http://docs.python.org/lib/socket-example.html > > Finally, a Socket programming howto: > http://www.amk.ca/python/howto/sockets/ > > I'm also told that the Twisted framework is excellent for this sort of > thing. > The problem with dealing with ports is that you'd have to open each port individually. So the OP, I presume, is trying to capture packets generically as they arrive at a particular point int he processing cycle to avoid that necessity. 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 aljosa.mohorovic at gmail.com Mon Apr 16 14:16:46 2007 From: aljosa.mohorovic at gmail.com (Aljosa Mohorovic) Date: 16 Apr 2007 11:16:46 -0700 Subject: looking for library to read ppt files Message-ID: <1176747406.722209.126900@w1g2000hsg.googlegroups.com> i'm looking for a way to read ppt (powerpoint) files using python and to convert slides into jpeg files. any links or tips how to do this? From wswilson at gmail.com Sun Apr 1 21:36:04 2007 From: wswilson at gmail.com (asdf1234234) Date: 1 Apr 2007 18:36:04 -0700 Subject: can a method access/set another's variables? Message-ID: <1175477764.549115.159410@n59g2000hsh.googlegroups.com> My code is: -a.py- import b class A: def __init__(self): pass def my_method(self): var = 1 self.var = 2 b.set_var(self) print var print self.var my_a = A() my_a.my_method() -b.py- def set_var(self): var = 2 self.var = 2 I want both var and self.var to be 2 at the end. Is there anything I can pass to set_var() that will give it access to the variables in my_method() like I can use self for the variables in the class A? Thanks! From larry.bates at websafe.com Mon Apr 16 14:36:27 2007 From: larry.bates at websafe.com (Larry Bates) Date: Mon, 16 Apr 2007 13:36:27 -0500 Subject: moving multiple directories In-Reply-To: <1176740512.975411.158380@p77g2000hsh.googlegroups.com> References: <1176740512.975411.158380@p77g2000hsh.googlegroups.com> Message-ID: <4623C22B.2000304@websafe.com> DataSmash wrote: > Hi, > I need to organize thousands of directories full of files. > I want to move these directories into other subdirectories. > For example, all the directories that start with 01, move to > a directory named "one", all directories that start with 02, move > to a directory name "two", and so on.... > > I can't seem to find any easy way to do this. > Looks like shutil.move only lets you move if the subdirectory DOES > NOT exist, so after the first directory moves, the script blows up on > the second move. > I guess you could use shutil.copy or shutil.copytree but then you have > to > delete as well. Much longer process when you have hundreds of > gigabytes of data. > > Thanks for your help! > R.D. > Use win32.moveFile method instead. This links directly to the Windows MoveFile method that just moves the directory entries around. >From Win32 Documentation: win32api.MoveFile MoveFile(srcName, destName) Renames a file, or a directory (including its children). Parameters srcName : string The name of the source file. destName : string The name of the destination file. Comments This method can not move files across volumes. -Larry From QncyMI at netscape.net Sat Apr 14 17:26:35 2007 From: QncyMI at netscape.net (Major Quaternion Dirt Quantum) Date: 14 Apr 2007 14:26:35 -0700 Subject: KOREAN MOON revolves around BUSH In-Reply-To: <1176575332.342215.235820@y80g2000hsf.googlegroups.com> References: <1176575332.342215.235820@y80g2000hsf.googlegroups.com> Message-ID: <1176585995.072878.240230@e65g2000hsc.googlegroups.com> you should look at the LaRouche site for old & current exposes; the LaRouciacs have been a frequent target of the Wash.Times, which is distributed for nothing on Capitol Hill (it has always been run at a loss, funded by the Moonie syndicates). > During a time when the activities of the KCIA were the subject of a US > congressional investigation - dubbed Koreagate - Phillips pointed out > that "within Washington councils, Bush was a powerful voice against > any unnecessary crackdown on the US activities of allied intelligence > services." > Late last year, Business Week reported Neil Bush's Ignite! Inc. - an > educational software company featuring what it calls "curriculum on > wheels," or COWs - received a million dollars from "a foundation > linked to the controversial Reverend Sun Myung Moon... for a COWs > research project in Washington-area schools." > > But perhaps the most tangible aspect of the close relationship between > the Bush family and Rev. Moon is the unbending support the Washington > Times has given to George W. Bush since he announced he was running > for the presidency. In recent years, the newspaper's editorial and > opinion pages have consistently supported the president's "war on > terror" and war in Iraq. > > "The Rev. Moon is a monster in the laboratory of conservative > politics; no one wants to think about him, yet in order to ensure his > continued support they must periodically feed his appetite for > tribute," John Gorenfeld, an investigative reporter and a long-time > chronicler of Moon's activities, told reporters. "One of Moon's > paybacks at Times-sponsored events is to have his picture taken and > rub shoulders with the politically powerful and well-connected." > > "Besides the gift of the support of the Washington Times, Bush and his > son have accepted large amounts of money from Moon's church," said > Gorenfeld, the author of a forthcoming book about the Rev. Moon and > U.S. politics. thus: I am still somewhat confuzed, both by the scattershot writing of AP, and the Euclidean proof. anyway, I found this "simpler" one than Euclid's, but I will slightly confound the matter by first showing, Analysis. The proof just given is conceptually even simpler than the original proof due to Euclid, since it does not use Eudoxus's mehtod of "reductio ad absurdum," proof by contradiction. And unlike most other proofs of the theorem, it does not require P.30 of _Elements_ (sometimes called "Euclid's Lemma") that states: if p is a prime and p|ab, then either p|a or p|b. Moreover, our proof is constructive, and it gives integers with an arbitrary number of prime factors. NB: he also mentions Goldbach's proof, using the coprimality of the Fermat numbers, and "Hermite's very simple proof concerning n! + 1!" I'm sure that other folks have not understood Eculid's proof, before this, but AP may be the longest-ever hold-out, or died trying to get into The Book (of world records and/ or Erdos .-) thus: Natsios's rebuff of Rice and Prendergast, was somewhat startling to those present who are involved in African policy. Rice and Prendergast, along with Anthony Lake-former National Security Advisor (1993-97)-were the hard core of the anti-Sudan Africa policy grouping which consistently misled President Clinton, until the very end of his two Administrations. In an Oct. 2 Washington Post guest column, Rice, Lake, and Rep. Donald Payne (D- N.J.) issued a bone-chilling demand for military action against Sudan, in the name of fighting genocide. Titled, "We Saved Europeans. Why Not Africans," the trio referred to the use of force to "save" Kosovo, and called for bombing, blockading Port Sudan, and other actions against Sudan. At immediate issue is the make-up of an international peacekeeping force in Sudan. What is referred to as a "hybrid UN-AU peacekeeping mission" has been proposed by Kofi Annan, after consultations with the UN Security Council and the African Union (AU). This "hybrid" idea is the latest UN proposal to Khartoum, after the vote in August of Security Council Resolution 1706, authorizing a UN peacekeeping force, that is intended to supercede the current African Union Mission in Sudan (AMIS). As of late November, it was unclear what kind of UN deployment would be accepted by the government of Sudan, even if the chain of command is run by African military leaders at the top, since Khartoum in the past has rejected any deployment of troops with Chapter VII mandate. On Nov. 20, Natsios simply stated that Jan. 1 is his deadline for Sudan to agree to a UN plan, or else "Plan B"-which he did not specify-would be the recourse. Whether Natsios's more conciliatory tone represents a real shift in policy, or reflects the military limitations for a robust military deployment into Darfur, is also unclear. However one should not underestimate the desperation of Dick Cheney's controllers to start a new war in response to the monetary-financial meltdown now gathering speed. They may have already anticipated the rejection of the UN-AU hybrid force by the Sudan government, and are preparing for some type of Plan B military action against Sudan using the Darfur crisis, and/or the escalating conflict between Sudan and Chad, as the pretext. Darfur 'Mini-Summit' http://www.larouchepub.com/other/1998/rice_2546.html thus: uh yeah; Borat wants you in Sudan, why, Baby?... Harry Potter wants you in Iran -- yeah, Baby; shag'US with a spoon? --DARFURIA CONSISTS OF ARABs & nonARABs; NEWS-ITEM: we are marching to Darfuria, Darfuria, Darfuria! Harry Potter IIX, ?Ordeal @ Oxford//Sudan ^ Aircraft Carrier! http://larouchepub.com/other/2007/3410caymans_hedges.html ALgoreTHEmovieFORpresident.COM: http://larouchepub.com/eirtoc/site_packages/2007/al_gore.html From nogradi at gmail.com Sun Apr 22 10:28:23 2007 From: nogradi at gmail.com (Daniel Nogradi) Date: Sun, 22 Apr 2007 16:28:23 +0200 Subject: Dictionaries and dot notation In-Reply-To: <462B6227.5070405@web.de> References: <23087554.X5dcTmlj7P@beaureve.gmx.net> <462B6227.5070405@web.de> Message-ID: <5f56302b0704220728t190da75fw104fe811c908a025@mail.gmail.com> > > This may be pretty obvious for most of you: > > > > When I have an object (an instance of a class "Foo") I can access > > attributes via dot notation: > > > > aFoo.bar > > > > however when I have a dictionary > > > > aDict = {"bar":"something"} > > > > I have to write > > > > aDict["bar"] > > > > What if I want to create a datastructure that can be used in dot > > notation without having to create a class, i.e. because those objects > > have no behavior at all? > > > > I know that accessing an instance variable via bracket notation would > > really have to be written as: > > > > aFoo.__dict__['bar'] > > > > but this does not bring me any further, because I would still have to > > plug in that __dict__ thing into my datastructure, which leads us to > > the same question as above. > > > > Can anyone tell me what I am missing here? What's wrong with creating a dummy class? class data: pass mydata = data( ) mydata.foo = 'foo' mydata.bar = 'bar' print mydata.foo print mydata.bar Daniel From python at rcn.com Thu Apr 5 12:17:43 2007 From: python at rcn.com (Raymond Hettinger) Date: 5 Apr 2007 09:17:43 -0700 Subject: Review/commit patch? In-Reply-To: <141cf$46151a53$4275d90a$2820@FUSE.NET> References: <1175787825.722182.93410@n59g2000hsh.googlegroups.com> <141cf$46151a53$4275d90a$2820@FUSE.NET> Message-ID: <1175789863.571800.105030@o5g2000hsb.googlegroups.com> > > [Kevin Walzer] > >> How long does it take for a patch at the Python SF tracker to be > >> reviewed and/or committed? I am unfamiliar with how the process works. > > >> (I originally submitted a bug report, then figured out how to patch the > >> item in question, and subsequently submitted a patch.) > > > Which bug report and patch is yours? > > bug:https://sourceforge.net/tracker/?func=detail&atid=105470&aid=1691411&... > patch:https://sourceforge.net/tracker/?func=detail&atid=305470&aid=1693258&... I've assigned these to Ronald Oussoren who is maintaining the MacOS support for IDLE. The timing of the response pretty much depends on his availability and interest. If we get close to the Py2.5.2 release (the 2.5.1 branch is already frozen) and there has been no action, then re-assign to me and bump-up the priority. Raymond From jmcmonagle at velseis.com.au Tue Apr 3 21:29:57 2007 From: jmcmonagle at velseis.com.au (John McMonagle) Date: Wed, 04 Apr 2007 11:29:57 +1000 Subject: Tkinter, how to get a button's bg color In-Reply-To: <1175648943.553642.201330@y66g2000hsf.googlegroups.com> References: <1175648943.553642.201330@y66g2000hsf.googlegroups.com> Message-ID: <4612FF95.5080508@velseis.com.au> upftftip at gmail.com wrote: > I am new to Tkinter. Following an example, I executed the following: > > window = Tk() > b = Button(window) > b.configure(bg = '#FF00FF') > b.grid(row = 0, column = 0) > > how can I later get the value of this button's background color? > > Thanks. > b.cget('bg') From claird at lairds.us Tue Apr 10 23:50:54 2007 From: claird at lairds.us (Cameron Laird) Date: Wed, 11 Apr 2007 03:50:54 +0000 Subject: How to get IP address of client from CGI module? References: Message-ID: In article , John Nagle wrote: > The documentation for Python's CGI module doesn't seem to say how to get >the IP address of the client. Don't see an obvious way to get that info >from reading the source, either. Ideas? > > John Nagle os.environ['REMOTE_ADDR']? From jorgen.maillist at gmail.com Wed Apr 11 08:21:38 2007 From: jorgen.maillist at gmail.com (Jorgen Bodde) Date: Wed, 11 Apr 2007 14:21:38 +0200 Subject: Why does not my wx.html.HtmlWindow work? In-Reply-To: <20070408041527.M16419@uniqsys.com> References: <1176003505.794328.62170@n76g2000hsh.googlegroups.com> <20070408041527.M16419@uniqsys.com> Message-ID: <11e49df10704110521p14da3bcfx13395749b71dcfc9@mail.gmail.com> Hi, Coming from the wx community, I do know that the wx.HtmlWindow is NOT meant to load full blown web pages with. It has no concept of javascript, CSS, and other complex DOM properties. If you really want to display complex web pages in a window, look at wxMozilla or the wxIE binding. So the reason it freaks out might be related to the fact the page is too complex, or that the simplistic engine cannot cope with html tags out in the wild. Regards, - Jorgen On 4/8/07, Carsten Haese wrote: > On 7 Apr 2007 20:38:25 -0700, liqfemail at gmail.com wrote > > Below are my source code: > > [snip > > html.LoadPage(" > > http://www.pythonthreads.com/articles/python/incorporating-into- > > wxpython-part-1.html") > > [snip] > > Have you tried loading a simpler page, something like http://www.google.com? > > -Carsten > > -- > http://mail.python.org/mailman/listinfo/python-list > From apardon at forel.vub.ac.be Tue Apr 17 02:39:42 2007 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 17 Apr 2007 06:39:42 GMT Subject: Queue enhancement suggestion References: <7x4pngluel.fsf_-_@ruckus.brouhaha.com> <7xabx7wp5k.fsf@ruckus.brouhaha.com> Message-ID: On 2007-04-17, Paul Rubin wrote: > Antoon Pardon writes: >> The problem is this doesn't work well if you have multiple producers. >> One producer can be finished while the other is still putting values >> on the queue. > > Right, you'd wait for all the producers to finish, then finish the queue: > for p in producer_threads: p.join() > q.finish() > >> The solution I have been thinking on is the following. >> >> Add an open and close operation. Only threads that have the queue >> open can access it. The open call should specify whether you >> want to read or write to the queue or both. When all writers >> have closed the queue and the queue is empty a q.get will >> raise an exception. This may be done by putting a sentinel >> on the queue when the last writer closed the queue. > > That's an idea, but why would readers need to open the queue? That has to do with how I implemented it. My implementation puts n sentinels on the queue when there are n readers at the moment the last writer closes the queue. I also treat writers differently from read-writers. Read-writers never block, while writers can be blocked if the queue is "full". -- Antoon Pardon From steve at holdenweb.com Thu Apr 19 13:20:00 2007 From: steve at holdenweb.com (Steve Holden) Date: Thu, 19 Apr 2007 13:20:00 -0400 Subject: Python un-plugging the Interpreter In-Reply-To: References: Message-ID: <4627A4C0.2040905@holdenweb.com> John Nagle wrote: > S.Mohideen wrote: >> Hi All, >> I was thinking about the feasbility of adjusting Python as a >> compiled language. Being said that I feel these are the following >> advantages of doing so -- >> 1) Using the powerful easy-to -use feature of Python programming >> language constructs. >> 2) Making the program to run at par with the compiled version of C/C++ >> program- this is the main benefit which can be derived out of this. >> 3) Highly re-use existing Python code for High performance application. >> 4) Acheive true parallelism and performance by getting rid of the >> middle-man Interpreter and GIL. >> >> I know this must be appearing like a foolish idea. But I would like to >> know the opinion of people who might have thought about it. > > It's a great idea. Look at ShedSkin, PyPy, and Jython, all of > which tried to do it, and none of which really became finished > products. > That's not really fair. ShedSkin and PyPy are still works in progress. Jython was feature-complete, and has merely suffered from delayed maintenance - the current maintainers are getting closer to current language standards as we speak. Even CPython is a worl in progress eben though it's normally treated as the reference implementation. The one compiling implementation you don't mention, of course, is IronPython. This compiles to the .NET/Mono CLR, which in turn can use JIT techniques to generate machine code that the runtime will cache und er the right circumstances. Overall, then, I think the picture's a little rosier than you paint it even though there's always room for improvement. 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 aspineux at gmail.com Fri Apr 6 13:44:15 2007 From: aspineux at gmail.com (aspineux) Date: 6 Apr 2007 10:44:15 -0700 Subject: BaseHTTPRequestHandler reading .html with python code In-Reply-To: <1175853130.368154.103090@y80g2000hsf.googlegroups.com> References: <1175853130.368154.103090@y80g2000hsf.googlegroups.com> Message-ID: <1175881455.909948.126640@w1g2000hsg.googlegroups.com> On 6 avr, 11:52, gcmart... at gmail.com wrote: > H! > > I was wondering how I can do something like this. Use a template engine like : Genshi Django/Jinja Cheetah Kid template For more engine look at http://www.turbogears.org/cogbin/ And maybe what you are looking fore is a complete framework like : turbogears pylon django Hope this help > > file.html > --------- > hello world > > print 'hello world' > #or display str(time.localtime()[7]) > > > webserver.py > --------- > def do_GET(self): > try: > if self.path.endswith(".html"): > f = open(curdir + sep + self.path) #self.path has / > test.html > self.send_response(200) > self.send_header('Content-type', 'text/html') > self.end_headers() > # now display the hello world and run the python code. > self.wfile.write(f.read()) > f.close() > return > > I saw the mod python for apache and some PSP but I really want to know > how they do this. > Is there are special module for doing this ? > > Or is there something like this: > --------------------------- > 1. a running python program > 2. include with write(f.read()) a extra python code inside the already > running python program. > > How they handle this ? From howe.steven at gmail.com Tue Apr 24 14:06:35 2007 From: howe.steven at gmail.com (Steven Howe) Date: Tue, 24 Apr 2007 11:06:35 -0700 Subject: Catching a specific IO error In-Reply-To: References: Message-ID: <462E472B.5070208@gmail.com> Steve Holden wrote: > Thomas Kr?ger wrote: > >> Tina I schrieb: >> >>> Now, this works but of course it catches every IOError, and I can not >>> figure out how to restrict it to only catch the "[Errno 2]"? >>> >> There's an example that uses the error number: >> http://docs.python.org/tut/node10.html#SECTION0010300000000000000000 >> >> > So what you'll need to do is catch all IOError exceptions, then test to > see if you've got (one of) the particular one(s) you are interested in. > If not then you can re-raise the same error with a bare "raise" > statement, and any containing exception handlers will be triggered. If > there are none then you will see the familiar traceback termination message. > > regards > Steve > you could also use some pre-testing of the filename os.path.isfile, os.path.isdir, os.path.split are good functions to test file/directory existence. Also to verify that you have permission to manipulate a file, os.access is a good function. sph From gagsl-py2 at yahoo.com.ar Wed Apr 18 15:32:51 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 18 Apr 2007 16:32:51 -0300 Subject: unicode data - accessing codepoints > FFFF on narrow python builts References: <1491.3232-2184-285262936-1176889076@email.cz> Message-ID: En Wed, 18 Apr 2007 06:37:56 -0300, escribi?: > Hi all, > I'd like to ask about the usage of unicode data on a narrow python build. > Unicode string literals \N{name} work even without the (explicit) import > of unicodedata and it correctly handles also the "wider" unicodes > planes - over FFFF > >>>> u"\N{LATIN SMALL LETTER E}" > u'e' >>>> u"\N{GOTHIC LETTER AHSA}" > u'\U00010330' > > The unicode data functions works analogous in the basic plane, but > behave differently otherwise: > >>>> unicodedata.lookup("LATIN SMALL LETTER E") > u'e' >>>> unicodedata.lookup("GOTHIC LETTER AHSA") > u'\u0330' > > (0001 gets trimmed) > > Is it a bug in unicodedata, or is this the expected behaviour on a > narrow build? Looks like a bug, but I'm not sure whether in unicodedata or in general Unicode support: py> x=u"\N{GOTHIC LETTER AHSA}" py> ord(x) Traceback (most recent call last): File "", line 1, in TypeError: ord() expected a character, but string of length 2 found py> unicodedata.name(x) Traceback (most recent call last): File "", line 1, in TypeError: need a single Unicode character as parameter py> len(x) 2 py> list(x) [u'\ud800', u'\udf30'] That looks like UTF-16 (?) but seen as two characters instead of one. Probably in a 32bits build Python should refuse to use such character (and limit Unicode support to the basic plane?) (or not?) (if not, what's the point of sys.maxunicode?) (enough parenthesis for now). Anyway a better place for bug reports is http://sourceforge.net/tracker/?group_id=5470 -- Gabriel Genellina From g.brandl at gmx.net Sun Apr 15 13:00:37 2007 From: g.brandl at gmx.net (Georg Brandl) Date: Sun, 15 Apr 2007 19:00:37 +0200 Subject: proposed PEP: iterator splicing In-Reply-To: References: <7xirbyi5d7.fsf_-_@ruckus.brouhaha.com> Message-ID: Steven Bethard schrieb: > Paul Rubin wrote: >> The boilerplate >> >> def some_gen(): >> ... >> for x in some_other_gen(): >> yield x >> ... >> >> is so common (including the case where some_other_gen is the same as >> some_gen, i.e. it's a recursive call) that I find myself wanting >> a more direct way to express it: >> >> def some_gen(): >> ... >> yield *some_other_gen() >> >> comes to mind. Less clutter, and avoids yet another temp variable >> polluting the namespace. >> >> Thoughts? > > This has been brought up before and there was mixed support: > > http://www.python.org/dev/summary/2006-01-16_2006-01-31/#yielding-from-a-sub-generator > > My guess is that the only way it has any chance is if someone takes the > time to implement it and posts a full-fledged PEP to python-dev. BTW, I've implemented a different feature, namely extended unpacking, such as a, *b, c = range(10) where I already had to add the concept of a ``starred'' expression. If someone wants to do it, we can probably share some code. Georg -- Thus spake the Lord: Thou shalt indent with four spaces. No more, no less. Four shall be the number of spaces thou shalt indent, and the number of thy indenting shall be four. Eight shalt thou not indent, nor either indent thou two, excepting that thou then proceed to four. Tabs are right out. From pythoncurious at gmail.com Tue Apr 17 03:40:23 2007 From: pythoncurious at gmail.com (pythoncurious at gmail.com) Date: 17 Apr 2007 00:40:23 -0700 Subject: C++ extension problem In-Reply-To: References: <1176741526.541997.52100@e65g2000hsc.googlegroups.com> Message-ID: <1176795623.296920.184220@d57g2000hsg.googlegroups.com> On Apr 16, 9:31 pm, Michael Hoffman wrote: > I can't answer your question since I have no experience writingextensiontypes. I know this is at least partially a learning exercise > for you, but might I suggest that your time might be better spent > learning Boost.Python instead? It is "aC++library which enables > seamless interoperability betweenC++and the Python programming language." > > http://www.boost.org/libs/python/doc/ > -- > Michael Hoffman Yes, that's good advice. Unfortunately, boost has not been working very well with the tools I'm forced to use (Sun studio). Otherwise I would have started there. /Matt From kw at codebykevin.com Mon Apr 2 18:27:27 2007 From: kw at codebykevin.com (Kevin Walzer) Date: Mon, 02 Apr 2007 18:27:27 -0400 Subject: Submit patches for documentation Message-ID: What's the best way to submit patches for Python documentation at the SourceForge patch tracker if you are not writing LaTeX? I would like to submit some simple text updates. However, if I do this, I'm not clear what files I should run a diff against. Or is simply submitting the updates as a text file, with a note indicating which documentation files they replace, sufficient? -- Kevin Walzer Code by Kevin http://www.codebykevin.com From 80xuuxk02 at sneakemail.com Tue Apr 10 10:23:37 2007 From: 80xuuxk02 at sneakemail.com (Lucas Malor) Date: 10 Apr 2007 14:23:37 -0000 Subject: Problem with getting an option value Message-ID: <10292-66264@sneakemail.com> Peter Otten wrote: > Lucas Malor wrote: >> >> The problem is options is an instance, so options."delete", for example, >> is wrong; I should pass options.delete . How can I do? > > Use getattr(): Thank you. Do you know also if I can do a similar operation with functions? I want to select with a string a certain get() function of ConfigParser: if type == "int" : funcname = "getint" elif type == "bool" : funcname = "getboolean" etc. How can I invoke the funcion with its name in a string? PS: your answers had not arrived to my mail account. Is because I'm using a disposal address? Or simply it's because I'm not registered to the list? -------------------------------------- Protect yourself from spam, use http://sneakemail.com From jstroud at mbi.ucla.edu Wed Apr 18 17:45:19 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Wed, 18 Apr 2007 14:45:19 -0700 Subject: Do other Python GUI toolkits require this? In-Reply-To: References: Message-ID: Kevin Walzer wrote: > From the introduction to PyObjC, the Python-Objective-C bridge on Mac > OS X: > > "As described in Objective-C for PyObjC users the creation of > Objective-C objects is a two-stage process. To initialize objects, first > call a class method to allocate the memory (typically alloc), and then > call an initializer (typically starts with init). Some classes have > class methods which perform this behind the scenes, especially classes > that create cached, immutable, or singleton instances." > > An example: > > myObject = NSObject.alloc().init() > > I know Tkinter doesn't require any manual memory allocation of this > sort. Does wxPython, PyQt, PyGtk require anything like this when > creating objects? > This appears more or less unique to Objective C. It looks that with PyObjC, you have to interact with the Objective C runtime to manage memory. This is not required, thankfully, with any other GUI tookits I've seen. I think the main difference is that PyObjC is not a GUI toolkit per se, but is simply a means to make the Objective C runtime (and hence Cocoa) available via a python layer. James From tjreedy at udel.edu Thu Apr 19 14:59:54 2007 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 19 Apr 2007 14:59:54 -0400 Subject: comparison with None References: <_JAVh.1700$jR5.897@trnddc08> <462709FB.9020607@gmail.com> Message-ID: | Alan Isaac wrote: | > "Terry Reedy" wrote in message | > news:mailman.6686.1176934558.32031.python-list at python.org... | > | >> Should be in the reference manual section on comparisons. | > Only to this extent: | > http://www.python.org/doc/2.4/ref/comparisons.html | > | > objects of different types always compare unequal, and are ordered | > consistently but arbitrarily. This is the sentence I was referring to. The key word is 'arbitrary', meaning withoug any particular reason why, as in "why does None compare as it does?" | > (This unusual definition of comparison was used to simplify the | > definition of operations like sorting That was broken when complex numbers were added. | > In the future, the comparison rules for objects of different types are | > likely to change.) Will change in 3.0. | > ... Most other types compare unequal unless they are the same object; | > the choice whether one object is considered smaller or larger than | > another one is made arbitrarily but consistently within one execution | > of a program. | > | > This does not provide a direct answer to "why" None comparisons. Yes it does. There is no 'why'! | > (As far as I can tell, None is less than any object.) This is an artifact of the current CPython implementation. | > However, Gary Herron's explanation makes sense: this provides a stable | > sort when None is involved, and meets the criterion that objects of | > different types must always compare unequal. However this would also | > be true if None always compared greater than any object, and the current | > behavior does not seem to be guaranteed. >From the viewpoint of the language, the current behavior is an arbitrary artifact. But here, I suspect, is the implementation why. CPython compares mixed objects by type object address. It is *currently* written and compiled so that NoneType has the lowest address among type objects. Terry Jan Reedy From nyamatongwe+thunder at gmail.com Sun Apr 15 06:43:31 2007 From: nyamatongwe+thunder at gmail.com (Neil Hodgson) Date: Sun, 15 Apr 2007 10:43:31 GMT Subject: tuples, index method, Python's design In-Reply-To: <7xvefym5r6.fsf@ruckus.brouhaha.com> References: <1176200361.260546.280510@n76g2000hsh.googlegroups.com> <740c3aec0704100824m132c45fbi5c4c3ec0c0fa3a67@mail.gmail.com> <1176489534.568939.249910@q75g2000hsh.googlegroups.com> <7x3b33k0l9.fsf@ruckus.brouhaha.com> <1176572775.382873.282850@q75g2000hsh.googlegroups.com> <7xr6qmrg4x.fsf@ruckus.brouhaha.com> <1176618596.238855.122000@d57g2000hsg.googlegroups.com> <7xvefym5r6.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin: > I still don't get it. UTF-16 is just a data compression scheme, right? > I mean, s[17] isn't the 17th character of the (unicode) string regardless > of which memory byte it happens to live at? It could be that that accessing > it takes more than constant time, but that's hidden by the implementation. Python Unicode strings are arrays of code units which are either 16 or 32 bits wide with the width of a code unit determined when Python is compiled. s[17] will be the 18th code unit of the string and is found by indexing with no ancillary data structure or processing to interpret the string as a sequence of code points. This is the same technique used by other languages such as Java. Implementing the Python string type with a data structure that can switch between UTF-8, UTF-16 and UTF-32 while preserving the appearance of a UTF-32 sequence has been proposed but has not gained traction due to issues of complexity and cost. Neil From steve at holdenweb.com Wed Apr 25 10:23:35 2007 From: steve at holdenweb.com (Steve Holden) Date: Wed, 25 Apr 2007 10:23:35 -0400 Subject: Would You Write Python Articles or Screencasts for Money? In-Reply-To: References: <462DCCE6.9060908@taupro.com> <1hx2dvj.10ek1v51noh1otN%aleax@mac.com> Message-ID: Anton Vredegoor wrote: > Steve Holden wrote: >>> When cash is involved, it's important to avoid even the slightest >>> hint of a suggestion of a suspicion of a conflict of interest; >>> that, I guess, is why firms that run contests with cash prizes >>> always declare employees and their families "not eligible", and why >>> I think the PSF should do likewise in this case. >>> >> That's a good point, and also a valid reason for restricting the >> voting community to PSF members. Thanks, Alex. > > So in order to avoid a suspicion of a conflict of interest you want to > turn the whole thing into private property of the PSF? > > That is the most ridiculous suggestion I have ever I presume that interruption came to us courtesy of the PSU? Since it's the PSF's money I don't see why the voting shouldn't be restricted to PSF members. I could be persuaded otherwise, but I haven't yet heard anything persuasive. At least most PSF members start out with a record of contribution to some aspect of Python, which is the reason they were invited to membership in the first place. Or should we ask the Perl Foundation to vote on awards too? regards Steve -- Steve Holden +1 571 484 6266 +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 sickcodemonkey at gmail.com Mon Apr 9 17:08:22 2007 From: sickcodemonkey at gmail.com (Sick Monkey) Date: Mon, 9 Apr 2007 17:08:22 -0400 Subject: recursively removing files and directories In-Reply-To: <1176144250.874365.141820@n59g2000hsh.googlegroups.com> References: <1176144250.874365.141820@n59g2000hsh.googlegroups.com> Message-ID: <2adc542f0704091408k5cbb6fd6tdd6c25f52315f384@mail.gmail.com> Here is some code that could be useful.... It does not check the directories for 0 files, but that shouldn't be too difficult to add. ############################################# from os import listdir, unlink from os.path import isdir, isfile, islink, join, getmtime deldir = "C:\Some\Dir" delFileType = ".txt" # or You could use Regex. # ------------------------------------- def del_entry(_name): try: if isdir(_name): print "Do Nothing" else: #print "now" unlink(_name) # or remove(_name) sys.stdout.write("Delete FILE %s\n" % (_name)) except IOError: sys.stderr.write("Cannot delete %s\n" % (_name)) # ------------------------------------- def list_dir(_dir,_action): if not isdir(_dir): print "%s is not a directory" % (_dir) return for file in listdir(_dir): path = join(_dir, file) if isdir(path): list_dir(path, _action) else: # isfile() or islink() if path.rfind(delFileType) != -1: #print path _action(path) # Run it list_dir(deldir, del_entry) ############################################# On 9 Apr 2007 11:44:10 -0700, bahoo wrote: > > Hi, > > I found a message on Jan 16, 2006 regarding the same topic, except > that I wanted to remove only certain files that satisfy the format > "ABC_XXX_XXX.dat", but not the other files. Once the files are > removed, if a folder becomes empty, I want to remove the folder as > well. > > The solution to the Jan 16 2006 message required many lines of python > code. I was wondering if there is a simpler solution to my problem at > hand, perhaps by using more specialized functions? > > Thanks! > bahoo > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From sjmachin at lexicon.net Tue Apr 17 08:39:27 2007 From: sjmachin at lexicon.net (John Machin) Date: 17 Apr 2007 05:39:27 -0700 Subject: OverflowError: mktime argument out of range ??? In-Reply-To: References: <11e49df10704150341p1a9056e7hfba36a523517fad3@mail.gmail.com> <1176640607.972087.153470@o5g2000hsb.googlegroups.com> <1176735739.422686.227960@d57g2000hsg.googlegroups.com> <1176761366.967796.102110@y5g2000hsa.googlegroups.com> Message-ID: <1176813567.497258.296120@n76g2000hsh.googlegroups.com> On Apr 17, 7:39 pm, "Jorgen Bodde" wrote: > Thanks again, > > I will explain what happened. I am a python newbie. Even GvR was a Python newbie once :-) > The time and > datetime modules are confusing at the beginning, but after diving into > them I started to understand the structure. So what I did was using > the time module for date storage, but I came to understand that time > is actually more used for file dates and times. That would explain the > epoch and 1970 boundaries as there are not much files before the > pre-PC era to keep timestamps for. > > Basically it would have been clearer if the time module would have > been called 'filetime' as datetime kind of supercedes the time by > removing all boundaries and still presenting all methods to the user. The time module was intended to match the functionality of the C standard library time.h kit, and named accordingly. The datetime module came much later. > > Onca again, it was confusing for someone starting with python, but I > think I got it now. I cannot claim it was not documented, I was more > surprised that there was a boundary and decided to ask before reading > the python docs, sorry .... For the benefit of those who do eventually read the docs, you may like to propose a doc patch for the time module: a sentence or two at the start, stating that the datetime module is more suited to general data processing than the time module. Cheers, John From fuzzyman at gmail.com Sun Apr 22 10:36:57 2007 From: fuzzyman at gmail.com (Fuzzyman) Date: 22 Apr 2007 07:36:57 -0700 Subject: No speedup on multi-processor machine? In-Reply-To: References: <1177189332.916296.205280@d57g2000hsg.googlegroups.com> <1177197495.821701.140390@b58g2000hsg.googlegroups.com> Message-ID: <1177252617.489113.5630@d57g2000hsg.googlegroups.com> On Apr 22, 1:03 am, Neil Hodgson wrote: > Fuzzyman: > > > IronPython is *definitely* not restricted by the GIL. > > IronPython is currently mostly slower than CPython although the > particular problem should be tested to see if IronPython helps. > > Some recent benchmarks between IronPython and CPython:http://sparcs.kaist.ac.kr/~tinuviel/pybench/ Not when running on the .NET platform, there is not a lot of difference overall: http://www.voidspace.org.uk/python/weblog/arch_d7_2007_04_21.shtml#e688 Fuzzyman http://www.voidspace.org.uk/ironpython/index.shtml > > Neil From rtw at freenet.co.uk Sun Apr 8 13:01:29 2007 From: rtw at freenet.co.uk (Rob Williscroft) Date: Sun, 08 Apr 2007 12:01:29 -0500 Subject: Why does not my wx.html.HtmlWindow work? References: <1176003505.794328.62170@n76g2000hsh.googlegroups.com> Message-ID: liqfemail at gmail.com wrote in news:1176003505.794328.62170 at n76g2000hsh.googlegroups.com in comp.lang.python: > Below are my source code: > > import wx > import wx.html > > class MyHtmlFrame(wx.Frame): > > def __init__(self, parent, title): > wx.Frame.__init__(self, parent, -1, title, size=(600,400)) > html = wx.html.HtmlWindow (self) > if "gtk2" in wx.PlatformInfo: > html.SetStandardFonts() > html.LoadPage(" > http://www.pythonthreads.com/articles/python/incorporating-into > -wxpython-part-1.html") > > app = wx.PySimpleApp() > frm = MyHtmlFrame(None, "Simple HTML Browser") > frm.Show() > app.MainLoop() > > It is just an example in the book "wxPython in action". But every time > when I try to get it run, my CPU is fully occupied, and there is no > frame that comes into existence. Why? > I think your problem is that you call LoadPage before app.MainLoop() is called, IOW you need to call LoadPage in an event handler: import wx import wx.html class MyHtmlFrame(wx.Frame): HOME = "http://www.google.co.uk" def __init__(self, parent, title): wx.Frame.__init__(self, parent, -1, title, size=(600,400)) self.html = wx.html.HtmlWindow (self) if "gtk2" in wx.PlatformInfo: self.html.SetStandardFonts() self.done_show = False wx.EVT_IDLE( self, self.OnShow ) self.html.SetPage( "Loading ..." % self.HOME ) def OnShow( self, event ): if self.done_show: return self.done_show = True self.html.LoadPage( self.HOME ) app = wx.PySimpleApp() frm = MyHtmlFrame(None, "Simple HTML Browser") frm.Show() app.MainLoop() Note: the URL you loading takes ages to show, which is why I use: http://www.google.co.uk above. Rob. -- http://www.victim-prime.dsl.pipex.com/ From arigo at tunes.org Tue Apr 24 14:47:01 2007 From: arigo at tunes.org (arigo at tunes.org) Date: Tue, 24 Apr 2007 11:47:01 -0700 Subject: EuroPython 2007 - call for refereed papers Message-ID: <20070424184701.GA2267@bespin.org> Hi all, He're a reminder to submit a talk at EuroPython! Like each year, we have both the regular conference (see call at http://indico.cern.ch/conferenceCFA.py?confId=13919) and a somewhat separated Refereed Papers section. Here is the call for the latter. The deadline for both is the 18th of May. ======================================================================== EuroPython 2007 Vilnius, Lithuania 9-11 July Call for Refereed Papers http://www.europython.org/ ======================================================================== EuroPython is the only conference in the Python world that has a properly prestigious peer-reviewed forum for presenting technical and scientific papers. Such papers, with advanced and highly innovative contents, can equally well stem from academic research or industrial research. We think this is an important function for EuroPython, so we are even making some grants available to help people with travel costs. We will be happy to consider papers in subject areas including, but not necessarily limited to, the following: * Python language and implementations * Python modules (in the broadest sense) * Python extensions * Interoperation between Python and other languages / subsystems * Scientific applications of Python * Python in Education * Games * Agile Methodologies and Testing * Social Skills We are looking for Python-related scientific and technical papers of advanced, highly innovative content that present the results of original research (be it of the academic or "industrial research" kind), with proper attention to "state of the art" and previous relevant literature/results (whether such relevant previous literature is itself directly related to Python or not). We do not intend to let the specific subject area block a paper's acceptance, as long as the paper satisfies other requirements: innovative, Python-related, reflecting original research, with proper attention to previous literature. Abstracts ========= Please submit abstracts of no more than 200 words to the refereeing committee. You can send submissions no later than 18 May 2007. We shall inform you whether your paper has been selected and announce the conference schedule on the 25 May 2007. For all details regarding the submission of abstracts, please see the EuroPython website (http://www.europython.org). WARNING: Independently of their topic, all abstracts must be submitted *in the Refereed Papers track* in order to be considered by the refereeing committee! If your abstract is accepted, you must submit your corresponding paper before 29 June 2006. Last-minute changes will be accepted until the start of the conference. You should submit the paper as a PDF file, in A4 format, complete, "stand-alone", and readable on any standards-compliant PDF reader (basically, the paper must include all fonts and figures it uses, rather than using external pointers to them; by default, most PDF-preparation programs typically produce such valid "stand-alone" PDF documents). There are no strict typesetting rules. Refereeing ========== The refereeing committee, selected by Armin Rigo, will examine all abstracts and papers. The committee may consult external experts as it deems fit. Referees may suggest or require certain changes and editing in submissions, and make acceptance conditional on such changes being performed. We expect all papers to reflect the abstract as approved and reserve the right, at our discretion, to reject a paper, despite having accepted the corresponding abstract, if the paper does not substantially correspond to the approved abstract. Presentation ============ The paper must be presented at EuroPython by one or more of the authors. Presentation time will be between half an hour and an hour, including time for questions and answers, depending on each paper's details, and also on the total number of talks approved for presentation. Proceedings =========== We will publish the conference's proceedings in purely electronic form. By presenting a paper, authors agree to give the EuroPython conference non-exclusive rights to publish the paper in electronic forms (including, but not limited to, partial and total publication on web sites and/or such media as CDROM and DVD-ROM), and warrant that the papers are not infringing on the rights of any third parties. Authors retain all other intellectual property rights on their submitted abstracts and papers excepting only this non-exclusive license. Subsidised travel ================= We have funds available to subsidise travel costs for some presenters who would otherwise not be able to attend EuroPython. When submitting your abstract, please indicate if you would need such a subsidy as a precondition of being able to come and present your paper. (Yes, this possibility does exist even if you are coming from outside of Europe. Papers from people in New Zealand who can only come if their travel is subsidised, for example, would be just fine with us...). -+- Armin Rigo From aleax at mac.com Mon Apr 9 10:20:35 2007 From: aleax at mac.com (Alex Martelli) Date: Mon, 9 Apr 2007 07:20:35 -0700 Subject: shelve error References: <1175746456.995618.186190@e65g2000hsc.googlegroups.com> <1175746966.023613.178830@n76g2000hsh.googlegroups.com> <1175756092.643182.142420@n76g2000hsh.googlegroups.com> <1hw9lxy.ldrc541w507xyN%aleax@mac.com> Message-ID: <1hwakan.16tt7fbesyrb1N%aleax@mac.com> Peter Otten <__peter__ at web.de> wrote: > Alex Martelli wrote: > > > BTW, if you DO want to call shelve.open on a path f that may correspond > > to an arbitrary existing file (and want to toss away the previous > > contents of that file, if any) the correct way to call is then: > > > > s = shelve.open(whatever_path, 'n') > > > > since 'n' truncates an existing file, or creates a new one, as needed. > > It's not entirely arbitrary since you get an exception if that file is not a > valid database: > > >>> open("tmp.db", "w").write("garbage") > >>> import shelve > >>> shelve.open("tmp.db", "n") > Traceback (most recent call last): > File "", line 1, in > File "/usr/local/lib/python2.5/shelve.py", line 225, in open > return DbfilenameShelf(filename, flag, protocol, writeback) > File "/usr/local/lib/python2.5/shelve.py", line 209, in __init__ > Shelf.__init__(self, anydbm.open(filename, flag), protocol, writeback) > File "/usr/local/lib/python2.5/anydbm.py", line 80, in open > raise error, "db type could not be determined" > anydbm.error: db type could not be determined You're right -- anydbm.open, even when asked to "truncate the file", still does mandate that the file, if it exists, be in some proper DBM format (to determine which DBM module it will use to open it). This is not intuitive, and needs to be mentioned in the Nutshell. Alex From gagsl-py2 at yahoo.com.ar Sun Apr 22 20:27:13 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sun, 22 Apr 2007 21:27:13 -0300 Subject: serializable object references References: <1242622.P0zHLAfcMH@beaureve.gmx.net> <25065059.0D4t2YsirZ@beaureve.gmx.net> Message-ID: En Sun, 22 Apr 2007 12:47:10 -0300, Martin Drautzburg escribi?: > I was thinking that it would be nice if a web application could talk to > real objects. The client side does not need to know the internals of an > object, it acts as a "view" for server-side models. All it has to be > able to do is invoke methods on "its" model. So a view could just > store "its" object-reference in an instance variable and pass it to the > server, where my problem of looking it up comes in. This is more or less what several web frameworks do. You publish objects; URLs are mapped to method objects; URL parameters become method parameters. See http://wiki.python.org/moin/WebFrameworks > I am currently learning about web services but my feeling is > that "state" is not an integral part of this concept, rather an add-on, > but I may be mistaken here. > > But for any reasonable web application you have to introduce state one > way or the other. My impression is, that this is achieved with "session > objects", which hold all the state of a session (again I may be > mistaken). But this would be a strange concept in an OO world. You > might as well put "ALL" state into a global "state" state object, where > all the class methods deposit their state and classes would hold > behavior only and no state. This is of course nothing an OO programmer > would want to do. You can have a "persistent" state (stored in a backend database) and "transitory" state (kept in session objects). -- Gabriel Genellina From ndbecker2 at gmail.com Sat Apr 7 07:07:07 2007 From: ndbecker2 at gmail.com (Neal Becker) Date: Sat, 07 Apr 2007 07:07:07 -0400 Subject: block scope? References: <7xr6qwal50.fsf@ruckus.brouhaha.com> <7xtzvseqzo.fsf@ruckus.brouhaha.com> Message-ID: James Stroud wrote: > Paul Rubin wrote: >> John Nagle writes: >>> In a language with few declarations, it's probably best not to >>> have too many different nested scopes. Python has a reasonable >>> compromise in this area. Functions and classes have a scope, but >>> "if" and "for" do not. That works adequately. >> >> I think Perl did this pretty good. If you say "my $i" that declares >> $i to have block scope, and it's considered good practice to do this, >> but it's not required. You can say "for (my $i=0; $i < 5; $i++) { ... }" >> and that gives $i the same scope as the for loop. Come to think of it >> you can do something similar in C++. > > How then might one define a block? All lines at the same indent level > and the lines nested within those lines? > > i = 5 > for my i in xrange(4): > if i: # skips first when i is 0 > my i = 100 > if i: > print i # of course 100 > break > print i # i is between 0 & 3 here > print i # i is 5 here > > > Doesn't leave a particularly bad taste in one's mouth, I guess (except > for the intended abuse). > > James Yes, the above is pretty much what I had in mind. +1. From flyzone at technologist.com Fri Apr 13 06:08:05 2007 From: flyzone at technologist.com (Flyzone) Date: 13 Apr 2007 03:08:05 -0700 Subject: split and regexp on textfile In-Reply-To: <1176456611.648400.254850@q75g2000hsh.googlegroups.com> References: <1176451192.364949.8260@w1g2000hsg.googlegroups.com> <1176453634.577706.326170@y80g2000hsf.googlegroups.com> <1176454505.336514.90910@p77g2000hsh.googlegroups.com> <1176455681.424814.223830@q75g2000hsh.googlegroups.com> <1176456611.648400.254850@q75g2000hsh.googlegroups.com> Message-ID: <1176458885.245615.319070@n76g2000hsh.googlegroups.com> On 13 Apr, 11:30, "Flyzone" wrote: > all together :( Damn was wrong mine regexp: pat = re.compile("[A-Z][a-z][a-z][ ][A-Z][a-z][a-z][ ][0-9| ][0-9][ ] [0-9][0-9][:][0-9][0-9]",re.M|re.DOTALL) now is working! :) Great! really thanks for the helps! A little question: the pat.split can split without delete the date? From rw at smsnet.pl Mon Apr 23 09:17:57 2007 From: rw at smsnet.pl (Rob Wolfe) Date: 23 Apr 2007 06:17:57 -0700 Subject: Tutorial creates confusion about slices In-Reply-To: References: Message-ID: <1177334277.241487.142430@b75g2000hsg.googlegroups.com> Antoon Pardon wrote: > The following is part of the explanation on slices in the > tutorial: > > The best way to remember how slices work is to think of the indices as > pointing between characters, with the left edge of the first character > numbered 0. Then the right edge of the last character of a string of n > characters has index n, for example: > > +---+---+---+---+---+ > | H | e | l | p | A | > +---+---+---+---+---+ > 0 1 2 3 4 5 > -5 -4 -3 -2 -1 > > This is all very well with a simple slice like: > > "HelpA"[2:4] => "lp" > > > But it give the wrong idea when using the following extended slice: > > "HelpA"[4:2:-1] => "Ap" > > So this doesn't result in the reverse of the previous expression while > the explanation above suggest it does. Clearly I understand that differently: >>> "HelpA"[-2:-4:-1] 'pl' -- Regards, Rob From swq22 at yahoo.com Fri Apr 27 15:41:16 2007 From: swq22 at yahoo.com (swq22 at yahoo.com) Date: Fri, 27 Apr 2007 21:41:16 +0200 Subject: http pipelining References: Message-ID: On Fri, 27 Apr 2007 13:50:21 -0400, Steve Holden wrote: >swq22 at yahoo.com wrote: >> Which python module is capable of pipelining http requests? >> >> (I know httplib can send mulitple requests per tcp connection, but in >> a strictly serial way. ) >> >> >There's nothing in the standard library, I believe, that includes both >client and server functionality in the same module. So you would need to >glue them together. > >If you want a simple net proxy server I seem to remember the chameleon >system allows you to write one in about twelve lines. If it has to be >HTTP-specific, with header parsing and the like, you might want to think >about Twisted, which supports both client and server functionality and >tries to make it easy to plumb things together in pipelines. Sorry for my confused question. What I'm looking for is to emulate what a modern HTTP 1.1 browser like Firefox does(when network.http.pipelining is enabled) 1.Open TCP connetion. send multiple requests without waiting for a reply: 2.GET /url1 3.GET /url2 4.GET /url3 5.read 1st reply 6.read 2st reply 7.read 3st reply 8.Close TCP connection. I'll be using Apache or IIS as my web server. From gagsl-py2 at yahoo.com.ar Sun Apr 15 14:56:51 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sun, 15 Apr 2007 15:56:51 -0300 Subject: Getting started with python References: <1176598011.463543.96990@q75g2000hsh.googlegroups.com> <1176608302.928513.274400@y5g2000hsa.googlegroups.com> Message-ID: En Sun, 15 Apr 2007 10:46:54 -0300, Army1987 escribi?: > "Paddy" ha scritto nel messaggio > news:1176608302.928513.274400 at y5g2000hsa.googlegroups.com... > >> On a different tack, from: >> http://tickletux.wordpress.com/2007/01/24/using-fizzbuzz-to-find-developers-who-grok-coding/ >> It seems you need to learn how to write a Fizz-Buzz >> program to get a job now-a-days :-) > > Something less idiotic? I took longer to type a program to do that than > to > figure out how to do that. We've used it as part of a test a few weeks ago. You'd be surprised on how many guys couldn't write anything remotely sensible. -- Gabriel Genellina From mangabasi at gmail.com Wed Apr 4 07:24:01 2007 From: mangabasi at gmail.com (Mangabasi) Date: 4 Apr 2007 04:24:01 -0700 Subject: Calling Fortran from Python In-Reply-To: References: <1175640339.648190.207530@y66g2000hsf.googlegroups.com> Message-ID: <1175685841.847487.173440@w1g2000hsg.googlegroups.com> Robert, Thanks for your prompt response. I think I got a lot closer but no cigar yet. This is the output C:\fortrandll>f2py -c -m sample sample.pyf sample.for numpy_info: FOUND: define_macros = [('NUMERIC_VERSION', '"\\"24.2\\""')] include_dirs = ['C:\\Python24\\include'] running build running config_fc running build_src building extension "sample" sources creating c:\docume~1\fb\locals~1\temp\tmpcosvgv creating c:\docume~1\fb\locals~1\temp\tmpcosvgv\src f2py: sample.pyf Reading fortran codes... Reading file 'sample.pyf' Post-processing... Block: sample Block: sample Post-processing (stage 2)... Building modules... Building module "sample"... Constructing wrapper function "sample"... ierr1,ierr2,aout = sample(ain) Wrote C/API module "sample" to file "c:\docume~1\fb \locals~1\temp\tmpcos vgv\src/samplemodule.c" adding 'c:\docume~1\fb\locals~1\temp\tmpcosvgv\src\fortranobject.c' to sources . adding 'c:\docume~1\fb\locals~1\temp\tmpcosvgv\src' to include_dirs. copying C:\python24\lib\site-packages\f2py2e\src\fortranobject.c -> c: \docume~1\ fb\locals~1\temp\tmpcosvgv\src copying C:\python24\lib\site-packages\f2py2e\src\fortranobject.h -> c: \docume~1\ fb\locals~1\temp\tmpcosvgv\src running build_ext No module named msvccompiler in scipy_distutils, trying from distutils.. error: The .NET Framework SDK needs to be installed before building extensions f or Python. I think I have a problem with distutils' msvccompiler.py. It may be the MacroExpander in distutils guessing the visual studio path incorrectly or something related to the registry keys. Is there a way to specify the C compiler path to f2py so that it does not rely on the distutils? Or maybe I am totally off base here, I don't know. Any thoughts? From steve at holdenweb.com Mon Apr 23 13:31:17 2007 From: steve at holdenweb.com (Steve Holden) Date: Mon, 23 Apr 2007 13:31:17 -0400 Subject: Shebang or Hashbang for modules or not? In-Reply-To: References: <1176308951.932721.197630@y80g2000hsf.googlegroups.com> Message-ID: Michael Hoffman wrote: > Steven W. Orr wrote: >> On Saturday, Apr 21st 2007 at 19:18 +0100, quoth Michael Hoffman: >> >> =>Chris Lasher wrote: >> =>> Should a Python module not intended to be executed have shebang/ >> =>> hashbang (e.g., "#!/usr/bin/env python") or not? I'm used to having a >> =>> shebang in every .py file but I recently heard someone argue that >> =>> shebangs were only appropriate for Python code intended to be >> =>> executable (i.e., run from the command line). >> => >> =>Personally I include it in all of them, as part of boilerplate in a >> =>template. >> >> I'd recommend againt it. The shebang doesn't do you any good unless it's >> also in the presence of a file that has its executable bit set. > > It doesn't do any bad either, so I don't understand why you would > recommend against it. > > And the bash function I use to create new files from the template also > does chmod a+x. > > Not to mention that I have emacs set such that things with shebangs at > the top are automatically chmod a+x, so in my programming environment, > having a shebang on files I create and being executable are one and the > same. > >> For example, let's leave python out for a second: I have a shell script. >> And I also have lots of files which are not intended to be executed which >> are also shell scripts, but which are sucked in by the shell "." or >> "source" command (which is *somewhat* analogous to python's import). Lots >> of these shell "library" scripts can't execute as standalone. The same >> thing is possible with pything scripts. >> >> Of course, anything that has >> if __name__ == "__main__": >> in it should always have a shebang and be executable. > > That's in my template as well. :) > > I try to write all my modules so that they can easily be adapted to run > as scripts, and all my scripts so that they can easily be adapted to use > as modules. This has served me well many, many times. I see no reasons > to create an artificial barrier to doing this by leaving the shebang out > of files where it has no ill effect. If you ever create a module that *shouldn't be run you can always put if __name__ == "__main__": print "Do not run this script: it is a module for import only" at the end of it. But what's the point? regards Steve -- Steve Holden +1 571 484 6266 +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 Fri Apr 27 17:55:33 2007 From: nogradi at gmail.com (Daniel Nogradi) Date: Fri, 27 Apr 2007 23:55:33 +0200 Subject: if __name__ == 'main': & passing an arg to a class objec In-Reply-To: <1177708104.277756.245360@t38g2000prd.googlegroups.com> References: <1177708104.277756.245360@t38g2000prd.googlegroups.com> Message-ID: <5f56302b0704271455v27436869h1fa6171178ccdf4d@mail.gmail.com> > The lines > > if __name__ == 'main': > someClass().fn() > > appear at the end of many examples I see. Is this to cause a .class > file to be generated? Python doesn't generate .class files, and the example you mean is probably more like if __name__ == '__main__': .........whatever............ which causes the whatever block to be executed when the program is run from the command line (as opposed to being imported). > The last line of the sample below has a string parameter. When I > mimicked this I got an error stating that the class constructor did > not take an arg, which seems correct. > > Thanks, > > gtb > > > # Generated by MaxQ [com.bitmechanic.maxq.generator.CompactGenerator] > from CompactTest import CompactTest > > class MaxQTest(CompactTest): > # Recorded test actions. > def runTest(self): > self.msg('Test started') > > # ^^^ Insert new recordings here. (Do not remove this line.) > > > # Code to load and run the test > if __name__ == 'main': > MaxQTest('MaxQTest').Run() It's hard to say what MaxQTest takes as an argument without seeing the code. If you post more details it might be easier to help you, but in any case this may be useful: http://python.org/doc/tut/ Daniel From jstroud at mbi.ucla.edu Wed Apr 25 00:17:11 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Tue, 24 Apr 2007 21:17:11 -0700 Subject: TK-grid problem, please help In-Reply-To: References: <3CgWh.23821$PL.17381@newsread4.news.pas.earthlink.net> Message-ID: Hertha Steck wrote: > Hello, > > Ray schrieb: > >> Hi, Thanks for the help. >> >> >> I was trying to find a book "Python TK" something on last Friday. >> but didn't find it :-) >> > > There is only one printed book, all the details here: > > http://wiki.python.org/moin/GuiBooks > > HTH > Hertha This is inaccurate. There is only one book listed in the wiki. Python Programming by Mark Lutz has an excellent Tkinter section as well as an *incredible* amount of other information. Also, it has recently been updated. It is probably the most relevant book for making a complete transition from novice python programmer to expert python programmer. James From steveo at syslang.net Fri Apr 6 13:51:49 2007 From: steveo at syslang.net (Steven W. Orr) Date: Fri, 6 Apr 2007 13:51:49 -0400 (EDT) Subject: Prevent Modification of Script? In-Reply-To: <1175735097.856840.177510@e65g2000hsc.googlegroups.com> References: <1175735097.856840.177510@e65g2000hsc.googlegroups.com> Message-ID: On Wednesday, Apr 4th 2007 at 18:04 -0700, quoth ts-dev: =>Is it possible to prevent modification of a python file once its been =>deployed? File permissions of the OS could be used..but that doesn't =>seem very secure. => =>The root of my question is verifying the integrity of the application =>and the scripts being run. Is this possible, if so, how? I'm going to take a stab at this one even though I'm a really junior pythonian. I know others have already responded, but I'd like to offer a couple of suggestions that have nothing to do with python. (BTW, I do applaud the previous answers that suggest that this is really a non-problem in the first place.) 1. *IF* you are on a linux target platform then it's likely that you have a package management system in use, either rpm or deb. In either case, you have the ability to verify by checksum, every file of any package. In the case of rpm, just use the -V option. 2. You also have the ability to set the immutable flag on ext2/ext3 filesystems. See lsattr/chattr commands. Of course, if you can get root access then you can shut off immutability, but you can also replace your package management tools as well. AAAUUUGGGHHH!!! -- 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 kyosohma at gmail.com Mon Apr 23 15:54:52 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: 23 Apr 2007 12:54:52 -0700 Subject: Learning Python - First Project In-Reply-To: <1177353879.444542.163020@p77g2000hsh.googlegroups.com> References: <1177339942.371167.93970@b75g2000hsg.googlegroups.com> <1177353879.444542.163020@p77g2000hsh.googlegroups.com> Message-ID: <1177358092.342220.98160@n59g2000hsh.googlegroups.com> On Apr 23, 1:44 pm, kyoso... at gmail.com wrote: > On Apr 23, 9:52 am, KDawg44 wrote: > > > > > Hi, > > > I am new to Python and am trying to write a little front end to > > another application in Python. > > > What I want is to have a gui pop up listing some items with several > > buttons. The guts of the program I am not having any trouble with but > > the GUI part I am (or more accurately, the transition between GUI > > pieces). > > > The first GUI that pops up lists some groups in a listbox and gives > > the user the choice to create a new group, open a group, rename the > > group, or delete the group. The new group and rename group buttons > > pop up a dialog gui asking for the name/new name. The Open Group is > > to open another GUI listing projects within that group in a list with > > similar options (New Project, Open Project, Rename Project, Delete > > Project). > > > My question is, how should I create all these GUIs? Should each GUI > > be its own class with its own __init__? Then is the first GUI the > > root (how I have it set up now) and all other GUIs using Toplevel()? > > > I hope this makes sense (because it only sort of makes sense in my > > head). > > > THanks for any suggestions. > > I am assuming you are using Tkinter for your GUI front-end. You should > be able to just use standard dialog boxes for your "new group" and > "rename group" dialogs and a custom hand-coded dialog for the other > one. All three can be called with ShowModal() instead of Toplevel(). > And yes, the custom dialog would work best if you made it into a > separate class. > > You could also put that information for the GUI that list projects > into a "tree" widget of some sort, maybe with a splitter window. I > haven't had much luck with Tkinter's tree widgets though. PMW and Tix > both have rather poor docs unless you enjoy man pages. You might check > out wxPython instead. It has an excellent demo that is very good at > showing you not only what all it can do, but how it is done:www.wxpython.org. > > Good luck! > > Mike Sorry about the dual posting. This thing isn't posting correctly for me today. Mike From skulka3 at gmail.com Thu Apr 26 17:48:29 2007 From: skulka3 at gmail.com (skulka3 at gmail.com) Date: 26 Apr 2007 14:48:29 -0700 Subject: Python CGI and Browser timeout Message-ID: <1177624109.532664.105840@t39g2000prd.googlegroups.com> Hello, I am creating a simple cgi script which needs to retrieve and process a huge number of records from the database (more than 11,000) and write the results to a file on disk and display some results when processing is complete. However, nothing needs to be displayed while the processing is on. I was facing browser timeout issue due to the time it takes to process these records. In order to work around this problem, I started printing empty strings (i.e. print "") so that the browser does not timeout. Is there a better solution to avoid browser timeouts? Thanks, From steve at holdenweb.com Fri Apr 13 09:33:49 2007 From: steve at holdenweb.com (Steve Holden) Date: Fri, 13 Apr 2007 09:33:49 -0400 Subject: tuples, index method, Python's design In-Reply-To: References: <1175953520.316208.241490@o5g2000hsb.googlegroups.com> <7xzm5igbrb.fsf@ruckus.brouhaha.com> <1176200361.260546.280510@n76g2000hsh.googlegroups.com> <740c3aec0704100824m132c45fbi5c4c3ec0c0fa3a67@mail.gmail.com> Message-ID: Antoon Pardon wrote: > On 2007-04-12, Carsten Haese wrote: >> On Thu, 2007-04-12 at 14:10 +0000, Antoon Pardon wrote: >>> People are always defending duck-typing in this news group and now python >>> has chosen to choose the option that makes duck-typing more difficult. >> Au contraire! The "inconsistent" behavior of "in" is precisely what >> duck-typing is all about: Making the operator behave in a way that makes >> sense in its context. > > No it isn't. Ducktyping is about similar objects using a similar > interface to invoke similar behaviour and getting similar result. > > So that if you write a function you don't concern yourself with > the type of the arguments but depend on the similar behaviour. > Please note that "similar" does not mean "exact". The behavior of str.__contains__ and list.__contains__ is similar. Duck-typing allows natural access to polymorphism. You appear to be making semantic distinctions merely for the sake of continuing this rather fatuous thread. > Suppose someone writes a function that acts on a sequence. > The algorithm used depending on the following invariant. > > i = s.index(e) => s[i] = e > > Then this algorithm is no longer guaranteed to work with strings. > Because strings have different properties than other sequences. I can't help pointing out that your invariant is invalid for tuples also, because tuples don't have a .index() method. > > On the other hand I subclass list and add a sub method > to check for the argument being a sublist of the object. > Now I write a function that depends on this functionality. > But although strings have the functionality I can't use > them as argument because the functionality is invoked > in a different way. > >> Nobody seems to be complaining about "+" behaving >> "inconsistently" depending on whether you're adding numbers or >> sequences. > > You are wrong. I already mentioned problems with it. The > problem is that there are structures that are numbers and > sequences at the same time. So I have a choice. Either I > overload the "+" to get an addition or to get a concatanation. > > In the first case I can't trust my structure to work with > functions that expect a general sequence because they > may depend on the fact that "+" concatenates. In the > other case I can't trust my structure to work with > numbers because they may depend on the fact that "+" > behaves like an addition. > Good grief. -- 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 seanmccallister at gmail.com Sat Apr 28 18:33:27 2007 From: seanmccallister at gmail.com (Sean McCallister) Date: Sat, 28 Apr 2007 18:33:27 -0400 Subject: CPython vs. Jython/JPython Message-ID: Is this stephen coursen, once married to michelle coursen from linden NJ? From slm_guzel at hotmail.com Tue Apr 3 16:46:29 2007 From: slm_guzel at hotmail.com (gslm) Date: 3 Apr 2007 13:46:29 -0700 Subject: ImageGrab Message-ID: <1175633189.066504.251290@b75g2000hsg.googlegroups.com> root = tk.Tk() def click(): x=button1.winfo_rootx() y=button1.winfo_rooty() image=PIL.ImageGrab.grab((x,y,x+260,y+250)) image.save( 'tmp.jpeg') button1 = tk.Button(root, compound=tk.TOP, width=60, height=50,bg='black', command=click) button1.pack() root.mainloop() Hi! How can I save only the button area and then open this image file and print this? If you help, I'll be very happy! Thanks and regards... From tjreedy at udel.edu Wed Apr 4 19:56:31 2007 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 4 Apr 2007 19:56:31 -0400 Subject: Why NOT only one class per file? References: <1175721799.714907.52770@o5g2000hsb.googlegroups.com> Message-ID: "Chris Lasher" wrote in message news:1175721799.714907.52770 at o5g2000hsb.googlegroups.com... |A friend of mine with a programming background in Java and Perl places | each class in its own separate file in . I informed him that keeping | all related classes together in a single file is more in the Python | idiom than one file per class. He asked why, and frankly, his valid | question has me flummoxed. Ask him why he does not wear a straightjacket all the time. It is great for one's posture ;-) From khabkr at yahoo.com Wed Apr 11 07:36:57 2007 From: khabkr at yahoo.com (A.B., Khalid) Date: 11 Apr 2007 04:36:57 -0700 Subject: THREADS use 100 % CPU all the time In-Reply-To: <1176284321.528102.112740@o5g2000hsb.googlegroups.com> References: <1176284321.528102.112740@o5g2000hsb.googlegroups.com> Message-ID: <1176291417.888693.107050@w1g2000hsg.googlegroups.com> On Apr 11, 2:38 am, matthiasja... at gmx.net wrote: > Hi all, > > I have a application where I use different threads. actually all is > working - BUT I just discovered that the [b]CPU is always 100 % [/ > b]used. > > on the 32-bit machine athlon XP, as well as on the amd 64-bit AMD > Athlon(TM) 64 X2 Dual-Core. > > I have to admit I'm not used to threads. I actually use a thirdparty > scheduler [url]http://www.webwareforpython.org/TaskKit/Docs/Source/ > Docs/TaskKit.Scheduler.html[/url] > but I checked and a very simple exampe with threading gives me also > all the time 100% CPU. > > [code] > > import threading, time > > class TestThread ( threading.Thread ): > def run ( self ): > print 'TEST' > > t = TestThread() > t.start() > > while (True): > pass > > [/code] > > Does anyone know how to run this without consuming all CPU. > > regards, > > MJ You need your program to sleep a while to allow a switch to other tasks. Like so: ### import threading, time class TestThread(threading.Thread): def run(self): print 'TEST' t = TestThread() t.start() while (True): time.sleep(0.01) pass ### Regards From sjmachin at lexicon.net Tue Apr 24 21:09:22 2007 From: sjmachin at lexicon.net (John Machin) Date: Wed, 25 Apr 2007 11:09:22 +1000 Subject: Catching a specific IO error In-Reply-To: References: Message-ID: <462EAA42.2080608@lexicon.net> On 25/04/2007 4:06 AM, Steven Howe wrote: > Steve Holden wrote: >> Thomas Kr?ger wrote: >> >>> Tina I schrieb: >>> >>>> Now, this works but of course it catches every IOError, and I can not >>>> figure out how to restrict it to only catch the "[Errno 2]"? >>>> >>> There's an example that uses the error number: >>> http://docs.python.org/tut/node10.html#SECTION0010300000000000000000 >>> >>> >> So what you'll need to do is catch all IOError exceptions, then test >> to see if you've got (one of) the particular one(s) you are interested >> in. If not then you can re-raise the same error with a bare "raise" >> statement, and any containing exception handlers will be triggered. If >> there are none then you will see the familiar traceback termination >> message. >> >> regards >> Steve >> > you could also use some pre-testing of the filename os.path.isfile, > os.path.isdir, os.path.split are good > functions to test file/directory existence. In general, this is laborious, tedious, and possibly even platform dependent. Then you still need to wrap the open call in try/accept. Why bother? In particular, (1) please explain how os.path.split helps with existence testing: Python 2.5.1 (r251:54863, Apr 18 2007, 08:51:08) [MSC v.1310 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. | >>> import os.path | >>> os.path.split(r'no\such\path\nothing.nix') ('no\\such\\path', 'nothing.nix') (2) please explain why you avoided mentioning os.path.exists. From nyamatongwe+thunder at gmail.com Tue Apr 24 17:53:01 2007 From: nyamatongwe+thunder at gmail.com (Neil Hodgson) Date: Tue, 24 Apr 2007 21:53:01 GMT Subject: how to serialize a COM object ? In-Reply-To: <1177445437.543694.49070@r3g2000prh.googlegroups.com> References: <1177445437.543694.49070@r3g2000prh.googlegroups.com> Message-ID: <1%uXh.23478$M.19517@news-server.bigpond.net.au> vml wrote: > I have a COM object. > > I would like to pass this com object from a server to a client through > a socket. As Diez mentioned, this may be possible through Distributed COM (DCOM). Its not very popular any more with techniques such as SOAP being more widely implemented. DCOM is fiddly to set up particularly the security aspects. IIRC I did get it to work with Python but that was maybe 8 years ago. Here's an overview of DCOM: http://msdn2.microsoft.com/en-us/library/ms809311.aspx Neil From basilisk96 at gmail.com Mon Apr 2 23:43:33 2007 From: basilisk96 at gmail.com (Basilisk96) Date: 2 Apr 2007 20:43:33 -0700 Subject: Generic logic/conditional class or library for classification of data In-Reply-To: References: <1175403286.809692.100080@n59g2000hsh.googlegroups.com> Message-ID: <1175571813.229254.210580@l77g2000hsb.googlegroups.com> Thanks for the help, guys. Dictionaries to the rescue! Steven, it's certainly true that runtime creation of attributes does not fit well here. At some point, an application needs to come out of generics and deal with logic that is specific to the problem. The example I gave was classification of books, which is relatively easy to understand. The particular app I'm working with deals with specialty piping valves, where the list of rules grows complicated fairly quickly. So, having said that "attributes are not known at design time", it seems that dictionaries are best for the generic core functionality: it's easy to iterate over arbitrary "key, value" pairs without hiccups. I can even reference a custom function by a key, and call it during the iteration to do what's necessary. The input/output dictionaries would dictate that behavior, so that would be the implementation-specific stuff. Easy enough, and the core functionality remains generic enough for re-use. Michael, I looked at the sample snippets at that link, and I'll have to try it out. Thanks! From rschroev_nospam_ml at fastmail.fm Sun Apr 15 10:56:58 2007 From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven) Date: Sun, 15 Apr 2007 14:56:58 GMT Subject: tuples, index method, Python's design In-Reply-To: <7xvefym5r6.fsf@ruckus.brouhaha.com> References: <1176200361.260546.280510@n76g2000hsh.googlegroups.com> <740c3aec0704100824m132c45fbi5c4c3ec0c0fa3a67@mail.gmail.com> <1176489534.568939.249910@q75g2000hsh.googlegroups.com> <7x3b33k0l9.fsf@ruckus.brouhaha.com> <1176572775.382873.282850@q75g2000hsh.googlegroups.com> <7xr6qmrg4x.fsf@ruckus.brouhaha.com> <1176618596.238855.122000@d57g2000hsg.googlegroups.com> <7xvefym5r6.fsf@ruckus.brouhaha.com> Message-ID: <_2rUh.121507$eJ3.917600@phobos.telenet-ops.be> Paul Rubin schreef: > "Rhamphoryncus" writes: >> Indexing cost, memory efficiency, and canonical representation: pick >> two. You can't use a canonical representation (scalar values) without >> some sort of costly search when indexing (O(log n) probably) or by >> expanding to the worst-case size (UTF-32). Python has taken the >> approach of always providing efficient indexing (O(1)), but you can >> compile it with either UTF-16 (better memory efficiency) or UTF-32 >> (canonical representation). > > I still don't get it. UTF-16 is just a data compression scheme, right? > I mean, s[17] isn't the 17th character of the (unicode) string regardless > of which memory byte it happens to live at? It could be that that accessing > it takes more than constant time, but that's hidden by the implementation. > > So where does the invariant c==s[s.index(c)] fail, assuming s contains c? I didn't get it either, but now I understand. Like you, I thought Python Unicode strings contain a canonical representation (in interface, not necessarily in implementation) but apparently that is not true; see Neil's post and the reference manual (http://docs.python.org/ref/types.html#l2h-22). A simple example on my Python installation, apparently compiled to use UTF-16 (sys.maxunicode == 65535): >>> s = u'\u1d400' >>> s.index(s) 0 >>> s[0] u'\u1d40' >>> s == s[0] False In this case s[0] is not the full Unicode scalar, but instead just the first part of the surrogate pair consisting of 0x1D40 (in s[0]) and 0x0000 (in s[1]). -- If I have been able to see further, it was only because I stood on the shoulders of giants. -- Isaac Newton Roel Schroeven From nyamatongwe+thunder at gmail.com Thu Apr 5 18:01:31 2007 From: nyamatongwe+thunder at gmail.com (Neil Hodgson) Date: Thu, 05 Apr 2007 22:01:31 GMT Subject: RFC: Assignment as expression (pre-PEP) In-Reply-To: <1175807326.466842.219820@p77g2000hsh.googlegroups.com> References: <1175802680.021987.39220@p77g2000hsh.googlegroups.com> <1175807326.466842.219820@p77g2000hsh.googlegroups.com> Message-ID: <%keRh.9812$M.739@news-server.bigpond.net.au> darklord at timehorse.com: > else: > my_match = capper_re.match(f): > if my_match: > capper = capper_re.match(f).group(1) > if capper == 'JJ' or capper == 'JeffreyJacobs': > capper = 'Jeffrey C. Jacobs' > past_title = True The assignment to my_match here is not used, so the test can be "if capper_re.match(f)" which can then merge up into the previous else as an elif dropping one level of indentation. Neil From marcus at schnupfnase.com Mon Apr 16 21:07:50 2007 From: marcus at schnupfnase.com (schnupfy) Date: 16 Apr 2007 18:07:50 -0700 Subject: strange behaviour sys.argv Message-ID: <1176772070.349541.80890@y5g2000hsa.googlegroups.com> Hi, I am not used to python and I am wondering about this thing: If I execute this from the shell: /root/mk/services.py 192.168.1.101 critical "192.168.1.101 192.168.1.101 SNMPv2-MIB::sysUpTime.0 14:13:02:57.06 SNMPv2- MIB::snmpTrapOID.0 SNMPv2-SMI::enterprises.789.0.13 SNMPv2- SMI::enterprises.789.0.2"cfCannotTakeover == 1 priority == critical" SNMP-COMMUNITY-MIB::snmpTrapAddress.0 192.168.1.101 SNMP-COMMUNITY- MIB::snmpTrapCommunity.0 "public"" I have the following cmd arguments: ['/root/mk/services.py', '192.168.1.101', 'critical', '192.168.1.101 192.168.1.101 SNMPv2-MIB::sysUpTime.0 14:13:02:57.06 SNMPv2- MIB::snmpTrapOID.0 SNMPv2-SMI::enterprises.789.0.13 SNMPv2- SMI::enterprises.789.0.2cfCannotTakeover', '==', '1', 'priority', '==', 'critical SNMP-COMMUNITY-MIB::snmpTrapAddress.0 192.168.1.101 SNMP-COMMUNITY-MIB::snmpTrapCommunity.0 public'] If I execute the same thing from a bash script: #!/bin/bash TRAP='192.168.1.101 192.168.1.101 SNMPv2-MIB::sysUpTime.0 14:13:02:57.06 SNMPv2-MIB::snmpTrapOID.0 SNMPv2-SMI::enterprises. 789.0.13 SNMPv2-SMI::enterprises.789.0.2"cfCannotTakeover == 1 priority == critical" SNMP-COMMUNITY-MIB::snmpTrapAddress.0 192.168.1.101 SNMP-COMMUNITY-MIB::snmpTrapCommunity.0 "public"' HOST=$(echo "$TRAP" | awk '{print $1}') SEVERITY='critical' /root/mk/services.py $HOST $SEVERITY \"$TRAP\" I get the following result: ['/root/mk/services.py', '192.168.1.101', 'critical', '"192.168.1.101', '192.168.1.101', 'SNMPv2-MIB::sysUpTime.0', '14:13:02:57.06', 'SNMPv2-MIB::snmpTrapOID.0', 'SNMPv2- SMI::enterprises.789.0.13', 'SNMPv2-SMI::enterprises. 789.0.2"cfCannotTakeover', '==', '1', 'priority', '==', 'critical"', 'SNMP-COMMUNITY-MIB::snmpTrapAddress.0', '192.168.1.101', 'SNMP- COMMUNITY-MIB::snmpTrapCommunity.0', '"public""'] Can someone help me with that? This is the output of echo /root/mk/services.py $HOST $SEVERITY \"$TRAP \" /root/mk/services.py 192.168.1.101 critical "192.168.1.101 192.168.1.101 SNMPv2-MIB::sysUpTime.0 14:13:02:57.06 SNMPv2- MIB::snmpTrapOID.0 SNMPv2-SMI::enterprises.789.0.13 SNMPv2- SMI::enterprises.789.0.2"cfCannotTakeover == 1 priority == critical" SNMP-COMMUNITY-MIB::snmpTrapAddress.0 192.168.1.101 SNMP-COMMUNITY- MIB::snmpTrapCommunity.0 "public"" Thank you. Cheers Marcus From cam.ac.uk at mh391.invalid Fri Apr 13 05:20:28 2007 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Fri, 13 Apr 2007 10:20:28 +0100 Subject: Try problem In-Reply-To: <1176455642.199343.136720@l77g2000hsb.googlegroups.com> References: <1176455642.199343.136720@l77g2000hsb.googlegroups.com> Message-ID: SamG wrote: > import sys > try: > s=1 > if s==1: > sys.exit(0) > else: > sys.exit(1) > except SystemExit,s: > if (s==0): > print s > else: > print "Hello" > > How come i always end up getting the "Hello" printed on the screen as > logically i should a '0' printed? After the exception is raised, s is not an int. It is an exception object. You want s.message. -- Michael Hoffman From gdonald at gmail.com Fri Apr 13 16:09:14 2007 From: gdonald at gmail.com (Greg Donald) Date: Fri, 13 Apr 2007 15:09:14 -0500 Subject: Python editor/IDE on Linux? In-Reply-To: <1176494048.627760.323630@p77g2000hsh.googlegroups.com> References: <1176494048.627760.323630@p77g2000hsh.googlegroups.com> Message-ID: <15e66e4e0704131309o306995b1r89274fa47c1def9f@mail.gmail.com> On 13 Apr 2007 12:54:08 -0700, azrael wrote: > try wing ide. i tried it and i love it. it's available for windows as > well for linux Good thing those are the only two operating system out there.. err.. I meant, good thing there's Emacs. -- Greg Donald http://destiney.com/ From linusno at gmail.com Thu Apr 12 12:34:52 2007 From: linusno at gmail.com (=?ISO-8859-1?Q?Linus_Nordstr=F6m?=) Date: Thu, 12 Apr 2007 18:34:52 +0200 Subject: bittorent In-Reply-To: <461D16B7.9090407@ncee.net> References: <1eb3a0e10704110922v17f83f79se5972dce07415a5@mail.gmail.com> <461D110F.8080908@rpath.com> <461D16B7.9090407@ncee.net> Message-ID: <1eb3a0e10704120934g3d52b73fge2d5d343a61eb20a@mail.gmail.com> I might have been a bit unclear on what i was looking for, im not looking for a finished bitorrent client, but rather module that can parse a .torrent file, or info on how i would goabout to write something that can do that. On 4/11/07, Shane Geiger wrote: > > > Jonathan Smith wrote: > > Linus Nordstr?m wrote: > > > >> Hello > >> Im planing playing a bit whit bittorrent, but I'm having some trouble > >> about where to start. So if anyone could point me in the right > >> direction it would be much appreciated. > >> The best would be if there are some already written modules that > >> handle downloading and seeding torrents, but if that cant be found a > >> good source on how one dose to build some sort of bitorrent client > >> would be nice. > >> > From dborne at gmail.com Mon Apr 16 10:25:50 2007 From: dborne at gmail.com (Dave Borne) Date: Mon, 16 Apr 2007 09:25:50 -0500 Subject: Writing Log CSV (Efficiently) In-Reply-To: <17955.33861.211843.361355@montanaro.dyndns.org> References: <7554276584215132819@unknownmsgid> <6e42ec490704160700i20469453j6af39db62dd6b427@mail.gmail.com> <17955.33861.211843.361355@montanaro.dyndns.org> Message-ID: <6e42ec490704160725t4478842bs47fbf3ea444f1b57@mail.gmail.com> On 4/16/07, skip at pobox.com wrote: > > Dave> Python has built in logging support. It's pretty flexible as far > Dave> as formatting output. I can get a bit complicated to set up, but > Dave> it will handle traffic well. > > Really? I've found it to be a dog in heavy logging situations. > > Skip Well I've never flogged the logging system very hard, so listen to Skip here if you're concerned about performance. I also don't think logging will integrate easily with the built in csv module. There's always ','.join(column_list)... -Dave From martin at v.loewis.de Sat Apr 7 18:15:15 2007 From: martin at v.loewis.de (=?ISO-8859-15?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sun, 08 Apr 2007 00:15:15 +0200 Subject: Custom Python Runtime In-Reply-To: References: <2NudnVn5jsm2QIvbnZ2dnUVZ_vqpnZ2d@comcast.com> <46176493$0$4042$9b622d9e@news.freenet.de> Message-ID: <461817f3$0$23925$9b622d9e@news.freenet.de> > Is this information somewhere on python.org? This is at least an > occasional question here. Part of it. The way Python finds its landmark is in the sources (so it is on svn.python.org/projects/python/trunk/PC/getpathp.c); the minimum set of modules is nowhere documented (and will certainly change from release to release). Regards, Martin From steve at holdenweb.com Tue Apr 24 13:09:44 2007 From: steve at holdenweb.com (Steve Holden) Date: Tue, 24 Apr 2007 13:09:44 -0400 Subject: Generate report containing pdf or ps figures? In-Reply-To: <132sdmde3vg6kf3@corp.supernews.com> References: <132pnp6r4qg0lc2@corp.supernews.com> <132sdmde3vg6kf3@corp.supernews.com> Message-ID: Grant Edwards wrote: > On 2007-04-24, Steve Holden wrote: > >>>> I've looked at ReportLab's documentation, but although it >>>> appears to be able to use bitmap images (e.g jpeg) it doesn't >>>> appear to be able to use vector images (EPS/PDF/SVG). >>>> >>>> Is there a PDF generation library that can place EPS or >>>> PDF figures on a page? >>> . >>> . >>> . >>> You're stuck. > [...] >> In fairness to ReportLab I'd like to say that their *commercial* >> products can do everything the OP asks for and more besides, but >> unfortunately they are mostly targeted at the "enterprise" (read: big >> money) market. > > This is just a smallish app for internal use by 1-2 people, so > I probably can't justify spending much cash. I'll check on the > ReportLab pricing. By the time I figure out how to bundle > Ghostscript with py2exe, it will probably have been cheaper to > pay for a copy of ReportLab. But it's usually easier to spend > a week of engineering time that it is to spend $1000. > In which case you can safely spend almost six months before anyone complains about the cost justification :-( regards Steve -- Steve Holden +1 571 484 6266 +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 aspineux at gmail.com Thu Apr 12 08:02:17 2007 From: aspineux at gmail.com (aspineux) Date: 12 Apr 2007 05:02:17 -0700 Subject: Nice "bug" to loose a contest In-Reply-To: <1176032438.921825.42730@b75g2000hsg.googlegroups.com> References: <1176029528.528010.210230@n59g2000hsh.googlegroups.com> <1176032438.921825.42730@b75g2000hsg.googlegroups.com> Message-ID: <1176379337.181738.229760@n59g2000hsh.googlegroups.com> On 8 avr, 13:40, "aspineux" wrote: > This code works like the python one, > I dont use buffered stdio f... functions, > but the more 'system call' read and write > > int main() > { > char buf[120]; > int len; > > while (len=read(1, buf, sizeof(buf))) { > write(1, buf, len); > } > return 0; > > } > > I dont understand what is appening, But I have an idea ! It is possible to open a file in RW mode, nothing exceptional with that. And when connected in a terminal, you are connected through a file called a PTY ! This "file" is open in RW ! File descriptors 0, 1 and 2 are certainly a "view" of this PTY and then in fact the same thing ! > but you have to know their is a link between > stdin and stdout in 'terminal mode', when you make a read on stdin, > stdout is automatically flushed, this link disappears when onr is not > liked to a terminal. > This is to facilitate user input, to avoid to put a flush after each > write, > in fact before any user input. > > Hope someone else will give the trick > > On 8 avr, 12:52, "stdazi" wrote: > > > Hello, > > > Yesterday, I was at a programming competition. We programmed on Linux > > liveCD's and Python was one of the allowed languages (among C and > > Java). I cared just about the algorithmic approach so I used Python. > > One of the main rules is, that the code reads its standard input and > > dumps the result on the standard output. Here happened my bigger > > programming mistake ever - I used the following approach : > > > ==== > > import sys > > print sys.stdout.readlines() # TYPO ! stdin != stdout > > ==== > > > So the WEIRD issue is, that it worked and, executing the following > > code I get : > > > ==== > > azi at magicb0x ~ $ python la.py > > test > > test #2 > > ['test \n', 'test #2\n'] > > azi at magicb0x ~ $ > > ==== > > > Ok, as the algorithm worked perfectly, and all the test cases we were > > given were positive, I've continued with the next problem, copy/ > > pasting the above idiom... When they tested the code, they used file > > redirection like : > > > == > > python la.py < /somefile > > == > > > And, my code resulted in no output/input (=> 0 points), which can be > > proved here too : > > > ==== > > azi at magicb0x ~ $ python la.py < /etc/passwd > > > === > > > Some friend of mine told me that's the Unix way, (stdout can act like > > stdin) so I tried some C code : > > > === > > 1 #include > > 2 > > 3 int main() { > > 4 char buf[120]; > > 5 while (fgets(buf, sizeof(buf), stdout) != NULL) { > > 6 puts(buf); > > 7 } > > 8 return 0; > > 9} > > === > > > The code returns with no delay, so I'm really wondering where is that > > nice sys.{stdin,stdout} feature inplemented as pydoc doesn't mention > > anything. I'd spot the mistake before submitting the problem solutions > > if it was written in C :) > > > Thanks! From dgdev3141 at yahoo.com Mon Apr 16 11:18:42 2007 From: dgdev3141 at yahoo.com (dgdev) Date: 16 Apr 2007 08:18:42 -0700 Subject: How to better pickle an extension type Message-ID: <1176736722.383507.37810@n59g2000hsh.googlegroups.com> I would like to pickle an extension type (written in pyrex). I have it working thus far by defining three methods: class C: # for pickling __getstate__(self): ... # make 'state_obj' return state_obj __reduce__(self): return C,(args,to,__init__),me.__getstate__() # for unpickling __setstate__(self,state_obj): self.x=state_obj.x ... This gets the class pickling and unpickling. However, I'd like to not specify arguments for __init__ (as I do now in __reduce__), and so not have __init__ invoked during unpickling. I would like to have the pickling machinery somehow create an uninitialized object, and then call its __setstate__, where I can re- create it from 'state_obj'. Is there a kosher way to do so, that is without me having to have a special mode in the constructor for when the object is being created by the unpickler? From ask at me Thu Apr 12 21:29:17 2007 From: ask at me (alf) Date: Thu, 12 Apr 2007 20:29:17 -0500 Subject: wx and SOAPpy interaction Message-ID: <7KSdndOfrr1uQYPbnZ2dnUVZ_vmqnZ2d@comcast.com> Hi, there is problem when I import (python 2.4) wx and SOAPpy at the same time. I narrowed the problem to following (on Linux): >>import wx >>import pyexpat Traceback (most recent call last): File "", line 1, in ? ImportError: /apps/public/python_2.4.4/lib/python2.4/lib-dynload/pyexpat.so: undefined symbol: XML_StopParser any insight? Andy From NikitaTheSpider at gmail.com Sun Apr 15 15:48:43 2007 From: NikitaTheSpider at gmail.com (Nikita the Spider) Date: Sun, 15 Apr 2007 15:48:43 -0400 Subject: Python Feature Request: (?) Group all file-directory-related stdlib functions in one place References: <1176546615.450418.268090@y5g2000hsa.googlegroups.com> <4620b4c9$0$14410$9b622d9e@news.freenet.de> Message-ID: In article <4620b4c9$0$14410$9b622d9e at news.freenet.de>, "Martin v. L?wis" wrote: > > Currently file-directory-related functionality in the Python standard > > library is scattered among various modules such as shutil, os, > > dircache etc. So I request that the functions be gathered and > > consolidated at one place. Some may need renaming to avoid conflicts > > or for clarification. > > > > Please see PEP 355. Thanks for bringing this to my attention; I was not aware of this PEP. The organization of the stdlib's file- and path-related functions gives me headaches so I'd like to see it change. But note that GvR has pronounced that PEP 355 is dead: http://mail.python.org/pipermail/python-dev/2006-September/069087.html -- Philip http://NikitaTheSpider.com/ Whole-site HTML validation, link checking and more From a-alpha at otenet.gr Sat Apr 14 17:33:58 2007 From: a-alpha at otenet.gr (A - J) Date: Sun, 15 Apr 2007 00:33:58 +0300 Subject: Willa Ford Angelina Joli Paris Hilton Message-ID: Willa Ford Angelina Joli Paris Hilton www.alphasearch.GR -------------- next part -------------- An HTML attachment was scrubbed... URL: From steven.bethard at gmail.com Tue Apr 10 10:35:56 2007 From: steven.bethard at gmail.com (Steven Bethard) Date: Tue, 10 Apr 2007 08:35:56 -0600 Subject: Why is __getslice__ still implemented? In-Reply-To: <87irc4wpxp.fsf@wilson.homeunix.com> References: <87irc4wpxp.fsf@wilson.homeunix.com> Message-ID: Torsten Bronger wrote: > Hall?chen! > > According to , > __getslice__ is deprecated. At the moment, I derive an own class > from unicode and want to implement my own slicing. I found that I > have to override __getslice__ since __getitem__ isn't called when I > have something like my_instance[a:b] in my code. > > According to > , this may > have efficiency reasons, however, I agree with > news:1102645919.114898.139820 at f14g2000cwb.googlegroups.com that this > is quite confusing. It forces people to implement a deprecated > function after all. I think the docs should say that you still have > to override __getslice__ when subclassing from a built-in type, > unless I really don't understand the issue correctly. Yes, you do still need to implement __getslice__ if you're subclassing a class (like unicode or list) which provides it. The __getslice__ method can't be removed entirely for backwards compatibility reasons (though it is being removed in Python 3000). If you have a specific suggestion for what doc should be updated and how, that would be helpful. Please post it to: http://sourceforge.net/tracker/?group_id=5470&atid=105470 (It doesn't need to be a real patch. Plain text is fine as long as you indicate where in the documentation it needs to go.) Steve From steve at holdenweb.com Thu Apr 5 09:14:25 2007 From: steve at holdenweb.com (Steve Holden) Date: Thu, 05 Apr 2007 09:14:25 -0400 Subject: operator overloading In-Reply-To: <1175726966.127531.273500@b75g2000hsg.googlegroups.com> References: <1175679412.741899.45990@l77g2000hsb.googlegroups.com> <1175711246.488717.262560@e65g2000hsc.googlegroups.com> <1175726966.127531.273500@b75g2000hsg.googlegroups.com> Message-ID: <4614F631.7060302@holdenweb.com> sjdevnull at yahoo.com wrote: > On Apr 4, 4:55 pm, "Terry Reedy" wrote: >> "Ziga Seilnacht" wrote in message >> >> news:1175711246.488717.262560 at e65g2000hsc.googlegroups.com... >> | This looks like a bug in Python. It works for all the other >> | operators: > [SNIP] >> | >>> i ** 3 >> | 74088 >> | >> | You should submit a bug report to the bug tracker: >> | >> |http://sourceforge.net/bugs/?group_id=5470 >> >> Nice test. I thought maybe __pow__ might be different in not having a >> reverse form, but indeed, int has an __rpow__ method. >> >> Before submitting, make sure that this does not work in 2.5, and then say >> so in the bug report. In fact, copy the version/system info that the >> interactive interpreter puts up when it starts. > > FWIW: > Python 2.5 (r25:51908, Jan 21 2007, 03:10:25) > [GCC 3.4.6 20060404 (Red Hat 3.4.6-3)] on HOSTNAME_REDACTED > Type "help", "copyright", "credits" or "license" for more information. >>>> class MyInt(int): > ... __pow__ = int.__add__ > ... >>>> i=MyInt(42) >>>> i**3 > 74088 > Interestingly, Jython doesn't suffer from this drawback, which I suspect is due to special-casing of the __pow__ operator that was discussed quite recently on python-dev without anybody noticing this aspect of things. C:\jython2.2b1>jython [...] >>> class S(int): ... pass ... >>> S.__pow__ = S.__add__ >>> s = S(12) >>> s ** 2 14 >>> Note that it still doesn't work to override the *instance's* method. 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 steven.bethard at gmail.com Tue Apr 24 14:41:18 2007 From: steven.bethard at gmail.com (Steven Bethard) Date: Tue, 24 Apr 2007 12:41:18 -0600 Subject: If Dict Contains a particular key In-Reply-To: References: <000001c78695$ed321540$c7963fc0$@rawlins@thinkbluemedia.co.uk> <1177436682.3441.15.camel@dot.uniqsys.com> Message-ID: Steven Howe wrote: > Carsten Haese wrote: >> On Tue, 2007-04-24 at 18:28 +0100, Robert Rawlins - Think Blue wrote: >> >>> Hello Guys, >>> >>> >>> >>> I?m Looking to build a quick if/else statement that checks a >>> dictionary for a key like follows. >>> >>> >>> >>> If myDict contains ThisKey: >>> >>> Do this... >>> >>> Else >>> >>> Do that... >>> >> >> I'm pretty sure you'll find the answer to this question somewhere in >> http://docs.python.org/tut/tut.html >> >> -Carsten >> >> >> > or try: > thedict = { 'a': 1, 'b':2, 'c':3 } > if 'a' in thedict.keys(): > print thedict['a'] Better yet, just: if 'a' in thedict: ... There's no need for the call to keys(). STeVe From ecir.hana at gmail.com Mon Apr 16 09:28:19 2007 From: ecir.hana at gmail.com (ecir.hana at gmail.com) Date: 16 Apr 2007 06:28:19 -0700 Subject: yield, curry, mix-in, new.function, global, closure, .... what will work? In-Reply-To: <7xbqhp6sdu.fsf@ruckus.brouhaha.com> References: <1176657848.944538.169780@p77g2000hsh.googlegroups.com> <7xy7ktmrzn.fsf@ruckus.brouhaha.com> <1176684145.537202.68090@p77g2000hsh.googlegroups.com> <7xbqhp6sdu.fsf@ruckus.brouhaha.com> Message-ID: <1176730099.467774.212440@q75g2000hsh.googlegroups.com> On Apr 16, 3:05 am, Paul Rubin wrote: > ecir.h... at gmail.com writes: > > > Please, can you elaborate further, I'm not sure if I understood. > > Should I lock global variables i, j during the execution of run()? In > > that case I have to apologize, I showed rather simplified version of > > the actual problem I have - in fact changer() and run() will be a bit > > more complex thus executing a bit longer and perhaps causing a dead-lock. > > Put both variables into one shared object with a lock (see the docs for > threading.RLock()). Acquire the lock before modifying or reading the > variables, and release it afterwards. That is the traditional way. Thanks for the reply! And at the same time, please bear with me. If I understand correctly: when one thread acquires the lock, every other thread has to wait. If so, this is not exacly what I would like to have since the thread might take a bit longer to finish. The reason why I try so hard to use local variables is that they are inherently thread-safe. So I don't even mind to copy changer() every time run() is called - run() has it's own local variables i, j, no one has to touch them except it's ("local") function changer(). But the problem is, I don't know how to propagate run()'s variables into changer() without declarating them as changer()'s arguments (it would be ok to append the declaration during run-time, though, if I only knew how). From __peter__ at web.de Mon Apr 16 03:07:18 2007 From: __peter__ at web.de (Peter Otten) Date: Mon, 16 Apr 2007 09:07:18 +0200 Subject: Queue enhancement suggestion References: <7x4pngluel.fsf_-_@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > I'd like to suggest adding a new operation > > Queue.finish() > > This puts a special sentinel object on the queue. The sentinel > travels through the queue like any other object, however, when > q.get() encounters the sentinel, it raises StopIteration instead > of returning the sentinel. It does not remove the sentinel from > the queue, so further calls to q.get also raise StopIteration. > That permits writing the typical "worker thread" as > > for item in iter(q.get): ... I'd go one step further and implement Queue.__iter__(). The worker than would do for item in q: ... > without having to mess with the task-counting stuff that recently got > added to the Queue module. The writing end of the queue simply > calls .finish() when it's done adding items. > > Someone in an earlier thread suggested > > # writing side > sentinel = object() > q.put(sentinel) > > ... > # reading side > for item in iter(q.get, sentinel): ... > > however that actually pops the sentinel, so if there are a lot of > readers then the writing side has to push a separate sentinel for > each reader. I find that argument convincing. Peter From troy.melhase at gmail.com Sat Apr 14 21:33:11 2007 From: troy.melhase at gmail.com (Troy Melhase) Date: Sat, 14 Apr 2007 17:33:11 -0800 Subject: function with list argument defaulting to [] - what's going on here??? In-Reply-To: <46217e8f$0$19437$4c368faf@roadrunner.com> References: <46217e8f$0$19437$4c368faf@roadrunner.com> Message-ID: On 4/14/07, Mike wrote: > While trying to write a recursive function involving lists, I came > across some (to me) odd behavior which I don't quite understand. Here's > a trivial function showing the problem. from http://docs.python.org/ref/function.html : Default parameter values are evaluated when the function definition is executed. This means that the expression is evaluated once, when the function is defined, and that that same ``pre-computed'' value is used for each call. This is especially important to understand when a default parameter is a mutable object, such as a list or a dictionary: if the function modifies the object (e.g. by appending an item to a list), the default value is in effect modified. From nagle at animats.com Thu Apr 5 20:55:38 2007 From: nagle at animats.com (John Nagle) Date: Thu, 05 Apr 2007 17:55:38 -0700 Subject: Why NOT only one class per file? In-Reply-To: <46154b8c$0$14532$426a34cc@news.free.fr> References: <1175721799.714907.52770@o5g2000hsb.googlegroups.com> <46142acc$0$7532$426a34cc@news.free.fr> <4614b40e$0$26843$426a74cc@news.free.fr> <1175778276.603838.86500@l77g2000hsb.googlegroups.com> <2O9Rh.24647$uo3.24013@newssvr14.news.prodigy.net> <46154b8c$0$14532$426a34cc@news.free.fr> Message-ID: Bruno Desthuilliers wrote: > John Nagle a ?crit : > >> Nate Finch wrote: > Having source code as text files may not be such a bad thing. Diffing, > grepping and versioning binary files is not that easy... There are tools for that sort of thing, although they're not well known in the open source world. Check out "http://www.alienbrain.com" and view the demo. Alienbrain is used for configuration management on major game development projects, where there are dozens of different types of "assets", from code to motion capture data to images to audio to video to 3D geometry. All the stuff programmers expect, like build management, version control, history, and differencing, are all there. But they're not limited to text files. I'm not suggesting this for Python, but it's interesting to consider that perhaps web development needs tools more like this. John Nagle From time.swift at gmail.com Fri Apr 6 18:34:37 2007 From: time.swift at gmail.com (ts-dev) Date: 6 Apr 2007 15:34:37 -0700 Subject: Hide the python-script from user In-Reply-To: <8ktie4-0i9.ln1@athlon.my> References: <8ktie4-0i9.ln1@athlon.my> Message-ID: <1175898877.869321.112310@w1g2000hsg.googlegroups.com> On Apr 6, 3:19 pm, hlubenow wrote: > recently there was a thread about hiding the python-script from the user. > The OP could use Interesting - thanks From bearophileHUGS at lycos.com Thu Apr 12 04:40:32 2007 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 12 Apr 2007 01:40:32 -0700 Subject: Newbie help with array handling In-Reply-To: <1176364734.439383.252930@o5g2000hsb.googlegroups.com> References: <1176364734.439383.252930@o5g2000hsb.googlegroups.com> Message-ID: <1176367232.252193.150460@n76g2000hsh.googlegroups.com> loial: > I am new to python and am converting an awk script to python It seems there are many people trying to convert awk code to Python :-) > I need to store some data in an array/table of some form > keyvalue1, value1, value2, value3 > keyvalue2, value1,value2, value3 > keyvalue3, value1,value2,value3 > etc > I will later need to sort in keyvalue order and also need to be able > to check if a key already exists The problem with multiple values is easy to manage, you just put them into a list: [value1, value2, value3] Such list can be used as the a value for a key:value pair inside a dict, etc. The problem is that Python doesn't have a built-in sorted dictionary data structure. So if you need it there are some solutions: 1) If you don't need to cheek presence often, and you don't need to remove many key:value pairs, then you can just use a list of lists like this (a Python list is an array of references dynamic on the right): data = [[keyvalue1, value1, value2, value3], [keyvalue2, value1,value2, value3], [keyvalue3, value1,value2,value3], ...] Then you can test the presence of a key with something like: key in (subl[0] for subl in data) Such list data can be sorted too according to the key (untested), if the keys are sortable objects: from operator itemgetter data.sort(key=itemgetter(0)) 2) If you need the dict characteristics a lot, then you may use a dict (but keys must be hashable objects): ddata = {keyvalue1:[value1, value2, value3], keyvalue2:[value1, value2, value3], ...} This allows quick presence testing, insertions and removals, but it can't be sorted according to the keys. So you may need to keep a sorted list of the keys: skeys = sorted(ddata) Then you can use skeys as you need, fetching the values from ddata if/ when you need them (note that there is a bisect standard module too that may help the management of a sorted list). But you have to keep the two structures updated at the same time, or re-create new skeys now and then... 3) If you want to be sure the two structures are always the same, then you may need to find an ordered dict class around (or you can write it yourself, but it may be too difficult for you), such implementation usually keep a dict and a list inside, and keep them in sync. You can probably use it as a normal dict, so its usage is rather clean and easy. Most of such implementations have a slow removal and add of items, because removing/adding them from the list requires time. If you need to perform many such operations on a lot of data, then there is a way to do that too, using a different implementation of ordered dict, you can start from this, that uses a double linked list structure, it's slow, but such time is costant (note that this keeps the order of the insertions, it doesn't sort keys according to their natural order, so you need to modify the code): http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/498195 Bye, bearophile From thorsten at thorstenkampe.de Mon Apr 2 11:05:25 2007 From: thorsten at thorstenkampe.de (Thorsten Kampe) Date: Mon, 2 Apr 2007 16:05:25 +0100 Subject: I18n issue with optik References: Message-ID: * Steven Bethard (Sun, 01 Apr 2007 10:21:40 -0600) > Thorsten Kampe wrote: > I'm not very experienced with internationalization, but if you change:: > > gettext.install('test') > > to:: > > gettext.install('test', unicode=True) > > what happens? Actually, this is the solution. But there's one more problem: the solution only works when the Terminal encoding is not US-ASCII. Unfortunately (almost) all terminals I tried are set to US-ASCII (rxvt under Cygwin, Console[1] running bash, Poderosa[2] running bash). Only the Windows Console is CP852 and this works. I got the tip to set a different encoding by sys.stdout = codecs.EncodedFile(sys.stdout, 'utf-8') but unfortunately this does not change the encoding of any Terminal. So my question is: how can I set a different encoding to sys.stdout (or why can I set it without any error but nothing changes?) Thorsten [1] http://sourceforge.net/project/screenshots.php?group_id=43764 [2] http://en.poderosa.org/present/about_poderosa.html From cginboston at hotmail.com Sat Apr 14 13:53:12 2007 From: cginboston at hotmail.com (Chaz Ginger) Date: Sat, 14 Apr 2007 17:53:12 GMT Subject: Minimal Linux system to run Python Message-ID: I have a need for the minimal Linux system to run Python. Basically I want the system to boot up and instead of starting up Init/etc. I would love it to run python (and a python script I have written). Before embarking on doing it myself I was wondering if anyone knew of just such a system? Peace, Chaz From fdemmer at gmail.com Wed Apr 18 06:36:52 2007 From: fdemmer at gmail.com (Florian Demmer) Date: 18 Apr 2007 03:36:52 -0700 Subject: 2.5 from source install problem with extensions Message-ID: <1176892612.378898.34580@e65g2000hsc.googlegroups.com> Hi! I am doing a from source installation of Python 2.5 on some old Debian machine. As the target directoy I want /opt/somename so i added it to the configure like so: ./configure --prefix=/opt/somedir The following make works fine as far as I can see. Then the make install also actually works and installs python in /opt/somedir with all its subdirectoris (bin, lib, man, include). The extensions (*.so) however get put in /usr/local/lib/... and there also in the wrong python directoy: 2.4 This is a c/p of the make install output: [...] running build_scripts running install_lib changing mode of /usr/local/lib/python2.4/site-packages/_struct.so to 755 changing mode of /usr/local/lib/python2.4/site-packages/_ctypes.so to 755 [...] (How) can I change the install_dir for the extensions? Why does it use python2.4 anyway?! What env var or else is set here that I cannot find? thanks! From jstroud at mbi.ucla.edu Tue Apr 10 16:40:54 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Tue, 10 Apr 2007 13:40:54 -0700 Subject: NLTK, Random Sentence Generators? In-Reply-To: <87k5wkcuv6.fsf@localhost.localdomain> References: <87slb8d3uj.fsf@localhost.localdomain> <3CJSh.7608$u03.3757@newssvr21.news.prodigy.net> <87k5wkcuv6.fsf@localhost.localdomain> Message-ID: Passer By wrote: > James Stroud writes: > > >>Passer By wrote: >> >> >>>Has any created or not of examples of random sentence generators >>>using n-gram models (or other models might be interesting). I >>>know of one example from a course at MIT, but besides that >>>nothing. Any help would be great. >>> >> >>Best is to just cull text from your spam folder as these are often >>generated by similar means--but somehow I think you knew that. >> > > > Emotive on Usenet? Thats original. > > Anonimity on usenet? That's suspiscious. From bbxx789_05ss at yahoo.com Mon Apr 23 18:38:10 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: 23 Apr 2007 15:38:10 -0700 Subject: Learning Python - First Project In-Reply-To: <1177367541.059834.18420@o5g2000hsb.googlegroups.com> References: <1177339942.371167.93970@b75g2000hsg.googlegroups.com> <1177352775.828143.9910@y5g2000hsa.googlegroups.com> <1177367105.564414.312320@y5g2000hsa.googlegroups.com> <1177367541.059834.18420@o5g2000hsb.googlegroups.com> Message-ID: <1177367890.088488.93290@l77g2000hsb.googlegroups.com> Uhhmm...how are you supposed to close a ShapedWindow(under Miscellaneous)? From apardon at forel.vub.ac.be Mon Apr 23 03:52:54 2007 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 23 Apr 2007 07:52:54 GMT Subject: Do other Python GUI toolkits require this? References: <1177014799.004875.262060@y80g2000hsf.googlegroups.com> Message-ID: On 2007-04-20, Dennis Lee Bieber wrote: > On 20 Apr 2007 12:25:40 GMT, Antoon Pardon > declaimed the following in comp.lang.python: > >> >> But if a wrong idea is circulating and nobody ever tries to correct it, >> people will continue with the wrong idea. All I did was make a simple >> remark, that as I suggested anyone could ignore, but that would allow >> those willing to learn, to further investigate. >> > But is it a "wrong idea" if 999 people interpret the phrase one way, > and just 1 insists upon an interpretation that, while correct in a small > technical area, results in misunderstanding when speaking with the other > 999? > > The lay person sees "productivity" as movement on the x-axis (I'm > "here" [start of job], I need to get "there" [end of job]). I dare you. Give some people some data: Like the productivity of each month in a year and ask them to put those numbers on a graph. I bet most will put the months on the x-axis and the productivity on the y-axis. -- Antoon Pardon From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Thu Apr 26 18:26:19 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Fri, 27 Apr 2007 00:26:19 +0200 Subject: Atribute error References: <1177620754.659481.66240@s33g2000prh.googlegroups.com> Message-ID: <59cn8bF2jtnobU1@mid.individual.net> gtb wrote: > In file Test1.py below I get a attribute error on the line > "self.logon()". Seems like the class doesn't have this attribute. > It worked earlier when Test1 was derived from > class newLogon but that does not seem logical to me. What's the definition of CompactTest? Regards, Bj?rn -- BOFH excuse #143: had to use hammer to free stuck disk drive heads. From apardon at forel.vub.ac.be Thu Apr 12 04:11:32 2007 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 12 Apr 2007 08:11:32 GMT Subject: tuples, index method, Python's design References: <1175953520.316208.241490@o5g2000hsb.googlegroups.com> <7xzm5igbrb.fsf@ruckus.brouhaha.com> <1176200361.260546.280510@n76g2000hsh.googlegroups.com> <740c3aec0704100824m132c45fbi5c4c3ec0c0fa3a67@mail.gmail.com> Message-ID: On 2007-04-11, Terry Reedy wrote: > > "BJrn Lindqvist" wrote in message > news:740c3aec0704100824m132c45fbi5c4c3ec0c0fa3a67 at mail.gmail.com... > On 4/10/07, Steve Holden wrote: >> One might perversely allow extension to lists and tuples to allow >> >> [3, 4] in [1, 2, 3, 4, 5, 6] >> >> to succeed, but that's forcing the use case beyond normal limits. > > I'd love to have that! There are at least one million use cases for > finding a sequence in a sequence and implementing it yourself is > non-trivial. Plus then both list and tuple's index methods would work > *exactly* like string's. It would be easier to document and more > useful. A big win. > >======================= > It would be ambiguous: [3,4] in [[1,2], [3,4], [5,6]] is True now. > > Strings are special in that s[i] can only be a (sub)string of length 1. > 'b' in 'abc' is True. This makes looking for longer substrings easy. > > However, [2] in [1,2,3] is False. IE, list[i] is not normally a list. So > looking for sublists is different from looking for items. Well I think this illustrates nicely what can happen if you design by use cases. Let us assume for a moment that finding out if one list is a sublist of a second list gets considered something usefull enough to be included in Python. Now the in operator can't be used for this because it would create ambiguities. So it would become either a new operator or a new method. But whatever the solution it would be different from the string solution. Now if someone would have thought about how "st1 in st2" would generalize to other sequemce if st1 contained more than one character they probably would have found the possible inconsistency that could create and though about using an other way than using the in-operator for this with strings. A way that wouldn't create ambiguities when it was considered to be extended to other sequences. -- Antoon Pardon From wgwigw at gmail.com Sat Apr 7 22:17:01 2007 From: wgwigw at gmail.com (momobear) Date: 7 Apr 2007 19:17:01 -0700 Subject: How to tell when a file is opened In-Reply-To: <1175970161.126550.257090@n59g2000hsh.googlegroups.com> References: <1175960486.759715.317140@y80g2000hsf.googlegroups.com> <1175970161.126550.257090@n59g2000hsh.googlegroups.com> Message-ID: <1175998621.538446.177880@y80g2000hsf.googlegroups.com> > Will look into NTFS change journals when I get some spare time. How can we get NTFS change journals? Is there any API for this purpose or we could implement our own? there're an api in windows help us montior file changes. win32file.ReadDirectoryChangesW From spamtrap at dot-app.org Thu Apr 5 17:55:07 2007 From: spamtrap at dot-app.org (Sherm Pendley) Date: Thu, 05 Apr 2007 17:55:07 -0400 Subject: Why NOT only one class per file? References: <1175721799.714907.52770@o5g2000hsb.googlegroups.com> <46142acc$0$7532$426a34cc@news.free.fr> <4614b40e$0$26843$426a74cc@news.free.fr> <1175778276.603838.86500@l77g2000hsb.googlegroups.com> <46150c0f$0$3184$426a74cc@news.free.fr> <1175801106.797489.85730@l77g2000hsb.googlegroups.com> Message-ID: "Nate Finch" writes: > As to the guy who writes 1000+ line classes .... dude, refactor some. > You're trying to make the class do too much, almost by definition. You haven't even seen my code, you don't even know what language it's in, but you're telling me it's wrong? Wow - and I thought *I* was arrogant. sherm-- -- Web Hosting by West Virginians, for West Virginians: http://wv-www.net Cocoa programming in Perl: http://camelbones.sourceforge.net From Michael.J.Fromberger at Clothing.Dartmouth.EDU Mon Apr 16 01:19:30 2007 From: Michael.J.Fromberger at Clothing.Dartmouth.EDU (Michael J. Fromberger) Date: Mon, 16 Apr 2007 01:19:30 -0400 Subject: How to initialize a table of months. References: Message-ID: In article , "Steven W. Orr" wrote: > I'm reading a logfile with a timestamp at the begging of each line, e.g., > > Mar 29 08:29:00 > > I want to call datetime.datetim() whose arg2 is a number between 1-12 so I > have to convert the month to an integer. > I wrote this, but I have a sneaky suspicion there's a better way to do it. > > mons = {'Jan':1, 'Feb':2, 'Mar':3, 'Apr':4, 'May':5, 'Jun':6, > 'Jul':7, 'Aug':8, 'Sep':9, 'Oct':10, 'Nov':11, 'Dec':12 } > > def mon2int( mon ): > global mons > return mons[mon] > > Is there a generator expression or a list comprehension thingy that would > be *betterer*? (I realize it's probably not that important but I find lots > of value in learning all the idioms.) There's no harm in your method as written, though it were probably wise to tolerate variations in capitalization. But if you want to be cute about it, you could write something like this to set up your table: from datetime import date months = dict((date(1900, x+1, 1).strftime('%b').lower(), x+1) for x in xrange(12)) def month2int(mName): return months[mName.lower()] If you don't like the lookup table, you can get a nicely portable result without it by using time.strptime(), e.g., import time def month2int(mName): return time.strptime(mName, '%b').tm_mon # parses "short" names Without knowing anything further about your needs, I would probably suggest the latter simply because it makes the hard work be somebody else's problem. Cheers, -M -- Michael J. Fromberger | Lecturer, Dept. of Computer Science http://www.dartmouth.edu/~sting/ | Dartmouth College, Hanover, NH, USA From aahz at pythoncraft.com Mon Apr 23 19:38:18 2007 From: aahz at pythoncraft.com (Aahz) Date: 23 Apr 2007 16:38:18 -0700 Subject: Namespaces/introspection: collecting sql strings for validation References: <1921780.hifcbgjtIO@beaureve.gmx.net> <1hwzkoo.118nt2f1htv72tN%aleax@mac.com> Message-ID: In article <1hwzkoo.118nt2f1htv72tN%aleax at mac.com>, Alex Martelli wrote: >Martin Drautzburg wrote: >> >> The problem is the first part: how can I lookup the callers module and >> the classobjs defined in there? Or finding any constant strings in the >> caller's module would also be just fine. Or is there a completely >> different way to do such a thing? > >Don't do black magic in production code. > >For just hacking around, see sys._getframe -- it can give you a frame >object from where you can introspect into your caller's globals -- and >the inspect module of the standard Python library. > >But don't put such black magic in production. The completely different >way is: just don't. Could you expand on that? After all, that's exactly what we do to implement a super() that works with classic classes -- and it's certainly production code. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "...string iteration isn't about treating strings as sequences of strings, it's about treating strings as sequences of characters. The fact that characters are also strings is the reason we have problems, but characters are strings for other good reasons." --Aahz From S.Mientki-nospam at mailbox.kun.nl Sat Apr 14 07:02:21 2007 From: S.Mientki-nospam at mailbox.kun.nl (Stef Mientki) Date: Sat, 14 Apr 2007 13:02:21 +0200 Subject: Double backslash in filepaths ? In-Reply-To: <87y7kvb5yv.fsf@pobox.com> References: <700ec$46209de2$d443bb3a$21603@news.speedlinq.nl> <87y7kvb5yv.fsf@pobox.com> Message-ID: John J. Lee wrote: > Stef Mientki writes: > >> It looks like sometimes a single backslash is replaced by a double backslash, >> but sometimes it's not ??? >> See the error message below, >> the first backslash is somewhere (not explicitly in my code) replaced, >> but the second is not ??? >> Is it in general better to use double backslash in filepaths ? > [...] >> IOError: [Errno 2] No such file or directory: 'D:\\data_to_test\test_global.pd' > > '\t' is the tab character. '\d' is not a valid escape sequence, so > the backslash there survives intact. repr() normalises the string on > output, so the (single!) backslash in '\d' is displayed, as always in > the repr of strings, as '\\'. > > You should either use this: > > 'D:\\data_to_test\\test_global.pd' > > > Or this: > > r'D:\data_to_test\test_global.pd' > > See also: > > http://www.python.org/doc/faq/general/#why-can-t-raw-strings-r-strings-end-with-a-backslash > > > Or even this, which will work unless you're using crufty software that > doesn't like slash path separators (cmd.exe being one of those pieces > of software): > > 'D:/data_to_test/test_global.pd' > > > John thanks John and Michael, this is a very helpful explanation. cheers, Stef From bearophileHUGS at lycos.com Wed Apr 4 04:52:55 2007 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 4 Apr 2007 01:52:55 -0700 Subject: Need help on reading line from file into list In-Reply-To: <4612c400$0$26325$426a74cc@news.free.fr> References: <1175630106.220186.107900@y66g2000hsf.googlegroups.com> <4612b8f2$0$28546$426a74cc@news.free.fr> <1175633434.823351.69800@q75g2000hsh.googlegroups.com> <4612c400$0$26325$426a74cc@news.free.fr> Message-ID: <1175676774.949776.278150@l77g2000hsb.googlegroups.com> Bruno Desthuilliers: > result = [line.strip() for line in f.readlines()] Probably better, lazily: result = [line.strip() for line in infile] Bye, bearophile From 12cc104 at gmail.com Sun Apr 22 19:20:29 2007 From: 12cc104 at gmail.com (proctor) Date: 22 Apr 2007 16:20:29 -0700 Subject: recursion depth problem In-Reply-To: <1177283144.316024.284000@y80g2000hsf.googlegroups.com> References: <1177267774.416169.276780@e65g2000hsc.googlegroups.com> <1177275314.846022.249000@e65g2000hsc.googlegroups.com> <1177276111.720137.315710@b75g2000hsg.googlegroups.com> <1177282027.798037.48210@o5g2000hsb.googlegroups.com> <1177283144.316024.284000@y80g2000hsf.googlegroups.com> Message-ID: <1177284029.000090.246580@q75g2000hsh.googlegroups.com> On Apr 22, 5:05 pm, tac-tics wrote: > Yes, you should use a for loop in this situation. > > Certain functional languages, such as Scheme and various LISP dialects > allow for what is called "tail recursion" which effectively eliminates > this problem by internally converting recursion to iteration. Python > isn't really cut out for heavy recursive work, and the "Pythonic" way > of doing things is through the lovely for loop. hi tac-tics, by using a for loop, do you mean in the same sense that the "xselections" function uses a for loop on the page: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/190465 ? or are you referring to a different technique for this? thanks for your help. i really appreciate it. proctor. From tkpmep at hotmail.com Wed Apr 18 20:32:36 2007 From: tkpmep at hotmail.com (tkpmep at hotmail.com) Date: 18 Apr 2007 17:32:36 -0700 Subject: Using the Python interpreter Message-ID: <1176942756.283173.234750@n76g2000hsh.googlegroups.com> Instead of starting IDLE as I normally do, I started the Python interpreter and tried to run a program. I got a Python prompt (>>>), and then tried unsuccessfully to run a Python script named Script1.py that runs perfectly well in IDLE. Here's what I did: >>>Script1.py Traceback (most recent call last): File "", line 1, in ? NameError: name Script1 is not defined >>>python Script1.py File "", line 1 python Script1.py SyntaxError: invalid syntax I can load it (and have it execute) by typing >>>import Script1 0 1 2 3 4 and if I edit it, I can then execute it by reloading it >>>import Script1 0 1 2 3 4 But this seems contrived - is there no way to repeatedly run Script1 from the interpreter without reloading it? Thomas Philips From bbxx789_05ss at yahoo.com Mon Apr 30 10:00:29 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: 30 Apr 2007 07:00:29 -0700 Subject: Restricting the alphabet of a string In-Reply-To: References: Message-ID: <1177941629.309093.97400@y5g2000hsa.googlegroups.com> On Apr 30, 5:53 am, "Nathan Harmston" wrote: > Hi, > > I ve being thinking about playing around with bit strings but use in > some encoding problems I m considering and was trying to decide how to > implement a bit string class. Is there a library out there for doing > basic things with bit strings already is my first question? > > I know that I can extend string to bit string, but is there anyway I > can force the alphabet to be restricted to 1's and 0's (or even 1, 0 > and -1, as an extension to from trinary strings). > > class Binary_String(String): > pass > > Many Thanks > > Nathan You could do something like this: class Binary_String(str): def __init__(self, val): i = 0 for char in val: if char not in "-101": raise ValueError("illegal character at index " + str(i) + "\nOnly -1,0,1 allowed.") i+=1 self.val = val b = Binary_String("1a0101") --output:-- Traceback (most recent call last): File "test1.py", line 13, in ? b = Binary_String("1a100") File "test1.py", line 6, in __init__ raise ValueError("illegal character at index " + str(i) ValueError: illegal character at index 1 Only -1,0,1 allowed. From tjreedy at udel.edu Wed Apr 11 15:42:39 2007 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 11 Apr 2007 15:42:39 -0400 Subject: Nested dictionaries trouble References: <1176317876.917874.58040@n59g2000hsh.googlegroups.com> Message-ID: "IamIan" wrote in message news:1176317876.917874.58040 at n59g2000hsh.googlegroups.com... | Hello, | | I'm writing a simple FTP log parser that sums file sizes as it runs. I | have a yearTotals dictionary with year keys and the monthTotals | dictionary as its values. The monthTotals dictionary has month keys | and file size values. The script works except the results are written | for all years, rather than just one year. I'm thinking there's an | error in the way I set my dictionaries up or reference them... | | import glob, traceback | | years = ["2005", "2006", "2007"] | months = ["01","02","03","04","05","06","07","08","09","10","11","12"] | # Create months dictionary to convert log values | logMonths = | {"Jan":"01","Feb":"02","Mar":"03","Apr":"04","May":"05","Jun":"06","Jul":"07","Aug":"08","Sep":"09","Oct":"10","Nov":"11","Dec":"12"} | # Create monthTotals dictionary with default 0 value | monthTotals = dict.fromkeys(months, 0) | # Nest monthTotals dictionary in yearTotals dictionary | yearTotals = {} | for year in years: | yearTotals.setdefault(year, monthTotals) try yearTotals.setdefault(year, dict.fromkeys(months, 0)) so you start with a separate subdict for each year instead of 1 for all. tjr From silverburgh.meryl at gmail.com Wed Apr 4 01:00:35 2007 From: silverburgh.meryl at gmail.com (silverburgh.meryl at gmail.com) Date: 3 Apr 2007 22:00:35 -0700 Subject: How can I time how much each thread takes? Message-ID: <1175662835.758899.13340@o5g2000hsb.googlegroups.com> Hi, I have the following code which spawn a number of thread and do something (in the run method of MyThread). how can I record how much time does EACH thread takes to complete the 'run'? for j in range(threadCount): t = MyThread(testNo) threads.append(t) t.start() testNo += 1 for t in threads: print "len = %d", len(threads) t.join() I have read example of timeit.Timer() funcion, but I don' t know how can i use it in a multiple thread program? Thank you for any help. From a.schmolck at gmail.com Wed Apr 4 11:46:37 2007 From: a.schmolck at gmail.com (Alexander Schmolck) Date: 04 Apr 2007 16:46:37 +0100 Subject: String manipulation References: <1175699768.427986.210310@l77g2000hsb.googlegroups.com> Message-ID: Alexander Schmolck writes: > That doesn't work. What about "kindest\nregard"? I think you're best of > reading the whole file in (don't forget to close the files, BTW). I should have written "that may not always work, depending of whether the set phrases you're interested in can also span lines". If in doubt, it's better to assume they can. 'as From sgeiger at ncee.net Thu Apr 12 14:37:23 2007 From: sgeiger at ncee.net (Shane Geiger) Date: Thu, 12 Apr 2007 13:37:23 -0500 Subject: Newbie help with array handling In-Reply-To: <180b672e0704120112v136b85e1t88be039ef742c15b@mail.gmail.com> References: <1176364734.439383.252930@o5g2000hsb.googlegroups.com> <180b672e0704120112v136b85e1t88be039ef742c15b@mail.gmail.com> Message-ID: <461E7C63.6030400@ncee.net> """ Since you are a beginner and since RCCILA (Runnable, Commented Code Is Least Ambiguous) I'm proving this example code to help you get used to manipulating data with python. This should give you an idea of how to juggle a bit. After you learn how to do this you likely still will not be juggling in the optimal way, but you will at least be able to manage your data. Not having an ordered dictionary causes beginners some grief because they haven't yet wrapped their minds around the way the basic data types work. (I don't recally understand why ordered dictionaries are not part of the standard library. It seems that this would be a commonly used feature.) However, UserDict is part of the standard library, and it can be used to create an ordered dict. Due to Python's attempt to be accessible to all people, I would think a little more support for an ordered dictionary would be in Python already. Nevertheless, beginners often stumble because they think they need an ordered dict when they really just need to learn to use various data types together. I think this covers the basics. If you can think of something not covered, let me know so I can add it to my examples. """ ## dictionary d1 = { 'keyvalue2':[ 'value21', 'value22', 'value23'], 'keyvalue3':[ 'value31', 'value32', 'value33'], 'keyvalue1':['value11', 'value12', 'value13'] } d2 = { 'keyvalue4':[ 'value41', 'value42', 'value43'], 'keyvalue6':[ 'value61', 'value62', 'value63'], } # merge the two dictionaries d1.update(d2) print d1.has_key('keyvalue3') # True # get the values of a dictionary key v1,v2,v3 = d1['keyvalue3'] print v1,v2,v3 # value31 value32 value33 # now they are combined print d1 # {'keyvalue4': ['value41', 'value42', 'value43'], 'keyvalue6': ['value61', 'value62', 'value63'], 'keyvalue1': ['value11', 'value12', 'value13'], 'keyvalue3': ['value31', 'value32', 'value33'], 'keyvalue2': ['value21', 'value22', 'value23']} # now they are a list of tuples myList = list( d1.items() ) print myList # [('keyvalue4', ['value41', 'value42', 'value43']), ('keyvalue6', ['value61', 'value62', 'value63']), ('keyvalue1', ['value11', 'value12', 'value13']), ('keyvalue3', ['value31', 'value32', 'value33']), ('keyvalue2', ['value21', 'value22', 'value23'])] myList.sort() # sorts on the first item in the tuple print myList # [('keyvalue1', ['value11', 'value12', 'value13']), ('keyvalue2', ['value21', 'value22', 'value23']), ('keyvalue3', ['value31', 'value32', 'value33']), ('keyvalue4', ['value41','value42', 'value43']), ('keyvalue6', ['value61', 'value62', 'value63'])] newDictionary = {} # loop through all the items in the list and create a dictionary for key, values in myList: newDictionary[key] = values print newDictionary # 'keyvalue4': ['value41', 'value42', 'value43'], 'keyvalue6': ['value61', 'value62', 'value63'], 'keyvalue1': ['value11', 'value12', 'value13'], 'keyvalue3': ['value31', 'value32', 'value33'], 'keyvalue2': ['value21', 'value22', 'value23']} > do something like this > {keyvalue1:[ value1, value2, value3],keyvalue2:[value1,value2, > value3],keyvalue3,:[value1,value2,value3]} > > On 12 Apr 2007 00:58:54 -0700, *loial* < admin at loial.co.uk > > wrote: > > I am new to python and am converting an awk script to python > > I need to store some data in an array/table of some form > > keyvalue1, value1, value2, value3 > keyvalue2, value1,value2, value3 > keyvalue3, value1,value2,value3 > etc > > I will later need to sort in keyvalue order and also need to be able > to check if a key already exists > > It is not clear how to do this in python. All the examples I see have > just a key and a single value > > -- > 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 -- 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 phil at riverbankcomputing.co.uk Thu Apr 12 05:48:46 2007 From: phil at riverbankcomputing.co.uk (Phil Thompson) Date: Thu, 12 Apr 2007 10:48:46 +0100 Subject: Pyqt programming question In-Reply-To: <1176369822.364743.243700@n76g2000hsh.googlegroups.com> References: <1176369822.364743.243700@n76g2000hsh.googlegroups.com> Message-ID: <200704121048.46781.phil@riverbankcomputing.co.uk> On Thursday 12 April 2007 10:23 am, Marcpp wrote: > I have a program (python + pyqt), with a button I'll would to open a > new dialog window to input text, when press save or ok, this text is > returned to the principal program. > I've seek in internet but i don't find anything. Use QInputDialog.getText() Phil From soyouthinkimgonnalikethis at hotmail.com Sat Apr 7 13:23:06 2007 From: soyouthinkimgonnalikethis at hotmail.com (Eric Price) Date: Sat, 07 Apr 2007 12:23:06 -0500 Subject: Can't Get Email Interface Working In-Reply-To: <9afea2ac0704070953o6a1b8abbjcce6b6789e809088@mail.gmail.com> Message-ID: >From: "Tim Williams" >To: "Eric Price" >CC: hlubenow2 at gmx.net, python-list at python.org >Subject: Re: Can't Get Email Interface Working >Date: Sat, 7 Apr 2007 17:53:28 +0100 > >On 07/04/07, Eric Price wrote: >>Good grief! And they call a 722-line program "simple"?! LOL! >>I did what I need to do with a __one_line_shell_script__ LOL! >>Naw, if I have to go through all that, I'll skip on python this time >>around, >>thank you very much! >>Eric > >Yup, its not so simple > >Your problem is : > >File "/usr/local/lib/python2.4/mimetools.py", line 130, in choose_boundary > hostid = socket.gethostbyname(socket.gethostname()) >socket.gaierror: (8, 'hostname nor servname provided, or not known') > >What do you get if you do the following in your interpreter? > > >>>>import socket >>>>socket.gethostname() >'twilliams' >>>>socket.gethostbyname(socket.gethostname()) >'194.129.107.254' >>>> >>>import socket >>>socket.gethostname() 'server312.example.com' >>>socket.gethostbyname(socket.gethostname()) Traceback (most recent call last): File "", line 1, in ? socket.gaierror: (8, 'hostname nor servname provided, or not known') >>> Obviously, I substituted "example.com" above; however, the host that comes back no longer exists, so it may as well be "example.com"! And the server # is courtesy of the server farm. In fact, the whole thing is. What do? TIA, Eric _________________________________________________________________ Can?t afford to quit your job? ? Earn your AS, BS, or MS degree online in 1 year. http://www.classesusa.com/clickcount.cfm?id=866145&goto=http%3A%2F%2Fwww.classesusa.com%2Ffeaturedschools%2Fonlinedegreesmp%2Fform-dyn1.html%3Fsplovr%3D866143 From bbxx789_05ss at yahoo.com Tue Apr 10 23:19:02 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: 10 Apr 2007 20:19:02 -0700 Subject: Does python have the static function member like C++ In-Reply-To: <1176260903.362329.59370@o5g2000hsb.googlegroups.com> References: <1176260903.362329.59370@o5g2000hsb.googlegroups.com> Message-ID: <1176261542.704649.240350@n76g2000hsh.googlegroups.com> On Apr 10, 9:08?pm, "???????????????" wrote: > I define the class like this: > class AAA: > ? ? counter = 0 > ? ? def __init__(self): > ? ? ? ? pass > ? ? def counter_increase(): > ? ? ? ? AAA.counter += 1 > ? ? ? ? print "couter now :", AAA.counter > > But how could I call the function "counter_incrrease" ? > > Thanks ! 1) class AAA: counter = 0 def __init__(self): pass @staticmethod def counter_increase(): AAA.counter += 1 print "couter now :", AAA.counter AAA.counter_increase() 2) class AAA: counter = 0 def __init__(self): pass def counter_increase(): AAA.counter += 1 print "couter now :", AAA.counter counter_increase = staticmethod(counter_increase) AAA.counter_increase() 3) class AAA: counter = 0 def __init__(self): pass def counter_increase(self): AAA.counter += 1 print "couter now :", AAA.counter aaa = AAA() AAA.counter_increase(aaa) From ebgssth at gmail.com Sun Apr 22 19:18:16 2007 From: ebgssth at gmail.com (js ) Date: Mon, 23 Apr 2007 08:18:16 +0900 Subject: file.read() returns an emtpy even if its currenet position is not at the end In-Reply-To: <1177278089.827367.18720@e65g2000hsc.googlegroups.com> References: <1177278089.827367.18720@e65g2000hsc.googlegroups.com> Message-ID: Thank you for reply. I've just found the bug report on this. http://sourceforge.net/tracker/index.php?func=detail&aid=1523853&group_id=5470&atid=105470 Nobody seems to be working on this, though. On 22 Apr 2007 14:41:29 -0700, Alberto Valverde wrote: > On Apr 22, 6:51 pm, "js " wrote: > > Hi list. > > > > I'm writing a tail -f like program in python > > and I found file.read() doesn't work as I think it should. > > > > Here's the code illustrating my problem. > > > > ### > > #!/usr/bin/env python > > import os, sys > > filename = "test.out" > > > > f = open(filename, "w+") > > f.write("Hello") > > f.flush() > > > > f.seek(0, 2) > > > > statinfo = os.stat(filename) > > print "file size: %d" % statinfo.st_size > > print "position : %d" % f.tell() > > line = f.read() > > print "line : [%s]" % line > > > > # Writing the same file using another fd > > f2 = open(filename, "a+") > > f2.write("World") > > f2.flush() > > f2.close() > > > > statinfo = os.stat(filename) > > print "file size: %d" % statinfo.st_size > > print "position : %d" % f.tell() > > line = f.read() # read() returns emtpy!! readlines?() works ok > > ### > > > > Running the above, I got the following. > > ### > > file size: 5 > > position : 5 > > line : [] > > file size: 10 > > position : 5 > > ### > > > > So my question is > > why the second f.read() returns an emtpy?>From tell() and its st_size I'm sure that file descriptor is not at the EOF > > > > and read()'s doc says > > "An empty string is returned when EOF is encountered immediately". > > Using readline() or readlines() instead of read() works great though. > > > > I'm using Python 2.4.3 on OS X. > > > > Probably I'm missing something but I could't figure out. > > > > Thanks in advance. > > I've hit into the same issue recently when implementing more or less > the same thing and found that doing f.seek(f.tell()) on the file > object when empty strings start to come out allows you to continue > read()ing after hitting EOF if the file grows again. > > I finally dropped the "hack" and used readline instead since it made > me a little bit uneasy though... > > Alberto > > -- > http://mail.python.org/mailman/listinfo/python-list > From cam.ac.uk at mh391.invalid Wed Apr 25 07:27:23 2007 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Wed, 25 Apr 2007 12:27:23 +0100 Subject: Coding conventions for class names In-Reply-To: References: <1177492705.232244.312520@c18g2000prb.googlegroups.com> Message-ID: Marc 'BlackJack' Rintsch wrote: > In <1177492705.232244.312520 at c18g2000prb.googlegroups.com>, Kay Schluehr > wrote: > >> set, int, float, list, object,... >> >> Don't see any of the basic types following the capitalized word >> convention for classes covered by PEP 08. This does not hold only for >> __builtins__ in the strict sense but also for types defined in builtin >> modules like datetime. > > Most built-ins are easy to explain: They were functions long before it > was possible to use them as base classes and stayed lowercase for > backwards compatibility. Don't know about `set` and `object`. I guess > it's foolish consistency!? Well originally there was sets.Set (uppercase). It became set when it went to being a built-in. -- Michael Hoffman From gagsl-py2 at yahoo.com.ar Thu Apr 12 00:58:03 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 12 Apr 2007 01:58:03 -0300 Subject: Strange Behavior with Old-Style classes and implicit __contains__ References: <1176334655.677943.70030@q75g2000hsh.googlegroups.com> Message-ID: En Thu, 12 Apr 2007 01:23:08 -0300, Steven D'Aprano escribi?: > On Thu, 12 Apr 2007 00:32:32 -0300, Gabriel Genellina wrote: > >> First I want to say that __getitem__ should raise IndexError, not >> KeyError, to indicate "not found" > > How do you know the Original Poster's class was meant to be a sequence > rather than a mapping? Ouch, no, sorry, disregard that comment. -- Gabriel Genellina From ZeeGeek at gmail.com Sun Apr 15 18:17:02 2007 From: ZeeGeek at gmail.com (ZeeGeek) Date: 15 Apr 2007 15:17:02 -0700 Subject: Standardizing XML In-Reply-To: <20070415201312.7b3dd2d7@localhost.localdomain> References: <1176625793.392269.24060@n59g2000hsh.googlegroups.com> <462215bc$1@griseus.its.uu.se> <1176660139.990518.239470@l77g2000hsb.googlegroups.com> <20070415201312.7b3dd2d7@localhost.localdomain> Message-ID: <1176675422.582118.129660@l77g2000hsb.googlegroups.com> On Apr 15, 1:13 pm, Jonathan Ballet wrote: > Le 15 Apr 2007 11:02:20 -0700, > "ZeeGeek" a ?crit : > > > Thanks for correcting me. I worded it inproperly. For example, in > > the code returned by Live Space, they use
instead of
so > > that Blogger will complain that this tag is not valid because it > > doesn't have a closing tag. Another example is that the contents of a > > lot of the tag attributes like "color" and "size" are not surrounded > > by quotes. > > Maybe you can try BeautifulSoup module which aims to handle things like > that :http://www.crummy.com/software/BeautifulSoup/ Wow, this tool is fantastic. Thank you very much. From steve at REMOVEME.cybersource.com.au Wed Apr 18 04:16:19 2007 From: steve at REMOVEME.cybersource.com.au (Steven D'Aprano) Date: Wed, 18 Apr 2007 18:16:19 +1000 Subject: What makes an iterator an iterator? References: <87hcrekw34.fsf@benfinney.id.au> Message-ID: On Wed, 18 Apr 2007 16:58:23 +1000, Ben Finney wrote: > Steven D'Aprano writes: > >> class Parrot(object): >> def __iter__(self): >> return self >> def __init__(self): >> self.next = self._next() >> def _next(self): >> for word in "Norwegian Blue's have beautiful plumage!".split(): >> yield word > > Clearly the problem is you've misused an apostrophe. Python doesn't > like the plural getting an apostrophe. > > I thought the rule wa's that any time you 'see an 'S, you put an apo'strophe before it. If that's wrong, 'shouldn't it rai'se an exception? -- 'Steven D'Aprano From hg at nospam.org Tue Apr 17 04:47:00 2007 From: hg at nospam.org (hg) Date: Tue, 17 Apr 2007 10:47:00 +0200 Subject: Syntax error References: <9w5Vh.8580$OT4.3503@newsfe19.lga> Message-ID: Marc 'BlackJack' Rintsch wrote: > In <9w5Vh.8580$OT4.3503 at newsfe19.lga>, hg wrote: > >> I had the customer comment out the first two lines of the file: >> >> """ >> #!/bin/env python >> # -*- coding: iso-8859-15 -*- >> """ >> >> ... and the problem disappeared. >> >> I am at a loss. >> >> Any clue ? > > There was once a bug in Python that lead to such "errors" if an encoding > comment was used. So your costumer might check his Python version and > maybe he should update. > > Ciao, > Marc 'BlackJack' Rintsch Thanks, The troubling part is that I package python in the release ... but I'll check anyway. hg From vaj at tempinbox.com Sat Apr 21 15:46:12 2007 From: vaj at tempinbox.com (Rico) Date: 21 Apr 2007 12:46:12 -0700 Subject: A simple photosharing application written in Python Message-ID: <1177184772.362630.51620@b75g2000hsg.googlegroups.com> I d like to show you http://www.morecute.com It has been awesome runs on Fedora I wanted to share it early on so there is litte load on the server and the early adopter crowd can try it out thanks Jerry From isaac.rodriguez at comcast.net Sun Apr 15 11:27:30 2007 From: isaac.rodriguez at comcast.net (Isaac Rodriguez) Date: 15 Apr 2007 08:27:30 -0700 Subject: Calling private base methods In-Reply-To: References: <1176374675.347453.89340@n76g2000hsh.googlegroups.com> <1176404325.211501.26610@w1g2000hsg.googlegroups.com> <1176435087.708516.66470@o5g2000hsb.googlegroups.com> Message-ID: <1176650850.211487.294690@y80g2000hsf.googlegroups.com> > The fact that I had > to resort to this trick is a big indication of course that genuinely > private members (as opposed to a 'keep off' naming convention) are a bad > idea in general. The fact that you had to resort to this trick is a big indication that the library you were using is bad designed; it has nothing to do with private members being a bad idea. You were using a library which interface was in-complete (provided that you "genuinely" really needed to access the private member to do what you wanted to do). Private members is a great thing. They are the foundations of encapsulation and object oriented design. The fact that Python allows you to access "private" methods because the only "restriction" is the name mangling does not mean you should access them and use them directly. I don't see the way private members are handled in Python a strenght or a weakness of the language as compared to other languages. However, I do see libraries that do not provide all the needed interface methods as poor designed, or programmers that try to work around the public interface of a class when it is not needed as poor programmers. Thanks, - Isaac. From kyosohma at gmail.com Wed Apr 11 11:55:19 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: 11 Apr 2007 08:55:19 -0700 Subject: UnicodeEncodeError - a bit out of my element... In-Reply-To: <1176304567.142673.69710@y5g2000hsa.googlegroups.com> References: <1176304567.142673.69710@y5g2000hsa.googlegroups.com> Message-ID: <1176306919.035730.235740@n59g2000hsh.googlegroups.com> On Apr 11, 10:16 am, "erikcw" wrote: > Hi all, > > I'm trying to parse an email message, but am running into this > exception. > > Traceback (most recent call last): > File "wa.py", line 336, in ? > main() > File "wa.py", line 332, in main > print out['msg'] > UnicodeEncodeError: 'ascii' codec can't encode character u'\xd6' in > position 238: ordinal not in range(128) > > How can I decode/encode this string to print to stdout and send again > in another email? Do I have to know what language the email is in? > > Thanks! > Erik You'll need to do some encoding/decoding work. Check out the following links on unicode: http://www.reportlab.com/i18n/python_unicode_tutorial.html http://www.amk.ca/python/howto/unicode http://www.jorendorff.com/articles/unicode/python.html And here's a few links on parsing: http://docs.python.org/api/arg-parsing.html http://www.diveintopython.org/xml_processing/unicode.html Probably more information than you need, but it should help answer your question (and maybe any future questions about Unicode). Mike From hlubenow2 at gmx.net Tue Apr 3 18:18:07 2007 From: hlubenow2 at gmx.net (hlubenow) Date: Wed, 04 Apr 2007 00:18:07 +0200 Subject: way to extract only the message from pop3 References: <1175628970.874615.127020@y80g2000hsf.googlegroups.com> <1175629538.022033.212460@e65g2000hsc.googlegroups.com> Message-ID: kyosohma at gmail.com wrote: > I found a tutorial on parsing email that should help you: > > http://www.devshed.com/c/a/Python/Python-Email-Libraries-SMTP-and-Email-Parsing/ > > Also see the email module: > > http://www.python.org/doc/2.3.5/lib/module-email.html > > Mike Well, I couldn't work with that stuff, especially with that tutorial, some time ago. It worked better, when I took a look at the code, user "rogen" wrote in his first posting here: http://www.python-forum.de/topic-7507.html It's really not beautiful code, but as soon as you understand, what he does, you're almost there. See You H. From http Mon Apr 16 02:12:34 2007 From: http (Paul Rubin) Date: 15 Apr 2007 23:12:34 -0700 Subject: Queue enhancement suggestion Message-ID: <7x4pngluel.fsf_-_@ruckus.brouhaha.com> I'd like to suggest adding a new operation Queue.finish() This puts a special sentinel object on the queue. The sentinel travels through the queue like any other object, however, when q.get() encounters the sentinel, it raises StopIteration instead of returning the sentinel. It does not remove the sentinel from the queue, so further calls to q.get also raise StopIteration. That permits writing the typical "worker thread" as for item in iter(q.get): ... without having to mess with the task-counting stuff that recently got added to the Queue module. The writing end of the queue simply calls .finish() when it's done adding items. Someone in an earlier thread suggested # writing side sentinel = object() q.put(sentinel) ... # reading side for item in iter(q.get, sentinel): ... however that actually pops the sentinel, so if there are a lot of readers then the writing side has to push a separate sentinel for each reader. I found my code cluttered with for i in xrange(number_of_worker_threads): q.put(sentinel) which certainly seems like a code smell to me. From kyosohma at gmail.com Wed Apr 18 10:09:29 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: 18 Apr 2007 07:09:29 -0700 Subject: Wanted: Email Client with GUI In-Reply-To: References: Message-ID: <1176905369.228287.224870@l77g2000hsb.googlegroups.com> On Apr 18, 8:07 am, Franz Steinhaeusler wrote: > Hi, although I have googled, I didn't find a Python > email client program fitting to my needs. > > What I want is a program (it doesn't have to be so sophisticated > as thunderbird) written totally in python and using a gui > toolkit like pyqt, pygtk, wxpyhton or tkinter. > > Who knows such a program? ;) > > best regards, I'm not finding much either. There is this: http://sourceforge.net/projects/usablemail/ This also looked promising: http://wiki.laptop.org/go/Email It looks like their might be some kind of tkinter email client in the Programming Python book by Lutz. ( See http://proquest.safaribooksonline.com/0596000855/python2-CHP-11-SECT-4 ) Hope that helps. Mike From arkanes at gmail.com Tue Apr 10 14:20:47 2007 From: arkanes at gmail.com (Chris Mellon) Date: Tue, 10 Apr 2007 13:20:47 -0500 Subject: Kill thread or at least socket.getaddrinfo In-Reply-To: <1176228471.940919.272470@l77g2000hsb.googlegroups.com> References: <1174925296.683942.279070@b75g2000hsg.googlegroups.com> <1176228471.940919.272470@l77g2000hsb.googlegroups.com> Message-ID: <4866bea60704101120i1e15853ah75c3e2bf5a2e019d@mail.gmail.com> On 10 Apr 2007 11:07:51 -0700, lobais at gmail.com wrote: > On 26 Mar., 18:08, kyoso... at gmail.com wrote: > > you know the pid, you can kill it, but that's not always a > > clean way of accomplishing the task. > > So I have to open the connection in a new process... Sigh.. How I hate > this part of Python. > This isn't a python problem. You can't cleanly or safely kill threads, period. If you have to use blocking functions like this (you don't, you might consider using Twisted for your networking instead) the way you "cancel" it is to just stop waiting for the response and discard the response (or error) when it eventually comes. > -- > http://mail.python.org/mailman/listinfo/python-list > From sjmachin at lexicon.net Fri Apr 20 18:21:56 2007 From: sjmachin at lexicon.net (John Machin) Date: 20 Apr 2007 15:21:56 -0700 Subject: Significance of "start" parameter to string method "endswith" In-Reply-To: References: <1177016236.700474.16170@n59g2000hsh.googlegroups.com> Message-ID: <1177107716.353954.223460@p77g2000hsh.googlegroups.com> On Apr 20, 9:12 am, Steven D'Aprano wrote: > On Thu, 19 Apr 2007 13:57:16 -0700, Boris Dusek wrote: > >> > what is the use-case of parameter "start" in string's "endswith" > >> > method? > > >> def foo(function,instance,param): > >> if function(instance,param,2,4): > >> return True > >> else: return False > > >> The function must work whether you pass it > >> foo(str.endswith,"blaahh","ahh"), or > >> foo(str.startswith,"blaahh","aah"). This is a really bad example, but > >> it gets the point across that similar functions must have similar > >> parameters in order to be Pythonic. > > > Thanks for explanation, this point makes sense. And I agree that I can > > hardly imagine any use of both parameters :-). > > No, sorry, it doesn't make sense because not all string methods take the > same arguments! See, for instance, ''.translate() and ''.lower(). > > The best reason for giving string methods and functions start and end > parameters is to avoid copying potentially large lumps of text. Here's a > silly example. Instead of doing this: > > while text: > p = text.find('parrot') > buffer = text[:p] > text = text[p:] > do_something_with(buffer) > > You can do this: > > p = 0 > while text: > p = text.find('parrot', p) > do_something_with(buffer, p) > > which avoids copying text unnecessarily. ... but increases the care and attention required when coding: (1) "while text"? "while 1" is a more obvious way of stress-testing your CPU fan :-) but perhaps you meant "while p >= 0". (2) 4s/buffer/text/ Cheers, John From michael at jedimindworks.com Tue Apr 24 08:17:10 2007 From: michael at jedimindworks.com (Michael Bentley) Date: Tue, 24 Apr 2007 07:17:10 -0500 Subject: Python Screen Scraper In-Reply-To: References: Message-ID: <958FD401-CC98-4A9D-876A-93EBE6D0FB77@jedimindworks.com> On Apr 24, 2007, at 11:50 AM, James Stroud wrote: > Hello, > > Does anyone know of an example, however modest, of a screenscraper > authored in python? I am using Firefox. > > Basically, I am answering problems via my browser and being scored for > each problem. I have a tendency to go past my peak for training > efficiency, so I would like to scrape the result page for each > problem I > answer, compile statistics, and have a program alert me when I should > stop (based on score and accuracy--assuming training value is > related to > changes in these metrics). > > I have no idea how to go about writing such a beast and I am hoping > that > I could get some pointers or an example that could get me going in the > right direction. > > Parsing, etc, is not a problem, but I'm not exactly sure how I might > interface python with Firefox, forwarding scraped pages to my browser > (or forwarding from the browser to the scraper). > > Thanks in advance for any help or advice. Possibly the easiest thing will be to read from firefox' cache. Otherwise I think your only real options are to either build a proxy or sniff the wire... From __peter__ at web.de Tue Apr 17 02:21:16 2007 From: __peter__ at web.de (Peter Otten) Date: Tue, 17 Apr 2007 08:21:16 +0200 Subject: multirember&co References: <1176768854.720234.23320@w1g2000hsg.googlegroups.com> Message-ID: bearophileHUGS at lycos.com wrote: > Once in while I too have something to ask. This is a little problem > that comes from a Scheme Book (I have left this thread because this > post contains too much Python code for a Scheme newsgroup): > For fun I have tried to make it lazy, if may be useful if seq is a > very long iterable. So I've used tee: > > from itertools import ifilter, tee > > def multiremberandco4(el, iseq, fun): > iseq1, iseq2 = tee(iseq) > iterable1 = ifilter(lambda x: x == el, iseq1) > iterable2 = ifilter(lambda x: x != el, iseq2) > return fun(iterable1, iterable2) > > def leniter(seq): > count = 0 > for el in seq: > count += 1 > return count > > idata = iter(data) > print multiremberandco4('a', idata, lambda l1,l2: (leniter(l1), > leniter(l2))) > > > But from the docs: >in general, if one iterator is going to use most > or all of the data before the other iterator, it is faster to use > list() instead of tee().< > > So I have tried to create two iterables for the fun function scanning > seq once only, but I haven't succed so far (to do it I have tried to > use two coroutines with the enhanced generators, sending el to one or > to the other according to the value of x == el, this time I don't show > my failed versions), do you have suggestions? I think the showstopper here is fun() which could either combine or operate indepently on both iterables, e. g.: def fun(a, b): return [a*b for a, b in zip(a, b)] def fun(a, b): return sum(a), sum(b) If you changed multirembrandtco() to accept two functions that are guaranteed to be independent and to consume all items from their iterable argument, you could run them in two threads and provide the iterable items via a Queue that would block fun1() until pending items for fun2() are processed. You'd rather cut your ear off? No, that would be multivangoghco()... Peter From bill.scherer at verizonwireless.com Mon Apr 2 15:58:00 2007 From: bill.scherer at verizonwireless.com (Bill Scherer) Date: Mon, 02 Apr 2007 15:58:00 -0400 Subject: How do you escape % when formatting a string? In-Reply-To: References: Message-ID: <46116048.6020001@verizonwireless.com> erikcw wrote: > Hi, > > I'm trying to format a string like so: > > string = "You have a 75% chance of success with %s, don't use %s" %(a, > b) > > This gives me: > TypeError: not enough arguments for format string > > I've tried 75\%, but that doesn't seem to help. What am I missing? > > Thanks! > Erik > > You escape % with %, of course: string = "You have a 75%% chance of success with %s, don't use %s" %(a, b) From jasper at albumltd.co.nz Mon Apr 23 06:34:33 2007 From: jasper at albumltd.co.nz (Jasper Bryant-Greene) Date: Mon, 23 Apr 2007 22:34:33 +1200 Subject: Offer of free dedicated servers for the Python project Message-ID: <1177324473.4494.6.camel@artemis.jbg.local> Hi All Please don't interpret this as spam or as a posting of a commercial nature. I am here to point out an opportunity for the Python project to receive some free hardware support. I'm not here to sell anything :) My company, DirectScale, is offering 10 free dedicated servers to open-source projects. This can be Python, or any project related to Python, or any project at all, as long as its deliverables are licensed under an OSI-approved open-source license. The only requirement is that someone responsible for the project contact us via our website (www.directscale.com) outlining what they would use the servers for. I encourage any project who could make good use of some free servers to get in touch, as this opportunity will not last. Thanks for your time. -- Jasper Bryant-Greene Album Limited From gandalf at designaproduct.biz Wed Apr 11 14:25:56 2007 From: gandalf at designaproduct.biz (Laszlo Nagy) Date: Wed, 11 Apr 2007 20:25:56 +0200 Subject: how to pickle objects for database storage? In-Reply-To: <461D2702.4000902@designaproduct.biz> References: <461D2702.4000902@designaproduct.biz> Message-ID: <461D2834.9040609@designaproduct.biz> Laszlo Nagy ?rta: > krishnakant Mane ?rta: > >> hello, >> I have a strange but very interesting requirement? >> provided that a database can provide for an object data type like >> binary large object (blob), can I store a pickeled python object in >> it? >> >> > Why not? > >> I know oracle has blob and clob and believe that mysql/ postgre sql >> has some thing similar to store direct objects? >> Hmm, this is what I left out: - There is also a 'bytea' type ("byte array") in Pg, but I haven't used it - I'm not sure about MySQL, but I bet it has a better blob field type. By the way, do you think you could use ZODB? http://www.zope.org/Products/StandaloneZODB Best, Laszlo From thn at mail.utexas.edu Tue Apr 24 12:32:36 2007 From: thn at mail.utexas.edu (Thomas Nelson) Date: 24 Apr 2007 09:32:36 -0700 Subject: feedback on Until recipe Message-ID: <1177432355.978749.318930@t39g2000prd.googlegroups.com> Occasionally people post complaining about the lack of a "repeat...until" structure in python. I thought about it and came up with this recipe that I like. The only ugly thing is having to use lambdas, otherwise it's very terse and readable. Tell me what you think, and if anyone besides me thinks they might use it, I'll post it to the python cookbook. Thanks for your time, Tom class Until: """ >>> i = 0 >>> while Until(lambda: i<3): ... print "hello" ... i += 1 hello hello hello >>> while Until(lambda: i<2): ... print "hello" hello """ yet = True def __init__(self, mybool): if self.__class__.yet or mybool(): self.__class__.yet = False self.ans = True else: self.__class__.yet = True self.ans = False def __nonzero__(self): return self.ans From crystalcss at gmail.com Sat Apr 28 02:12:48 2007 From: crystalcss at gmail.com (Rajesh) Date: 27 Apr 2007 23:12:48 -0700 Subject: Crystal Concepts offering PHP-MYSQL & JAVA/J2EE Message-ID: <1177740768.292458.263580@q75g2000hsh.googlegroups.com> Crystal Concepts offering PHP-MYSQL & JAVA/J2EE courses on short term basis. For details contact, 19/2 New No 182 Kaliamman Koil Street, Virugambakkam Chennai 600 092 mail: crystalcss at gmail.com Mobile: 98407-28150 From deets at nospam.web.de Tue Apr 24 16:19:53 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 24 Apr 2007 22:19:53 +0200 Subject: how to serialize a COM object ? In-Reply-To: <1177445437.543694.49070@r3g2000prh.googlegroups.com> References: <1177445437.543694.49070@r3g2000prh.googlegroups.com> Message-ID: <59773dF2j160eU2@mid.uni-berlin.de> vml schrieb: > I have a problem : > > I have a COM object. > > I would like to pass this com object from a server to a client through > a socket. > > I tried to put the com object into a stringIO with the pickle module > but : > > "can't pickle PyIDispatch objects" > > > Is there other possibilities to pass a COM object through a network ? > (pyro) This isn't possible. There is a special kind of COM, called DCOM. I'm a bit rusty on that, but you should try and use that. Alternatively, you could of course create a pyro-backed proxy, that will delegate all calls to itself to the COM-object. Diez From braindead at braindead.com Sat Apr 7 20:05:30 2007 From: braindead at braindead.com (enquiring mind) Date: Sun, 08 Apr 2007 00:05:30 GMT Subject: beginner - py unicode Q error Message-ID: <461831CC.251C3EF4@braindead.com> Sorry, I miscopied this line of code: print verbs[0:2] and not as posted print verbs[:3] From martin at v.loewis.de Mon Apr 23 01:26:28 2007 From: martin at v.loewis.de (=?ISO-8859-15?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Mon, 23 Apr 2007 07:26:28 +0200 Subject: python style guide inconsistencies In-Reply-To: References: <462BBE6F.9000007@v.loewis.de> Message-ID: <462C4384.4000601@v.loewis.de> > I have the impression that tradition will change in 3.0 and your preference > realized. > Wrong? or have you not been following? I have not been following, so this might be the case. Regards, Martin From bbxx789_05ss at yahoo.com Fri Apr 13 05:36:47 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: 13 Apr 2007 02:36:47 -0700 Subject: reading from sys.stdin In-Reply-To: References: <1176366058.261031.111870@p77g2000hsh.googlegroups.com> <1176387908.406115.270630@w1g2000hsg.googlegroups.com> <1176438754.995753.50190@d57g2000hsg.googlegroups.com> <1176454871.538968.176620@n76g2000hsh.googlegroups.com> Message-ID: <1176457007.589050.285400@d57g2000hsg.googlegroups.com> On Apr 13, 3:13 am, Michael Hoffman wrote: > 7stud wrote: > > I assume all input is buffered by default, so I'm not sure how it > > explains things to say that input from sys.stdin is buffered. > > The difference with sys.stdin is that it has indeterminate length until > you signal EOF. I believe you'd get the same problem reading from, say, > a named pipe. > Couldn't you say the same thing about a file you are iterating over? > >> I typed many lines, but lst contains only one item, as expected. Same as > >> your regular file example: the file contains many lines, but only the > >> first goes into the list. > > > Interesting example--not as I expected! But there is a difference in > > the two examples isn't there? When you iterate over a file, the whole > > file isn't put into an internal buffer first, is it? > > It is if the file is smaller than the buffer size. > How is that relevant? > >> This should be f = iter(raw_input,"") and this will end in a EOFError > >> and stop on blank line. So you need a wrapper > > > Why a wrapper? > > Because without a wrapper you'll get EOFError, while the file iterator > would ordinarily give you StopIteration. > Did you run my example? Did you get an error? I don't get an error. From b83503104 at yahoo.com Tue Apr 3 17:12:04 2007 From: b83503104 at yahoo.com (bahoo) Date: 3 Apr 2007 14:12:04 -0700 Subject: How to check if OS is unix or pc Message-ID: <1175634724.398396.48720@y80g2000hsf.googlegroups.com> In Matlab, there is a "isunix" command. Is there something similar in python? Thanks! bahoo From bbxx789_05ss at yahoo.com Sun Apr 15 15:51:12 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: 15 Apr 2007 12:51:12 -0700 Subject: reading from sys.stdin In-Reply-To: References: <1176366058.261031.111870@p77g2000hsh.googlegroups.com> <1176387908.406115.270630@w1g2000hsg.googlegroups.com> <1176438754.995753.50190@d57g2000hsg.googlegroups.com> <1176454871.538968.176620@n76g2000hsh.googlegroups.com> <1176457007.589050.285400@d57g2000hsg.googlegroups.com> <1176538930.891355.230880@n59g2000hsh.googlegroups.com> <1176577574.338733.325790@n59g2000hsh.googlegroups.com> Message-ID: <1176666672.619314.98640@d57g2000hsg.googlegroups.com> On Apr 15, 10:59 am, Steve Holden wrote: > 7stud wrote: > > On Apr 14, 7:43 am, Steve Holden wrote: > >> 7stud wrote: > >>> On Apr 13, 6:20 am, Michael Hoffman wrote: > >> [...] > > >>> But if you hit return on a blank line, there is no error. In other > >>> words, will stop on a blank line and not return EOFError. > >>> Anyway, it seems everyone is saying that when you iterate over a file, > >>> the whole file is first read into memory. Therefore iterating over > >>> sys.stdin is consistent: you have to type Ctrl+D to signal EOF before > >>> the iteration can start. Is that about right? > >> No. The file content is usually buffered, but the buffering doesn't > >> necessarily include the whole content of the file. > > >> If you are iterating over the file the correct way to access the next > >> line is to call the file's .next() method, as I indicated before. > > >> If you are reading lines the appropriate way is to use readline(). > > >> And, as you have already seen an error message telling you, mixing the > >> two types is unlikely to give you usable results. > > > Does iterating over stdin work the same way? If one were to type in > > enough lines to fill the buffer would iteration begin before entering > > EOF with Ctrl+D? > > Why don't you try it and tell me? That's what the interactive > interpreter is for. > > 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 just typed in 700 lines of text, and the iteration hasn't begun yet. Should I keep going? From tejovathi.p at gmail.com Mon Apr 9 09:22:32 2007 From: tejovathi.p at gmail.com (Teja) Date: 9 Apr 2007 06:22:32 -0700 Subject: Kill thread In-Reply-To: <1176124708.672830.244710@q75g2000hsh.googlegroups.com> References: <1176110066.940676.173020@e65g2000hsc.googlegroups.com> <1176124708.672830.244710@q75g2000hsh.googlegroups.com> Message-ID: <1176124952.921020.137530@w1g2000hsg.googlegroups.com> On Apr 9, 6:18 pm, "Christian" wrote: > On Apr 9, 5:14 am, "Teja" wrote: > > > Hi all, > > > Can any on help me out in killing a thread (i.e deleteing the reources > > like, stack ,memory etc) which is started with > > win32process.beginthreadex()??? > > > Rite now, I am suspending the thread. But any pointers as to how to > > delete the thread permanently? > > > Its pretty urgent... Please... > > > Teja.P > > Well, the answer with Python threads is that you don't kill them - you > ask them to go away. But since you are using something in the pywin32 > package, that rule might not apply. Perhaps you would have better > luck asking on the python-win32 list:http://mail.python.org/mailman/listinfo/python-win32 > > Christianhttp://www.dowski.com Can TASKKILL kill threads? For the TASKKILL command TASKKILL /F /PID 1234 , I gave thread id instead of PID.... It didnt throw any error. Does that mean that thread is really killed, releasing all its resources> How can I ensure that the thread is killed? From cam.ac.uk at mh391.invalid Wed Apr 18 18:42:48 2007 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Wed, 18 Apr 2007 23:42:48 +0100 Subject: comparison with None In-Reply-To: <1176935680.707717.53490@y5g2000hsa.googlegroups.com> References: <3IqdnfRnCNWPC7vbnZ2dnUVZ_jqdnZ2d@rcn.net> <1176935680.707717.53490@y5g2000hsa.googlegroups.com> Message-ID: brzrkr0 at gmail.com wrote: > On Apr 18, 3:19 pm, Steven Howe wrote: >> I've read and found that 'None' comparisons is not always a good idea. >> Better to: >> from types import NoneType >> >> x = None >> if type( x ) == NoneType: >> # true >> < code > >> else: >> # false; do something else. >> < more code > >> >> Steven Howe > > Is that any better than this? > > if x is None: > # do something > else: > # do something else To the contrary, it's not as good. "if x is None" is much clearer, and probably faster. -- Michael Hoffman From Leisure.206 at gmail.com Mon Apr 30 15:24:18 2007 From: Leisure.206 at gmail.com (Leisure.206 at gmail.com) Date: 30 Apr 2007 12:24:18 -0700 Subject: Online Mafia Kills 13 drive by shootings Message-ID: <1177961058.287915.37690@l77g2000hsb.googlegroups.com> http://duhmafia.blogspot.com/ - Does the online Mafia Exist? From robert.rawlins at thinkbluemedia.co.uk Fri Apr 20 04:51:42 2007 From: robert.rawlins at thinkbluemedia.co.uk (Robert Rawlins - Think Blue) Date: Fri, 20 Apr 2007 09:51:42 +0100 Subject: Byte-Array to String In-Reply-To: <46278FF4.9070505@gmail.com> References: <000f01c7828f$8b8ce770$a2a6b650$@rawlins@thinkbluemedia.co.uk> <46278FF4.9070505@gmail.com> Message-ID: <004d01c78329$1e5f7a60$5b1e6f20$@rawlins@thinkbluemedia.co.uk> Morning Steve, That stuff looks mighty promising, I did play around with the toString() function yesterday but couldn't get the damned thing working. The syntax has me a little muddled, perhaps you can help out on this by taking a look at my code. #!/usr/bin/python import dbus bus = dbus.SystemBus() obj = bus.get_object('org.bluez', '/org/bluez') obj = bus.get_object('org.bluez', '/org/bluez/hci0') adapter = dbus.Interface(obj, 'org.bluez.Adapter') # Search For Obex Push Protocol result = adapter.GetRemoteServiceHandles('00:17:B0:A0:E7:09', 'opp') result2 = adapter.GetRemoteServiceRecord('00:17:B0:A0:E7:09', result[0]) Now 'result2' is basically that byte array, Unfortunately the API doesn't give any more information other than that the function returns a array{byte} so I can't really shed any more light on that however if I can just get it to output all the elements from that array then I will know which one it is I'm looking for. I tried to implement your suggestions below as they look pretty safe, but I couldn't get it to work, my syntax is pretty confused as I'm so new to the language. Like I say, there is only one element of the array I'm interested in, I just need to see them all before I know which it is. Thanks again Steve, Rob From: Steven Howe [mailto:howe.steven at gmail.com] Sent: 19 April 2007 16:51 To: Robert Rawlins - Think Blue Cc: python-list at python.org Subject: Re: Byte-Array to String Robert Rawlins - Think Blue wrote: Hello Guys, I have a byte array passed to me by dbus and I'm looking to convert it into a string? Is that possible? Sorry for seeming like a putts with these questions, I'm not used to all these complex data types :-D The byte array looks something like this when printed to screen. dbus.Array([dbus.Byte(54), dbus.Byte(0), dbus.Byte(24), dbus.Byte(9), dbus.Byte(0), dbus.Byte(0), dbus.Byte(10), dbus.Byte(0), dbu s.Byte(0), dbus.Byte(0), dbus.Byte(0), dbus.Byte(9), dbus.Byte(0), dbus.Byte(1), dbus.Byte(53), dbus.Byte(3), dbus.Byte(25), dbus. Byte(16), dbus.Byte(0), dbus.Byte(9), dbus.Byte(2), dbus.Byte(0), dbus.Byte(53), dbus.Byte(3), dbus.Byte(9), dbus.Byte(1), dbus.By te(1)], signature=dbus.Signature('y')) Thanks again, Rob When reading about array, I wondered what the hell it was good for. Now I see. It's a tool to build objects to pass to the Operating System or other applications. Something like ctypes. The OS might store data from left to right, or right to left, or not use IEEE standards (which VMS certainly doesn't). So the data you give/get from the system call must be massaged by the application before it's usable. python/lib/module-array.html (5.14 array -- Efficient arrays of numeric values) array.tostring( ) Convert the array to an array of machine values and return the string representation (the same sequence of bytes that would be written to a file by the tofile() method.) I wonder if this is the method you are looking for. So you have an object dbus.Array, which, obviously is from a call to the dbus (another application's data) that contains 28 byte arrays. I would assume you know which you want, say the first one. myDbusString01 = dbus.Array[0].tostring() or to get the lot: myDbusStrings = [] #create a new empty list for array in dbus.Array: myDbusStrings.append( array.tostring() ) At this point you should have the array converted. But you will still need a reference as to what you have. The call to the dbus should have some documentation abut what it's returning. Also I'd expect the second example to be very bad programming, as some of the array elements are probably not going to be characters. They could be integers, floats or booleans. So creating a dictionary to handle specific array element handling is probably a better, less error prone, method of attack. Not have the contents and defination of your dbus.array handy, I can't test this, but the approach seems reasonable. Steven Howe -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at holdenweb.com Fri Apr 6 12:23:05 2007 From: steve at holdenweb.com (Steve Holden) Date: Fri, 06 Apr 2007 12:23:05 -0400 Subject: Python and Java In-Reply-To: <131cp2sk7h45g43@corp.supernews.com> References: <131araimq483n27@corp.supernews.com> <131cp2sk7h45g43@corp.supernews.com> Message-ID: Ed Jensen wrote: > Steve Holden wrote: >> Ed Jensen wrote: >>> Steve Holden wrote: >>>> Jython is an implementation of Python that compiles to Java bytecode, >>>> but at the moment there's some version lag so it won't handle the mos >>>> recent language enhancements. Probably worth a look, though. >>>> >>>> http://www.jython.org/ >>> Does Jython compile to Java bytecode, or is Jython a Java >>> implementation of a Python interpreter? >> Please read what I wrote again. > > I read it and understood it just fine. My question was meant more > along the lines of, "Are you SURE it compiles to Java bytecode, and > isn't a Python interpreter written in Java?" I guess I didn't make > that clear. > > Anyway, I checked the Jython home page, and sure enough, Jython > compiles Python code to Java bytecode, as stated in the FAQ which can > be found at the following URL (in case anyone else reading this > message is following along and is interested): > > http://www.jython.com/Project/userfaq.html#what-is-jython > > In particular: > > 1.1 What is Jython? > > Jython implements the Python programming language on the Java(tm) > Platform. It consists of a compiler to compile Python source code down > to Java bytecodes which can run directly on a JVM, a set of support > libraries which are used by the compiled Java bytecodes, and extra > support to make it trivial to use Java packages from within Jython. > > Sorry if I bothered/annoyed you, Steve. No real problem, I just thought I had already answered the question you asked. Of course the web reference was, as you'd expect, definitive, and your quoting it in this group will probably help those weho follow along. Glad it sounds like Jython might suit you - it's a great integration job! 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 pete.forman at westerngeco.com Fri Apr 20 12:36:08 2007 From: pete.forman at westerngeco.com (Pete Forman) Date: Fri, 20 Apr 2007 17:36:08 +0100 Subject: matplotlib basic question References: <1177016327.543985.34500@o5g2000hsb.googlegroups.com> Message-ID: orangeDinosaur writes: > [...] But now, the figure window is completely unresponsive -- I > can't even close it without getting the "your program is not > repsonding" business. What am I missing? This behavior so far > seems pretty unintuitive. The best way out of this is to use IPython. It also needs a backend which remains responsive, WxAgg works but Tk did not last time I tried. IPython 0.8.1 is a release candidate which fixes some Windows issues in 0.8.0. If you want a stable package that has all the parts present out of the box then look at Enthought. -- Pete Forman -./\.- Disclaimer: This post is originated WesternGeco -./\.- by myself and does not represent pete.forman at westerngeco.com -./\.- the opinion of Schlumberger or http://petef.port5.com -./\.- WesternGeco. From khemkaamit at gmail.com Thu Apr 5 08:22:55 2007 From: khemkaamit at gmail.com (Amit Khemka) Date: Thu, 5 Apr 2007 17:52:55 +0530 Subject: Storing of folder structure in SQL DB In-Reply-To: <1175774302.652656.285260@d57g2000hsg.googlegroups.com> References: <1175774302.652656.285260@d57g2000hsg.googlegroups.com> Message-ID: <1360b7230704050522h6dd82fedseef04ccd43c68adc@mail.gmail.com> On 5 Apr 2007 04:58:22 -0700, Sergei Minayev wrote: > Hi All! > Can you please help me with the following problem: > I need to store a copy of local folders structure in MySQL database. > I have chosen the following table structure for that: > ------------------------------------------------ > | id | id_uplink | folder_name | > ------------------------------------------------ > id - unique property of each folder. > id_uplink - id of upper level folder is stored here (for example: if > id of c:\test is 1, than id_uplink of c:\test\python equals 1). > folder_name - name of folder. > You see, i dont want to store the path list, but the structure. > > The question is how to implement that in Python. I easily made it in C+ > + using recursion. But, unfortunately, I can't figure it out how to > make it in python using os.walk function (or can you recommend smth. > else???). :( Though it looks quite simple, but anyway. > > Best Regards, os.walk should be more than sufficient in your case. You can navigate the directory structure and at each 'new' directory find its parents id and assign a new-id to this 'new' directory. An Example: import os root='/my/root/directory' id =0 tree={root:(-1, id)} id+=1 for path, dirs, files in os.walk(root): for dir in dirs: if not tree.has_key(path+'/'+dir): tree[path+'/'+dir]=(tree[path][1], id) id+=1 It stores ids as a tuple (parent_id, id) in a dictionary(tree). Should be straight forward to modify to your requirements. Also you can make the following code more efficient by saving/caching some lookups ! 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 hg at nospam.org Thu Apr 26 07:50:40 2007 From: hg at nospam.org (hg) Date: Thu, 26 Apr 2007 13:50:40 +0200 Subject: Which are your favorite UML tools? References: Message-ID: Anastasios Hatzis wrote: > Hello, > > I'm working on the light-weight MDA tool pyswarm, > http://pyswarm.sourceforge.net/ (it is about a code-generator for > Python/PostgreSQL-based software. I plan to add support of UML CASE tools > other than the one supported currently. > > I would like to learn which UML tools you use (if any), preferrably if it > comes to modeling a Python application. So I'm asking you to tell me the > name of your favorite UML CASE tool(s). > > Please also provide the version of the tool you use (and perhaps also the > URL of the project/vendor). If this is not of general interest for this > list you can also reply directly to my email address. > > Thank you in advance. > > Best regards > Anastasios umbrello seems to finally have python import support .... hg From rockym.z at gmail.com Mon Apr 2 00:53:13 2007 From: rockym.z at gmail.com (Rocky Zhou) Date: 1 Apr 2007 21:53:13 -0700 Subject: python unzip: os.popen3("unzip ...") or import zipfile? Message-ID: <1175489593.805787.303890@d57g2000hsg.googlegroups.com> python unzip At first, I tried to use 'os.popen3("unzip ...") like this: fin, fout, ferr = os.popen3("unzip -o -d %s %s" % (dest, zipfile)) strerr = ferr.read() # This makes the program hanging up if strerr: print >> sys.stderr, strerr outlog.error(strerr) I want to know is this caused by the 'unzip' command does not print 'EOF'? or any other reasons? At last I did this to do 'unzip': import zipfile def _extract_all(self, destdir): namelist = self.namelist() namelist.sort() for name in namelist: if name.endswith('/'): print name os.mkdir(os.path.join(destdir, name)) else: outfile = open(os.path.join(destdir, name), 'wb') outfile.write(self.read(name)) outfile.close() zipfile.ZipFile.extract_all = _extract_all def unzip(...): zipo = zipfile.ZipFile(zipfn, 'r') zipo.extract_all(dest) But I still want to know the reason why can't os.popen3("unzip ...") be used. Thanks. From ben.newsam.remove.this at gmail.com Sat Apr 28 13:14:22 2007 From: ben.newsam.remove.this at gmail.com (Ben newsam) Date: Sat, 28 Apr 2007 18:14:22 +0100 Subject: Video: Professor of Physics Phd at Cal Tech says: 911 Inside Job References: <1177467203.719625.93920@u32g2000prd.googlegroups.com> <1177778159.628459.270060@c35g2000hsg.googlegroups.com> Message-ID: <470733pv7d4c06pjhnco0h48dkb6rrcbqs@4ax.com> On 28 Apr 2007 09:35:59 -0700, War Office <911falseflag at gmail.com> wrote: >(God's law whom gave you >and God's children whom's mass murder in Iraq you have allowed)? Hi Dennis! From spradml at gmail.com Thu Apr 26 13:34:18 2007 From: spradml at gmail.com (Pradnyesh Sawant) Date: Thu, 26 Apr 2007 23:04:18 +0530 Subject: passing tuple with pyqt4 signal/slot mechanism Message-ID: <80628d680704261034u2632a1ackb9b40cf4175a1fd2@mail.gmail.com> > > Also, in the modified code, why aint the method setLabel getting called? > > Works for me, Does the "setLabel" method get called in your case? In your previous reply, you mentioned that it doesn't. Can you tell me the reason why? > and I still don't know what versions you are using and on > which > platform. Whatever they are, try the latest release. Python 2.4.4c1 (#2, Oct 11 2006, 21:51:02) [GCC 4.1.2 20060928 (prerelease) (Ubuntu 4.1.1-13ubuntu5)] on linux2 -- warm regards, Pradnyesh Sawant -- Be yourself, everyone else is taken. --Anon From cam.ac.uk at mh391.invalid Tue Apr 24 18:29:48 2007 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Tue, 24 Apr 2007 23:29:48 +0100 Subject: os.system('tar -c * | tar -C dst') ##Any other suggestions... In-Reply-To: <1177448277.150142.146130@c18g2000prb.googlegroups.com> References: <1177448277.150142.146130@c18g2000prb.googlegroups.com> Message-ID: list.repository at gmail.com wrote: > I'm getting the following error: > > tar: You must specify one of the `-Acdtrux' options > Try `tar --help' or `tar --usage' for more information. > tar: -: Cannot write: Broken pipe > tar: Error is not recoverable: exiting now > > Any suggestions on a different approach or fix? What do you want to do? What do you think that is supposed to do? What does this have to do with Python? -- Michael Hoffman From steve at holdenweb.com Mon Apr 2 10:19:29 2007 From: steve at holdenweb.com (Steve Holden) Date: Mon, 02 Apr 2007 10:19:29 -0400 Subject: YouTube showing repr() of a tuple In-Reply-To: <460bc895$0$30091$4d3efbfe@news.sover.net> References: <460b9f48$0$30100$4d3efbfe@news.sover.net> <460bc895$0$30091$4d3efbfe@news.sover.net> Message-ID: Leif K-Brooks wrote: > Leif K-Brooks wrote: >> Thought this might amuse some of you: >> >> > > Better example: > > Both fixed by the time I managed to follow the links. 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 12cc104 at gmail.com Sun Apr 22 14:49:34 2007 From: 12cc104 at gmail.com (proctor) Date: 22 Apr 2007 11:49:34 -0700 Subject: recursion depth problem Message-ID: <1177267774.416169.276780@e65g2000hsc.googlegroups.com> hello, i have a small function which mimics binary counting. it runs fine as long as the input is not too long, but if i give it input longer than 8 characters it gives RuntimeError: maximum recursion depth exceeded in cmp i'm not too sure what i am doing improperly. is there really a lot of recursion in this code? ================== import sys def ch4(item, n=0): if n < len(item): if item[n] == '0': item[n] = '1' print ''.join(item) ch4(item) elif item[n] == '1': item[n] = '0' ch4(item, n+1) ch4(list(sys.argv[1])) ================== this function expects input in the form of a string of zeros, like this: python test-bin.py 00000000 and is expected to output a list of permutations like this: $ python test-bin.py 0000 1000 0100 1100 0010 1010 0110 1110 0001 1001 0101 1101 0011 1011 0111 1111 thanks for all help! sincerely, proctor From bbxx789_05ss at yahoo.com Thu Apr 19 20:51:30 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: 19 Apr 2007 17:51:30 -0700 Subject: wxPython and how to return text entry to main program? In-Reply-To: <1177011490.435609.155870@o5g2000hsb.googlegroups.com> References: <1177011490.435609.155870@o5g2000hsb.googlegroups.com> Message-ID: <1177030290.529322.56210@p77g2000hsh.googlegroups.com> On Apr 19, 1:38 pm, Tyler wrote: > Hello All: > > I am currently working on a project to create an FEM model for school. > I was thinking about using wxPython to gather the 12 input variables > from the user, then, after pressing the "Run" button, the GUI would > close, and the 12 input variables would then be available for the rest > of the program. > > So far, what I have been able to do is mostly a reverse engineering > job to get the frame to look right and return the text variable to a > dialog box. > > I have read about a "redirect" that could be used to send the values > to a file. But, then I would have to open the file and read in the > data from there. This seems crude and lacking elegance. > > Any help on how to get the program to output the data back to the main > python program and close when I press submit? My apologies if this is > something of a simple question, but I have only started in on wxPython > about a week ago, and Python this term. > > The codes I am using are below. > > Any help (or suggested reading material) is greatly appreciated. > > Cheers, > > t. > > MY MAIN PROGRAM > > #!/usr/bin/env python > import femGUI > app = femGUI.MyApp(False) > dlg = femGUI.FemInput() > dlg.Destroy() > app.MainLoop() > > # Then do something with inputs here.... > > THE FEMINPUT GUI CLASS > > import wx > > class FemInput(wx.Frame): > def __init__(self): > wx.Frame.__init__(self, None, -1, "Options Input Interface") > panel = wx.Panel(self) > > # First create the controls > > # Title > topLbl = wx.StaticText(panel, -1, "FEM 2D Basket Put Option > ",size=(420,-1)) > topLbl.SetFont(wx.Font(18, wx.SWISS, wx.NORMAL, wx.BOLD)) > > # S1 lower and upper bounds for grid > s1label = wx.StaticText(panel, -1, "S1 Low , S2 Low: ", > size=(220,-1)) > self.s1lower = wx.TextCtrl(panel, -1, "", size=(100,-1)); > self.s2lower = wx.TextCtrl(panel, -1, "", size=(100,-1)); > > # S2 lower and upper bounds for grid > s2label = wx.StaticText(panel, -1, "S1 High, S2 High: ", > size=(220,-1)) > self.s1upper = wx.TextCtrl(panel, -1, "", size=(100,-1)); > self.s2upper = wx.TextCtrl(panel, -1, "", size=(100,-1)); > > # S1 and S2 volatility > vlabel = wx.StaticText(panel, -1, "S1 Volatility, S2 > Volatility: ", size=(220,-1)) > self.v1vol = wx.TextCtrl(panel, -1, "", size=(100,-1)); > self.v2vol = wx.TextCtrl(panel, -1, "", size=(100,-1)); > > # Risk free rate and correlation > prlabel = wx.StaticText(panel, -1, "Interest Rate, > Correlation: ", size=(220,-1)) > self.risk = wx.TextCtrl(panel, -1, "", size=(100,-1)); > self.corr = wx.TextCtrl(panel, -1, "", size=(100,-1)); > > # Strike and Exercise Date > kTlabel = wx.StaticText(panel, -1, "Srike Price, Exercise > Date: ", size=(220,-1)) > self.strike = wx.TextCtrl(panel, -1, "", size=(100,-1)); > self.finalT = wx.TextCtrl(panel, -1, "", size=(100,-1)); > > # deltaT and deltaX > dTXlabel = wx.StaticText(panel, -1, "delta T, delta X: ", > size=(220,-1)) > self.deltaT = wx.TextCtrl(panel, -1, "", size=(100,-1)); > self.deltaX = wx.TextCtrl(panel, -1, "", size=(100,-1)); > > # Execute program > runBtn = wx.Button(panel, -1, "Run") > self.Bind(wx.EVT_BUTTON, self.OnSubmit, runBtn) > > # Now do the layout. > > # mainSizer is the top-level one that manages everything > mainSizer = wx.BoxSizer(wx.VERTICAL) > mainSizer.Add(topLbl, 0, wx.ALL, 5) > mainSizer.Add(wx.StaticLine(panel), 0, > wx.EXPAND|wx.TOP|wx.BOTTOM, 5) > > # femSizer is a grid that holds all of the address info > femSizer = wx.FlexGridSizer(cols=2, hgap=5, vgap=5) > femSizer.AddGrowableCol(1) > > # S1 and S2 LOWER label > femSizer.Add(s1label, 0, > wx.ALIGN_RIGHT|wx.ALIGN_CENTER_VERTICAL) > # the lower and upper S1 bounds are in a sub-sizer > s1Sizer = wx.BoxSizer(wx.HORIZONTAL) > s1Sizer.Add(self.s1lower, 1) > s1Sizer.Add((10,10)) # some empty space > s1Sizer.Add(self.s2lower, 1, wx.LEFT|wx.RIGHT, 5) > femSizer.Add(s1Sizer, 1, wx.EXPAND) > > # S1 and S2 HIGH label > femSizer.Add(s2label, 0, > wx.ALIGN_RIGHT|wx.ALIGN_CENTER_VERTICAL) > # the lower and upper S1 bounds are in a sub-sizer > s2Sizer = wx.BoxSizer(wx.HORIZONTAL) > s2Sizer.Add(self.s1upper, 1) > s2Sizer.Add((10,10)) # some empty space > s2Sizer.Add(self.s2upper, 1, wx.LEFT|wx.RIGHT, 5) > femSizer.Add(s2Sizer, 1, wx.EXPAND) > > # Volatility label > femSizer.Add(vlabel, 0, > wx.ALIGN_RIGHT|wx.ALIGN_CENTER_VERTICAL) > # the lower and upper S1 bounds are in a sub-sizer > volSizer = wx.BoxSizer(wx.HORIZONTAL) > volSizer.Add(self.v1vol, 1) > volSizer.Add((10,10)) # some empty space > volSizer.Add(self.v2vol, 1, wx.LEFT|wx.RIGHT, 5) > femSizer.Add(volSizer, 1, wx.EXPAND) > > # Risk free Rate and corelation > femSizer.Add(prlabel, 0, > wx.ALIGN_RIGHT|wx.ALIGN_CENTER_VERTICAL) > # the lower and upper S1 bounds are in a sub-sizer > rcSizer = wx.BoxSizer(wx.HORIZONTAL) > rcSizer.Add(self.risk, 1) > rcSizer.Add((10,10)) # some empty space > rcSizer.Add(self.corr, 1, wx.LEFT|wx.RIGHT, 5) > femSizer.Add(rcSizer, 1, wx.EXPAND) > > # Strike and Exercise Date > femSizer.Add(kTlabel, 0, > wx.ALIGN_RIGHT|wx.ALIGN_CENTER_VERTICAL) > # the lower and upper S1 bounds are in a sub-sizer > ktSizer = wx.BoxSizer(wx.HORIZONTAL) > ktSizer.Add(self.strike, 1) > ktSizer.Add((10,10)) # some empty space > ktSizer.Add(self.finalT, 1, wx.LEFT|wx.RIGHT, 5) > femSizer.Add(ktSizer, 1, wx.EXPAND) > > # deltaT and deltaX > femSizer.Add(dTXlabel, 0, > wx.ALIGN_RIGHT|wx.ALIGN_CENTER_VERTICAL) > # the lower and upper S1 bounds are in a sub-sizer > dtxSizer = wx.BoxSizer(wx.HORIZONTAL) > dtxSizer.Add(self.deltaT, 1) > dtxSizer.Add((10,10)) # some empty space > dtxSizer.Add(self.deltaX, 1, wx.LEFT|wx.RIGHT, 5) > femSizer.Add(dtxSizer, 1, wx.EXPAND) > > # now add the femSizer to the mainSizer > mainSizer.Add(femSizer, 0, wx.EXPAND|wx.ALL, 10) > > # The buttons sizer will put them in a row with resizeable > # gaps between and on either side of the buttons > btnSizer = wx.BoxSizer(wx.HORIZONTAL) > btnSizer.Add((10,10)) # some empty space > btnSizer.Add(runBtn) > btnSizer.Add((10,10)) # some empty space > mainSizer.Add(btnSizer, 0, wx.EXPAND|wx.BOTTOM, 10) > > panel.SetSizer(mainSizer) > > # Fit the frame to the needs of the sizer. The frame will > # automatically resize the panel as needed. Also prevent the > # frame from getting smaller than this size. > mainSizer.Fit(self) > mainSizer.SetSizeHints(self) > > def OnSubmit(self, evt): > s1low = self.s1lower.GetValue() > s2low = self.s2lower.GetValue() > s1high = self.s1upper.GetValue() > s2high = self.s2upper.GetValue() > s1vol = self.v1vol.GetValue() > s2vol = self.v2vol.GetValue() > irate = self.risk.GetValue() > pcorr = self.corr.GetValue() > kprice = self.strike.GetValue() > totalT = self.finalT.GetValue() > delT = self.deltaT.GetValue() > delX = self.deltaX.GetValue() > wx.MessageBox('You chose: \n %s \n %s \n %s \n %s \ > \n %s \n %s \n %s' % > (s1low,s2low,s1high,s2high,s1vol,s2vol,irate)) > # I want to do something like this below.... > # return s1low,s2low,s1high,s2high,s1vol,s2vol,irate > > class MyApp(wx.App): > > def OnInit(self): > frame = FemInput() > self.SetTopWindow(frame) > frame.Show() > return True > > # Needed if called as a module > if __name__ == '__main__': > app = MyApp(False) > app.MainLoop() You can do this: --- class MyFrame(wx.Frame): .. .. .. def OnSubmit(self, event): globals()["userInput"] = self.txtCtrlName.GetValue() self.Close() app = MyApp() app.MainLoop() print userInput ----- From ask at me Thu Apr 12 22:35:28 2007 From: ask at me (alf) Date: Thu, 12 Apr 2007 21:35:28 -0500 Subject: where to report bug/get help for wxpython Message-ID: Hi, I have another problem with wxpython - that is the best place to report bug - evident memory leak on Linux and win32. -- alf From gigs at hi.t-com.hr Wed Apr 25 18:12:32 2007 From: gigs at hi.t-com.hr (Gigs_) Date: Thu, 26 Apr 2007 00:12:32 +0200 Subject: tkinter listbox In-Reply-To: References: Message-ID: I have two listbox on frame, and at same time i need to use one option from both listbox. But when I click on first than on second listbox first get deselected. How to make this? Is it possiblE? From nagle at animats.com Thu Apr 5 15:50:45 2007 From: nagle at animats.com (John Nagle) Date: Thu, 05 Apr 2007 19:50:45 GMT Subject: UNICODE mode for regular expressions - time to change the default? Message-ID: Regular expressions are compiled in ASCII mode unless Unicode mode is specified to "rc.compile". The difference is that regular expressions in ASCII mode don't recognize things like Unicode whitespace, even when applied to Unicode strings. For example, Unicode character 0x00A0 is a "NO-BREAK SPACE", which is a form of whitespace. It's the Unicode equivalent of HTML's " ". This can create some strange bugs. Is the current default good? Or is it time to compile all regular expressions in Unicode mode by default? It shouldn't hurt processing of ASCII strings to do that. The current setup is really a legacy of when most things in Python didn't work in Unicode mode, and you didn't want to introduce Unicode unnecessarily. It's another one of those obscure Unicode "gotchas" that really should go away. John Nagle From aleax at mac.com Thu Apr 19 23:29:58 2007 From: aleax at mac.com (Alex Martelli) Date: Thu, 19 Apr 2007 20:29:58 -0700 Subject: comparison with None References: <3IqdnfRnCNWPC7vbnZ2dnUVZ_jqdnZ2d@rcn.net> Message-ID: <1hwu3hk.cf21dwlie1ouN%aleax@mac.com> Steven D'Aprano wrote: > But if you wanted to do extra work unnecessarily, a less unnecessary > amount of extra work would be: > > if type(x) == type(None): ... Of course, like the original poster's proposal, this CAN be faked out (while the 'is' test cannot, one more weird reason why it's better): >>> class metaWeird(type): ... def __eq__(self, other): return True ... >>> class Weird: __metaclass__ = metaWeird ... >>> x = Weird() >>> type(x) == type(None) True (warning to all innocent bystanders: don't try this at home, kids!-) Alex From steve at holdenweb.com Fri Apr 20 15:13:26 2007 From: steve at holdenweb.com (Steve Holden) Date: Fri, 20 Apr 2007 15:13:26 -0400 Subject: Newbie question regarding string.split() In-Reply-To: <1177095062.826018.63590@n59g2000hsh.googlegroups.com> References: <1177095062.826018.63590@n59g2000hsh.googlegroups.com> Message-ID: kevinliu23 wrote: > Hey guys, > > So I have a question regarding the split() function in the string > module. Let's say I have an string... > First of all, the string module is pretty much deprecated nowadays. What you are actually using, the .split() method of a string, is the preferred way to do it. If you are importing string, don't bother! > input = "2b 3 4bx 5b 2c 4a 5a 6" > projectOptions = (input.replace(" ", "")).split('2') > print projectOptions > > ['', 'b34bx5b', 'c4a5a6'] > > My question is, why is the first element of projectOptions an empty > string? What can I do so that the first element is not an empty > string? but the 'b34bx5b' string as I expected? > Because .split() returns a list of the strings surrounding each occurrence of the split argument. Because the string begins with the split argument it returns an empty string as the first element (since the assumption is you are interested in both sides of the separator). You can easily throw the first element away: del projectOptions [0] for example, or projectOptions = projectOptions[1:] But what do you want to do if the string *doesn't* begin with a 2? 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 maric at aristote.info Thu Apr 12 09:24:13 2007 From: maric at aristote.info (Maric Michaud) Date: Thu, 12 Apr 2007 15:24:13 +0200 Subject: Calling private base methods In-Reply-To: <11e49df10704120147x5d5df991r93d2b266a67e64ea@mail.gmail.com> References: <11e49df10704120147x5d5df991r93d2b266a67e64ea@mail.gmail.com> Message-ID: <200704121524.14304.maric@aristote.info> Le jeudi 12 avril 2007 10:47, Jorgen Bodde a ?crit?: > I thought I understood > how super() worked, but with 'private' members it does not seem to > work. I would add to what is already said, that you should just forget the private -public - protected concepts in Python. There is no access control to members in Python, but : - names not beginning by an underscore belong to the API of a class (C++ public) or module, whether they are methods or properties. - names beginning by a single underscore are used internally by a class or a module, the caller should not use/import them at all. - names enclosed by double underscore are parts of the language semantic, don't define yours. All these are conventions. Finally : - names beginning by double underscore are mangled at class creation time, they should be used only to avoid name collision in subclasses (practically this is rarely needed). Python is alot about conventions, please read and follow the PEP 8 : http://www.python.org/dev/peps/pep-0008/ -- _____________ Maric Michaud From steve at REMOVEME.cybersource.com.au Thu Apr 19 23:22:48 2007 From: steve at REMOVEME.cybersource.com.au (Steven D'Aprano) Date: Fri, 20 Apr 2007 13:22:48 +1000 Subject: List of Objects References: <1177037915.042476.153190@n76g2000hsh.googlegroups.com> Message-ID: On Thu, 19 Apr 2007 19:58:35 -0700, datamonkey.ryan wrote: > Howdy, a (possibly) quick question for anyone willing to listen. > I have a question regarding lists and Classes; I have a class called > "gazelle" with several attributes (color, position, etc.) and I need > to create a herd of them. I want to simulate motion of individual > gazelles, but I don't want to have to go through and manually update > the position for every gazelle (there could be upwards of 50). I was > planning to create an array of these gazelle classes, and I was going > to iterate through it to adjust the position of each gazelle. That's > how I'd do it in C, anyway. However, Python doesn't support pointers > and I'm not quite sure how to go about this. Any help you can provide > would be greatly appreciated. First method: create 1000 different gazelles: list_of_beasties = [] for i in xrange(1000): # create 1000 beasties args = (i, "foo", "bar") # or whatever list_of_beasties.append(Gazelle(args)) Second method: create 1000 different gazelles by a slightly different method: list_of_beasties = [Gazelle((i, "foo", "bar")) for i in xrange(1000)] Third method: create 1000 copies of a single gazelle: list_of_beasties = [Gazelle(args)] * 1000 # probably not useful... Forth method: create identical gazelles, then modify them: list_of_beasties = [Gazelle(defaults) for i in xrange(1000)] for i, beastie in enumerate(xrange(1000)): list_of_beasties[i] = modify(beastie) -- Steven D'Aprano From samjnaa at gmail.com Sat Apr 14 09:34:19 2007 From: samjnaa at gmail.com (jamadagni) Date: 14 Apr 2007 06:34:19 -0700 Subject: Python Feature Request: Add the "using" keyword which works like "with" in Visual Basic In-Reply-To: <58buojF2e7nifU1@mid.individual.net> References: <1176547372.584539.89170@q75g2000hsh.googlegroups.com> <58buojF2e7nifU1@mid.individual.net> Message-ID: <1176557659.625615.138080@d57g2000hsg.googlegroups.com> > Personally, I'd never use it. You are free to avoid using it of course. :) > In more complex modules, when you are > looking for, e. g., self.myVar and anotherObject.myVar, > this "using" statement decreases readability and maintainability > (in full text searching). IMHO. Why? Just search for self and you turn up using self. Just scan down (the block) and you get myVar. Similarly for anotherObject.myVar. Of course, you lose the possibility of just searching for self.myVar -- something lost, something gained, IMHO. From anders.u.persson at gmail.com Sat Apr 28 12:27:03 2007 From: anders.u.persson at gmail.com (anders) Date: 28 Apr 2007 09:27:03 -0700 Subject: I have a chance to do somting diffrent way not Python ?! Message-ID: <1177777623.038902.108590@y5g2000hsa.googlegroups.com> Hi! On my work we have a lot off diffrent server to make software for diffrent os from Windows, OS/X to Linux Solaris Everyting is scripted with shell, but Windows has batchfiles witch is very limited, compared to cshell etc. So my boss has told me that it okej if i want to make somting better och smooter, for the windows machine. First i looked a Ruby but didn't like it to interacting with the os, nothinh wrong but my eyes moved to Python becurse syntax is clean and every server (not windows) has Python as base installed, and in the future i could then move the script to run on all servers. So basicly i like advice about interac with os, compiler etc. Nice webblinks to read more and do/don't things. best regards Anders From jstroud at mbi.ucla.edu Sun Apr 29 16:15:35 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Sun, 29 Apr 2007 13:15:35 -0700 Subject: Counting In-Reply-To: References: <1177873864.502180.283390@u30g2000hsc.googlegroups.com> Message-ID: James Stroud wrote: > James Stroud wrote: >> Andy wrote: >>> Hi, the file below will print all the keywords in a file and also the >>> line # of the keyword. What I couldn't figure out is to count those >>> keywords per line. For example - "Line #1 has 3 keywords" >>> >>> Can I do like - >>> >>> total[j] = total[j] + numwords(k) >>> "Line number %d has %d keywords" % (j, total[j]) >>> >>> Seems sort of "illegal" in Python? >>> >>> >>> >>> ------------------------------------------------- >>> import keyword, sys, string, fileinput >>> def numwords(s): >>> list = string.split(s) >>> return len(list) >>> >>> # Get the file name either from the command-line or the user >>> if len(sys.argv) != 2: >>> name = raw_input("Enter the file name: ") >>> else: >>> name = sys.argv[1] >>> >>> inp = open(name,"r") >>> linelist = inp.readlines() >>> total, words,lines = 0, 0, 0 >>> >>> for i in range(len(linelist)): >>> line = linelist[i] >>> tempwords = line.split() >>> for k in tempwords: >>> if keyword.iskeyword(k): >>> total = total + numwords(k) >>> j = i + 1 >>> print" The word * %s * belongs in line number: %d" % (k, >>> j) >>> >>> print "Total keywords in this file are: %d" %(total) >>> >> >> You probably want something that goes a little like this: >> >> for i,line in enumerate(linelist): >> for k in line.split(): >> if keyword.iskeyword(k): >> total += line.count(k) >> print "The word '%s' belongs in line num: %d" % (k, i+1) >> >> print "Total keyords are: %d" % total >> >> James > > Oops, that over-counts, I forgot to put a continue in. Also, keeping a > cache of the split line will probably be faster. > > for i,line in enumerate(linelist): > line = line.split() > for k in line: > if keyword.iskeyword(k): > total += line.count(k) > print "The word '%s' belongs in line num: %d" % (k, i+1) > continue > > print "Total keyords are: %d" % total > > > James I should really wait until I've had some coffee. Not continue, but break! for i,line in enumerate(linelist): line = line.split() for k in line: if keyword.iskeyword(k): total += line.count(k) print "The word '%s' belongs in line num: %d" % (k, i+1) break print "Total keyords are: %d" % total From tjreedy at udel.edu Sat Apr 7 13:43:33 2007 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 7 Apr 2007 13:43:33 -0400 Subject: Custom Python Runtime References: <2NudnVn5jsm2QIvbnZ2dnUVZ_vqpnZ2d@comcast.com> <46176493$0$4042$9b622d9e@news.freenet.de> Message-ID: ""Martin v. L?wis"" wrote in message news:46176493$0$4042$9b622d9e at news.freenet.de... |> Is there a way to customize the Windows build? In my case, there is no need | > to build an installer. The best way is to have everything in a directory, as | > long as I know where to find Python and Python knows where to find the | > necessary libs. Any online docs describing this? Thanks! | | The interpreter will search for its libraries relative to the location | of the .exe file. So if you place python.exe and pythonxy.dll into | a directory, you need to add a Lib directory | | Inside Lib, the minimum file you need to have is os.py: Python will | use it as a landmark. If you run 'python.exe -S', this is all | you need. | | If you want site.py to work, you also need (tested for 2.4): | - site, codecs, copy_reg, locale, ntpath, stat, types UserDict, | encodings/__init__, encodings/aliases | | If you eliminate the aliasmbcs function from site.py, you can drop | codecs, locale, encodings/*. | | If you eliminate the copy_reg references from os.py, you can also drop | copy_reg. If this information somewhere on python.org? This is at least an occasional question here. tjr From stanc at al.com.au Thu Apr 5 02:32:33 2007 From: stanc at al.com.au (Astan Chee) Date: Thu, 05 Apr 2007 16:32:33 +1000 Subject: ok In-Reply-To: <1175754398.890967.254050@l77g2000hsb.googlegroups.com> References: <1175754398.890967.254050@l77g2000hsb.googlegroups.com> Message-ID: <46149801.2020404@al.com.au> How much does it pay? moiseau at gmail.com wrote: > hi looking for someone to bult my web site for me > > From i3dmaster at gmail.com Wed Apr 11 13:07:15 2007 From: i3dmaster at gmail.com (i3dmaster) Date: 11 Apr 2007 10:07:15 -0700 Subject: Universal Feed Parser issue In-Reply-To: References: <1176227922.910993.36910@y80g2000hsf.googlegroups.com> <1176267073.787216.80170@n76g2000hsh.googlegroups.com> Message-ID: <1176311235.792366.296010@b75g2000hsg.googlegroups.com> On Apr 11, 12:06 am, "Gabriel Genellina" wrote: > En Wed, 11 Apr 2007 01:51:13 -0300, i3dmaster > escribi?: > > > > > On Apr 10, 6:45 pm, "Gabriel Genellina" > > wrote: > >> En Tue, 10 Apr 2007 14:58:42 -0300, i3dmaster > >> escribi?: > > >> > > >> > ... > >> > > >> > > >> > > > >> > After parsed by feedparser, the timezone element does not get the > >> > attribute "America/Mountain". Same thing on status element. This does > >> > not sound an expected result. I am wondering if it should be > >> > considered a bug... > > >> Usually it's a good idea to read the documentation... > >>http://www.feedparser.org/docs/namespace-handling.html > > > I did. Perhaps its because of not 100% atom compatible of my feed > > format? See if I use gnosis xml utility to parse it, it works fine > > though... > > The link above answers *exactly* your question - have you actually read > the page? > > -- > Gabriel Genellina Hmm... well I don't know if I made my question clear then or you might have misread it?... Anyway, the namespace handling wasn't the issue of this question. feedparser handles it as expected but only when there is a text value associated with it. Look at the rdf file you will see the prism:issn element has a text value but in my case, the foo:timezone element DOES NOT have a text value but a Attribute or maybe attributes... What it looks like is feedparser simply ignores all the attributes when parsing it. This behavior wasn't seen from other xml parsers though. From steve at holdenweb.com Wed Apr 4 14:48:32 2007 From: steve at holdenweb.com (Steve Holden) Date: Wed, 04 Apr 2007 14:48:32 -0400 Subject: BeautifulSoup vs. real-world HTML comments In-Reply-To: <1175711322.448629.20300@y80g2000hsf.googlegroups.com> References: <1175711322.448629.20300@y80g2000hsf.googlegroups.com> Message-ID: Carl Banks wrote: > On Apr 4, 2:08 pm, John Nagle wrote: >> The syntax that browsers understand as HTML comments is much less >> restrictive than what BeautifulSoup understands. I keep running into >> sites with formally incorrect HTML comments which are parsed happily >> by browsers. Here's yet another example, this one from >> "http://www.webdirectory.com". The page starts like this: >> >> >> >> >> >> >> Environment Web Directory >> >> Those are, of course, invalid HTML comments. But Firefox, IE, etc. handle them >> without problems. >> >> BeautifulSoup can't parse this page usefully at all. >> It treats the entire page as a text chunk. It's actually >> HTMLParser that parses comments, so this is really an HTMLParser >> level problem. > > Google for a program called "tidy". Install it, and run it as a > filter on any HTML you download. "tidy" has invested in it quite a > bit of work understanding common bad HTML and how browsers deal with > it. It would be pointless to duplicate that work in the Python > standard library; let HTMLParser be small and tight, and outsource the > handling of floozy input to a dedicated program. > > eGenix have produced the mxTidy library that handily incorporates these features in a way that makes them easy for Python programmers to use. 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 Sat Apr 14 11:39:17 2007 From: aleax at mac.com (Alex Martelli) Date: Sat, 14 Apr 2007 08:39:17 -0700 Subject: ulimit on open sockets ? References: <1hwbp5h.1fnai9snzd1vpN%aleax@mac.com> <82069913-B174-4701-8E81-7A82FAB7D040@mac.com> Message-ID: <1hwjwgh.1rkbw2n1nrk94wN%aleax@mac.com> Maxim Veksler wrote: ... > Thank you. I'm attaching the full code so far for reference, sadly it > still doesn't work. It seems that select.select gets it's count of > fd's not from the amount passed to it by the sub_list but from the > kernel (or whatever) count for the process; The main issue here is It's not a problem of COUNT of FD's, i.e., how many you're passing to select; the problem is the value of the _highest_ number you can pass. It's an API-level limitation, not an issue with Python per se: the select API takes a "bit vector" of N bits, representing a set of FDs in that way, and N is fixed at kernel-compilation time (normally to 1024). The poll system call does not have this particular limitation, which is why select.poll may be better for you. Moreover, your code has other performance problems: > while 1: > for select_cap_sockets in slice_by_fd_limit(all_sockets): > ready_to_read, ready_to_write, in_error = > select.select(select_cap_sockets, [], [], 0) > for nb_active_socket in all_sockets: > if nb_active_socket in ready_to_read: A small issue is with the last two lines -- instead of looping directly on the small "ready-to-read" list, you're looping on the large all_sockets one and looking each up in the small list -- that's just throwing performance out of the window, and adding complexity, for no benefit whatsoever. The big issue is that you are "ceaselessly polling". If no socket is ready to read, you force select to return immediately anyway, and basically call select at once afterwards. You churn on the CPU without surcease, using 100% of it, hogging it for this "busy wait", possibly to the point of crowding out the kernel from some of the CPU time it needs to do useful work in the TCP-IP stack. Busy-wait is a bad thing... never call select with a timeout of 0 in a tight loop. This recommendation also applies to the polling-object that you can build with select.poll, and any other situation where you're waiting for another thread or process to deliver some data -- ideally you should wait in a blocking way, if that's unfeasible at least make sure you're letting some time pass between such calls, by using small but non-0 timeout (or even by inserting calls to time.sleep if that's what it takes). The risk of such "antipatterns" is a good reason why it would be better to use a well-designed, well-coded, well-debugged existing framework, such as Twisted, rather than roll your own, btw. With twisted, you can choose among many appropriate implementations of "reactor" (the key design pattern for async prorgramming) and activate the one that is most suitable for your needs (including, e.g., one based on epoll, which gives better performance than poll on suitable operating systems). If you're adamant on "rolling your own", though, you can find a Python epoll module at (it's said to be in alpha status, though; I believe there are other such modules around, but pyepoll seems to be the only one on Cheese Shop). Alex From eugene.vandenbulke at gmail.com Sun Apr 22 09:58:12 2007 From: eugene.vandenbulke at gmail.com (EuGeNe Van den Bulke) Date: Sun, 22 Apr 2007 15:58:12 +0200 Subject: Access to file dropped on .exe/.app icon References: <1177238512.066413.41660@n59g2000hsh.googlegroups.com> Message-ID: Martin wrote: > If i create an app using py2exe/py2app is there then a way on windows/ > mac to get access to a file dragged and dropped on to the .exe/.app > icon? > > Martin > I did something like that for a small program I wrote to learn more about Python Programming on Windows ... check it out http://www.3kwa.com/Tutorial/PumpItUp EuGeNe -- http://www.3kwa.com From s.mientki at id.umcn.nl Fri Apr 27 09:56:56 2007 From: s.mientki at id.umcn.nl (stef) Date: Fri, 27 Apr 2007 15:56:56 +0200 Subject: conditional print statement ? In-Reply-To: <1177590681.015153.67800@b40g2000prd.googlegroups.com> References: <2c923$462fb3e0$d443bb3a$18429@news.speedlinq.nl> <1177590681.015153.67800@b40g2000prd.googlegroups.com> Message-ID: <3a3f7$46320129$83aef404$30678@news1.tudelft.nl> > or (untested): > > if Print_Info: > def printOrNot(arg): > print arg > else: > def printOrNot(arg): > pass > > printOrNot(Datafile.readline()) > > thanks for the creative solution, and indeed it does work ;-) cheers, Stef Mientki From steve at REMOVEME.cybersource.com.au Mon Apr 30 06:08:51 2007 From: steve at REMOVEME.cybersource.com.au (Steven D'Aprano) Date: Mon, 30 Apr 2007 20:08:51 +1000 Subject: Dict Copy & Compare References: Message-ID: On Mon, 30 Apr 2007 09:40:53 +0100, Tim Golden wrote: > Robert Rawlins - Think Blue wrote: >> I'm looking for a little advice on dicts, firstly I need to learn how to >> copy a dict, I suppose I could just something like. > >> Self.newdict = self.olddict > >> But I fear that this only creates a reference rather than an actual copy, >> this means that as soon as I clear out the old one, the new one will >> effectively be empty. What's the best way to ACTUALY copy a dict into a new >> variable? > > Unless you have specialised needs, you can just say: > > d2 = dict (d1) Or you can say d2 = d1.copy() -- Steven D'Aprano From spohle at gmail.com Tue Apr 10 13:52:26 2007 From: spohle at gmail.com (spohle) Date: 10 Apr 2007 10:52:26 -0700 Subject: writing my own extension Message-ID: <1176227546.273023.235220@p77g2000hsh.googlegroups.com> hi, i use a lot the enumerate in my scripts and got really interested in possibly writing my own enumerate as an extension, for which i would want to extend it to be able to pass a start and step attribute. can anyone point me on my way with good examples for that and how to write extensions ? thank you in advance From dborne at gmail.com Mon Apr 30 09:51:30 2007 From: dborne at gmail.com (Dave Borne) Date: Mon, 30 Apr 2007 08:51:30 -0500 Subject: Cgi File Upload without Form In-Reply-To: <1177708242.553577.226530@n15g2000prd.googlegroups.com> References: <1177708242.553577.226530@n15g2000prd.googlegroups.com> Message-ID: <6e42ec490704300651u263f6f1ar9be74c611e307e58@mail.gmail.com> > Since I want to upload the data programmatically, a form based > solution is not good. Karsten, Could you explain this statement? When I want to move data to a server in a CGI environment, a form post is the easiest way I can think of. What are the specific restrictions making forms a problem? -Dave From kyosohma at gmail.com Tue Apr 10 15:49:00 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: 10 Apr 2007 12:49:00 -0700 Subject: OT: Question about RGB color method In-Reply-To: <461be63b$0$31839$c3e8da3@news.astraweb.com> References: <461be63b$0$31839$c3e8da3@news.astraweb.com> Message-ID: <1176234539.949555.92750@h3g2000cwc.googlegroups.com> On Apr 10, 2:32 pm, John Salerno wrote: > Sorry for this non-Python question, but since it's computer related I > know you guys will have an answer, and I don't really know where else to > ask. Mainly I'm just curious anyway. > > I'm wondering, why do computers use a RGB color scheme instead of the > primary colors? Is there something you can't do with yellow? It seems > weird that RGB can be combined to make all colors, when that's supposed > to be the job of the primary colors. I'm sure there some technical > computer-related reason that it had to be this way. > > Thanks. It's a pigment vs. light-beam thing. Check out http://en.wikipedia.org/wiki/RGB_color_model Mike From webraviteja at gmail.com Fri Apr 27 23:18:09 2007 From: webraviteja at gmail.com (Ravi Teja) Date: 27 Apr 2007 20:18:09 -0700 Subject: Interop between C# and Python In-Reply-To: <1177722543.098518.192840@h2g2000hsg.googlegroups.com> References: <1177722543.098518.192840@h2g2000hsg.googlegroups.com> Message-ID: <1177730289.935376.167590@e65g2000hsc.googlegroups.com> On Apr 27, 6:09 pm, urielka wrote: > i need a easy way to write a Python Service(be it SOAP or JSONRPC or > whatever) but i need to easily access it from C#,i created a web > service in ZSI(which is really easy) like this: > > from ZSI import dispatch > > def hello(): > return "hello" > > dispatch.AsServer(port=8080) > > simple and easy but how i access it from C#,where is the wsdl for the > service? > > is there any easier way to get this kind of interop?(not using a > custom protocol over sockets) > > thx, > Uriel Katz Use soaplib instead of ZSI. It has better WSDL support which makes it easier to create client stubs from other languages. http://trac.optio.webfactional.com/ Ravi Teja. From http Tue Apr 10 00:20:37 2007 From: http (Paul Rubin) Date: 09 Apr 2007 21:20:37 -0700 Subject: Queue get timeout parameter question References: <1176178232.836311.19390@p77g2000hsh.googlegroups.com> Message-ID: <7x1wisg8ru.fsf@ruckus.brouhaha.com> "Godzilla" writes: > After the time sync, say 15 seconds backward, the thread is sitting on > that get() method for a total of 17 seconds. We can only sync the > device once per day and the time can drift up to 15 seconds per day!! Try to avoid syncing lke that. System clocks drift but the drift rates tend to be constant, so there are schemes for gradually slowing down or speeding up the system clock in order to keep it synchronized with an external reference. > Anyone knows a solution to this problem or an alternative method? http://www.ntp.org From godzillaismad at gmail.com Tue Apr 10 04:06:50 2007 From: godzillaismad at gmail.com (Godzilla) Date: 10 Apr 2007 01:06:50 -0700 Subject: Queue get timeout parameter question In-Reply-To: References: <1176178232.836311.19390@p77g2000hsh.googlegroups.com> Message-ID: <1176192410.760903.219610@q75g2000hsh.googlegroups.com> On Apr 10, 5:38 pm, Thomas Kr?ger wrote: > Godzilla schrieb: > > > > > > > I have been using the queue module for a multithreaded environment and > > things seem to work well... until we had a requirement for the > > application to be able to time sync to the server. With the time sync, > > it actually disorientated the timeout in the queue's get() method... > > e.g. > > > get(item, 2.0) > > > After the time sync, say 15 seconds backward, the thread is sitting on > > that get() method for a total of 17 seconds. We can only sync the > > device once per day and the time can drift up to 15 seconds per day!! > > I had tried to get around this problem by having a sleep(2) (sleep is > > not local system time dependant) just before the get(), but that will > > slow down the application too much. > > > Anyone knows a solution to this problem or an alternative method? > > I was fixing a serious time drift problem on Linux lately. If your > server runs on Linux I can give you some hints: > > - set the system clock > - delete /etc/adjtime and resync system time and hardware time > "hwclock --systohc" > - on some distributions you may have to reboot > - give it some time to see if it is still drifting > - if only the system clocks drifts (see output of "hwclock; date") > you may have a timer related kernel problem. This may help: > * deactivate ACPI via kernel boot parameter > * change timer frequency > * try different setting for all timer related stuff like > CONFIG_HPET_TIMER or CONFIG_X86_PM_TIMER > > Thomas > > -- > sinature:http://nospam.nowire.org/signature_usenet.png- Hide quoted text - > > - Show quoted text - Thanks Thomas, I'm not running Linux but I will take some of your pointers as a guide. Cheers mate. From phil at riverbankcomputing.co.uk Thu Apr 26 12:00:46 2007 From: phil at riverbankcomputing.co.uk (Phil Thompson) Date: Thu, 26 Apr 2007 17:00:46 +0100 Subject: passing tuple with pyqt4 signal/slot mechanism In-Reply-To: <80628d680704260849n6c8da864i5cfc8bf4cbab5f6d@mail.gmail.com> References: <80628d680704260849n6c8da864i5cfc8bf4cbab5f6d@mail.gmail.com> Message-ID: <200704261700.46396.phil@riverbankcomputing.co.uk> On Thursday 26 April 2007 4:49 pm, Pradnyesh Sawant wrote: > Thanks for the reply Phil. Actually, as mentioned earlier, the code > that i sent was stripped; while stripping, i missed some things (class > D should have a run method). Also, i tried your suggestion of > connecting before emitting the signal, but am still getting the same > output (in the original code). the modified code is given below: > > class D(QtCore.QThread): > def __init__(self): > QtCore.QThread.__init__(self) > def run(self): > tpl = ("Primary", "priSec") > print "tpl:", tpl > self.emit(QtCore.SIGNAL("setLabel"), tpl) > class Gui(QtGui.QDialog): > def __init__(self, parent = None): > QtGui.QDialog.__init__(self, parent) > def setLabel(self, tpl): > print "####tpl:", tpl > print "**********tpl:", str(tpl) > if __name__ == "__main__": > app = QtGui.QApplication(sys.argv) > dialog = Gui() > d = D() > QtCore.QObject.connect(d, QtCore.SIGNAL("setLabel"), > dialog.setLabel, QtCore.Qt.QueuedConnection) > d.start() > sys.exit(dialog.exec_()) > > Also, in the modified code, why aint the method setLabel getting called? Works for me, and I still don't know what versions you are using and on which platform. Whatever they are, try the latest release. Phil From gagsl-py2 at yahoo.com.ar Fri Apr 20 15:20:55 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 20 Apr 2007 16:20:55 -0300 Subject: comparison with None References: <3IqdnfRnCNWPC7vbnZ2dnUVZ_jqdnZ2d@rcn.net> <2qzVh.7373$xL6.982@trnddc05> <_JAVh.1700$jR5.897@trnddc08> <1hwu26k.oyynyowsbxvcN%aleax@mac.com> <1hwuyed.1pfg5y31tp64kmN%aleax@mac.com> Message-ID: En Fri, 20 Apr 2007 11:40:00 -0300, Alex Martelli escribi?: > I'm still interested to know where that erroneous quote from Alan Isaac > comes from, because if it's in Python's docs, it can be fixed. It was a partial quote, that's why it appeared to be wrong: Library reference, 3.3 Comparisons "Objects of different types, except different numeric types and different string types, never compare equal; such objects are ordered consistently but arbitrarily." Reference Manual, 5.9 Comparisons "The objects need not have the same type. If both are numbers, they are converted to a common type. Otherwise, objects of different types always compare unequal, and are ordered consistently but arbitrarily." (Apart from the latter not menctioning string types too, looks good to me). -- Gabriel Genellina From steve at REMOVE.THIS.cybersource.com.au Thu Apr 19 19:25:16 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Fri, 20 Apr 2007 09:25:16 +1000 Subject: comparison with None References: <_JAVh.1700$jR5.897@trnddc08> Message-ID: On Thu, 19 Apr 2007 17:00:29 +0000, Alan Isaac wrote: > > "Steven D'Aprano" wrote in message > news:pan.2007.04.19.07.04.43.363933 at REMOVE.THIS.cybersource.com.au... >> You shouldn't expect comparisons between types to >> sort the same from one version of Python to another, although they may, >> and in the future (Python 3) it is likely to become an error to compare >> incomparable objects. > > Indeed, that was the basis of my original question. > I wondered why no exception was raised. > > Thanks, > Alan Isaac > > PS Note that the change you mention will conflict with > currently documented behavior: > "objects of different types always compare unequal". > So this seems like a large change. Absolutely -- that's why it is scheduled for Python 3, which is the release which is allowed to make backwards incompatible changes. -- Steven. From R.Brodie at rl.ac.uk Tue Apr 3 12:28:33 2007 From: R.Brodie at rl.ac.uk (Richard Brodie) Date: Tue, 3 Apr 2007 17:28:33 +0100 Subject: Stack experiment References: <5QuQh.152$9L1.108@read3.inet.fi> <1175616703.386553.147830@w1g2000hsg.googlegroups.com> <1175617229.555905.175790@w1g2000hsg.googlegroups.com> Message-ID: wrote in message news:1175617229.555905.175790 at w1g2000hsg.googlegroups.com... >> There is a stray leading space in it. > > Nah, I'd say there's a stray ([^0-9]) after the space. If you regard the spaces as being a required part of the postfix grammar, it would be simpler. But who would design a language where white space was significant ;) From spradml at gmail.com Sat Apr 28 14:02:51 2007 From: spradml at gmail.com (Pradnyesh Sawant) Date: Sat, 28 Apr 2007 23:32:51 +0530 Subject: ImportError: No module named QtOpenGL In-Reply-To: <80628d680704281101w4347b971u3807cec82531bed5@mail.gmail.com> References: <80628d680704281101w4347b971u3807cec82531bed5@mail.gmail.com> Message-ID: <80628d680704281102y5ccf2db5tf4ee6986b7162280@mail.gmail.com> Hello, I've written a small pyqt4 code, which on running on an ubuntu 6.10 system gives me the foll error: $ python2.4 updLbl.py Traceback (most recent call last): File "updLbl.py", line 1, in ? import PyQt4.Qt as qt File "/usr/lib/python2.4/site-packages/PyQt4/Qt.py", line 4, in ? from PyQt4.QtOpenGL import * ImportError: No module named QtOpenGL I've tried installing python-opengl, and also qt4-dev-tools, but the error persists. What pkg do i need to install to get rid of the error message? Thanks! -- warm regards, Pradnyesh Sawant -- Be yourself, everyone else is taken. --Anon From steve at holdenweb.com Sat Apr 21 11:56:05 2007 From: steve at holdenweb.com (Steve Holden) Date: Sat, 21 Apr 2007 11:56:05 -0400 Subject: Class Not Auto-Init On Import In-Reply-To: <2987.60099472037$1177145337@news.gmane.org> References: <2987.60099472037$1177145337@news.gmane.org> Message-ID: Robert Rawlins - Think Blue wrote: > Hello Guys, > > > > From my understanding of what I?ve read, the ?import? is meant to auto > Init my class ready for me to access its methods, but it doesn?t appear > too, I?m having to init them myself before I can access them, like this. > Importing a module (the first time) executes its code. This means that assignments bind to names in the module's namespace, class statements define classes in the module's namespace, def statements define functions in the module's namespace. The statement > > import LocationService > after, running the module's code, makes the module's namespace available as the name LocationService in the importing module's namespace. So "name" in the module's namespace can be referred to in the importing module as LocationService.name. > > Location = LocationService.LocationService() > So that statement creates an instance of the LocationService class defined in the LocationService module. Since no arguments are provided, the new instance's __init__() method is called with a single argument, the new instance itself. > > LocationService.setIP(?192.168.1.1?) > This isn't a call on a specific LocationService instance, it's a call on the SetIP method of the class (presumably you have to set the IP address of the server or whatever - typically class methods are used to invoke functions or set up conditions that must apply to all instances of the class. If you wanted to set the IP for a particular instance you would normally call a method instance, as in Location.SetIP('129.168.1.1') But if the class defines the method as a class method then a call like the above is likely to fail. So it's ultimately all down to the design of the class you are using. > > Why is this the case? Should i not just be able to access the setIP() > method by doing LocationService.setIP(?192.168.1.1?) Without having to > create my own inited reference? > That would make a certain amount of sense, but whether this would be acceptable depends how the class's __init__ method is defined. There's certainly nothing in the Python language that would *stop* you doing that. It seems that there might be a certain amount of confusion, either in your mind or in the module you are using, between object-oriented programming techniques and the more process-oriented traditional techniques. I don't know whether this will have helped or not. 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 Wed Apr 4 03:59:23 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: 4 Apr 2007 00:59:23 -0700 Subject: how to remove multiple occurrences of a string within a list? In-Reply-To: <1175637235.783612.45980@o5g2000hsb.googlegroups.com> References: <1175624433.206953.214290@n59g2000hsh.googlegroups.com> <1175626905.957243.301870@w1g2000hsg.googlegroups.com> <1175637235.783612.45980@o5g2000hsb.googlegroups.com> Message-ID: <1175673563.212459.322290@y66g2000hsf.googlegroups.com> On Apr 3, 3:53 pm, "bahoo" wrote: > > target = "0024" > > l = ["0024", "haha", "0024"] > > > > for index, val in enumerate(l): > > if val==target: > > del l[index] > > > print l > > This latter suggestion (with the for loop) seems to be buggy: if there > are multiple items in the list "l" equal to "target", then only the > first one will be removed! > > Thanks anyways. Prove it. From bj_666 at gmx.net Sat Apr 28 02:28:37 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Sat, 28 Apr 2007 08:28:37 +0200 Subject: My newbie annoyances so far References: <1177688082.758043.133920@r30g2000prh.googlegroups.com> <59f5btF2k70baU2@mid.individual.net> Message-ID: In <59f5btF2k70baU2 at mid.individual.net>, Bjoern Schliessmann wrote: > Dennis Lee Bieber wrote: > >> HP RPL made more sense: b if c [else d] end > > Please explain. > > HP RPL: b if c [else d] end > Python: b if c else d > > What's the "more sense" here? The HP RPL leaves even more questions. If the square brackets mean the ``else`` part is optional, what would be the result of the expression if `c` is `False`? Hypothetical HP RPL syntax construct in Python:: x = 42 if False end print x # -> ??? Ciao, Marc 'BlackJack' Rintsch From apardon at forel.vub.ac.be Tue Apr 10 01:59:28 2007 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 10 Apr 2007 05:59:28 GMT Subject: how can I clear a dictionary in python References: <1175121525.261424.72350@n76g2000hsh.googlegroups.com> Message-ID: On 2007-04-04, Aahz wrote: > In article , > Antoon Pardon wrote: >>On 2007-04-03, Aahz wrote: >>> In article , >>> Larry Bates wrote: >>>>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. >>> >>> Then you should explain why you didn't answer the question that was >>> asked. Answering a different question without explanation makes your >>> answer irrelevant at best, wrong at worst. >> >>This is not true. If this different question was in fact the intended >>question instead of the one actually asked. Anwering this different >>question can be more usefull than answering the one actually asked. > > Note carefully that I did not say, "Don't answer the question you think > should have been asked." What I said was, "If you answer a different > question, EXPLAIN WHY." Is that so difficult to understand? You are mixing up two things: On the one hand you are trying to get some moral behaviour accrosss: People should explain when answering a different question. On the second hand you are bringing an opinion: If they don't their answer is irrelevant at best. If someone disagrees with the second, repeating the first seems a bit beside the point. -- Antoon Pardon From flyzone at technologist.com Mon Apr 30 11:20:58 2007 From: flyzone at technologist.com (Flyzone) Date: 30 Apr 2007 08:20:58 -0700 Subject: regexp match string with word1 and not word2 In-Reply-To: References: <1177920984.247487.54620@c35g2000hsg.googlegroups.com> Message-ID: <1177946458.620210.68690@u30g2000hsc.googlegroups.com> James Stroud ha scritto: > The P.S: suggests homework, but this can't be homework because python > regex won't do this, so your teacher gets an F if its homework. You Not a homework, but a "workwork" :-) I'm writing a script to parse logfiles, and I have began to study python for this (bash was too much slow). When i'll finishi it, I'll post a link here if someone think that could be helpful. > require a negative look-behind assertion of variable length--not > possible in python regex. You will have to use something else--or maybe > you don't understand the homework problem. I was asking that cause in the code i wrote this: for y in range(0, len(skip_lst) ): if (re.search(skip_lst[y], line)): skip=1 break In skip_lst there are the regexp and strings (on one line) to match with "line". But rarely the rules to be matched need to have also a logical And. What could be the solution? Add another array with a "not" regexp? From tjreedy at udel.edu Thu Apr 12 12:56:04 2007 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 12 Apr 2007 12:56:04 -0400 Subject: bittorent References: <1eb3a0e10704110922v17f83f79se5972dce07415a5@mail.gmail.com><461D110F.8080908@rpath.com> <461D16B7.9090407@ncee.net> <1eb3a0e10704120934g3d52b73fge2d5d343a61eb20a@mail.gmail.com> Message-ID: "Linus Nordstr?m" wrote in message news:1eb3a0e10704120934g3d52b73fge2d5d343a61eb20a at mail.gmail.com... >I might have been a bit unclear on what i was looking for, im not >looking for a finished bitorrent client, but rather module that can >parse a .torrent file, or info on how i would goabout to write >something that can do that. And at least two of us told you at least two place to go look for such a module. tjr From robert.kern at gmail.com Thu Apr 12 15:53:16 2007 From: robert.kern at gmail.com (Robert Kern) Date: Thu, 12 Apr 2007 14:53:16 -0500 Subject: Portably generating infinity and NaN In-Reply-To: References: Message-ID: Michael Hoffman wrote: > What's the best way to portably generate binary floating point infinity > and NaNs? I only know two solutions: > > 1. Using the fpconst module proposed in IEEE 754, which I believe shifts > bits around. > > 2. Using an extension module (for example, numarray.ieeespecial will do it). > > I thought of using float(Decimal("nan")), but apparently > Decimal.__float__(self) is float(str(self)), which isn't portable. This is what numpy does (translated from the C): mul = 1e10 inf = mul tmp = 0.0 while True: inf *= mul if inf == tmp: break tmp = inf nan = inf / inf -- 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 steve at REMOVEME.cybersource.com.au Wed Apr 18 01:39:22 2007 From: steve at REMOVEME.cybersource.com.au (Steven D'Aprano) Date: Wed, 18 Apr 2007 15:39:22 +1000 Subject: What makes an iterator an iterator? Message-ID: I thought that an iterator was any object that follows the iterator protocol, that is, it has a next() method and an __iter__() method. But I'm having problems writing a class that acts as an iterator. I have: class Parrot(object): def __iter__(self): return self def __init__(self): self.next = self._next() def _next(self): for word in "Norwegian Blue's have beautiful plumage!".split(): yield word But this is what I get: >>> P = Parrot() >>> for word in P: ... print word ... Traceback (most recent call last): File "", line 1, in TypeError: iter() returned non-iterator of type 'Parrot' Why is my instance not an iterator? But I can do this: >>> for word in P.next: ... print word ... Norwegian Blue's have beautiful plumage! I find myself perplexed as to this behaviour. -- Steven D'Aprano From martin at v.loewis.de Thu Apr 26 07:09:57 2007 From: martin at v.loewis.de (=?ISO-8859-15?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Thu, 26 Apr 2007 13:09:57 +0200 Subject: Python not giving free memory back to the os get's me in real problems ... In-Reply-To: <132uv54ncsspm91@corp.supernews.com> References: <1177510121.882503.145560@n15g2000prd.googlegroups.com> <_LidnenBcrz7-rLbnZ2dnUVZ_tCtnZ2d@comcast.com> <59990rF2ja6c7U3@mid.dfncis.de> <132uv54ncsspm91@corp.supernews.com> Message-ID: <46308885.4080405@v.loewis.de> > I'm a bit fuzzy on this, but I don't think there _is_ a > practical way to "return memory to the OS" in many OSes. That's not true at all. Most C libraries these days manage to return memory to the operating system. On Win32 (which the OP is most likely to use), the operating system offers the VirtualFree function to release memory to the operating system. In MSVCRT, the small block allocator will invoke VirtualFree inside __sbh_free_block, when a block group becomes completely free on the C level; likewise, _heap_free_region invokes VirtualFree, so does _heapmin_region. In glibc 2 on Linux, public_fREe will invoke munmap to release the memory to the operating system if the chunk being freed was mmap'ed. glibc allocates chunks greater than mmap_threshold with mmap, which defaults to 128kiB - so Python's obmalloc arenas fall under that algorithm. For small blocks, glibc releases topmost memory through sbrk when it gets more than M_TRIM_THRESHOLD bytes (defaults to 128kiB as well). This algorithm isn't used when MORECORE_CANNOT_TRIM is defined, which it would only on systems where sbrk does not support negative arguments. Regards, Martin From mbm at mediamonger.ch Sun Apr 1 08:57:16 2007 From: mbm at mediamonger.ch (=?UTF-8?B?TWHDq2wgQmVuamFtaW4gTWV0dGxlcg==?=) Date: Sun, 01 Apr 2007 14:57:16 +0200 Subject: [Python-Dev] Python 3000 PEP: Postfix type declarations In-Reply-To: References: Message-ID: <460FAC2C.5020105@mediamonger.ch> > Is this supposed to be a joke? First of April? Likely. From clarence1126 at gmail.com Thu Apr 12 13:32:05 2007 From: clarence1126 at gmail.com (Clarence) Date: 12 Apr 2007 10:32:05 -0700 Subject: MRO theory In-Reply-To: <1176337288.148350.156350@n76g2000hsh.googlegroups.com> References: <1176317929.068559.263330@o5g2000hsb.googlegroups.com> <1176319581.754293.151420@p77g2000hsh.googlegroups.com> <1176337288.148350.156350@n76g2000hsh.googlegroups.com> Message-ID: <1176399125.873684.235920@d57g2000hsg.googlegroups.com> On Apr 11, 5:21 pm, "Carl Banks" wrote: > > There is real Java code that is causing a class construction failure > > because of an inability to construct a consistent mro. I've tried > > several > > approaches to make it work, and by accident, sorting the list of > > interface > > proxy classes, using the default comparison, make it work. > > It *might* not be an accident. Actually, what I meant to write was that my sorting was done by accident, but the heart of my question is, *was* it an accident? I don't have enough theory to answer that question. > > Because Java interfaces can be listed in any order, it's quite > possible that some interface hierarchies in Java violate Python's MRO > restrictions right out of the box. I would guess that JPype deals > with this situation by applying a consistent ordering to of bases when > it creates a proxy class. And it just might turn out that "order of > creation" is the sort key. Or something else could be the key > (alphabetical by name?). Regardless, sorted order just *might* be the > proper order to list bases to ensure MRO consistency. > > I'd suggest that this is probably a question better answered on the > JPype mailing list, since they would have answers and not just > speculations. It's a theoretical question, and Python implements the theory. And no, JPype does not deal with it at all; that's what I'm trying to fix. I know sorting by name does not work because that's one of the things I tried. You can start out with sorted base class lists, but the merging involved in creating the mro of a new class destroys that ordering. I find it very reasonable, however, to think that the creation order of the classes (implying constraints on the possible superclass relationships) may well be a property that the merge will always leave untouched. Hence my question. From http Sun Apr 15 14:59:33 2007 From: http (Paul Rubin) Date: 15 Apr 2007 11:59:33 -0700 Subject: tuples, index method, Python's design References: <1176200361.260546.280510@n76g2000hsh.googlegroups.com> <740c3aec0704100824m132c45fbi5c4c3ec0c0fa3a67@mail.gmail.com> <1176489534.568939.249910@q75g2000hsh.googlegroups.com> <7x3b33k0l9.fsf@ruckus.brouhaha.com> <1176572775.382873.282850@q75g2000hsh.googlegroups.com> <7xr6qmrg4x.fsf@ruckus.brouhaha.com> <1176618596.238855.122000@d57g2000hsg.googlegroups.com> <7xvefym5r6.fsf@ruckus.brouhaha.com> <_2rUh.121507$eJ3.917600@phobos.telenet-ops.be> Message-ID: <7xd525wjje.fsf@ruckus.brouhaha.com> Roel Schroeven writes: > In this case s[0] is not the full Unicode scalar, but instead just the > first part of the surrogate pair consisting of 0x1D40 (in s[0]) and > 0x0000 (in s[1]). Arrrrgggh. After much head scratching I think I now understand what you are saying. This appears to me to be absolutely nuts. What is the purpose of having a unicode string type, if its sequence elements are not guaranteed to be the unicode characters in the string? Might as well use byte strings for everything. Come to think of it, I don't understand why we have this plethora of encodings like utf-16. utf-8 I can sort of understand on pragmatic grounds, but aside from that I'd think UCS-4 should be used for everything, and when a space-saving compressed representation is desired, then use a general purpose data compression algorithm such as gzip. From gregcorradini at gmail.com Wed Apr 11 12:57:35 2007 From: gregcorradini at gmail.com (Greg Corradini) Date: Wed, 11 Apr 2007 09:57:35 -0700 (PDT) Subject: Creating Unique Dictionary Variables from List Message-ID: <9943321.post@talk.nabble.com> Hello All, I'm attempting to create multiple dictionaries at once, each with unique variable names. The number of dictionaries i need to create depends on the length of a list, which was returned from a previous function. The pseudo code for this problem would be: returnedlist = [x,y,z] count = 0 for i in returnedlist: if count < len(returnedlist): # then create a dictionary (beginning with variable dic) and add a unique ending such that # my final dictionary name would be dic + count for each i Any ideas about this? Greg -- View this message in context: http://www.nabble.com/Creating-Unique-Dictionary-Variables-from-List-tf3560471.html#a9943321 Sent from the Python - python-list mailing list archive at Nabble.com. From flifus at gmail.com Thu Apr 26 12:07:03 2007 From: flifus at gmail.com (flifus at gmail.com) Date: 26 Apr 2007 09:07:03 -0700 Subject: My python annoyances so far In-Reply-To: <59bf34F2k27v5U1@mid.individual.net> References: <1177541453.471959.120830@c18g2000prb.googlegroups.com> <59bf34F2k27v5U1@mid.individual.net> Message-ID: <1177603623.774892.230390@t38g2000prd.googlegroups.com> On 26 Apr, 12:00, Bjoern Schliessmann wrote: > fli... at gmail.com wrote: > > Hi all. I'm learning python these days. I'm going to use this > > thread to post, from time to time, my annoyances with python. I > > hope someone will clarify things to me where I have misunderstood > > them. > > > Annoyances: > > > 1. Underscores! What's the deal with that? Especially those double > > underscores. The best answer I read on this is that the double > > underscores denotes special methods that the interpreter may > > automatically use. > > That's right. But what's the annoyance here? > > It's a clear seperation. A bigger annoyance would be if the method > name were, e. g., "add". Now you define your own class, don't think > about this and define a method "add" yourself, and you wonder why > your class behaves strangely. > > > 2. There are modules, there are functions, and there are classes- > > methods! > > You forgot static methods and types. And all of them are objects. > > > Wouldn't it have been easier had everything either been a > > function or a class method? > > IMHO no (this isn't Java). Why should I have to define a class if I > just code a little script with a few functions? That would be > forcing the programmer into using a programming paradigm. > > Will you ask why there is no StringBuffer in Python? :) > > Regards, > > Bj?rn > > -- > BOFH excuse #385: > > Dyslexics retyping hosts file on servers Hi. You wrote c++, didn't you? Well, why do some things in the library have to be functions, and other things have to be class methods? Why aren't they all just either functions or class methods? like perhaps ruby. From lew at nospam.lewscanon.com Tue Apr 17 19:54:55 2007 From: lew at nospam.lewscanon.com (Lew) Date: Tue, 17 Apr 2007 19:54:55 -0400 Subject: is laziness a programer's virtue? In-Reply-To: <1176823224.099381.4630@n59g2000hsh.googlegroups.com> References: <1176757271.282365.319740@n76g2000hsh.googlegroups.com> <1176797558.403629.53140@b75g2000hsg.googlegroups.com> <1176823224.099381.4630@n59g2000hsh.googlegroups.com> Message-ID: Markus E Leypold >> Trying to correct Xah's behaviour is probably impossible. Ingo Menger wrote: > Perhaps somebody could ask the chinese government to put him in jail > for "hurting international society" :) Y'know, even in jest, calling for an oppressive regime to suppress even wrong-headed and self-serving garbage self-expression is immoral and horrible. How dare you? Free speech, free press and free expression of ideas is not something to take so lightly. -- Lew From arkanes at gmail.com Wed Apr 11 10:12:29 2007 From: arkanes at gmail.com (Chris Mellon) Date: Wed, 11 Apr 2007 09:12:29 -0500 Subject: tuples, index method, Python's design In-Reply-To: <588D53831C701746A2DF46E365C018CE01D2CA6B@LITEXETSP001.etrsouth.corp.entergy.com> References: <588D53831C701746A2DF46E365C018CE01D2CA6B@LITEXETSP001.etrsouth.corp.entergy.com> Message-ID: <4866bea60704110712p52c0e870v1e0d7b7a27383714@mail.gmail.com> On 4/11/07, Hamilton, William wrote: > > -----Original Message----- > > From: python-list-bounces+whamil1=entergy.com at python.org > [mailto:python- > > list-bounces+whamil1=entergy.com at python.org] On Behalf Of Steven > D'Aprano > > Sent: Wednesday, April 11, 2007 7:49 AM > > To: python-list at python.org > > Subject: Re: tuples, index method, Python's design > > > > (There is one other option: you care that 32 is somewhere in the > tuple, > > but you don't care where. That's when you use the "in" operator.) > > > > Anyway, that was the original design. When you see tuple, think > struct. If > > you have a struct, it doesn't make a whole lot of sense to ask "which > > field contains 32?", and so according to this intended usage, giving > > tuples index and count methods would be a Bad Idea: it just makes > extra > > work for the Python Dev team, for no benefit. > > > > Personally, I think that tuples do double-duty as *both* immutable > lists > > and structs/records. So even though index and count methods don't make > > sense for a struct, it does make sense for an immutable list, and I > for > > one would not object to seeing tuples grow those two methods. > > > >From another function, you receive a tuple of data that it extracted > from a stream. Within that tuple is a marker that indicates where the > head of the incoming stream's data structure is. You need to find the > marker and scan from that location on to sync your local data structure > to the incoming stream's data. > > Should the external function provide the stream data in a list rather > than a tuple? Probably, but someone else wrote the function so that's > out of your control. Can you cast the tuple to a list? Sure, but for a > large tuple that's potentially a large speed and memory hit. > > That probably the biggest general use case for tuple.index(). A > third-party module returns a tuple in which you need to find a piece of > data. > So, when you have a) a third party module that you cannot change and b) it shouldn't return a tuple but it does anyway and c) it's a big enough tuple that is large enough that conversion to a list is prohibitive, that's a "general" use case for tuple.index? Has this supposedly general and common use case actually happened? From jmcmonagle at velseis.com.au Wed Apr 25 21:43:59 2007 From: jmcmonagle at velseis.com.au (John McMonagle) Date: Thu, 26 Apr 2007 11:43:59 +1000 Subject: Where did my post go? In-Reply-To: <1177550534.197992.263190@u32g2000prd.googlegroups.com> References: <1177550534.197992.263190@u32g2000prd.googlegroups.com> Message-ID: <463003DF.4060308@velseis.com.au> flifus at gmail.com wrote: > I posted to this newsgroup earlier about my annoyances with python and > now I can't find the post. What did you do with it? > How "annoying". Seriously though, I saw it - delivered at 8:50 AEST. From robert.kern at gmail.com Wed Apr 4 18:11:25 2007 From: robert.kern at gmail.com (Robert Kern) Date: Wed, 04 Apr 2007 17:11:25 -0500 Subject: Numeric compiling problem under QNX 4.25 In-Reply-To: <1175723249.400296.169290@w1g2000hsg.googlegroups.com> References: <1175578324.426293.21970@y80g2000hsf.googlegroups.com> <1175622049.939184.28670@d57g2000hsg.googlegroups.com> <1175632439.676454.21830@q75g2000hsh.googlegroups.com> <1175723249.400296.169290@w1g2000hsg.googlegroups.com> Message-ID: ZMY wrote: > I finally figured out how to install Numeric Python on QNX4. To my > understanding of a QNX programmer's lecture, the problem of QNX4 is > that it doesn't support dynamic linking, so the linker can't link the > new compiled object files with existing python binary. The new module > must be built together with python itself. Ouch! Well, I'm glad you found a way to get going. If you have more problems, please join us on numpy-discussion, where you will find more people who have experience with Numeric than here. Just be sure to state up front that you need to use Numeric because you are on Python 2.2 to hold off the inevitable, "you should really migrate to numpy," spiel. http://www.scipy.org/Mailing_Lists -- 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 python at hope.cz Thu Apr 26 03:10:05 2007 From: python at hope.cz (python at hope.cz) Date: Thu, 26 Apr 2007 09:10:05 +0200 Subject: PIL and font colour In-Reply-To: References: <1177441923.378487.210310@r3g2000prh.googlegroups.com> Message-ID: <46306C6D.23666.1C9B9816@python.hope.cz> An HTML attachment was scrubbed... URL: From mccredie at gmail.com Mon Apr 30 16:01:52 2007 From: mccredie at gmail.com (Matimus) Date: 30 Apr 2007 13:01:52 -0700 Subject: Is it possible to merge xrange and slice? In-Reply-To: <1177956139.320184.50590@n76g2000hsh.googlegroups.com> References: <1177956139.320184.50590@n76g2000hsh.googlegroups.com> Message-ID: <1177963312.886921.127780@p77g2000hsh.googlegroups.com> > Which problems am I overlooking that prevent this? 1. Generators and slices serve two distinctly different tasks. 2. They may have the similar interfaces, but are implemented differently. Each optimized for its specific task. You are essentially asking "Why not do it?", to which I respond "Why do it?". How does this consolidation of features improve Python? From thorsten at thorstenkampe.de Mon Apr 2 13:30:07 2007 From: thorsten at thorstenkampe.de (Thorsten Kampe) Date: Mon, 2 Apr 2007 18:30:07 +0100 Subject: I18n issue with optik References: <46112f10$0$90271$14726298@news.sunsite.dk> Message-ID: * Damjan (Mon, 02 Apr 2007 18:29:06 +0200) > > Actually rxvt, Poderosa and console have the ability to display non- > > ASCII characters. I use the dejavu fonts that support non-ASCII, too. > > > > But the problem is even simpler: I can't even set the standard Windows > > console ("cmd") to Windows 1252 in Python. Although directly executing > > "chcp 1252" works. > > Maybe try to use http://sourceforge.net/projects/console it's claimed to be > muc better than the sucky CDM (I don't have windows to try it). It is definitely. But it just runs bash or cmd.exe so its capabilities (encoding) are defined by Windows or Cygwin. Thorsten From benjamin.han at gmail.com Thu Apr 12 15:57:49 2007 From: benjamin.han at gmail.com (Ben) Date: 12 Apr 2007 12:57:49 -0700 Subject: treating str as unicode in legacy code? Message-ID: <1176407869.541038.212410@p77g2000hsh.googlegroups.com> I'm left with some legacy code using plain old str, and I need to make sure it works with unicode input/output. I have a simple plan to do this: - Run the code with "python -U" so all the string literals become unicode litrals. - Add this statement str = unicode to all .py files so the type comparison (e.g., type('123') == str) would work. Did I miss anything? Does this sound like a workable plan? Thanks! From maxime.p at gmail.com Mon Apr 2 17:07:24 2007 From: maxime.p at gmail.com (Ulysse) Date: 2 Apr 2007 14:07:24 -0700 Subject: Extract information from HTML table In-Reply-To: References: <1175429635.278697.92690@b75g2000hsg.googlegroups.com> <1175439364.515873.142340@p15g2000hsd.googlegroups.com> <1175503135.234560.51730@n59g2000hsh.googlegroups.com> Message-ID: <1175548044.936163.50790@n59g2000hsh.googlegroups.com> On Apr 2, 9:28 pm, cla... at lairds.us (Cameron Laird) wrote: > In article <1175503135.234560.51... at n59g2000hsh.googlegroups.com>, > > > > anjesh wrote: > >On Apr 2, 12:54 am, "Dotan Cohen" wrote: > >> On 1 Apr 2007 07:56:04 -0700, Ulysse wrote: > > >> > I have seen the Beautiful Soup online help and tried to apply that to > >> > my problem. But it seems to be a little bit hard. I will rather try to > >> > do this with regular expressions... > > >> If you think that Beautiful Soup is difficult than wait till you try > >> to do this with regexes. Granted you know the exact format of the HTML > >> you are scraping will help, if you ever need to parse HTML from an > >> unknown source than Beautiful Soup is the only way to go. Not all HTML > >> authors close their td and tr tags, and sometimes there are attributes > >> to those tags. If you plan on ever reusing the code or the format of > >> the HTML may change, then you are best off sticking with Beautiful > >> Soup. > > >> Dotan Cohen > > >>http://lyricslist.com/http://what-is-what.com/ > > >Have you tried HTMLParser. It can do the task you want to perform > >http://docs.python.org/lib/module-HTMLParser.html > > >-anjesh > > Yes, except that these last two follow-ups UNDERstate the difficulty--in > fact, the impossibility--of achieving adequate results on this problem > with regular expressions. We'll help with the documentation for HTMLParser > and BeautifulSoup. REs are an invitation to madness. > > might amuse > those who want to think more about REs. r'(\d{2}\.\d{2}\.\d{4} - \d{2}:\d{2}:\d{2})\W*? \W*?(.*?).*?' r'(\d{2}\.\d{2}\.\d{4} - \d{2}:\d{2}:\d{2}).*?player\.php.*?>(.*?).*?(.*?)' r'(\d{2}\.\d{2}\.\d{4} - \d{2}:\d{2}:\d{2})\W*? \W*?Message au clan de :([a-zA-Z0-9_\-]+?)\W*
(.*?)' These three REs extract all data I need. That not exactly apply to the given string. I read the article but I didn't understood why REs are invitation to madness... From uriel.katz at gmail.com Fri Apr 27 23:25:57 2007 From: uriel.katz at gmail.com (urielka) Date: 27 Apr 2007 20:25:57 -0700 Subject: Interop between C# and Python In-Reply-To: <1177730289.935376.167590@e65g2000hsc.googlegroups.com> References: <1177722543.098518.192840@h2g2000hsg.googlegroups.com> <1177730289.935376.167590@e65g2000hsc.googlegroups.com> Message-ID: <1177730757.208859.274790@q75g2000hsh.googlegroups.com> thx i will try this. i am also trying XML-RPC,i wrote a basic generator(in python) that genrate a Interface from the XML-RPC service module,but maybe with soaplib i don`t need this if i use wsdl as Visual Studio can generate the code from the wsdl From claird at lairds.us Tue Apr 24 10:51:40 2007 From: claird at lairds.us (Cameron Laird) Date: Tue, 24 Apr 2007 14:51:40 +0000 Subject: Generate report containing pdf or ps figures? References: <132pnp6r4qg0lc2@corp.supernews.com> Message-ID: In article <132pnp6r4qg0lc2 at corp.supernews.com>, Grant Edwards wrote: >I need to be able to generate a PDF report which consists >mostly of vector images (which I can generate as encapsulated >Postscript, PDF, or SVG). What I need is a way to combine >these figures into a single PDF document. Right now the >reports consist entire of these figures, so I just write the >figures out to temp files and then use os.system() to run >ghostscript with appropriate options to combine them into a >single PDF file. > >I'd like to be able to add some text and/or place the figures >in a manner other than one per page in the output document. > >I've looked at ReportLab's documentation, but although it >appears to be able to use bitmap images (e.g jpeg) it doesn't >appear to be able to use vector images (EPS/PDF/SVG). > >Is there a PDF generation library that can place EPS or >PDF figures on a page? . . . You're stuck. If I understand what you're after, you're probably going to end up finding a way to leverage Ghostscript. There are a lot of ways to move forward in this area, but GS has most of 'em beat, despite all its liabilities. That's my summary. I've done quite a bit in this area, and am happy to talk about specifics. I have two recommendations: see if anything in resonates with you; and e-mail the nice folks at . I've taken the liberty of cross-posting to c.t.p. Python alone isn't big enough (yet) to solve your problem. From bbxx789_05ss at yahoo.com Tue Apr 3 14:26:24 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: 3 Apr 2007 11:26:24 -0700 Subject: File Object behavior In-Reply-To: References: Message-ID: <1175624784.625914.14660@e65g2000hsc.googlegroups.com> On Apr 3, 12:02 pm, Michael Castleton wrote: > When I open a csv or txt file with: > > infile = open(sys.argv[1],'rb').readlines() > or > infile = open(sys.argv[1],'rb').read() > > and then look at the first few lines of the file there is a carriage return > + > line feed at the end of each line - \r\n > This is fine and somewhat expected. My problem comes from then writing > infile out to a new file with: > > outfile = open(sys.argv[2],'w') > outfile.writelines(infile) > outfile.close() > > at which point an additional carriage return is inserted to the end of each > line - \r\r\n > The same behavior occurs with outfile.write(infile) also. I am doing no > processing > between reading the input and writing to the output. The file.writelines() documentation says that it > doesn't add line separators. Is adding a carriage return something > different? > At this point I have to filter out the additional carriage return which > seems like > extra and unnecessary effort. > I am using Python 2.4 on Windows XP sp2. > Can anybody help me understand this situation? > > Thanks > -- > View this message in context:http://www.nabble.com/File-Object-behavior-tf3520070.html#a9821538 > Sent from the Python - python-list mailing list archive at Nabble.com. > The file.writelines() documentation says that it > doesn't add line separators. Is adding a carriage return something > different? No. > Is this expected behavior? According to Python in a Nutshell(p. 217) it is. On windows, in text mode, when you write a \n to a file, the \n is converted to the system specific newline (which is specified in os.linesep). For windows, a newline is \r\n. Conversely, on windows, in text mode, when you read a \r\n newline from a file, it is converted to a \n. From ghirai at ghirai.com Sun Apr 1 10:24:06 2007 From: ghirai at ghirai.com (Ghirai) Date: Sun, 1 Apr 2007 17:24:06 +0300 Subject: p2p chat framework Message-ID: <917216446.20070401172406@ghirai.com> Hello python-list, Are there any p2p chat/filetransfer frameworks/examples floating around? If not, can someone give me some rough directions towards writing my own? Thanks. -- Best regards, Ghirai. From moiseau at gmail.com Thu Apr 5 02:26:38 2007 From: moiseau at gmail.com (moiseau at gmail.com) Date: 4 Apr 2007 23:26:38 -0700 Subject: ok Message-ID: <1175754398.890967.254050@l77g2000hsb.googlegroups.com> hi looking for someone to bult my web site for me From cjw at sympatico.ca Mon Apr 23 07:14:21 2007 From: cjw at sympatico.ca (Colin J. Williams) Date: Mon, 23 Apr 2007 07:14:21 -0400 Subject: [ANN] Pythonutils 0.3.0 In-Reply-To: <1177271163.678440.51370@b58g2000hsg.googlegroups.com> References: <1177271163.678440.51370@b58g2000hsg.googlegroups.com> Message-ID: Fuzzyman wrote: > There is a new (and long overdue) release of the `Pythonutils module > `_. > This is version **0.3.0**. > > * `Quick Download: Pythonutils 0.3.0.zip cgi-bin/voidspace/downman.py?file=pythonutils-0.3.0.zip>`_ > > > What is Pythonutils? > =============== > > Pythonutils is a collection of general utility modules that simplify > common programming tasks in Python. > > > The modules included are : > > * `ConfigObj `_ > 4.4.0 - Easy config file reading/writing > * `validate `_ > 0.2.3 - Validation and type conversion system > * `StandOut `_ > 3.0.0 - Simple logging and output control object > * `pathutils `_ > 0.2.5 - For working with paths and files > * `cgiutils `_ > 0.3.5 - {acro;CGI} helpers > * `urlpath `_ > 0.1.0 - Functions for handling URLs > * `odict `_ > 0.2.2 - Ordered Dictionary Class > > > For more details, visit the `Pythonutils Homepage www.voidspace.org.uk/python/pythonutils.html>`_. > > > What is New in 0.3.0? > ================ > > Several of the modules have been updated. The major changes are: > > * Removed the `listquote listquote.html>`_ module > * ConfigObj updated to 4.4.0 > * StandOut updated to 3.0.0 (*Not* backwards compatible, but much > improved) > Thanks, the modules are nicely documented. The odict is particularly welcome. Colin W. From a-alpha at otenet.gr Mon Apr 23 03:06:20 2007 From: a-alpha at otenet.gr (S S) Date: Mon, 23 Apr 2007 10:06:20 +0300 Subject: sharon stone paris hilton Message-ID: sharon stone paris hilton www.alphasearch.at www.alphasearch.be www.alphasearch.it www.alphasearch.info www.alphasearch.gr www.alphasearch.es www.alphasearch.se www.alphasearch.dk -------------- next part -------------- An HTML attachment was scrubbed... URL: From daraburke78 at gmail.com Wed Apr 18 19:15:53 2007 From: daraburke78 at gmail.com (dbee) Date: 18 Apr 2007 16:15:53 -0700 Subject: Third party script debugging on remote server ... Message-ID: <1176938153.119084.214700@d57g2000hsg.googlegroups.com> Right. I've got a really, really annoying/difficult/time consuming problem with my development environment. I'm using django to build a web app with paypal integration. My server is hosted remotely, and it is receiving IPN (payment notifications) POST requests from Paypal. I've checked on google and irc and this is my last shot at solving this before I go mad ... :-( The problem is that I can't debug those POST requests. Browser debugging is out of the question obviously cause I'm not at the computer, ( and it doesn't have X ). I've tried cgitb but that doesn't seem to work at all ... import cgitb; cgitb.enable(display=0,logdir='/tmp/',format='plain') import cgitb; cgitb.enable() ... neither of those commands have any effect. Although I do log other parts of the script to /tmp, so I know that it's reachable... mod_python absolutely refuses to error_log to the apache error_log. I have restarted it and it still won't flush whatever error buffer it may ( or may not ) have stored. I can re-constitute the requests in my browser using a GET request. But frankly, that's kinda messy - there are lots of paypal IPN combinations and I may have to integrate other applications with paypal. So ideally speaking I'm looking for a proper debugging environment for this kind of thing ... Basically, I either want mod_python to start error_logging properly, or I want some type of working traceback environment to be available. Help ! Server version: Apache/2.0.52 Server built: Aug 13 2006 03:29:43 CentOS4.x: (RedHat Clone) mod_python.i386 3.1.3-5.1 installed # httpd.conf ServerName mydomain.biz ServerAlias www.mydomain.biz SetHandler mod_python PythonPath "['/home/babo/django'] + sys.path" PythonHandler django.core.handlers.modpython SetEnv DJANGO_SETTINGS_MODULE mydomain.settings SetHandler None Options None My python.conf: ( seems pretty normal ) # # Mod_python is a module that embeds the Python language interpreter # within the server, allowing Apache handlers to be written in Python. # LoadModule python_module modules/mod_python.so # Override type-map handler for /var/www/manual SetHandler default-handler # This will cause files beneath /var/www/html with the extension .spam # to be handled by the Python script /var/www/html/eggs.py # # # AddHandler python-program .spam # PythonHandler eggs # # This will cause all requests to the /python heirachy of your # webserver to be handled by the python script /path/to/myhandler.py # # # SetHandler python-program # PythonPath "sys.path + ['/path/to']" # PythonHandler myhandler # # This will cause all requests to the /python heirachy of your # webserver to be handled by mod_python's Publisher handler # (see http://localhost/manual/mod/mod_python/hand-pub.html) # # This will cause the output of all requests to files beneath # /var/www/html with the extension .flt to be filtered through # the Python script /var/www/html/filter.py # # # PythonOutputFilter filter MYFILTER # AddOutputFilter MYFILTER .flt # From Martin.Drautzburg at web.de Sun Apr 22 07:07:27 2007 From: Martin.Drautzburg at web.de (Martin Drautzburg) Date: Sun, 22 Apr 2007 13:07:27 +0200 Subject: serializable object references Message-ID: <1242622.P0zHLAfcMH@beaureve.gmx.net> Is it possible to convert an object into a string that identifies the object in a way, so it can later be looked up by this string. Technically this should be possible, because things like <__main__.Foo instance at 0xb7cfb6ac> say everything about an object. But how can I look up the real object, when I only have this string? I know such a thing can be achieved with a dictionary that holds reference-object pairs. Is there another way? From fkasner at sbcglobal.net Sat Apr 14 17:54:41 2007 From: fkasner at sbcglobal.net (Fred Kasner) Date: Sat, 14 Apr 2007 21:54:41 GMT Subject: WOLFOWITZ AND HIS IRANIAN PROSTITUTE SALARY OF $190k/yr Re: Test Tube Zealots: The American Chemical Society Terminates the Membership of Chemists from Iran In-Reply-To: <1176571401.111829.122500@b75g2000hsg.googlegroups.com> References: <1175963599.167629.90830@y80g2000hsf.googlegroups.com> <1176571401.111829.122500@b75g2000hsg.googlegroups.com> Message-ID: lemnitzer at india.com wrote: > "I now direct you to agree to a proposal which includes the following > terms and conditions," Wolfowitz instructed. "You should accept > immediately her offer to be detailed to an outside institution of her > choosing, while retaining bank salary and benefits." > > The Wolfowitz memo went on say that Riza should receive a promotion, > draw a salary of 180,000 dollars (?90,000) and get annual pay > increases of 8%. > > Before the job change, Riza was believed to be getting paid close to > 133,000 dollars (?67,000). After the transfer, she received 193,590 > dollars (?97,000), according to the Government Accountability Project, > a watchdog group. > > Riza remains on the World Bank's payroll though she left the State > Department job last year and now works for Foundation for the Future, > an international organisation that gets some money from the > department. > > On Apr 7, 9:33 am, stj... at rock.com wrote: >> http://counterpunch.org/rahni04072007.html >> >> Test Tube Zealots: The American Chemical Society Terminates the >> Membership of Chemists from Iran >> >> By DAVID N. RAHNI >> >> The American Chemical Society (ACS) has once again led the way, with >> its "zealot" interpretation of "embargo" by the Department of >> Treasury's Office of Foreign Asset Control, by terminating the >> membership of its long-standing members in Iran, many of whom are post >> Ph.D. Alumni of American Universities. Several years ago, the ACS >> undertook a similar unprecedented action, under the same law. Then, it >> unilaterally stopped accepting scholarly and research manuscripts from >> Iranian scientists for its three dozen periodicals in the publication >> division. However, later, under embarrassing pressure from the >> American scientific community and its membership, the ACS retracted >> its decision and agreed to take it up instead with the federal >> government. Paradoxically and notwithstanding rhetoric, such ill- >> conceived measures are against the current U.S. Administration policy >> of promoting people-to-people contact as enunciated by the Assistant >> Secretary of State Nicholas Burns at the March 29 hearing of the >> Senate Foreign Relations Committee. >> >> Yudhijit Bhattacharjee, in Science Magazine, reported that the ACS >> Assistant General Counsel, David Smorodin when "re-reading the embargo >> rules, made the recommendation to terminate Iranian membership(Science >> Magazine, Vol. 315, 30 March 2007). One can not help but speculate >> whether or not such decision is truly serving the interests of member- >> based ACS or enforcing the laws to the limit as he has served as a >> U.S. Assistant District Attorney before joining the ACS. Nonetheless, >> despite the abrupt termination of individual membership of Iranian >> chemical scientists with no due process, the ACS has stated that while >> they [Iranians] can continue to purchase journals and other "non- >> sensitive products at full-rate, the ACS might apply for a special >> license from the Treasury Department to reinstate their memberships. >> This has in the meantime deprived American chemists to learn about the >> scholarly contributions of their Iranian peers. >> >> It should be noted that as in the past, the American Physical Society >> (APS), in contrast, stated, "We have NO plan to do anything similar, >> and continue to serve our members in Iran." Judy Franz, a director at >> the APS further stated that, "We would resist having to obtain a >> license to the extent we can." >> >> When interviewed by Science Magazine, the official publication of the >> American Association for the Advancement of Science (AAAS), David >> Rahni an Iranian-American chemistry professor in New York stated, "I, >> like most ACS members and peers in the scientific community, strongly >> question the ACS motive on this issue, and expect ACS,s leadership to >> refrain from allowing politics to taint the high stature the >> Organization has achieved." Rahni further stated that this has >> personally concerned him gravely since he has served the ACS with >> distinctions in the past thirty years, as typified by his positions as >> the chair of the ACS New York, the chair of the Middle Atlantic >> Regional Meeting, and the chair of Nichols Medal. 90% of the ACS >> projects, publications and activities are run by a huge cadre of >> volunteer professionals who, with no expectations, give their time, >> energy, money and intellects and talents to the advancement of the >> chemical sciences worldwide. It is painfully ironic to many, >> especially the ACS American members to witness the politicization of >> their disciplines through the ACS as they continue to register their >> grave concerns with the ACS lucratively remunerated executive >> directors. As a chemistry professor with having given fifty years of >> his life to the ACS and the profession so eloquently put it, "Never >> mind the Iranians as one may not give a darn about them and their >> plights, what, I am bewildered to speculate the ulterior motives of >> the ACS paid "professional leadership is to embarrass us as >> freethinking science. ACS is US and not its DC staff as they are >> required by our mandate to serve our interests and not create problems >> for us. >> >> The consensus among the nearly one million Americans of Iranian >> ancestry is to reaffirm their yearning commitment to the attainment of >> justice, security, stability, equity, transparency and human rights >> through "home-grown", indigenous and democratic reforms in Iran, but >> not at the expense of isolating the scientific community in their >> motherland from their peers worldwide. They further deplore any >> possible unilateral military action against Iran, as they firmly >> believe this is counter-productive to the organic, slow, but steady >> evolution of Iran through educational benchmark, cultural reforms and >> communication with the rest of the world. They further consider >> military action and/or isolation counter-productive to the credibility >> of their American homeland which would inevitably lead, once again, to >> the priceless loss of human life and loss of credibility for our >> nation in the international scene. >> >> Iran's chemist/chemical engineering professionals/scholars numbers >> tens of thousands. They are, by and large, members of the Iranian >> Chemical Society. However, many of them hold at least one overseas >> membership, mostly in the Royal Societies in the UK. There are >> currently 36 Iranian members in the American Chemical Society. The >> strong position of chemistry/chemical engineering in Iran is due to >> the oil and gas explorations by the petrochemical industry during the >> past 100 years, and due to some of Iran,s renowned past and >> contemporary chemists, scientists, and philosophers. The contributions >> of Americans of Iranian background to the chemistry and sciences, >> engineering and medicine, is unparalleled by other recent immigrant >> communities. There indeed exists an > news.htm>Iranian Chemists' Association of the ACS that since its >> inception in the 80, has reached out to over a thousand chemists of >> Iranian ancestry in the U.S. alone. It is well substantiated that as >> long as the diplomatic relations between the two nations remain at a >> hostile stalemate, a political cloud hovers over the personal and >> professional aspirations of Iranian-Americans. Specifically, senior >> and executive level professional opportunities for Iranian-Americans, >> particularly in government, higher education and the corporate world, >> remain chronically undermined. >> >> Iran, a multiethnic country of 70 million, traces its heritage to a >> long and illustrious history, 10,000 years in the making, with 2500 >> years of a continuous form of government. There are two million >> students in her higher education system, 60% of whom, especially in >> the sciences, engineering and medicine, are women. Its literacy rate >> is 90%, unprecedented in that part of the world. Iran or Persia as it >> was formerly known by the outside world until 1935, has indeed >> contributed immensely toward the advancement of science, technology >> and society for millennia. Rhazes, Avicenna, Algorithm, Omer Khayam, >> Farabi, Biruni, Hayyan, and many others are some of the epics that >> come to a western scholar,s mind. >> >> Despite the tremendous burden imposed on the Iranian students and >> scholars as they struggle to obtain a US visa (mostly denied) for >> doctoral studies, some of the brightest graduate students in Ivy >> League Universities (e.g., Stanford, Harvard, Berkeley, and MIT) are >> Iranians. Increasingly, however, they opt to pursue their doctoral >> studies in Australia, Canada and Europe. Iranian high school students >> have continuously ranked among the top few of the nations in the >> International Chemistry and other Science Olympiads, and Robotics and >> Computing Competitions. >> >> Isn't it ironic that when the ACS claims to be an international >> professional society, 130 years old, with a membership of 160,000, 10% >> of whom are from overseas, and an additional 20%, are naturalized >> Americans or permanent residents, that it forces the nationals of Iran >> out, deprives them from maintaining scientific communications with >> peers worldwide, and does not let them contribute toward the >> advancement of science worldwide? >> >> Notwithstanding the rhetoric and provocations leading to a possible >> disastrous confrontation by governments, a true scientist, or a >> credible organization of scientists such as the ACS, which does not >> recognize the boundaries of the world, should be capable to transcend >> all political barriers for the advancement of science. >> >> David N. Rahni, Ph.D. is a Professor of Chemistry at Pace University, >> in Pleasantville, New York and Adjunct Professor of Dermatology, New >> York Medical College. He is also an Adj. Prof. Envirnonmental Law at >> Pace U. He can be reached at: dnabira... at pace.edu > > If you would read C&EN News you would be aware that the response of the membership is hardly majority in favor of such actions. Had they polled the membership I doubt that the action would have been approved. The action of a state is not necessarily the will of even a majority of its citizens. Consider if you will the present popularity polls in regard to the President of the United States of America. FK From kw at codebykevin.com Mon Apr 23 09:55:04 2007 From: kw at codebykevin.com (Kevin Walzer) Date: Mon, 23 Apr 2007 09:55:04 -0400 Subject: Do other Python GUI toolkits require this? In-Reply-To: References: <462697A6.6010007@codebykevin.com> <57C90994-391D-4350-A2F2-29C1590A3335@jedimindworks.com> Message-ID: <462CBAB8.3050107@codebykevin.com> Michael Bentley wrote: > OK. In order to kill the-thread-that-would-not-die(tm), I think I know > what I must do. I'll print a correction: > > On Apr 19, 2007, at 2:22 AM, Michael Bentley wrote: >> ... I switched to PyObjC. The >> learning curve is rather steep IMO, but worth it. One thing I think >> I should mention though is that if you move to PyObjC -- do some >> projects in Objective C first. Otherwise your brain will implode. > > Should be changed to: > > .. I switched to PyObjC. The > learning-effort curve is rather steep IMO, but worth it. One thing I think > I should mention though is that if you move to PyObjC -- do some > projects in Objective C first. Otherwise your brain will implode. > > Hope this helps, > Michael ;-) > I had originally thought that learning PyObjC might preclude me from having to learn Objective-C, but that seems not to be the case. I have previously found the same to be true with PyQt and wxPython--not knowing the toolkits as they are implemented in C++ is a serious handicap. I've even found this to be the case with Tkinter: understanding the Tcl implementation of Tk (which I do, because I am also a Tcl developer) is a huge advantage. Am I wrong to conclude that, if you want to do GUI programming in Python, then some level of proficiency with another language is not just recommended, but almost required? This is the case at least in my experience. When I first started learning Python a couple of years ago, I spun my wheels with it for months, because I couldn't figure out where to get started with GUI programming. Finally I set Python aside and took up Tcl/Tk for awhile--its simplicity in building GUI's is more beginner-friendly. (No "there's more than one way to do it"--there's only one way to do it, and that's Tk.) Now, coming back to Python with the Tk model of GUI development burned in my brain, I appreciate the breadth of functions that Python supports--but I still find myself "dropping down into Tcl" (!) to assemble elements of my GUI's--either to write a Python wrapper, or figure out how to implement something in pure Python. I understand the argument for Python having lots of bindings to different GUI toolkits. If you are already proficient with a GUI toolkit in a compiled language (Gtk, wxWidgets, Cocoa, Qt) then presumably switching to Python will speed up your development--learning Python is easy if you already know C++, for instance, and usually the Python bindings are just a "thin wrapper" over the compiled bits. But if you come to Python from the other direction--you're a relative beginner and you want to learn GUI programming without the complexities of compiled languages--then it's a lot harder to get started, ironically. Even Tkinter is a challenge for someone who doesn't know Tcl. The basics are easy enough--buttons, menus, labels, images--but doing anything sophisticated, such as trees, column views, drag-and-drop, and so on, requires extensions that may or may not be implemented in Python. -- Kevin Walzer Code by Kevin http://www.codebykevin.com From mathieu.malaterre at gmail.com Wed Apr 25 11:50:15 2007 From: mathieu.malaterre at gmail.com (mathieu) Date: 25 Apr 2007 08:50:15 -0700 Subject: gcov-like python code coverage Message-ID: <1177516215.336440.315710@o40g2000prh.googlegroups.com> Just in case something already exist for this. Is there some tool, that can produce gcov-type coverage out of a python code ? I have an already existing regex code that turn gcov output into XML, which I'd like to reuse. thanks ! -Mathieu From duncan.booth at invalid.invalid Tue Apr 10 08:40:30 2007 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 10 Apr 2007 12:40:30 GMT Subject: tuples, index method, Python's design References: <1175867771.114540.61810@n76g2000hsh.googlegroups.com> <1175884427.779950.267220@y80g2000hsf.googlegroups.com> <1175953520.316208.241490@o5g2000hsb.googlegroups.com> <7xzm5igbrb.fsf@ruckus.brouhaha.com> Message-ID: Antoon Pardon wrote: > On 2007-04-10, Duncan Booth wrote: >> There is a cost to every new language feature: it has to be >> implemented, documented, maintained, and above all learned by the >> users. Good design involves, in part, not adding to these burdens >> except where there is a benefit at least equal to the cost. > > So what is the easiest to learn: "All sequences have an index method" > or "Such and so sequences have an index method and others don't" > > Which of the above is the easiest to document? The second would be if it were true. However it would mean you would have to add an index method to *all* sequences. FWIW, The current documentation says that 's.index' is a method defined on all *mutable* sequence types: almost as simple as your second wording but unfortunately misleading since strings also have index. > If someone states: "Show me your use case for using tuple.index and I > will show you how to avoid it." or words to that effect I think there > is little use trying. I genuinely cannot think of a use case. I didn't ask you to suggest one so I could show you how to avoid it, I asked you to suggest one so that we could take the discussion from the purely hypothetical to a more concrete discussion of whether it would be a worthwhile enhancement. Fair enough though. I'll assume you cannot think of a suitable use case either. From Martin.Drautzburg at web.de Mon Apr 23 15:44:43 2007 From: Martin.Drautzburg at web.de (Martin Drautzburg) Date: Mon, 23 Apr 2007 21:44:43 +0200 Subject: Namespaces/introspection: collecting sql strings for validation References: <1921780.hifcbgjtIO@beaureve.gmx.net> <2075208.bSjua6qmHG@beaureve.gmx.net> Message-ID: <1245443.HvheOGI05V@beaureve.gmx.net> Peter Otten wrote: >>>> def SQL(sql): > ... ? ? print sql > ... >>>> a = SQL("module") > module # that one was obvious >>>> class A: > ... ? ? b = SQL("class") > ... ? ? def method(self, c=SQL("default arg")): > ... ? ? ? ? ? ? d = SQL("method") > ... You are my hero. Indeed very cool! From gagsl-py2 at yahoo.com.ar Tue Apr 24 07:46:50 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Tue, 24 Apr 2007 08:46:50 -0300 Subject: Getting python script to write to input box on another window References: <1177406151.797865.141440@r30g2000prh.googlegroups.com> Message-ID: En Tue, 24 Apr 2007 06:15:51 -0300, sophie_newbie escribi?: > I'm wondering if there is a way to get a python script to write text > to an input box in a window of another program that is running? For > example a text box in a web browser window? You could use pyWinAuto on Windows. -- Gabriel Genellina From steve at holdenweb.com Sun Apr 22 21:06:07 2007 From: steve at holdenweb.com (Steve Holden) Date: Sun, 22 Apr 2007 21:06:07 -0400 Subject: Class Not Auto-Init On Import In-Reply-To: References: <2987.60099472037$1177145337@news.gmane.org> Message-ID: Dennis Lee Bieber wrote: > On Sat, 21 Apr 2007 11:56:05 -0400, Steve Holden > declaimed the following in comp.lang.python: > >> Robert Rawlins - Think Blue wrote: > >>> LocationService.setIP(?192.168.1.1?) >>> >> This isn't a call on a specific LocationService instance, it's a call on >> the SetIP method of the class (presumably you have to set the IP address >> of the server or whatever - typically class methods are used to invoke >> functions or set up conditions that must apply to all instances of the >> class. If you wanted to set the IP for a particular instance you would >> normally call a method instance, as in >> > Actually, in the absence of a "from ... import *", that isn't even a > call on the /class/. > > It's a call on a standalone setIP() located in the imported /module/ Indeed it is. Good catch. 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 bj_666 at gmx.net Mon Apr 16 06:09:48 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Mon, 16 Apr 2007 12:09:48 +0200 Subject: How to generate a continuous string References: <1176717806.754728.9600@y80g2000hsf.googlegroups.com> Message-ID: In <1176717806.754728.9600 at y80g2000hsf.googlegroups.com>, ??????????????? wrote: > How to generate a continuous string, like this > "aaaaaaaaaaaaaaaaaaaaaaa" > the number of characters is dynamic. Is there a module or function > implement this string ? > such as: duplicate_string(char, num) Even easier: multiply the string by a number. In [12]: 'a' * 5 Out[12]: 'aaaaa' Ciao, Marc 'BlackJack' Rintsch From tom at finland.com Tue Apr 3 12:35:13 2007 From: tom at finland.com (tom at finland.com) Date: Tue, 03 Apr 2007 16:35:13 GMT Subject: Stack experiment In-Reply-To: <5QuQh.152$9L1.108@read3.inet.fi> References: <5QuQh.152$9L1.108@read3.inet.fi> Message-ID: <5nvQh.164$9L1.102@read3.inet.fi> Ok, I got it running. Thank you! I removed the space and top of that I had foul indentation in return statement. I'll try the approaches you suggest. From bthom at cs.hmc.edu Wed Apr 25 17:30:49 2007 From: bthom at cs.hmc.edu (belinda thom) Date: Wed, 25 Apr 2007 14:30:49 -0700 Subject: sorting question Message-ID: Hi, I've had a look at http://wiki.python.org/moin/HowTo/Sorting, but am not sure if I can get the operator.itemgetter to do what I want for my particular need. I'm also not sure why creating my own cmp for pulling tuple parts out and passing it to a list sort doesn't just work. I'm sure this stuff is old hat to many on this list. Suggestions happily accepted. Suppose I've got a list like: l = [(-.3,(4,3)),(.2,(5,1)),(.10,(3,2))] and I want to sort on the 2nd item in the 2nd tuple. I've tried things like: cmp = lambda x,y : x[1][1] > y[1][1] l.sort(cmp=cmp) but l isn't then changed in place. Using sorted(l,operator.itemgetter(1)) behaves as I'd expect, but I really want something like operator.itemgetter(1).itemgetter(1), which (understandably) causes a syntax error. Thx, --b From rhamph at gmail.com Sun Apr 15 13:49:38 2007 From: rhamph at gmail.com (Rhamphoryncus) Date: 15 Apr 2007 10:49:38 -0700 Subject: tuples, index method, Python's design In-Reply-To: <7xvefym5r6.fsf@ruckus.brouhaha.com> References: <1176200361.260546.280510@n76g2000hsh.googlegroups.com> <740c3aec0704100824m132c45fbi5c4c3ec0c0fa3a67@mail.gmail.com> <1176489534.568939.249910@q75g2000hsh.googlegroups.com> <7x3b33k0l9.fsf@ruckus.brouhaha.com> <1176572775.382873.282850@q75g2000hsh.googlegroups.com> <7xr6qmrg4x.fsf@ruckus.brouhaha.com> <1176618596.238855.122000@d57g2000hsg.googlegroups.com> <7xvefym5r6.fsf@ruckus.brouhaha.com> Message-ID: <1176659378.618211.149550@d57g2000hsg.googlegroups.com> On Apr 15, 1:55 am, Paul Rubin wrote: > "Rhamphoryncus" writes: > > Indexing cost, memory efficiency, and canonical representation: pick > > two. You can't use a canonical representation (scalar values) without > > some sort of costly search when indexing (O(log n) probably) or by > > expanding to the worst-case size (UTF-32). Python has taken the > > approach of always providing efficient indexing (O(1)), but you can > > compile it with either UTF-16 (better memory efficiency) or UTF-32 > > (canonical representation). > > I still don't get it. UTF-16 is just a data compression scheme, right? > I mean, s[17] isn't the 17th character of the (unicode) string regardless > of which memory byte it happens to live at? It could be that that accessing > it takes more than constant time, but that's hidden by the implementation. > > So where does the invariant c==s[s.index(c)] fail, assuming s contains c? On linux (UTF-32): >>> c = u'\U0010FFFF' >>> c u'\U0010ffff' >>> list(c) [u'\U0010ffff'] On windows (UTF-32): >>> c = u'\U0010FFFF' >>> c u'\U0010ffff' >>> list(c) [u'\udbff', u'\udfff'] The unicode type's repr hides the distinction but you can see it with list. Your "single character" is actually two surrogate code points. s[s.index(c)] would only give you the first surrogate character -- Adam Olsen, aka Rhamphoryncus From mad.vijay at gmail.com Thu Apr 12 08:09:25 2007 From: mad.vijay at gmail.com (SamG) Date: 12 Apr 2007 05:09:25 -0700 Subject: Capturing the entry point of a script Message-ID: <1176379765.744534.148780@o5g2000hsb.googlegroups.com> If a function does not have main function defined and there is only a if __name__="__main__": how do i make a call to that using profile.runcall( ...) in my profiling script. Is there a way to find the entry point of a script and indentify it with module method. From aleax at mac.com Thu Apr 19 23:41:04 2007 From: aleax at mac.com (Alex Martelli) Date: Thu, 19 Apr 2007 20:41:04 -0700 Subject: Python Feature Request: Explicit variable declarations References: <1176546078.934340.253810@y5g2000hsa.googlegroups.com> Message-ID: <1hwu43c.dp5yo01rsqhjfN%aleax@mac.com> Jorgen Grahn wrote: > As a C and C++ programmer (not a C/C++ programmer), I have to say that Yeah, I wonder, what's C divided by C++ -- maybe about 0.731...? Alex From aleax at mac.com Thu Apr 26 10:32:40 2007 From: aleax at mac.com (Alex Martelli) Date: Thu, 26 Apr 2007 07:32:40 -0700 Subject: If Dict Contains a particular key References: <000001c78695$ed321540$c7963fc0$@rawlins@thinkbluemedia.co.uk> <1177436682.3441.15.camel@dot.uniqsys.com> <1177565430.992904.149450@n35g2000prd.googlegroups.com> Message-ID: <1hx61ry.19m17ui1eh6ekmN%aleax@mac.com> John Nagle wrote: ... > It would be useful if there was some direct way to get the value > associated with a key, and None if there's not one. >From : """ Guido's most important attribute besides Python itself is Guido's time machine, a device he is reputed to possess because of the unnerving frequency with which user requests for new features have been met with the response "I just implemented that last night..." """ or rather more often nowadays, as in this case, he implemented it many, many years ago -- method get of the dict type, as others already said. Alex From ebgssth at gmail.com Sun Apr 22 12:51:36 2007 From: ebgssth at gmail.com (js ) Date: Mon, 23 Apr 2007 01:51:36 +0900 Subject: file.read() returns an emtpy even if its currenet position is not at the end Message-ID: Hi list. I'm writing a tail -f like program in python and I found file.read() doesn't work as I think it should. Here's the code illustrating my problem. ### #!/usr/bin/env python import os, sys filename = "test.out" f = open(filename, "w+") f.write("Hello") f.flush() f.seek(0, 2) statinfo = os.stat(filename) print "file size: %d" % statinfo.st_size print "position : %d" % f.tell() line = f.read() print "line : [%s]" % line # Writing the same file using another fd f2 = open(filename, "a+") f2.write("World") f2.flush() f2.close() statinfo = os.stat(filename) print "file size: %d" % statinfo.st_size print "position : %d" % f.tell() line = f.read() # read() returns emtpy!! readlines?() works ok ### Running the above, I got the following. ### file size: 5 position : 5 line : [] file size: 10 position : 5 ### So my question is why the second f.read() returns an emtpy? >From tell() and its st_size I'm sure that file descriptor is not at the EOF and read()'s doc says "An empty string is returned when EOF is encountered immediately". Using readline() or readlines() instead of read() works great though. I'm using Python 2.4.3 on OS X. Probably I'm missing something but I could't figure out. Thanks in advance. From python-url at phaseit.net Mon Apr 2 15:47:11 2007 From: python-url at phaseit.net (Cameron Laird) Date: Mon, 2 Apr 2007 19:47:11 +0000 (UTC) Subject: Python-URL! - weekly Python news and links (Apr 2) Message-ID: QOTW: "This whole charset mess is not meant to be solved by mere mortals." - Thorsten Kampe, a day or so before solving his symptom with a codecs method: http://groups.google.com/group/comp.lang.python/msg/a2e573ccc54f66db http://groups.google.com/group/comp.lang.python/msg/a2e573ccc54f66db "... [T]here's almost never a reason to use the cmp= argument to sort() anymore. It's almost always better to use the key= argument." - STeVe Bethard http://groups.google.com/group/comp.lang.python/browse_thread/thread/67b996ccebb477f4/ wmi makes it easy for a Windows-hosted Python process to examine the process table: http://groups.google.com/group/comp.lang.python/browse_thread/thread/c38ff6f7e2469581/ wmi does much else, too, of course; its documentation rewards study. Mind the Exceptions! When overriding built-ins--and in many of life's other Pythonic moments--Exceptions are important to conform: http://groups.google.com/group/comp.lang.python/msg/2136bcbd13a022c2 John Nagle, Mark Dufour, Paul Boddie, ... usefully frame type annotation as a general issue of language development: http://groups.google.com/group/comp.lang.python/msg/78bb43f3679d51b5 http://groups.google.com/group/comp.lang.python/msg/d246e366c9d23378 Notice the larger thread to which this contributes advertises the virtues of Shed Skin 0.0.21. Testing has many specific idioms and ideas. Python's relation to testing deserves wider understanding: http://groups.google.com/group/comp.lang.python/browse_thread/thread/5854b5b6326e5d34/ ======================================================================== 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 should get through. To receive a new issue of this posting in e-mail each Monday morning (approximately), ask 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 ptmcg at austin.rr.com Tue Apr 10 16:38:22 2007 From: ptmcg at austin.rr.com (Paul McGuire) Date: 10 Apr 2007 13:38:22 -0700 Subject: problem with UDP broadcast on Windows XP In-Reply-To: <461bf42a$0$326$e4fe514c@news.xs4all.nl> References: <461a271c$0$323$e4fe514c@news.xs4all.nl> <461a6523$0$327$e4fe514c@news.xs4all.nl> <012e01c77b3c$09bd3ec0$03000080@hendrik> <461bf42a$0$326$e4fe514c@news.xs4all.nl> Message-ID: <1176237502.731802.92950@v33g2000cwv.googlegroups.com> On Apr 10, 3:30 pm, Irmen de Jong wrote: > > Hendrik van Rooyen wrote: > >> I am not sure if this is at all relevant - but I seem to recall seeing > >> something once that had a list of socket numbers, splitting them > >> between UDP & TCP - can the socket actually rx UDP? > Yeah, as I wrote: when I'm sending UDP packets to the port directly > > on the server's IP address, it responds just fine. > > It's just the broadcast packets that don't seem to arrive. > (sent to ('',9090) ) > > Steve Holden wrote: > > It's most likely, I suspect without knowing to much about it, that the > > service is stalling because of a failure to "pump" Windows messages. > > Irmen, are you taking any action in your service to ignore Windows > > messages that your service process receives? > > Hm, seeing that it processes TCP and "directed" UDP packets just fine, > there shouldn't be a problem here? > > No I'm not knowingly doing stuff that ignores windows messages... > > (I could maybe put up the code if someone wants to take a look but > not right now. Need to rip a fair deal out - there's a lot of > other stuff in there that's not relevant to the problem.) > > --Irmen I would investigate Windows security settings as a likely culprit. My guess is that you are running WinXP SP2 with the default security policies, which are likely to prohibit such promiscuous behavior. Here's a URL that may shed some light, it seems surprisingly instructive for MS support: http://support.microsoft.com/kb/842242 - Some programs seem to stop working after you install Windows XP Service Pack 2 -- Paul From jackson at hotmail.com Thu Apr 26 01:08:42 2007 From: jackson at hotmail.com (Bill Jackson) Date: Wed, 25 Apr 2007 22:08:42 -0700 Subject: random.py Message-ID: In random.py (Python 2.5.1), line 86 says: VERSION = 2 # used by getstate/setstate Then, in the definition of Random.setstate, we have: if version == 2: Why is it not: if version == self.VERSION: From mensanator at aol.com Thu Apr 26 01:30:31 2007 From: mensanator at aol.com (mensanator at aol.com) Date: 25 Apr 2007 22:30:31 -0700 Subject: If Dict Contains a particular key In-Reply-To: References: <000001c78695$ed321540$c7963fc0$@rawlins@thinkbluemedia.co.uk> <1177436682.3441.15.camel@dot.uniqsys.com> Message-ID: <1177565430.992904.149450@n35g2000prd.googlegroups.com> On Apr 24, 1:41 pm, Steven Bethard wrote: > Steven Howe wrote: > > Carsten Haese wrote: > >> On Tue, 2007-04-24 at 18:28 +0100, Robert Rawlins - Think Blue wrote: > > >>> Hello Guys, > > >>> I'm Looking to build a quick if/else statement that checks a > >>> dictionary for a key like follows. > > >>> If myDict contains ThisKey: > > >>> Do this... > > >>> Else > > >>> Do that... > > >> I'm pretty sure you'll find the answer to this question somewhere in > >>http://docs.python.org/tut/tut.html > > >> -Carsten > > > or try: > > thedict = { 'a': 1, 'b':2, 'c':3 } > > if 'a' in thedict.keys(): > > print thedict['a'] > > Better yet, just: > > if 'a' in thedict: > ... > > There's no need for the call to keys(). Why not if thedict.has_key('a'): pass elde: pass > > STeVe- Hide quoted text - > > - Show quoted text - From irmen.NOSPAM at xs4all.nl Mon Apr 9 07:43:23 2007 From: irmen.NOSPAM at xs4all.nl (Irmen de Jong) Date: Mon, 09 Apr 2007 13:43:23 +0200 Subject: [offtopic?] problem with UDP broadcast on Windows XP Message-ID: <461a271c$0$323$e4fe514c@news.xs4all.nl> Hello Sorry this might be a bit offtopic but I don't really know where else to post this question. If you could point me in the right direction that is much appreciated. I'm running into a weird thing on Windows XP. I'm using Python 2.5 with latest pywin32 from Mark Hammond. I have this UDP socket server that binds on ('',9090) and is used to be a broadcast responder. It works fine when I start the server from the cmd prompt. UDP broadcast packets sent to ('',9090) arrive in the server. However now I'm running the same server as a Windows NT Service. The same code is executed, the UDP server socket is bound to the same address. But this time, the UDP broadcast packets do NOT arrive.... !? When sending an UDP packet to the server's IP address directly, it works. So the socket server is running. Only thing is it doesn't seem to receive any broadcast packets. Is this a known 'feature' of a windows NT service? Doesn't windows allow a service to receive broadcast packets? Again, sorry that I post this here it is probably more of a windows question. But I don't know a good place to ask this type of thing. Thanks for any help, --Irmen de Jong From sjmachin at lexicon.net Sun Apr 22 03:50:02 2007 From: sjmachin at lexicon.net (John Machin) Date: 22 Apr 2007 00:50:02 -0700 Subject: Give me the google group address in Chinese. In-Reply-To: References: <1177208197.176088.121800@q75g2000hsh.googlegroups.com> Message-ID: <1177228202.443882.126200@b58g2000hsg.googlegroups.com> On Apr 22, 1:44 pm, Dennis Lee Bieber wrote: > On 21 Apr 2007 19:16:37 -0700, ???? declaimed the > following in comp.lang.python: > > > It's really annoying to find there are all English language posts here > > because I wanna talk about something about the Chinese related > > programs. > > > Could you give me some ? > [snip] > OTOH, what are "Chinese related programs"? Programs using GUIs > specifying some Unicode Chinese font for screen displays? A dubbed > version of "Monty Python and the Holy Grail"? The OP may be interested in the episode involving the knights who say 'Ni hao" :-) From steve at holdenweb.com Sat Apr 7 17:19:46 2007 From: steve at holdenweb.com (Steve Holden) Date: Sat, 07 Apr 2007 17:19:46 -0400 Subject: Understanding Python's interpreter In-Reply-To: <4617A8DA.30309@vrplumber.com> References: <20070407032024.bb27f5ee.rafaelc@dcc.ufmg.br> <20070407052239.38f9b21e.rafaelc@dcc.ufmg.br> <4617A8DA.30309@vrplumber.com> Message-ID: Mike C. Fletcher wrote: > Steve Holden wrote: >> Rafael Almeida wrote: >> > ... >> Because they aer smarter than you, without wishing to be too rude. >> > Replace that with "more experienced", please. Otherwise it is a bit > rude, despite your wishes. We've always been newbie positive on > Python-list, and new compiler writers are just as important educational > targets as new Python programmers. > Maybe I was feeling a little crabby this morning. "More experienced" is certainly a more appropriate way to express the sentiment. Thanks. 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 soren.skou.nielsen at gmail.com Thu Apr 26 02:23:53 2007 From: soren.skou.nielsen at gmail.com (Soren) Date: 25 Apr 2007 23:23:53 -0700 Subject: embedding matplotlib in wxpython Message-ID: <1177568633.776992.5700@t38g2000prd.googlegroups.com> Hi, I've been trying to embed matplotlib in wxpython. I want to be able to put a figure (axes) in a wx.Panel and place it somewhere in my GUI. The GUI should have other panels with buttons etc. that can control the output on the figure. I've been looking at the examples from the matplotlib website, but can't seem to get it to work.. Does anyone here have experience in embedding matplotlib in wxpython? I have attached my code.. it makes two panels.. one with a matplotlib plot, and one with a button.. but the plotpanel is just a small square in the corner.... !! .. Any help is appreciated! Thanks, Soren Code: ----------------------------------- import wx import pylab from matplotlib.numerix import arange, sin, cos, pi import matplotlib matplotlib.use('WXAgg') from matplotlib.backends.backend_wxagg import FigureCanvasWxAgg from matplotlib.backends.backend_wx import NavigationToolbar2Wx from matplotlib.figure import Figure matplotlib.interactive(False) class App(wx.App): def OnInit(self): self.frame = MainFrame("BioXtas - Autoplotter", (50,60), (700,700)) self.frame.Show() return True class MainFrame(wx.Frame): def __init__(self, title, pos, size): wx.Frame.__init__(self, None, -1, title, pos, size) pPanel = PlotPanel(self, -1) # Plot panel bPanel = ButtonPanel(self, 100,500, (200,100)) # button panel sizer = wx.BoxSizer(wx.VERTICAL) sizer.Add(pPanel,0) sizer.Add(bPanel,0) self.SetSizer(sizer) class ButtonPanel(wx.Panel): def __init__(self, Parent, xPos, yPos, insize): pos = (xPos, yPos) wx.Panel.__init__(self, Parent, -1, pos, style = wx.RAISED_BORDER, size = insize) button = wx.Button(self, -1, 'HELLO!!', (10,10), (150,50)) class NoRepaintCanvas(FigureCanvasWxAgg): """We subclass FigureCanvasWxAgg, overriding the _onPaint method, so that the draw method is only called for the first two paint events. After that, the canvas will only be redrawn when it is resized. """ def __init__(self, *args, **kwargs): FigureCanvasWxAgg.__init__(self, *args, **kwargs) self._drawn = 0 def _onPaint(self, evt): """ Called when wxPaintEvt is generated """ if not self._isRealized: self.realize() if self._drawn < 2: self.draw(repaint = False) self._drawn += 1 self.gui_repaint(drawDC=wx.PaintDC(self)) class PlotPanel(wx.Panel): def __init__(self, parent, id = -1, color = None,\ dpi = None, style = wx.NO_FULL_REPAINT_ON_RESIZE, **kwargs): wx.Panel.__init__(self, parent, id = id, style = style, **kwargs) self.figure = Figure(None, dpi) self.canvas = NoRepaintCanvas(self, -1, self.figure) self._resizeflag = True self.Bind(wx.EVT_IDLE, self._onIdle) self.Bind(wx.EVT_SIZE, self._onSize) self._SetSize() def draw(self): if not hasattr(self, 'subplot'): self.subplot = self.figure.add_subplot(111) theta = arange(0, 45*2*pi, 0.02) rad = (0.8*theta/(2*pi)+1) r = rad*(8 + sin(theta*7+rad/1.8)) x = r*cos(theta) y = r*sin(theta) #Now draw it self.subplot.plot(x,y, '-r') def _onSize(self, event): self._resizeflag = True def _onIdle(self, evt): if self._resizeflag: self._resizeflag = False self._SetSize() self.draw() def _SetSize(self, pixels = None): """ This method can be called to force the Plot to be a desired size, which defaults to the ClientSize of the panel """ if not pixels: pixels = self.GetClientSize() self.canvas.SetSize(pixels) self.figure.set_figsize_inches(pixels[0]/ self.figure.get_dpi(), pixels[1]/self.figure.get_dpi()) if __name__ == "__main__": app = App(0) app.MainLoop() From olsongt at verizon.net Tue Apr 3 11:59:31 2007 From: olsongt at verizon.net (olsongt at verizon.net) Date: 3 Apr 2007 08:59:31 -0700 Subject: Python at Google Message-ID: <1175615971.496164.129170@b75g2000hsg.googlegroups.com> Here's an article about python at google. Apologies in advance. http://valleywag.com/tech/google/missing-python-tracked-down-249208.php From paul at boddie.org.uk Fri Apr 20 05:52:38 2007 From: paul at boddie.org.uk (Paul Boddie) Date: 20 Apr 2007 02:52:38 -0700 Subject: Python's handling of unicode surrogates In-Reply-To: <0QXVh.16735$M.14016@news-server.bigpond.net.au> References: <0QXVh.16735$M.14016@news-server.bigpond.net.au> Message-ID: <1177062758.289618.24630@y80g2000hsf.googlegroups.com> On 20 Apr, 07:02, Neil Hodgson wrote: > Adam Olsen: > > > To solve this I propose Python's unicode type using UTF-16 should have > > gaps in its index, allowing it to only expose complete unicode scalar > > values. Iteration would produce surrogate pairs rather than > > individual surrogates, indexing to the first half of a surrogate pair > > would produce the entire pair (indexing to the second half would raise > > IndexError), and slicing would be required to not separate a surrogate > > pair (IndexError otherwise). > > I expect having sequences with inaccessible indices will prove > overly surprising. They will behave quite similar to existing Python > sequences except when code that works perfectly well against other > sequences throws exceptions very rarely. This thread and the other one have been quite educational, and I've been looking through some of the background material on the topic. I think the intention was, in PEP 261 [1] and the surrounding discussion, that people should be able to treat Unicode objects as sequences of characters, even though GvR's summary [2] in that discussion defines a character as representing a code point, not a logical character. In such a scheme, characters should be indexed contiguously, and if people should want to access surrogate pairs, there should be a method (or module function) to expose that information on individual (logical) characters. > > Reasons to treat surrogates as undivisible: > > * \U escapes and repr() already do this > > * unichr(0x10000) would work on all unicode scalar values > > unichr could return a 2 code unit string without forcing surrogate > indivisibility. This would work with the "substring in string" and "string.index(substring)" pseudo-sequence API. However, once you've got a character as a Unicode object, surely the nature of the encoded character is only of peripheral interest. The Unicode API doesn't return two or more values per character for those in the Basic Multilingual Plane read from a UTF-8 source - that's inconsequential detail at that particular point. [...] > I think that effort would be better spent on an implementation that > appears to be UTF-32 but uses UTF-16 internally. The vast majority of > the time, no surrogates will be present, so operations can be simple and > fast. When a string contains a surrogate, a flag is flipped and all > operations go through more complex and slower code paths. This way, > consumers of the type see a simple, consistent interface which will not > report strange errors when used. I think PEP 261 was mostly concerned with providing a "good enough" solution until such a time as a better solution could be devised. > BTW, I just implemented support for supplemental planes (surrogates, > 4 byte UTF-8 sequences) for Scintilla, a text editing component. Do we have a volunteer? ;-) Paul [1] http://www.python.org/dev/peps/pep-0261/ [2] http://mail.python.org/pipermail/i18n-sig/2001-June/001107.html From deets at nospam.web.de Mon Apr 16 18:03:23 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 17 Apr 2007 00:03:23 +0200 Subject: Pyqt calling a custom dialog and returning the vars In-Reply-To: <1176753980.142797.268800@e65g2000hsc.googlegroups.com> References: <1176753980.142797.268800@e65g2000hsc.googlegroups.com> Message-ID: <58ia5dF2fsd6nU1@mid.uni-berlin.de> Marcpp schrieb: > I call a dialog from a principal program but cannot return the value > of the > variables (text box's). Here is a example... > > > > from ui import Agenda > from dialog1 import dialogo1 > from PyQt4 import * > import dbm > import sys > > class principal (QApplication): > > def __init__(self, args): > """ In the constructor we're doing everything to get our > application > started, which is basically constructing a basic > QApplication by > its __init__ method, then adding our widgets and finally > starting > the exec_loop.""" > QApplication.__init__(self,args) > > # We pass None since it's the top-level widget, we could in > fact leave > # that one out, but this way it's easier to add more dialogs > or widgets. > self.maindialog = ag(None) > > self.setMainWidget(self.maindialog) > self.maindialog.show() > self.exec_loop() > > class ag (Agenda): > ... > ... > def _slotAddClicked(self): > d=dialogo1() > d.exec_() > d.connect(d.buttonOk,SIGNAL("clicked()"),self._procesadialog1) Shouldn't you connect the signal _before_ the dialog is shown? > def _procesadialog1(): > d=dialogo1() > drempresa = d.dempresa.text() > print drempresa # > <-------------------------------------------------------- Nothing > appears > ... > ... > if __name__ == "__main__": > app = principal(sys.argv) > Diez From bborcic at gmail.com Sat Apr 21 05:21:00 2007 From: bborcic at gmail.com (Boris Borcic) Date: Sat, 21 Apr 2007 11:21:00 +0200 Subject: lambda generator - curious behavior in 2.5 Message-ID: <4629d7a5_3@news.bluewin.ch> >>> x = (lambda : ((yield 666),(yield 777),(yield 888)))() >>> x.next() 666 >>> x.next() 777 >>> x.next() 888 >>> x.next() (None, None, None) >>> x = (lambda : ((yield 666),(yield 777),(yield 888)) and None)() >>> x.next() 666 >>> x.next() 777 >>> x.next() 888 >>> x.next() Traceback (most recent call last): File "", line 1, in x.next() StopIteration >>> From kelvin.you at gmail.com Mon Apr 23 04:24:00 2007 From: kelvin.you at gmail.com (=?utf-8?B?5Lq66KiA6JC95pel5piv5aSp5rav77yM5pyb5p6B5aSp5rav5LiN6KeB5a62?=) Date: 23 Apr 2007 01:24:00 -0700 Subject: ctypes: how to make a structure pointer to point to a buffer Message-ID: <1177316640.305123.52040@y5g2000hsa.googlegroups.com> first, I'm try the POINTER to convesion the pointer type. but failed. class STUDENT(Structure): _fields_ = [('name', c_int), ('id', c_int), ('addition', c_ubyte)] buffer = c_byte * 1024 student_p = cast(buffer, POINTER(STUDENT)) The parameter of the POINTER must be ctypes type. How could I attach the buffer pointer to the structure STUDENT ? From pudugramam.s.narayanan at jpmchase.com Fri Apr 20 15:49:10 2007 From: pudugramam.s.narayanan at jpmchase.com (pudugramam.s.narayanan at jpmchase.com) Date: Fri, 20 Apr 2007 15:49:10 -0400 Subject: vi editing mode does not work: Python install ok Message-ID: Hi Could someone kindly give me an answer to this: I have installed Python 2.5 on my linux box 2.4.9-e.35enterprise that has readline.so version 4.2. During configure, I got the message checking for readline in -lreadline... no checking for rl_callback_handler_install in -lreadline... no checking for rl_pre_input_hook in -lreadline... no checking for rl_completion_matches in -lreadline... no So I then updated Modules/Setup to include readline readline: readline.c -L/usr/lib -lreadline -ltermcap. Python got installed correctly as per the logs. I then modified ~/.inputrc with set editing-mode vi Now when I run the interpreter, I am not able to perform "vi" style editing. How come??? Narayan ----------------------------------------- This communication is for informational purposes only. It is not intended as an offer or solicitation for the purchase or sale of any financial instrument or as an official confirmation of any transaction. All market prices, data and other information are not warranted as to completeness or accuracy and are subject to change without notice. Any comments or statements made herein do not necessarily reflect those of JPMorgan Chase & Co., its subsidiaries and affiliates. This transmission may contain information that is privileged, confidential, legally privileged, and/or exempt from disclosure under applicable law. If you are not the intended recipient, you are hereby notified that any disclosure, copying, distribution, or use of the information contained herein (including any reliance thereon) is STRICTLY PROHIBITED. Although this transmission and any attachments are believed to be free of any virus or other defect that might affect any computer system into which it is received and opened, it is the responsibility of the recipient to ensure that it is virus free and no responsibility is accepted by JPMorgan Chase & Co., its subsidiaries and affiliates, as applicable, for any loss or damage arising in any way from its use. If you received this transmission in error, please immediately contact the sender and destroy the material in its entirety, whether in electronic or hard copy format. Thank you. Please refer to http://www.jpmorgan.com/pages/disclosures for disclosures relating to UK legal entities. -------------- next part -------------- An HTML attachment was scrubbed... URL: From __peter__ at web.de Sun Apr 8 02:37:50 2007 From: __peter__ at web.de (Peter Otten) Date: Sun, 08 Apr 2007 08:37:50 +0200 Subject: Not understanding absolute_import References: <1175776410.788058.309080@w1g2000hsg.googlegroups.com> <1175992978.756288.17030@w1g2000hsg.googlegroups.com> Message-ID: Nate Finch wrote: > On Apr 5, 8:33 am, "Nate Finch" wrote: >> I've been trying to use fromabsolute_importand it's giving me a hell >> of a headache. I can't figure out what it's *supposed* to do, or >> maybe rather, it doesn't seem to be doing what I *think* it's supposed >> to be doing. > > > No one? Is this too simple a question, or is it just that no one is > using this? The latter, I suppose. The PEP has the following example: """ package/ __init__.py subpackage1/ __init__.py moduleX.py moduleY.py subpackage2/ __init__.py moduleZ.py moduleA.py Assuming that the current file is either moduleX.py or subpackage1/__init__.py, following are correct usages of the new syntax: from .moduleY import spam from .moduleY import spam as ham from . import moduleY from ..subpackage1 import moduleY from ..subpackage2.moduleZ import eggs from ..moduleA import foo from ...package import bar from ...sys import path """ I tried that and it turned out that you have to change from ...package import bar from ...sys import path to from ..package import bar from ..sys import path for the code to run without raising an exception. I therefore assume that the current implementation erroneously mixes the top level and its immediate child level, and I suggest that you file a bug report. Peter From Jun.Jin.act at gmail.com Tue Apr 17 21:17:02 2007 From: Jun.Jin.act at gmail.com (Jun.Jin.act+group.python@gmail.com) Date: 17 Apr 2007 18:17:02 -0700 Subject: rewrite for achieving speedup In-Reply-To: <4umdnWdZhZNVe7nbnZ2dnUVZ_gGdnZ2d@comcast.com> References: <1176821334.217154.36350@y80g2000hsf.googlegroups.com> <4umdnWdZhZNVe7nbnZ2dnUVZ_gGdnZ2d@comcast.com> Message-ID: <1176859022.813949.304600@b75g2000hsg.googlegroups.com> On Apr 17, 11:25 pm, Steven Bethard wrote: > Steve Holden wrote: > > Johnny Blonde wrote: > >> Hello Group! > > >> I really tried hard for two hours to rewrite the following expression > >> (python 2.4): > >> -------------------------- > >> teilnehmer = [] > >> for r in Reisen.select(AND(Reisen.q.RESVON <= datum, Reisen.q.RESBIS > >>> = datum)): > >> for g in r.BUCHUNGEN: > >> for t in g.aktiveTeilnehmer: > >> teilnehmer.append(t) > >> -------------------------- > > >> to something like > >> -------------------------- > >> teilnehmer = [x for x in ........] > >> -------------------------- > > >> Reisen is a SQLObject class, Reisen.select(...), aktiveTeilnehmer and > >> BUCHUNGEN all are of the type SelectResults. > > >> unfortunately i just can?t figure it out to make it work. > >> i hope someone maybe can help me? > > >> I hope to gain performance by rewriting it... > > >> Thanks a lot for your help! > > > >>> lt = [[[1,2,3], [2,3,4]], [[3,4,5], [4,5,6]]] > > >>> lf = [c for a in lt for b in a for c in b] > > >>> lf > > [1, 2, 3, 2, 3, 4, 3, 4, 5, 4, 5, 6] > > > Untested: > > > teilnehmer = [t for r in Reisen.select(AND(Reisen.q.RESVON <= datum, > > reisen.q.RESBIS >= datum)) for g in r.BUCHUNGEN for t in > > g.aktiveTeilnehmer] > > Note also that you can probably get most of the speedup above by binding > the append method to a function-local name:: > > teilnehmer = [] > append = teilnehmer.append > for r in Reisen.select(...): > for g in r.BUCHUNGEN: > for t in g.aktiveTeilnehmer: > append(t) > > That's pretty much all a list comprehension is doing anyway. > > STeVe hi steve, why would binding to a function-local name speeds up performance? sorry for asking such a simple question. many thanks. From S.Mientki-nospam at mailbox.kun.nl Fri Apr 27 18:17:00 2007 From: S.Mientki-nospam at mailbox.kun.nl (Stef Mientki) Date: Sat, 28 Apr 2007 00:17:00 +0200 Subject: [ANN] Portable SciPy v0.1 released Message-ID: <2418d$463275ce$d443bb3a$25239@news.speedlinq.nl> Portable SciPy, is an easy installer of SciPy for M$ windows users. For this moment, you can find the description page, with all links here http://oase.uci.kun.nl/~mientki/data_www/pic/jalcc/python/portable_scipy.html For future use, it's advised to always use my redirector page http://pic.flappie.nl/ The simple method described here, can be used to create any set of Python packages + other programs, with just a few lines of code (example available). have fun, and let me hear what you think of it. Stef Mientki From half.italian at gmail.com Tue Apr 24 01:57:09 2007 From: half.italian at gmail.com (half.italian at gmail.com) Date: 23 Apr 2007 22:57:09 -0700 Subject: Python Widget to read in user input box in blog In-Reply-To: <1177379827.873957.47760@n76g2000hsh.googlegroups.com> References: <1177379827.873957.47760@n76g2000hsh.googlegroups.com> Message-ID: <1177394229.733565.242560@n35g2000prd.googlegroups.com> On Apr 23, 6:57 pm, ecpbm... at gmail.com wrote: > Hey, > > I am helping to develop a project that displays images based on user > input. One possible way of implementing this is via a widget that > when it is run, would read in the users input from an input text field > (probably from a blog), and replace it with the HTML that would > display those images. This is more a proof of concept, so really all > I am wondering is if there is a good way in Python to read in the text > the user has typed and change it before the user hits submit? > > Thanks Here's another way. Although I'm not really sure whether you are talking about a web app or a local gui app. #! /usr/bin/env python from Tkinter import * class Window(Frame): def __init__(self, parent=None): Frame.__init__(self, parent) Label(self, text="Enter the path to a gif").pack(padx=5, pady=5) self.label = Label(self, text="") self.label.pack(padx=5, pady=5) self.entry = Entry(self, text="") self.entry.pack(padx=5, pady=5) self.pack() self.update() def update(self): try: self.image = PhotoImage(file=self.entry.get()) self.label.config(image=self.image) except TclError: self.label.config(text=self.entry.get(), image="") self.after(20, self.update) if __name__ == '__main__': root = Tk() Window().mainloop() ~Sean From steven.bethard at gmail.com Mon Apr 30 14:00:26 2007 From: steven.bethard at gmail.com (Steven Bethard) Date: Mon, 30 Apr 2007 12:00:26 -0600 Subject: regexp match string with word1 and not word2 In-Reply-To: <1177946577.080567.73400@u30g2000hsc.googlegroups.com> References: <1177920984.247487.54620@c35g2000hsg.googlegroups.com> <9rGdnQGHaNy1mqvbnZ2dnUVZ_v_inZ2d@comcast.com> <1177946577.080567.73400@u30g2000hsc.googlegroups.com> Message-ID: Flyzone wrote: > On 30 Apr, 17:11, Steven Bethard wrote: > >> You don't need a regexp:; > > I need a regexp.....i'm parsing a file with a rule-file that contains > also regexp and strings too.... Well then it seems like you might want to rethink this rule-file approach since your problem is clearly not amenable to regular expressions. That said, here's a regexp that might work:: ((?!two:).)*one((?!two:).)* That makes a negative lookahead assertion at each character in the string. STeVe From larry.bates at websafe.com Wed Apr 18 13:19:13 2007 From: larry.bates at websafe.com (Larry Bates) Date: Wed, 18 Apr 2007 12:19:13 -0500 Subject: Newbie: import In-Reply-To: <1176914096.493758.77120@o5g2000hsb.googlegroups.com> References: <1176914096.493758.77120@o5g2000hsb.googlegroups.com> Message-ID: genkuro at gmail.com wrote: > I thought import used relative paths from either the python executable > or the script being executed. I have a script pulling in code from an > arbitrary directory. How is this happening? > > It's a RHEL 4 environment by the way. I couldn't find any relevant > environment variables. > > Thanks from a newbie for any insight. > PYTHONPATH environment variable is next in line to be searched. -Larry From irstas at gmail.com Sun Apr 1 06:23:59 2007 From: irstas at gmail.com (irstas at gmail.com) Date: 1 Apr 2007 03:23:59 -0700 Subject: re.findall() hangs in python In-Reply-To: <1175397176.567214.194810@n59g2000hsh.googlegroups.com> References: <1175397176.567214.194810@n59g2000hsh.googlegroups.com> Message-ID: <1175423039.310796.50200@n76g2000hsh.googlegroups.com> On Apr 1, 6:12 am, "silverburgh.me... at gmail.com" wrote: > But when 'data' does not contain pattern, it just hangs at > 're.findall' > > pattern = re.compile("(.*) re.S) That pattern is just really slow to evaluate. What you want is probably something more like this: re.compile(r']*src\s*=\s*"([^"]*img[^"]*)"') "dot" is usually not so great. Prefer "NOT end-character", like [^>] or [^"]. From grante at visi.com Tue Apr 24 18:28:43 2007 From: grante at visi.com (Grant Edwards) Date: Tue, 24 Apr 2007 22:28:43 -0000 Subject: Generate report containing pdf or ps figures? References: <132pnp6r4qg0lc2@corp.supernews.com> <132sa3jkr5uv0a9@corp.supernews.com> <7mv1g4-jtn.ln1@lairds.us> <5d988$462e80a4$54d1d767$14779@news.chello.no> Message-ID: <132t14r3oo6da95@corp.supernews.com> On 2007-04-24, David Boddie wrote: > However, it doesn't seem that either are capable of inserting the kinds of > vector files you are using. > > It may be worth writing a quick and dirty PDF writer using an > existing backend library, though I can imagine that the hard > work would involve reading the different input formats you > want to use. I can generate quite a few different vector formats, and I'll use whichever one the library can accept. > Anyway, for future reference, the following projects might prove to be > inspiring: > > http://pyx.sourceforge.net/ It looks like that's Postscript output rather than PDF. > http://pybrary.net/pyPdf/ That's almost what I'm looking for, except it appears it can only rotate/crop pages and not scale/translate them. I've been looking at the new version (4.20 of Gnuplot, and some features have been added to the pdf terminal type that almost solves my problem as well. It appears I've got a number of 80% solutions from which to choose. ;) -- Grant Edwards grante Yow! Hey, waiter! I want at a NEW SHIRT and a PONY TAIL visi.com with lemon sauce! From mccredie at gmail.com Fri Apr 13 00:32:35 2007 From: mccredie at gmail.com (Matimus) Date: 12 Apr 2007 21:32:35 -0700 Subject: reading from sys.stdin In-Reply-To: References: <1176366058.261031.111870@p77g2000hsh.googlegroups.com> <1176387908.406115.270630@w1g2000hsg.googlegroups.com> Message-ID: <1176438754.995753.50190@d57g2000hsg.googlegroups.com> On Apr 12, 8:20 am, Maric Michaud wrote: > Le jeudi 12 avril 2007 16:25, Matimus a ?crit : > > > # Then you check to see if your file is interactive > > if f.isatty(): > > # This is unbuffered, and will iterate the same as f > > f = iter(raw_input(),"") > > This should be f = iter(raw_input,"") and this will end in a EOFError and stop > on blank line. > So you need a wrapper like : > > >>> def stdin_iterator() : > > ... while(True) : > ... try : yield raw_input() > ... except EOFError : return > ... > > >>> f = stdin_iterator() > > Do you really need to iterate on the file this way instead of using the > straightforward readline method ? > > >>> import sys > >>> l=sys.stdin.readline() > >>> while(l) : > > ... print l, > ... l=sys.stdin.readline() > > -- > _____________ > > Maric Michaud > _____________ > > Aristote -www.aristote.info > 3 place des tapis > 69004 Lyon > Tel: +33 4 26 88 00 97 > Mobile: +33 6 32 77 00 21 You are correct, I looked back to a program I wrote a while ago where I ran into this issue. Here is the actual solution I used: if f.isatty(): f = iter(f.readline,"") From bironelynch at gmail.com Tue Apr 3 12:26:09 2007 From: bironelynch at gmail.com (Birone Lynch) Date: Tue, 3 Apr 2007 18:26:09 +0200 Subject: Problem with filter() Message-ID: """Sorry folks my mistake def is_dev should be: > > def is_Dev(stringy): > stringx = stringy.split('-') > if stringx[0] == '': > if stringx[1] == r'win32': > if stringx[2] == r'app': > if stringx[4] == r'dev.tar.gz': > return 1 > > But now the results of the filter is an empty list and i know it shouldn't > be.""" > > I think the problem is the first "if" - using the list from your previous mail, stringx[0] is never empty. So the filter fn never returns true, & the return list is empty... stringx[4] never matches either. This is what I did: >>> compFiles=['logs', 'rqp-8.2.104.0.dep', 'rqp-8.2.93.0.dep', ' rqp-win32-app-8.2.96.0-inst.tar.gz', 'rqp-win32-app-8.2.96.0-inst.tar.gz '] >>> for i in compFiles: print i.split('-') # ie the equivalent of stringx ['logs'] ['rqp', '8.2.104.0.dep'] ['rqp', '8.2.93.0.dep'] ['rqp', 'win32', 'app', ' 8.2.96.0', 'inst.tar.gz'] ['rqp', 'win32', 'app', ' 8.2.96.0', 'inst.tar.gz'] Birone PS - I'm new at this. Please forgive me if I got it totally wrong! -------------- next part -------------- An HTML attachment was scrubbed... URL: From whamil1 at entergy.com Thu Apr 5 11:42:43 2007 From: whamil1 at entergy.com (Hamilton, William ) Date: Thu, 5 Apr 2007 10:42:43 -0500 Subject: Project organization and import redux Message-ID: <588D53831C701746A2DF46E365C018CE01D2CA5F@LITEXETSP001.etrsouth.corp.entergy.com> I apologize for bringing up something that's a month dead. But, I've been reading through the recent archives and came across this discussion, and want to make sure I understand a particular about the interactive prompt. "Martin Unsal" wrote: > I'm perfectly well aware that I'm not going to be able to reload a > widget in the middle of a running GUI app, for example. I'm not > looking for gotcha free, I'll settle for minimally useful. > > Here's an analogy. In C, you can do an incremental build and run your > modified application without having to first reboot your computer. In > Python, where reload() is essentially the incremental build process, > and the interpreter is essentially a virtual machine, you guys are > saying that my best option is to just "reboot" the virtual machine to > make sure I have a "clean slate". It may be the path of least > resistance, but to say that it is necessary or inevitable is 1960s > mainframe thinking. Yes, the interpreter is a virtual machine. But the interactive prompt is not a command line in that virtual machine. Instead, it is the statement that is about to be executed by a program running in that virtual machine. When you type a statement and press enter, that statement is executed as the next line of the program. It's analogous to using a debugger to step through a C program line by line, except you're providing those lines immediately rather than having to write and compile them in advance. Restarting the interactive prompt isn't like rebooting the computer; it's just restarting a program that is running on the computer. At worst, the interpreter is a computer that automatically shuts down when the program running on it ends. Is this a valid understanding of the workings of the interactive prompt, or am I way off base? --- -Bill Hamilton whamil1 at entergy.com From larry.bates at websafe.com Wed Apr 25 10:36:19 2007 From: larry.bates at websafe.com (Larry Bates) Date: Wed, 25 Apr 2007 09:36:19 -0500 Subject: Python not giving free memory back to the os get's me in real problems ... In-Reply-To: <1177510121.882503.145560@n15g2000prd.googlegroups.com> References: <1177510121.882503.145560@n15g2000prd.googlegroups.com> Message-ID: <_LidnenBcrz7-rLbnZ2dnUVZ_tCtnZ2d@comcast.com> leuchte at gmail.com wrote: > So I read quite a few things about this phenomenon in Python 2.4.x but > I can hardly believe that there is really no solution to my problem. > > We use a commercial tool that has a macro functionality. These macros > are written in python. So far nothing extraordinary. > > Our (python-)macro uses massively nested loops which are unfortunately > necessary. These loops perform complex calculations in this commercial > tool. To give you a quick overview how long this macros runs: > > The outer loop takes 5-7 hours for one cycle. Each cycle creates one > outputfile. So we would like to perform 3-5 outer cycles en bloc. > Unfortunately one of our computers (768MB RAM) crashes after just ~10% > of the first cycle with the following error message: > > http://img2.freeimagehosting.net/uploads/7157b1dd7e.jpg > > while another computer (1GB RAM) crashes after ~10% of the fourth > loop. While the virtual memory on the 1gb machine was full to the > limit when it crashed the memory usage of the 768mb machine looked > this this: > > http://img2.freeimagehosting.net/uploads/dd15127b7a.jpg > > The moment I close the application that launched the macro, my > ressources get freed. > > So is there a way to free my memory inside my nested loops? > > thanks in advance, > tim > Let's see for this I need to get out my crystal ball... If it is a commercial application, you should contact their tech support for a solution. The problem isn't specifically a Python problem but rather an implementation problem with their app. -Larry From bill.sloman at ieee.org Tue Apr 24 16:47:12 2007 From: bill.sloman at ieee.org (bill.sloman at ieee.org) Date: 24 Apr 2007 13:47:12 -0700 Subject: *** Dr G Polya BRILLIANTLY analyses the Virgina Shooting Incident *** In-Reply-To: <1177416547.394200.314950@r3g2000prh.googlegroups.com> References: <1177266754.126153.202760@b58g2000hsg.googlegroups.com> <1177287460.376404.323520@b58g2000hsg.googlegroups.com> <1177416547.394200.314950@r3g2000prh.googlegroups.com> Message-ID: <1177447632.371289.38180@r30g2000prh.googlegroups.com> On Apr 24, 2:09 pm, Quadibloc wrote: > The Real Andy wrote: > > Makes me wonder about the credibility of any statement Dr Gideon Polya > > makes. > > . > I never thought that I would feel the urge to call someone an > edelweiss-eating Tanzanian devil, but Dr. Polya proved that I lacked > imagination. > > (Note that "Tanzanian" is pronounced Tan.zan._ee_.yan, not > Tan._zayn_.ee.an; one wouldn't want to spoil the effect.) What really spoils the effect is that Dr. Polya lives in Tasmania, a state of Australia, and not in Tanzania, which is a country in East Africa. Semi-literate Americans do tend to confuse the two places, as they also tend confuse Australia and Austria. Oddly enough, edelweiss grows in Austria, so Dr. Polya would have to import it from Europe if he were in the habit of dining on edelweiss - which would be an eccentric habit, even in Austria, where the flower doesn't form part of the normal diet. -- Bill Sloman, Nijmegen From DanBishop04 at gmail.com Thu Apr 26 20:53:48 2007 From: DanBishop04 at gmail.com (DanBishop04 at gmail.com) Date: 26 Apr 2007 17:53:48 -0700 Subject: Correct behavior? In-Reply-To: <1177634055.017575.236810@t39g2000prd.googlegroups.com> References: <1177634055.017575.236810@t39g2000prd.googlegroups.com> Message-ID: <1177635228.144366.74600@o40g2000prh.googlegroups.com> On Apr 26, 8:34 pm, asker wrote: > Hello: > I have next Python 2.5.1 instructions: > > >>> a=12.34 > >>> b=11.23 > >>> print a+b > > 23.57 > > >>> print "%15.2f" % (a+b) > > 23.57 > > But:>>> print "%15.2f" % a+b > > Traceback (most recent call last): > File "", line 1, in > TypeError: cannot concatenate 'str' and 'float' objects > > Is this correct for Python to issue this error? The % operator has higher precedence than +. Thus, "%15.2f" % a+b == ("%15.2f" % a)+b, an illegal str+float addition. From KDawg44 at gmail.com Mon Apr 23 10:52:22 2007 From: KDawg44 at gmail.com (KDawg44) Date: 23 Apr 2007 07:52:22 -0700 Subject: Learning Python - First Project Message-ID: <1177339942.371167.93970@b75g2000hsg.googlegroups.com> Hi, I am new to Python and am trying to write a little front end to another application in Python. What I want is to have a gui pop up listing some items with several buttons. The guts of the program I am not having any trouble with but the GUI part I am (or more accurately, the transition between GUI pieces). The first GUI that pops up lists some groups in a listbox and gives the user the choice to create a new group, open a group, rename the group, or delete the group. The new group and rename group buttons pop up a dialog gui asking for the name/new name. The Open Group is to open another GUI listing projects within that group in a list with similar options (New Project, Open Project, Rename Project, Delete Project). My question is, how should I create all these GUIs? Should each GUI be its own class with its own __init__? Then is the first GUI the root (how I have it set up now) and all other GUIs using Toplevel()? I hope this makes sense (because it only sort of makes sense in my head). THanks for any suggestions. From rehceb at no.spam.plz Sun Apr 1 16:38:18 2007 From: rehceb at no.spam.plz (Rehceb Rotkiv) Date: Sun, 01 Apr 2007 15:38:18 -0500 Subject: Overlapping matches Message-ID: In the re documentation, it says that the matching functions return "non- overlapping" matches only, but I also need overlapping ones. Does anyone know how this can be done? Regards, Rehceb Rotkiv From cam.ac.uk at mh391.invalid Mon Apr 16 15:08:24 2007 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Mon, 16 Apr 2007 20:08:24 +0100 Subject: getting from command line options to file In-Reply-To: <1176748372.685762.169820@w1g2000hsg.googlegroups.com> References: <1176748372.685762.169820@w1g2000hsg.googlegroups.com> Message-ID: CSUIDL PROGRAMMEr wrote: > hi folks > I am new to python. I have a module does call a os.command(cmd) where > cmd is a rpm command. > Instead of using os.command and getting the results on command line , > i would like to dump the output in a file. Is os.command(cmd > > filename) the most efficient command?? I think the best thing to do would be something like this (Python 2.5): from __future__ import with_statement import subprocess with file("test.out", "w") as outfile: subprocess.check_call(["ls", "/etc"], stdout=outfile) -- Michael Hoffman From cam.ac.uk at mh391.invalid Fri Apr 13 08:20:33 2007 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Fri, 13 Apr 2007 13:20:33 +0100 Subject: reading from sys.stdin In-Reply-To: <1176457007.589050.285400@d57g2000hsg.googlegroups.com> References: <1176366058.261031.111870@p77g2000hsh.googlegroups.com> <1176387908.406115.270630@w1g2000hsg.googlegroups.com> <1176438754.995753.50190@d57g2000hsg.googlegroups.com> <1176454871.538968.176620@n76g2000hsh.googlegroups.com> <1176457007.589050.285400@d57g2000hsg.googlegroups.com> Message-ID: 7stud wrote: > On Apr 13, 3:13 am, Michael Hoffman wrote: >> 7stud wrote: >>> I assume all input is buffered by default, so I'm not sure how it >>> explains things to say that input from sys.stdin is buffered. >> The difference with sys.stdin is that it has indeterminate length until >> you signal EOF. I believe you'd get the same problem reading from, say, >> a named pipe. >> > > Couldn't you say the same thing about a file you are iterating over? Only if the file has indeterminate length. Regular files have a length. >>>> This should be f = iter(raw_input,"") and this will end in a EOFError >>>> and stop on blank line. So you need a wrapper >>> Why a wrapper? >> Because without a wrapper you'll get EOFError, while the file iterator >> would ordinarily give you StopIteration. > > Did you run my example? Did you get an error? I don't get an error. Yes I did. I did get an error. >>> lst = [] >>> f = iter(raw_input, "") >>> for line in f: ... lst.append(line) ... abc def Traceback (most recent call last): File "", line 1, in EOFError -- Michael Hoffman From apardon at forel.vub.ac.be Tue Apr 24 08:39:55 2007 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 24 Apr 2007 12:39:55 GMT Subject: Tutorial creates confusion about slices References: Message-ID: On 2007-04-24, Michael Bentley wrote: > > On Apr 24, 2007, at 6:35 AM, Antoon Pardon wrote: > >> People don't read tutorials in a strictly linear fashion. They can >> continue to later subjects and then come back here to see how things >> tie together. So the fact that it is only confusing to those who >> know more than is already presented doesn't seem a very good reason >> to leave it in. > > Yet they understand that earlier in the document, there is likely to > be a less complete coverage of a given topic. There is in fact, a > link on that page that includes a more complete coverage of that > topic (which I mentioned to you in an earlier message IIRC). That there is more complete coverage elsewhere is no good reason to come with an explanation that suggests things working in a way that will be contradicted by that more complete coverage. Even after people have read the more complete coverage it is still very possible that they will come back to this part of the text and get the wrong idea of how things work. A more complete coverage elsewhere is not an adequate remedy for a tekst suggesting things working differently than they actually do. Sure in the long run people will figger out how things actually work and that the explanation given in that section is totally inadequate for negative steps. But I prefer that people don't loose too much time figgering out that a particular explanation only works for particular cases and not in general. > Submit a patch if you want it changed. I'm sure your valuable > insights will greatly improve the quality of the python documentation. Fat chance, if they reason like you. -- Antoon Pardon From lucaberto at libero.it Mon Apr 16 11:57:02 2007 From: lucaberto at libero.it (luca72) Date: 16 Apr 2007 08:57:02 -0700 Subject: file resume Message-ID: <1176739022.736716.245950@y80g2000hsf.googlegroups.com> Hello at all: if i have one file written in binary mode, how can i append others binary data to this file after the its closure. ex my_file = open('blabal', 'wb') then i write something and then my_file.close() now if i need to open it again and append other binary data how can i proceed? Regards Luca From aahz at pythoncraft.com Mon Apr 30 14:42:18 2007 From: aahz at pythoncraft.com (Aahz) Date: 30 Apr 2007 11:42:18 -0700 Subject: Any Good tools to create CSV Files? References: <1177811756.255774.315260@q75g2000hsh.googlegroups.com> Message-ID: In article , Bart Willems wrote: >Aahz wrote: >> >> In all fairness, the csv module is new in Python 2.3, and I'm sure I'm >> not the only person still using Python 2.2 for production. > >That is true, on the other hand, Reportlab is made for at least Python >2.4, "although it will work with 2.3" - so he has 2.3 at least :) I've been using ReportLab since the 2.1 days, if not farther back. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "Look, it's your affair if you want to play with five people, but don't go calling it doubles." --John Cleese anticipates Usenet From harry.g.george at boeing.com Fri Apr 27 09:12:51 2007 From: harry.g.george at boeing.com (Harry George) Date: Fri, 27 Apr 2007 13:12:51 GMT Subject: Command-line option equiv of PYTHONPATH References: <1177648804.947472.112830@s33g2000prh.googlegroups.com> Message-ID: Antoon Pardon writes: > On 2007-04-27, James Stroud wrote: > > Rajesh wrote: > >> Hi, > >> > >> The '-I' option adds the path to the list of directories that > >> contains modules that can be included in a script. I can use it as "#!/ > >> usr/bin/perl -I" thereby not asking the user of > >> the script to set the in their environment. > >> > >> Is there any equivalent command-line option to the python binary or a > >> command-line version of PYTHONPATH? > >> > >> Regards > >> Rajesh > > > > Why not just modify sys.path within the actual script? > > Maybe because he has multiple versions of modules he wants to test his > script against. > > -- > Antoon Pardon Here are some approaches we've used: 1. Write a small script which sets PYTHONPATH and then calls the app. Make a different script for each setup you need. 2. Use a small script to set a couple of envvars, which in turn are used to find the right config file, which has all the config decisions you want. archtool_path= os.getenv('ARCHTOOL_PATH') archtool_cfg = os.getenv('ARCHTOOL_CFG') sys.path.insert(0,archtool_path) import archtool exec "import archtool.%s as cfg" % archtool_cfg -- Harry George PLM Engineering Architecture From gandalf at designaproduct.biz Wed Apr 11 13:26:49 2007 From: gandalf at designaproduct.biz (Laszlo Nagy) Date: Wed, 11 Apr 2007 19:26:49 +0200 Subject: ValueError: too many values to unpack In-Reply-To: <1176311618.617765.120560@p77g2000hsh.googlegroups.com> References: <1176311618.617765.120560@p77g2000hsh.googlegroups.com> Message-ID: <461D1A59.5060901@designaproduct.biz> fscked ?rta: > Trying to use CSV to read in a line with 11 fields and I keep getting > this error. I have googled a bit and have been unable to figure it out. > > Probably you have more than 11 values in some (or all) of the rows in the CSV file. Try this code: L = (1,2,3,4,5) a1,a2,a3 = L If you are sure that you only need a certain number of values, "the first N columns": a1,a2,a3 = L[:3] Then you still can have a "not enough values to unpack" error, guess what that means. ;-) Laszlo From steve at REMOVEME.cybersource.com.au Tue Apr 17 04:29:18 2007 From: steve at REMOVEME.cybersource.com.au (Steven D'Aprano) Date: Tue, 17 Apr 2007 18:29:18 +1000 Subject: Handling sorted dictionaries References: <1176796915.492317.203190@p77g2000hsh.googlegroups.com> Message-ID: On Tue, 17 Apr 2007 01:01:55 -0700, loial wrote: > The following code gives the error > > d=sortedmachines[machine] > TypeError: list indices must be integers > > > What works for the unsorted dictionary does not work for the sorted > dictionary. > Can anyone help? The error message you got tells you what the problem is. sortedmachines is not a "sorted dictionary". There is no such thing -- dictionaries, also known as "hash tables" in other languages, are unsorted. sortedmachines is a _list_, just like the error message says, and the index must be an integer. > sortedmachines=sorted(machines) sortedmachines is now the sorted _keys_ copied from machines. Try calling "print sortedmachines" and looking at what you get. > for machine in sortedmachines: > d=sortedmachines[machine] Try this instead: d = machines[machine] -- Steven D'Aprano From gnewsg at gmail.com Sun Apr 29 18:19:32 2007 From: gnewsg at gmail.com (billiejoex) Date: 29 Apr 2007 15:19:32 -0700 Subject: Interrupting ftplib.storbinary() In-Reply-To: <1177597797.296812.226620@t39g2000prd.googlegroups.com> References: <1177597797.296812.226620@t39g2000prd.googlegroups.com> Message-ID: <1177885171.964151.223330@y5g2000hsa.googlegroups.com> On 26 Apr, 16:29, Florian Demmer wrote: > Hi! > > I have a number of ftp uploads running in parallel using > ftplib.storbinary and threading and in case one of them fails I need > to interrupt all the others (but not exit the program completely)... > do you guys have an idea how i could implement the interruption as > cleanly as possible? > > thanks! You could interrupt the transfer by directly using the lower 'ftp- data' socket instead of the storbinary() method. Try the following code (not tested): import ftplib file = open('file.ext', 'r') ftp = ftplib.FTP() ftp.connect(host='127.0.0.1', port=21) ftp.login(user='user', passwd='passwd') conn = ftp.transfercmd('stor file.ext', rest=None) # the 'shared' var. change it to # 1 when you want to stop the transfer stop = 0 while 1: chunk = file.read(8192) conn.sendall(chunk) if not chunk: print "finished" break elif stop: print "stopped" break conn.close() ftp.close() From gh at gregor-horvath.com Sun Apr 29 13:52:47 2007 From: gh at gregor-horvath.com (Gregor Horvath) Date: Sun, 29 Apr 2007 19:52:47 +0200 Subject: howto check is object a func, lambda-func or something else? In-Reply-To: <1177867182.115406.4640@h2g2000hsg.googlegroups.com> References: <1177867182.115406.4640@h2g2000hsg.googlegroups.com> Message-ID: <73086$4634db6f$547078de$28786@news.chello.at> dmitrey schrieb: > howto check is object Arg1 > - a func, lambda-func > - something else? > > I tried callable(Arg1), but callable(lambda-func) returnes False I don't understand your problem: >>> callable(lambda:0) True Please post your relevant code. Greg From bdesth.quelquechose at free.quelquepart.fr Tue Apr 10 17:23:02 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Tue, 10 Apr 2007 23:23:02 +0200 Subject: pluie documentation in english In-Reply-To: <1176208792.766963.304080@q75g2000hsh.googlegroups.com> References: <1176109628.413745.285120@n76g2000hsh.googlegroups.com> <1176114900.964184.46880@y80g2000hsf.googlegroups.com> <461b479a$0$27407$ba4acef3@news.orange.fr> <1176208792.766963.304080@q75g2000hsh.googlegroups.com> Message-ID: <461bf71b$0$2127$426a74cc@news.free.fr> Eric_Dexter at msn.com a ?crit : > On Apr 10, 3:14 am, "M?ta-MCI" > wrote: > >>Bonjour ! >> >>Avec Internet-Explorer 6 : >> >>Dans Internet-explorer, par le menu, faire : Outils + Options_internet >>Aller sur le dernier onglet (Avanc?), et cocher : autoriser le contenu actif >> >>(d?sol? pour le fran?ais, mais mon anglais est vraiment trop mauvais). >> >>Et, merci pour l'info, ?a m'a permis d'ajouter un item ? la F.A.Q. With IE6: In IE6, use the tools/internet options menu, go to the last tab ('Advanced'), and check "allow active content" [1]. (pardon my french, but my english is way too bad) Oh, and thanks for the feedback, I added an entry for this in the FAQ. HTH [1] translator's note : I don't have IE6 (I don't use windows), so please someone correct me if that's not the correct label here. From mail at microcorp.co.za Wed Apr 4 09:56:34 2007 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Wed, 4 Apr 2007 15:56:34 +0200 Subject: how to remove multiple occurrences of a string within a list? References: <1175624433.206953.214290@n59g2000hsh.googlegroups.com><1175626905.957243.301870@w1g2000hsg.googlegroups.com><1175637235.783612.45980@o5g2000hsb.googlegroups.com> <1175673563.212459.322290@y66g2000hsf.googlegroups.com> Message-ID: <000201c77752$9d1d1160$03000080@hendrik> > On Apr 3, 3:53 pm, "bahoo" wrote: My first submission handles duplicates, but not triplicates and more. Here is one that seems a bit more bulletproof: duplist = [1, 2, 3, 4, 'haha', 1, 2, 3, 4, 5, 1,2,3,4,6,7,7,7,7,7] copylist = duplist[:] fullset = set(duplist) for x in duplist: del(copylist[copylist.index(x)]) if x in copylist: if x in fullset: fullset.remove(x) print list(fullset) when it is run, I get: IDLE 1.1.3 ==== No Subprocess ==== >>> [5, 6, 'haha'] >>> Now how would one do it and preserve the original order? This apparently simple problem is surprisingly FOS... But list comprehension to the rescue : >>>[x for x in duplist if duplist.count(x) == 1] ['haha', 5, 6] >>> *shakes head* duh... why does it take so long? : - ( - Hendrik From michael at jedimindworks.com Tue Apr 17 08:52:06 2007 From: michael at jedimindworks.com (Michael Bentley) Date: Tue, 17 Apr 2007 07:52:06 -0500 Subject: Help on Shelve.... In-Reply-To: <1176810739.765433.47470@n59g2000hsh.googlegroups.com> References: <1176810739.765433.47470@n59g2000hsh.googlegroups.com> Message-ID: <1694D7B7-2DE1-4F7F-870A-654DB399EF26@jedimindworks.com> On Apr 17, 2007, at 6:52 AM, Clement wrote: > Can i use Shelve for storing large amount of data around 6GB.. Is it > stable...? if any problems come, can i retrive the document.. Do you know for sure your filesystem handles files that big? From user at example.net Tue Apr 17 22:25:20 2007 From: user at example.net (Brandon D Cartwright) Date: Tue, 17 Apr 2007 19:25:20 -0700 Subject: retarded twits posting horseshit in technical groups References: <1176818165.135834.214220@y80g2000hsf.googlegroups.com> Message-ID: On Tue, 17 Apr 2007 15:43:02 -0700, MassiveProng wrote: >On 17 Apr 2007 06:56:05 -0700, thermate at india.com Gave us: > >>We know that... > > You're a fucking retard. But you are a text book example of a retard shoveling horseshit to technical groups.This is why you are universally hated and despised. Much of the discourse in any group you pollute revolves around ways to kill file and filter you and your troll followers to save the group from disintegration. I guess self-recognition is too difficult and painful for you but you really are in no position to criticize anyone else. From aisaac at american.edu Tue Apr 24 22:09:42 2007 From: aisaac at american.edu (Alan Isaac) Date: Wed, 25 Apr 2007 02:09:42 GMT Subject: gotcha or bug? random state reset on irrelevant import References: <33yXh.5839$Fc1.4387@trnddc05> <462EB311.2010508@lexicon.net> Message-ID: "John Machin" wrote in message news:462EB311.2010508 at lexicon.net... > It's not irrelevant; the test2 module has to be *executed* as part of > the import. [...] seed(314) is executed. OK, I understand this is the right answer. But another way to look at the question is: is it a good design to only be able to use seed to set a global state? (See for contrast numpy.random, for which my appreciation has just increased yet again.) Cheers, Alan Isaac From rNOSPAMon at flownet.com Mon Apr 23 12:46:59 2007 From: rNOSPAMon at flownet.com (Ron Garret) Date: Mon, 23 Apr 2007 09:46:59 -0700 Subject: Select weirdness References: <462b3e47$0$326$e4fe514c@news.xs4all.nl> <462c54cb$0$336$e4fe514c@news.xs4all.nl> Message-ID: In article , "Gabriel Genellina" wrote: > En Mon, 23 Apr 2007 04:33:22 -0300, Ron Garret > escribi?: > > > I have not been able to find a proxy server that can proxy to unix > > sockets, so I need to write my own. Conceptually its a very simple > > thing: read the first line of an HTTP request, parse it with a regexp to > > extract the sandbox name, connect to the appropriate unix server socket, > > and then bidirectionally pipe bytes back and forth. But it has to do > > this for multiple connections simultaneously, which is why I need select. > > No. This is what the *server* should do, not the *handler*. The server > listens on incoming requests, and creates a new handler for each one. > Inside a handler, you don't have to worry about multiple connections. > If you want to process simultaneous connections, inherit your server from > ThreadingMixIn or ForkingMixIn (or use one of the predefined server > classes). Ah, good point. But that still leaves the problem of keep-alive connections. I still need to be able to forward data in both directions without knowing ahead of time when it will arrive. (I think I can solve the problem by using send and recv directly BTW.) rg From kw at codebykevin.com Thu Apr 19 08:09:17 2007 From: kw at codebykevin.com (Kevin Walzer) Date: Thu, 19 Apr 2007 08:09:17 -0400 Subject: Future Python Gui? In-Reply-To: <1176952141.007295.272000@e65g2000hsc.googlegroups.com> References: <1176859699.906386.326720@b75g2000hsg.googlegroups.com> <1176923448.998078.170760@e65g2000hsc.googlegroups.com> <46267C84.8040505@codebykevin.com> <1176941169.750013.216660@e65g2000hsc.googlegroups.com> <4caef$4626b6f4$4275d90a$19707@FUSE.NET> <1176952141.007295.272000@e65g2000hsc.googlegroups.com> Message-ID: <46275BED.3050808@codebykevin.com> bcwhite at pobox.com wrote: > However, that file is completely useless without instructions on how > to use it, and there are no instructions within the page or file. > > That is: > - exactly where does it get installed In your Python site-packages directory. > - what else needs to get installed (eg. some dll) The Tile package. Install ActiveTcl from http://www.activestate.com, find the Tile package, and copy it to Python's installation of Tcl/Tk (find the libs directory--I'm not on a Windows box ATM and don't remember exactly). > - where do you find these other things http://www.activestate.com > - where does that something else get installed See above. > - how do you import this module import Tile > - how does use of Tkinter change (if at all) once imported > It shouldn't change at all. I use Frame for Tkinter frames and Tile.Frame for Tile frames, since a lot of the widgets have the same names. Here's a sample: from Tkinter import * import Tile root = Tk() root.tk.call('package', 'require', 'tile') def printme(): print "You clicked me" frame = Tile.Frame(root) frame.pack(fill=BOTH, expand=TRUE) button = Tile.Button(frame, text="Print", command=printme) button.pack() root.mainloop() HTH, Kevin -- Kevin Walzer Code by Kevin http://www.codebykevin.com From danfan1981 at yahoo.com Sun Apr 22 10:34:26 2007 From: danfan1981 at yahoo.com (danfan1981 at yahoo.com) Date: 22 Apr 2007 07:34:26 -0700 Subject: No speedup on multi-processor machine? In-Reply-To: <1177200844.134908.192110@q75g2000hsh.googlegroups.com> References: <1177189332.916296.205280@d57g2000hsg.googlegroups.com> <1177197495.821701.140390@b58g2000hsg.googlegroups.com> <1177200844.134908.192110@q75g2000hsh.googlegroups.com> Message-ID: <1177252466.855178.58010@y5g2000hsa.googlegroups.com> Thanks guys. But I think IronPython only works on Windows machine, but I am using a Sun machine. I was suggested to use Jython, which can run on Sun. But I need to use Numpy for matrix operations, which is only available to CPython. From lobais at gmail.com Tue Apr 17 16:12:30 2007 From: lobais at gmail.com (Thomas Dybdahl Ahle) Date: Tue, 17 Apr 2007 22:12:30 +0200 Subject: Compare regular expressions References: <1176753723.382697.268430@y80g2000hsf.googlegroups.com> <58je5lF2hg4r3U2@mid.uni-berlin.de> <1176836355.261501.94400@l77g2000hsb.googlegroups.com> Message-ID: Den Tue, 17 Apr 2007 11:59:15 -0700 skrev Paddy: > On Apr 17, 9:17 am, "Diez B. Roggisch" wrote: >> Paddy schrieb: >> > you could OR all the individual RE's test them all at once then find >> > out which matched. >> >> > big_re = "|".join( r"(?P<__match_%i__>%s)" % (i, r) >> > for i,r in enumerate(regexps) ) >> >> This doesn't answer the question if two of the sub-expressions matched. Hm, if I were to OR them all the time, then I wouldn't get any boost from compiling. I'll probably just stick with a try them all solution, and then change it if I run into something that does the right thing. I believe it can make the code something like 7 or 10 times faster. From mail at timgolden.me.uk Mon Apr 9 07:21:52 2007 From: mail at timgolden.me.uk (Tim Golden) Date: Mon, 09 Apr 2007 12:21:52 +0100 Subject: how to use the string '\\.\' In-Reply-To: <1176117103.670611.291740@n59g2000hsh.googlegroups.com> References: <1176117103.670611.291740@n59g2000hsh.googlegroups.com> Message-ID: <461A21D0.9000705@timgolden.me.uk> ??????????????? wrote: > print r'\\.\' > > This line will cause error. I just want to print the > \\.\ > why the prefix character "r" isn't effective. Thanks! Because of the way in which Python parses strings, you can't end a string -- even a raw one -- with an odd (1, 3, 5 etc) number of backslashes. In you example, you'd have to do this: print "\\\\.\\" although, depending on what the code was doing, you might be able to use forward slashes instead; a surprising number of Microsoft's APIs allow forward slashes as well as backslashes. Not, however, anything which is interpreted by the command shell (which sees a forward slash as a flag indicator) nor typically anything handled by the Shell subsystem. TJG From pete.forman at westerngeco.com Mon Apr 23 08:09:47 2007 From: pete.forman at westerngeco.com (Pete Forman) Date: Mon, 23 Apr 2007 13:09:47 +0100 Subject: matplotlib basic question References: <1177016327.543985.34500@o5g2000hsb.googlegroups.com> <1177092157.763869.77600@o5g2000hsb.googlegroups.com> Message-ID: <8xcj5m2c.fsf@wgmail2.gatwick.eur.slb.com> Robert Kern writes: > Colin J. Williams wrote: > >> I'm not sure that scipy has been updated to Python 2.5 > > ? scipy certainly works with 2.5. Are you referring to something > else perhaps? Yes, the Python Enthought Edition was being discussed and it is currently based on Python 2.4.3. http://code.enthought.com/enthon/ -- Pete Forman -./\.- Disclaimer: This post is originated WesternGeco -./\.- by myself and does not represent pete.forman at westerngeco.com -./\.- the opinion of Schlumberger or http://petef.port5.com -./\.- WesternGeco. From pavlovevidence at gmail.com Wed Apr 4 18:02:16 2007 From: pavlovevidence at gmail.com (Carl Banks) Date: 4 Apr 2007 15:02:16 -0700 Subject: BeautifulSoup vs. real-world HTML comments In-Reply-To: References: <1175711322.448629.20300@y80g2000hsf.googlegroups.com> <1175717833.872281.6300@l77g2000hsb.googlegroups.com> Message-ID: <1175724136.054215.249970@p77g2000hsh.googlegroups.com> On Apr 4, 4:55 pm, Robert Kern wrote: > Carl Banks wrote: > > On Apr 4, 2:43 pm, Robert Kern wrote: > >> Carl Banks wrote: > >>> On Apr 4, 2:08 pm, John Nagle wrote: > >>>> BeautifulSoup can't parse this page usefully at all. > >>>> It treats the entire page as a text chunk. It's actually > >>>> HTMLParser that parses comments, so this is really an HTMLParser > >>>> level problem. > >>> Google for a program called "tidy". Install it, and run it as a > >>> filter on any HTML you download. "tidy" has invested in it quite a > >>> bit of work understanding common bad HTML and how browsers deal with > >>> it. It would be pointless to duplicate that work in the Python > >>> standard library; let HTMLParser be small and tight, and outsource the > >>> handling of floozy input to a dedicated program. > >> Well, BeautifulSoup is just such a dedicated library. > > > No, not really. > > Yes, it is. Whether it succeeds in all particulars is besides the point. The > only mission of BeautifulSoup is to handle bad HTML. I think the authors of BeautifulSoup have the right to decide what their own mission is. Carl Banks From hlubenow2 at gmx.net Tue Apr 10 11:09:07 2007 From: hlubenow2 at gmx.net (hlubenow) Date: Tue, 10 Apr 2007 17:09:07 +0200 Subject: Check for keypress on Linux xterm ? References: <131m56dsgr7or38@corp.supernews.com> Message-ID: Grant Edwards wrote: > On 2007-04-09, hlubenow wrote: > >> My problem is, I don't want my program to wait for the keypress. >> I just want to check, if a key is currently pressed and if not, I'd like >> to continue with my program (like "INKEY$" in some BASIC-dialects). > > The answer to this frequently asked question is actually in the FAQ: > > http://www.python.org/doc/faq/library.html#how-do-i-get-a-single-keypress-at-a-time > > Google finds us further examples: > > http://mail.python.org/pipermail/pythonmac-sig/2004-February/010140.html > http://mail.python.org/pipermail/python-list/2000-June/041251.html You're answer is only less than half correct: Most of the given examples use something like c = sys.stdin.read(1) like my example does. This blocks input. At the end of your last link the author there says it. He also shows some ways into my direction. I'll test them. H. From newsgroups at nospam.nowire.org Mon Apr 9 01:52:23 2007 From: newsgroups at nospam.nowire.org (=?ISO-8859-1?Q?Thomas_Kr=FCger?=) Date: Mon, 09 Apr 2007 07:52:23 +0200 Subject: Crypto Suggestion/Help In-Reply-To: References: Message-ID: Jimmy E Touma schrieb: > I need some advise on doing the following. I have a Linux application > that allows users to access it via a code (password). At the end of the > day, I gather a log of activities of the users and zip the file and > would like to encrypt it so that the users can not access it or tamper > with it. Only manager should. If I use a private/public key for doing so > I have to store the private key on my computer. What is a good way to > encrypt a file and have the key well hidden on the same computer? If you > have any other way to do, like MD5 or similar, please let me know. You don't need encryption, cryptographic hashes or Python. What you need are just the basic UNIX/Linux permissions. Thomas From gagsl-py2 at yahoo.com.ar Sat Apr 7 22:52:08 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: 7 Apr 2007 19:52:08 -0700 Subject: beginner - py unicode Q In-Reply-To: <46182E68.34A35F01@braindead.com> References: <46182E68.34A35F01@braindead.com> Message-ID: <1176000728.809656.276030@p77g2000hsh.googlegroups.com> enquiring mind wrote: > I read the posting by Rehceb Rotkiv and response but don't know if it > relates to my problem in any way. > > I only want to write German to the screen/console for little German > programs/exercises in python. No file w/r will be used. > > #! /usr/bin/env python > # -*- coding: utf-8 -*- > # Filename: 7P07png.py > # SUSE Linux 10 Python 2.4.1 gedit 2.12.0 > > print 'Ich z?hle zw?lf wei? H?te.' > print 'Wollen Sie' > verbs = ( 'k?mmen' , 'essen' , 'trinken' ) > print verbs[:3] > > print ' program ends ' > > console display is: Ich z?hle zw?lf wei? H?te. > Wollen Sie > ('k\xc3\xb6mmen', 'essen', 'trinken') > program ends > > The first 2 print statements in German print perfectly to screen/console > but not the 3rd. In the 3rd you don't print a string, you print a tuple. Python internally uses repr() on each item, joins them using "," and puts parenthesis around the whole thing. That's not usually what you want; that representation is good for debugging. (See below) > I also tried unicode string u'k?mmen', but it did not fix problem. Working in Unicode may be useful, but it's not your current problem. > I found this reference section but I am not sure it applies or how to > use it to solve my problem.: Forget about setdefaultencoding! > I just thought of this. I suppose because this is py source code, it > should not be German but a reference/key to u'strings' to print German > text to the screen? No... > The ultimate console output I seek, of course, using a while or for loop > and/or random access for second verb, for example: > Wollen Sie k?mmen? > Wollen Sie essen? > Wollen Sie trinken? Had you tried this before, you would have no problems. for verb in verbs: print 'Wollen Sie', verb, '?' This way you print an individual item, and you can control exactly how you like it displayed. Another way: for verb in verbs: print 'Wollen Sie %s?' % verb -- Gabriel Genellina From marcpp at gmail.com Mon Apr 16 16:06:20 2007 From: marcpp at gmail.com (Marcpp) Date: 16 Apr 2007 13:06:20 -0700 Subject: Pyqt calling a custom dialog and returning the vars Message-ID: <1176753980.142797.268800@e65g2000hsc.googlegroups.com> I call a dialog from a principal program but cannot return the value of the variables (text box's). Here is a example... from ui import Agenda from dialog1 import dialogo1 from PyQt4 import * import dbm import sys class principal (QApplication): def __init__(self, args): """ In the constructor we're doing everything to get our application started, which is basically constructing a basic QApplication by its __init__ method, then adding our widgets and finally starting the exec_loop.""" QApplication.__init__(self,args) # We pass None since it's the top-level widget, we could in fact leave # that one out, but this way it's easier to add more dialogs or widgets. self.maindialog = ag(None) self.setMainWidget(self.maindialog) self.maindialog.show() self.exec_loop() class ag (Agenda): ... ... def _slotAddClicked(self): d=dialogo1() d.exec_() d.connect(d.buttonOk,SIGNAL("clicked()"),self._procesadialog1) def _procesadialog1(): d=dialogo1() drempresa = d.dempresa.text() print drempresa # <-------------------------------------------------------- Nothing appears ... ... if __name__ == "__main__": app = principal(sys.argv) From david at boddie.org.uk Sat Apr 7 13:51:15 2007 From: david at boddie.org.uk (David Boddie) Date: Sat, 07 Apr 2007 19:51:15 +0200 Subject: Is http://cheeseshop.python.org/pypi/ having issues References: <1175967418.642658.46930@l77g2000hsb.googlegroups.com> Message-ID: <44f1b$4617da15$54d1d767$21800@news.chello.no> On Saturday 07 April 2007 19:36, RobJ wrote: > Has any one noticed any issues with http://cheeseshop.python.org/pypi/ > ? I have been trying for hours to install packages (using > easy_install) but the connection keeps timing out. Don't worry, you're not the first person to notice: http://mail.python.org/pipermail/catalog-sig/2007-April/001050.html Maybe someone can suggest a workaround for easy_install while the server is unavailable. David From arkanes at gmail.com Wed Apr 11 10:14:02 2007 From: arkanes at gmail.com (Chris Mellon) Date: Wed, 11 Apr 2007 09:14:02 -0500 Subject: tuples, index method, Python's design In-Reply-To: <740c3aec0704101534y3c65f5a7je382f97e1f6301b7@mail.gmail.com> References: <1176210960.3430.20.camel@dot.uniqsys.com> <740c3aec0704100810g5f962e8eu614fbaedecf3608e@mail.gmail.com> <1176219856.3430.76.camel@dot.uniqsys.com> <740c3aec0704101021i1fd79ef2l99eac4ced1e252d9@mail.gmail.com> <1176226682.3430.86.camel@dot.uniqsys.com> <4866bea60704101104r4600d281h135286b66378f4d4@mail.gmail.com> <740c3aec0704101534y3c65f5a7je382f97e1f6301b7@mail.gmail.com> Message-ID: <4866bea60704110714g27fed46o798f4bc5b9dcbdf@mail.gmail.com> On 4/10/07, BJ?rn Lindqvist wrote: > > > while not game_has_ended: > > > for current_player in p: > > > player_does_something(current_player) > > > > > > > I'm curious why someone would even consider using a tuple in this case > > regardless. I think that much of the desire for tuple.index is because > > people use a tuple where they could have a list, but either a) some > > vestige of B&D language programming comes out and they want to make > > Maybe someone had to much alcohol when they were coding? Maybe they > don't know better? Maybe they thought that an index method on a > sequence made sense? Who are you to spoil their fun? Could it be that > YOU are the B&D person? > If you want a language that just adds whatever methods anyone thinks of, along with whatever aliases for it any can think of, to every data type, you know where to find Ruby. From gagsl-py2 at yahoo.com.ar Thu Apr 5 13:27:19 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 05 Apr 2007 14:27:19 -0300 Subject: AW: Write to a binary file References: <131a2eeq2feuefe@corp.supernews.com> Message-ID: En Thu, 05 Apr 2007 11:38:06 -0300, Grant Edwards escribi?: > On 2007-04-05, Thomi Aurel RUAG A wrote: > >> The output was: >> --- Start --- >> Pytest write> 02 36 00 01 0a b0 77 >> Pytest write> 02 36 00 01 0a >> Pytest write> b0 77 >> --- END --- > > I'm surprised that the normal file object's write method does > that -- especially for a "binary" file. IMO, it's a bug when a > binary file object treats 0x0a differently than other byte > values. A write() call on a Python file object gets directly translated into a fwrite() C runtime library call. Any special handling is made inside that library. > But, using the file object to read/write a device is > probably not a good idea because of undefined behavior like > that. File objects also do their own buffering, which I > suspect isn't what you want. I agree - using os.open, os.write etc. appears to be the right thing here. -- Gabriel Genellina From tjreedy at udel.edu Fri Apr 27 20:09:48 2007 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 27 Apr 2007 20:09:48 -0400 Subject: Portable SciPy v0.1 released References: <2418d$463275ce$d443bb3a$25239@news.speedlinq.nl><1177714703.751242.61090@e65g2000hsc.googlegroups.com> Message-ID: | > On Apr 27, 6:17 pm, Stef Mientki | > wrote: | >>Portable SciPy, is an easy installer of SciPy for M$ windows users. Thanks Stef for posting this. The write-up on your site looks pretty clear. | Beliavsky wrote: | > If you have an announcement for Windows users, I suggest that you not | > needlessly turn them off by abbreviating Microsoft as M$ . You don't | > like Windows, His linked web-page http://oase.uci.kun.nl/~mientki/data_www/pic/jalcc/python/portable_scipy.html starts "As a spoiled M$ windows user, I'm used to 'one-button' installations...". And so he made one and explains how. Methinks you doth project too much. |> but many of us Windows users don't like the anti-Windows | > snobs. There is nothing wrong with making money by selling software. He did not there was. "James Stroud" wrote in message news:f0u0qi$dcb$1 at zinnia.noc.ucla.edu... | | Yes, dollar signs are very derogatory. Please do not use them in the | future, either as prefixes to variables, or especially as suffixes to | abbreviations. This is a *python* list for crying out loud! Heh, heh. (This is almost certainly satire, for those who don't notice.) tjr From gslindstrom at gmail.com Sun Apr 29 14:03:39 2007 From: gslindstrom at gmail.com (gDog) Date: 29 Apr 2007 11:03:39 -0700 Subject: Video: Professor of Physics Phd at Cal Tech says: 911 Inside Job In-Reply-To: <1177793419.474675.156860@y80g2000hsf.googlegroups.com> References: <1177467203.719625.93920@u32g2000prd.googlegroups.com> <1177780530.539758.275660@c35g2000hsg.googlegroups.com> <1177792809.503415.182480@o5g2000hsb.googlegroups.com> <1177793419.474675.156860@y80g2000hsf.googlegroups.com> Message-ID: <1177869819.781641.88780@n59g2000hsh.googlegroups.com> On Apr 28, 2:50 pm, Major Quaternion Dirt Quantum wrote: > here's a question that came-up recently, > in battling with the controlled-demo advocates > at teh Promenade: > > how is it that the metal was still molten, > after weeks? snip...snip...snip... I say it's time to bring in the Mythbusters!! *That* will put and end to all of this. --greg From kyosohma at gmail.com Mon Apr 30 10:47:40 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: 30 Apr 2007 07:47:40 -0700 Subject: Update to Python Quick Reference Card (for Python 2.4) (v0.67) In-Reply-To: References: Message-ID: <1177944460.362670.214900@y5g2000hsa.googlegroups.com> On Apr 30, 7:42 am, Laurent Pointal wrote: > PQRC (Python Quick Reference Card) is a condensed documentation for > Python and its main libraries, targetting production of printed quick > reference cards. > Its available as OpenDocument .odt files and as A4 and USLetter > formatted PDF files ready to print. > Its distributed under a Creative Commons Attribution - NonCommercial - > ShareAlike - 2.5 License, with allowing in-house print for curses. > > Modifications since previous publication: > Switching to DejaVu font. > Rework styles. > Get around bad index page numbers generation bug. > Small corrections. > > Its here:http://www.limsi.fr/Individu/pointal/python/pqrc/ > > Note: Next version will target Python 2.5. I'll keep version for Python > 2.4 but should only make minor updates. > > -- > Laurent POINTAL > CNRS-LIMSI d?pt. CHM, groupes AMI et PS > Courriel: laurent.poin... at limsi.fr (prof) > laurent.poin... at laposte.net (perso) > Ouebe:http://www.limsi.fr/Individu/pointal/ > T?l. 01 69 85 81 06 (prof) > Fax. 01 69 85 80 88 This is pretty cool. Kind of like the Python Phrasebook, but even more succinct. Thanks! Mike From horpner at yahoo.com Mon Apr 23 11:46:13 2007 From: horpner at yahoo.com (Neil Cerutti) Date: 23 Apr 2007 17:46:13 +0200 Subject: When are immutable tuples *essential*? Why can't you just use lists *everywhere* instead? References: <1177088796.622928.224890@d57g2000hsg.googlegroups.com> <1177089206.550423.288670@q75g2000hsh.googlegroups.com> <58sf33F2b1q8tU1@mid.individual.net> <1177103370.022138.110320@n59g2000hsh.googlegroups.com> <1177108560.660288.171890@n76g2000hsh.googlegroups.com> Message-ID: On 2007-04-23, Chris Cioffi wrote: > On 23 Apr 2007 17:19:15 +0200, Neil Cerutti > wrote: >> So the question becomes: Why do Python dictionaries require >> keys to be of an immutable type? > > Dictionary keys are hashed values. If you change the key, you > change the hash and lose the pointer to the referenced object. Other dictionary-like implementations (C++ std::map for example) simply exhort you not to change keys (C++ makes it hard to ignore the exhortation) or suffer undefined behavior. Perhaps avoiding a cause of undefined behavior was the Python reason for the requirement. > Or: Because. ;-) Heh, heh. I was wondering, if we dig deep enough, wether we'll end up back at, "just an optimization," as the reason. -- Neil Cerutti From __peter__ at web.de Sun Apr 1 12:48:52 2007 From: __peter__ at web.de (Peter Otten) Date: Sun, 01 Apr 2007 18:48:52 +0200 Subject: Pickling a class with a __getattr__ References: <1175445521.216223.130470@y80g2000hsf.googlegroups.com> Message-ID: Peter Bengtsson wrote: > Hi, I'm trying to pickle an object instance of a class that is like a > dict but with a __getattr__ and I'm getting pickling errors. > This is what happens when I'm trying to be clever: > >>>> import cPickle as pickle >>>> class Dict(dict): > ... def __getattr__(self, key): > ... return self.__getitem__(key) > ... >>>> friend = Dict(name='Zahid', age=40) >>>> friend > {'age': 40, 'name': 'Zahid'} >>>> friend.name > 'Zahid' >>>> v=pickle.dumps(friend) > Traceback (most recent call last): > File "", line 1, in ? > File "/usr/lib/python2.4/copy_reg.py", line 73, in _reduce_ex > getstate = self.__getstate__ > File "", line 3, in __getattr__ > KeyError: '__getstate__' > > > Why can't I pickle the slightly more featurefull class there called > 'Dict'? Because you allow your __getattr__() implementation to raise the wrong kind of exception. >>> from cPickle import dumps, loads >>> class Dict(dict): ... def __getattr__(self, key): ... try: ... return self[key] ... except KeyError: ... raise AttributeError ... >>> friend = Dict(name="Zaphod", age=42) >>> v = dumps(friend) >>> p = loads(v) >>> p {'age': 42, 'name': 'Zaphod'} Peter From jzgoda at o2.usun.pl Sun Apr 29 06:46:09 2007 From: jzgoda at o2.usun.pl (Jarek Zgoda) Date: Sun, 29 Apr 2007 12:46:09 +0200 Subject: Asynchronous XML-RPC client library? In-Reply-To: <46346ab6$0$18128$9b622d9e@news.freenet.de> References: <46346ab6$0$18128$9b622d9e@news.freenet.de> Message-ID: Martin v. L?wis napisa?(a): >> Is there anything like that? Googling yields many articles on async >> servers, but virtually nothing on clients. I have to talk to remote in >> an environment that does not allow threads... > > My recommendation would be to use xmlrpclib, and combine it with > the async framework that you currently use. Found a recipe, finally. Not that it was easy and the weird thing is it was posted to PyGTK list and I even replied to this post... Here's the link to the code by Andrew Kuchling, for the impatient: http://www.mail-archive.com/pygtk at daa.com.au/msg12971.html -- Jarek Zgoda http://jpa.berlios.de/ From exarkun at divmod.com Tue Apr 17 10:03:57 2007 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Tue, 17 Apr 2007 10:03:57 -0400 Subject: Queue enhancement suggestion In-Reply-To: Message-ID: <20070417140357.19381.1194346364.divmod.quotient.2439@ohm> On 17 Apr 2007 13:32:52 GMT, Antoon Pardon wrote: >On 2007-04-17, Hendrik van Rooyen wrote: > [snip] >> Not sure I understand this - it sounds vaguely incestous to me. >> I normally use a GUI with two queues, one for input, one for >> output, to two threads that front end two named pipes to >> the next process - I try to avoid more than one thing reading or >> writing to one end of a queue or a pipe, so the dataflow diagram >> for my stuff always looks like a TinkerToy... > >The problem is that sometimes the gui thread has something to show >too. With the added problem that the code wanting to show something >doesn't know when it is executing the gui thread or an other. So >it is very difficult to avoid the gui thread putting things on the >queue. But since the gui thread is the single reader, it will dead >lock if the queue happens to be full at the moment the gui thread >want to add another item. > This is pretty easily solved: def sendToGUI(event): if isInGUIThread(): gui.scheduleCall(event) else: guiQueue.put(event) Jean-Paul From martin at v.loewis.de Sat Apr 7 04:52:03 2007 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sat, 07 Apr 2007 10:52:03 +0200 Subject: Convert xml symbol notation In-Reply-To: <1175899141.354348.207530@q75g2000hsh.googlegroups.com> References: <1175899141.354348.207530@q75g2000hsh.googlegroups.com> Message-ID: <46175BB3.4010304@v.loewis.de> > I'm working on a script to download and parse a web page, and it > includes xml symbol notation, such as ' for the ' character. Does > anyone know of a pre-existing python script/lib to convert the xml > notation back to the actual symbol it represents? If you have this given in an XML file (rather than an HTML file which is not well-formed XML), you could use an XML parser for the entire file. This would automatically unescape character references. Likewise, you can parse it with HTMLParser, which will invoke the handle_charref method for these. If you just want to unescape references, you can use the code in http://effbot.org/zone/re-sub.htm HTH, Martin From Krishna.K.1900 at gmail.com Sun Apr 15 20:06:59 2007 From: Krishna.K.1900 at gmail.com (Krishna.K.1900 at gmail.com) Date: 15 Apr 2007 17:06:59 -0700 Subject: working of round() Message-ID: <1176682019.215351.114560@y80g2000hsf.googlegroups.com> Does round() always perfectly return the output expected or are there some artifacts which don't allow perfect functionality Using python 2.5: >>> round(12.234, 2) 12.23 >>> round(12.234, 3) 12.234 >>> round(12.234, 1) 12.199999999999999 >>> but was expecting 12.2 Also, for round(x,n), can't 'x' be an expression round(5.25/2, 2) was expecting 2.62 , but >>> round(5.25/2, 2) 2.6299999999999999 From robert.rawlins at thinkbluemedia.co.uk Thu Apr 26 04:48:54 2007 From: robert.rawlins at thinkbluemedia.co.uk (Robert Rawlins - Think Blue) Date: Thu, 26 Apr 2007 09:48:54 +0100 Subject: Scheduler Module Help Message-ID: <007201c787df$b96b1d10$2c415730$@rawlins@thinkbluemedia.co.uk> Hello Guys, I'm using the sched module to create a set of functions that run every 10 or 20 minutes whilst the application is running, however it would seem that the moment I run scheduler.run() it prevents any other operations in my application from running, its sits dormant until it runs the scheduled functions. Any ideas on what might be the root of this issue? Thanks, Rob -------------- next part -------------- An HTML attachment was scrubbed... URL: From marcpp at gmail.com Thu Apr 12 05:23:42 2007 From: marcpp at gmail.com (Marcpp) Date: 12 Apr 2007 02:23:42 -0700 Subject: Pyqt programming question Message-ID: <1176369822.364743.243700@n76g2000hsh.googlegroups.com> I have a program (python + pyqt), with a button I'll would to open a new dialog window to input text, when press save or ok, this text is returned to the principal program. I've seek in internet but i don't find anything. From Glich.Glich at googlemail.com Thu Apr 26 15:06:42 2007 From: Glich.Glich at googlemail.com (Glich) Date: 26 Apr 2007 12:06:42 -0700 Subject: SPE In-Reply-To: References: <1177602331.523239.54930@b40g2000prd.googlegroups.com> Message-ID: <1177614402.334319.72830@n35g2000prd.googlegroups.com> After posting this message I realized the stupid mistake I had made! But it was too late to change! I think patching it with py2exe would be a good idea. Greetings also, Glich From apardon at forel.vub.ac.be Wed Apr 11 09:55:40 2007 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 11 Apr 2007 13:55:40 GMT Subject: tuples, index method, Python's design References: <1175867771.114540.61810@n76g2000hsh.googlegroups.com> <1175884427.779950.267220@y80g2000hsf.googlegroups.com> <1175953520.316208.241490@o5g2000hsb.googlegroups.com> <7xzm5igbrb.fsf@ruckus.brouhaha.com> <1176200361.260546.280510@n76g2000hsh.googlegroups.com> <1176214831.3430.49.camel@dot.uniqsys.com> Message-ID: On 2007-04-11, Marc 'BlackJack' Rintsch wrote: > In , Antoon Pardon wrote: > >> On 2007-04-11, Steven D'Aprano wrote: >>> Lists are designed for sequences of homogeneous items, e.g.: >>> >>> L = [1, 2, 4, 8, 16, 32] >>> while tuples are designed to be more like structs or records, with >>> heterogeneous items, e.g.: >>> >>> T = ("Fred", 32, 12.789, {}, None, '\t') >> >> I think you are confused. Last time I heard this homogeneous items stuf, >> it had nothing to do with the types being the same. They were homogeneous >> because they somehow belonged together and heterogeneous because they >> just happened to live together. Similarity of type played no part in >> calling the data homogeneous or heterogeneous. > > Then you are confused. The typical use case for tuples are database > records. The columns in the table can have completely different types but > the values in a row, represented as a Python tuple, of course belong > together. Don't blame me. I don't agree with the view. But that was sort of the explanation that was given here last time I remember this topic came up in defending why tuples and lists differ in a number of ways that are less obvious. They wrote about lists containing homogeneous items and tuples containing hetergenous items but stressed rather strongly that this shouldn't be understood in terms of type similarities. > The homogeneous objects in lists must not be of the same type but share > some behavior so it makes sense to apply some operation on all the > elements. For example get the length of each item or sum them all up. No they don't. The counter example is using a list as a stack when evaluating expressions. You can use one stack to store the still to be treated numbers and operands and those two don't need common behaviour. -- Antoon Pardon From s_broscious at comcast.net Fri Apr 13 18:00:27 2007 From: s_broscious at comcast.net (Scott) Date: Fri, 13 Apr 2007 18:00:27 -0400 Subject: Question About Creating Lists References: <1176414392.977660.16610@o5g2000hsb.googlegroups.com> Message-ID: > And that's a really sideways way to take a swipe at someone while > pretending to be too high-minded to do it (plus see James's comments about > other possible explanations). If you kiddies would take this fight out > into the playground perhaps the rest of the class can continue. It wasn't meant as a swipe, it was an example of what he did turned around. There was no fight, at least on my end. What happened was I was confronted something that I didn't appreciate it, and I made it known, just as most people would if it happened face to face. > It *would* be helpful if you "just asked the question". You said in your > original post that "... I need to know the petty just because I need to > know", but that's an abuse of the word need unless you suffer from a quite > unusual psychological compulsion. I see the point to getting to the point (lol). Most people don't worry about my ramblings, and I've found that if they aren't included I get a 1-2 line answer. That 1-2 line answer, while fine for most, just WILL not help me. It actually makes it worse. I have a compulsion for knowledge that pass' far beyond what most people would call healthy. So much so that I take medications I'm not about to list here. If I attempt to learn something and don't understand it, my entire mindset is taken over by my desire. I CAN NOT sleep, eat, or function "normally" until I KNOW even the mundane. I hate using the following example, but it helps some people understand how my mind thinks. Have you ever seen a crack addict walking down the street (or on tv) and their thoroughly searching the ground for the crack that they dropped (that they never really had)? Take that and substitute crack for knowledge and you'll have me. SO now you see why I start my posts the way I do. > To you. Get over it, this is Usenet. You will experience worse if you > stick at it long enough. I've already come to this understanding just as most who frequent any type of "community" online, what with all the internet tough guys who frequent most forums. That's in no way a knock at 7stud just an observation of most troublemakers. But just because we all know its there, doesn't make it acceptable, nor does it mean anyone should have to tolerate it just because they chose to hop online. When someone makes it known a certain thing bothers them, the polite thing to do would be to stop. I bet if I TYPED IN CAPS LOCKS FOR EVERYTHING I WROTE, someone, if not everyone, would say something. Its the same idea with what I did. There are plenty of ways to stop this kind of treatment online, and if more people knew that all they had to do was make a call to thier ISP, or to the local police department with even just a pseudonym, that kind of treatment would become less acceptable. I deal with these types of reports every day at work. Fines can be impossed no matter where the harrasser is, and depending on the context can actually involve jail time. Of course this actual issue is very petty, and all that is/should be needed, was my addressing the fact that it was not polite. That should of been the end of it, and it seems to have been. Believe it or not the problem lies with the people getting harrased, not the harrasser. They believe nothing will be done and so they don't try, and then they come to accept it. How wrong they are. From admin at loial.co.uk Thu Apr 26 08:54:32 2007 From: admin at loial.co.uk (loial) Date: 26 Apr 2007 05:54:32 -0700 Subject: Store variable name in another variable Message-ID: <1177592072.498517.139260@b40g2000prd.googlegroups.com> I need to store a list of variable names in a dictionary or list. I then later need to retrieve the names of the variables and get the values from the named variables. The named variables will already have been created and given a value. I hope thats clear!!! How can I do this? From maxime.p at gmail.com Mon Apr 2 15:18:48 2007 From: maxime.p at gmail.com (Ulysse) Date: 2 Apr 2007 12:18:48 -0700 Subject: Launch script on Linux using Putty In-Reply-To: References: <1175467029.572354.138930@y66g2000hsf.googlegroups.com> <1175536278.510176.183360@l77g2000hsb.googlegroups.com> <1312jhhpbll3ta7@corp.supernews.com> Message-ID: <1175541528.954409.304230@n76g2000hsh.googlegroups.com> On Apr 2, 8:54 pm, Michael Hoffman wrote: > [Michael Hoffman] > > >> If you are running bash, you can do this: > > [Grant Edwards] > > > He's not running bash. He's running busybox's shell. > > There's a nohup applet for busybox. > > > [He'd be far better off asking his question in an OpenWRT or > > Busybox forum, since it's got absolutely nothing to do with > > Python.] > > I was going to say that originally, but then I realized that the daemon > solution is on-topic. So is masking SIGHUP. > -- > Michael Hoffman Actually the "./myscript.py &" command seems to work well. I can close the Putty console, and then after logging the command "top" show me that my process is still running. From deets at nospam.web.de Wed Apr 25 19:13:25 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 26 Apr 2007 01:13:25 +0200 Subject: My python annoyances so far In-Reply-To: <1177541453.471959.120830@c18g2000prb.googlegroups.com> References: <1177541453.471959.120830@c18g2000prb.googlegroups.com> Message-ID: <59a5kqF2jaqhaU1@mid.uni-berlin.de> flifus at gmail.com schrieb: > Hi all. I'm learning python these days. I'm going to use this thread > to post, from time to time, my annoyances with python. I hope someone > will clarify things to me where I have misunderstood them. > > Annoyances: > > 1. Underscores! What's the deal with that? Especially those double > underscores. The best answer I read on this is that the double > underscores denotes special methods that the interpreter may > automatically use. For example, 4+4 get expanded by the interpreter to > 4.__add__(4). http://docs.python.org/ref/specialnames.html > 2. There are modules, there are functions, and there are classes- > methods! Wouldn't it have been easier had everything either been a > function or a class method? I'm not sure what you mean here. modules are modules, they can contain functions, classes, top-level code. Functions and class-methods are similar, but there are some differences that make sense. But I'm not sure if you really _mean_ class methods, given that you confuse so much. The python community is a unusually friendly bunch of people. Yet you should consider not calling things you don't understand "annoyances". Diez From duncan.booth at invalid.invalid Sun Apr 15 14:41:33 2007 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 15 Apr 2007 18:41:33 GMT Subject: Calling private base methods References: <1176374675.347453.89340@n76g2000hsh.googlegroups.com> <1176404325.211501.26610@w1g2000hsg.googlegroups.com> <1176435087.708516.66470@o5g2000hsb.googlegroups.com> <1176650850.211487.294690@y80g2000hsf.googlegroups.com> Message-ID: "Isaac Rodriguez" wrote: >> The fact that I had >> to resort to this trick is a big indication of course that genuinely >> private members (as opposed to a 'keep off' naming convention) are a bad >> idea in general. > > > The fact that you had to resort to this trick is a big indication that > the library you were using is bad designed; it has nothing to do with > private members being a bad idea. You were using a library which > interface was in-complete (provided that you "genuinely" really needed > to access the private member to do what you wanted to do). I agree with that to a certain extent, but I've never found any situation where I gained any benefit because someone had made part of the implementation private, only ever found annoyance because someone had made something private which shouldn't have been. The problem is that when people design interfaces they don't (and cannot) know all the situations in which the code is going to be used in the future. Clearly separating the published interface from the implementation details is a good thing, but physically preventing access to those details is IMHO a bad thing. From C.delete_this.Sanders at BoM.GOv.AU Fri Apr 13 01:42:08 2007 From: C.delete_this.Sanders at BoM.GOv.AU (Charles Sanders) Date: Fri, 13 Apr 2007 15:42:08 +1000 Subject: Problem with algorithm In-Reply-To: <1176434937.258002.162220@p77g2000hsh.googlegroups.com> References: <1176434160.047703.214600@q75g2000hsh.googlegroups.com> <1176434937.258002.162220@p77g2000hsh.googlegroups.com> Message-ID: <461f1831$0$6621$c30e37c6@lon-reader.news.telstra.net> mensanator at aol.com wrote: > On Apr 12, 10:16?pm, "Jia Lu" wrote: >> Hi all. >> ?I want to create a large list like: >> >> aaaa ~ zzzz >> >> Is there any good algorithm to do this? > > Sure. > test = '01' > > for m in test: > for n in test: > for o in test: > for p in test: > print m+n+o+p [snip] Forgive any silly mistakes I have made (I've been teaching myself python for about 1 week) but there is a moderately well known algorithm for this that extends to arbitrary lengths of both the list of alternatives and the length of the required output, and avoids deeply nested loops. I know that it is no better for small and constant output lengths, but for longer lengths or if the output length can vary it should be better. There is a similar algorithm if duplicates are not allowed (ie abcd ... wxyz). My attempt at a python translation of the algorithm: def m_from_n ( v, m ): """ Print all combinations of m things from v[0] ... v[n-1], duplicates OK. Yields a list. """ x = [0] * m while True: yield [ v[i] for i in x ] i = m - 1 while i>=0 and x[i]==len(v)-1: x[i] = 0 i = i - 1 if i >= 0: x[i] = x[i] + 1 else: return for y in m_from_n( "xyz", 2 ): print ''.join(y) xx xy xz yx yy yz zx zy zz for y in m_from_n( [0,1], 3 ): print y [0, 0, 0] [0, 0, 1] [0, 1, 0] [0, 1, 1] [1, 0, 0] [1, 0, 1] [1, 1, 0] [1, 1, 1] for y in m_from_n( "abcdefghijklmnopqrstuvwxyz", 4 ): print ''.join(y) should more or less do what you want. Charles From steven.bethard at gmail.com Sun Apr 22 11:18:06 2007 From: steven.bethard at gmail.com (Steven Bethard) Date: Sun, 22 Apr 2007 09:18:06 -0600 Subject: Python "robots.txt" parser broken since 2003 In-Reply-To: References: Message-ID: John Nagle wrote: > Terry Reedy wrote: >> "John Nagle" wrote in message >> news:FvtWh.11824$YL5.6282 at newssvr29.news.prodigy.net... >> | This was reported in 2003, and a patch was uploaded in 2005, but the >> patch >> | never made it into Python 2.4 or 2.5. >> >> If the patch is still open, perhaps you could review it. >> > I tried it on Python 2.4 and it's in our production system now. > But someone who regularly does check-ins should do this. If you post such a review (even just the short sentence above) to the patch tracker, it often increases the chance of someone committing the patch. Steve From griebel at konzept-is.de Thu Apr 12 05:56:03 2007 From: griebel at konzept-is.de (Dr. Peer Griebel) Date: Thu, 12 Apr 2007 11:56:03 +0200 Subject: sys.excepthook and threads In-Reply-To: <4608ee59$0$17589$426a34cc@news.free.fr> References: <4608ee59$0$17589$426a34cc@news.free.fr> Message-ID: <20070412101016.1DA8A1E4014@bag.python.org> ian schrieb: > 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 I think sys.excepthook is a thread local variable. This means the variable has to be set by the thread for which it should be active. You did set sys.excepthook in your main thread. This setting is not propagated to your newly created thread. This is my observation... Peer From gandalf at designaproduct.biz Thu Apr 5 07:15:54 2007 From: gandalf at designaproduct.biz (Laszlo Nagy) Date: Thu, 05 Apr 2007 13:15:54 +0200 Subject: calling super() In-Reply-To: <00f301c776f7$6b8a1680$fefea8c0@haengma> References: <1175714555.413502.77390@o5g2000hsb.googlegroups.com> <461405D9.8040203@designaproduct.biz> <00f301c776f7$6b8a1680$fefea8c0@haengma> Message-ID: <4614DA6A.3050305@designaproduct.biz> John Clark wrote: > Please be aware that super() has it's own set of gotchas - it's not as clean > as you would hope. For more info: http://fuhm.org/super-harmful/ > > (I'm not the author, I was referred to this article while struggling with > wxPython and super()) > This was interesting! I'm using single inheritance in most of the cases. In very rare cases I use mixin classes, but they do not have constructors. In this situlation, I hope I'm right and I can safely use super(). I must agree that if a class uses "super" in its constructor, then all its descendants and bases must also use super. However, I'm using super in other cases. For example, for threading.Thread descendants, extensively, without any problems. Am I right in what I'm doing? Thanks, Laszlo From tjreedy at udel.edu Wed Apr 4 19:50:42 2007 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 4 Apr 2007 19:50:42 -0400 Subject: operator overloading References: <1175679412.741899.45990@l77g2000hsb.googlegroups.com><1175711246.488717.262560@e65g2000hsc.googlegroups.com> <1175726966.127531.273500@b75g2000hsg.googlegroups.com> Message-ID: wrote in message news:1175726966.127531.273500 at b75g2000hsg.googlegroups.com... | FWIW: | Python 2.5 (r25:51908, Jan 21 2007, 03:10:25) | [GCC 3.4.6 20060404 (Red Hat 3.4.6-3)] on HOSTNAME_REDACTED | Type "help", "copyright", "credits" or "license" for more information. | >>> class MyInt(int): | ... __pow__ = int.__add__ | ... | >>> i=MyInt(42) | >>> i**3 | 74088 Thanks. Bug report submitted http://sourceforge.net/tracker/index.php?func=detail&aid=1694663&group_id=5470&atid=105470 or http://python.org/sf/1694663 Terry Jan Reedy From robert.kern at gmail.com Sat Apr 21 23:09:02 2007 From: robert.kern at gmail.com (Robert Kern) Date: Sat, 21 Apr 2007 22:09:02 -0500 Subject: No speedup on multi-processor machine? In-Reply-To: References: <1177189332.916296.205280@d57g2000hsg.googlegroups.com> <1177197885.077863.314470@n59g2000hsh.googlegroups.com> Message-ID: John Nagle wrote: > There's a numerics library > for Python called NumPy, but it doesn't have a convolution function, > although it has an FFT, which may be useful. In [1]: from numpy import * In [2]: convolve? Type: function Base Class: Namespace: Interactive File: /Library/Frameworks/Python.framework/Versions/2.5/lib/python2.5/site-packages/numpy-1.0.3.dev3714-py2.5-macosx-10.3-fat.egg/numpy/core/numeric.py Definition: convolve(a, v, mode='full') Docstring: Returns the discrete, linear convolution of 1-D sequences a and v; mode can be 'valid', 'same', or 'full' to specify size of the resulting sequence. -- 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 jstroud at mbi.ucla.edu Thu Apr 5 08:06:05 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Thu, 05 Apr 2007 12:06:05 GMT Subject: Welch essential for learning Tkinter well? In-Reply-To: References: Message-ID: Dick Moores wrote: > In a couple of places recently I've seen Brent Welch's _Practical > Programming in Tcl & Tk_ () recommended for > learning Tkinter well. > > So a couple of questions: > > 1) Is it really good for learning Tkinter, even though it doesn't > mention Tkinter at all (in the 4th edition at least)? > > 2) If it is good for learning Tkinter, can I get by with a cheaper, used > copy of the 3rd edition? > > Thanks, > > Dick Moores > Probably better is to get Grayson (google "Grayson Tkinter"). It covers Tkinter <--> Tcl/Tk mapping to sufficient extent for Tkinter proficiency. I have found the online Tcl/Tk documentation to fill in the gaps. Tkinter seems to me to have been created largely automatically and so has much of the documentation that maps it to Tcl/Tk. This begs the question, is anyone truly an expert in Tkinter? James From gagsl-py2 at yahoo.com.ar Fri Apr 6 22:35:49 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sat, 07 Apr 2007 04:35:49 +0200 Subject: Understanding Python's interpreter In-Reply-To: <20070407032024.bb27f5ee.rafaelc@dcc.ufmg.br> References: <20070407032024.bb27f5ee.rafaelc@dcc.ufmg.br> Message-ID: Rafael Almeida wrote: > I'm studying compilers now on my university and I can't quite > understand one thing about the python interpreter. Why is its input a > binary file (pyc)? The LOAD_CONST opcode is 100 (dec) and STORE_FAST's > is 125 (dec). The translation of the following code: > > foo.py: > x = 10 > > Could be this: > > foo.pyc: > 100 10 > 125 0 > > That way you wouldn't need code such as > static void > w_long(long x, WFILE *p) > { > w_byte((char)( x & 0xff), p); > w_byte((char)((x>> 8) & 0xff), p); > w_byte((char)((x>>16) & 0xff), p); > w_byte((char)((x>>24) & 0xff), p); > } > since you could read it with strtol and write back using a simple > printf. So you wouldn't need a buch of casts by simple using ascii > input and output. A "simple" printf or strtol involves hundreds of instructions. And people want Python to execute fast... > What's the reason for having it in a binary form instead of writting > it in ascii? (yeah, I know ascii would be binary also, but I think you > get my point.) Speed? Eficiency? File size? Ease of use? A .pyc *could* be written in ASCII, but what do you gain? Replacing a few trivial functions in the Python core with a printf/scanf equivalent? At the same time you lose a lot of speed, so I don't see the point. > So I was writting this interpreter for some assembly language defined > in class and I did something like python does, so I had a binary file > to interpret. After a while I thought it was far harder to program. Why harder? Once you read the file, they're just numbers. Anyway, being harder to program the *interpreter* is not a problem, if you gain something like speed or eficiency for the interpreted language. > And when I tried to code an assembler my problems got greater, as I > wanted to code it in python (the interpreter was in C++) and I had a > hard time trying to figure out how I would print something that's not a > ascii or unicode string. As for the benefits, I couldn't figure out any. Sorry, I could not understand what you said here. -- Gabriel Genellina From solstice.dhiver at laposte.net Sun Apr 29 16:19:26 2007 From: solstice.dhiver at laposte.net (solstice.dhiver) Date: Sun, 29 Apr 2007 22:19:26 +0200 Subject: opening a new tab in opera does not work Message-ID: hi. i am using python 2.5.1 when i run import webbrowser webbrowser.get('opera').open_new_tab("http://www.osnews.com") i got a True after the last command but nothing happen at all in opera ! any one got that too ? i use opera 9.20 if i run in a command-line this opera -remote 'openURL(http://osnews.com,new-page)' it works that's off-topic but when i run webbrowser.get('konqueror').open_new_tab("http://www.osnews.com") it open a new tab in opera (yes !) because i have defined my default webbrowser in kde to be opera(precisely opera -newpage) From len-l at telus.net Wed Apr 4 23:10:38 2007 From: len-l at telus.net (Lenard Lindstrom) Date: Thu, 05 Apr 2007 03:10:38 GMT Subject: Calling Fortran from Python In-Reply-To: <1175729338.287712.305870@e65g2000hsc.googlegroups.com> References: <1175640339.648190.207530@y66g2000hsf.googlegroups.com> <1175685841.847487.173440@w1g2000hsg.googlegroups.com> <1175718204.410453.29510@q75g2000hsh.googlegroups.com> <1175726427.114890.7990@y80g2000hsf.googlegroups.com> <1175729338.287712.305870@e65g2000hsc.googlegroups.com> Message-ID: Mangabasi wrote: > On Apr 4, 5:48 pm, Robert Kern wrote: >> Mangabasi wrote: >>> Would Python 2.5 work with Visual Studio 6.6? >> No. >> >> -- >> 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 > > I will try the GCC then. It is a shame that I could not get calldll > to work. It was very simple to use. I think I am making a mistake > with the argument types but not sure. > > Thanks for your help, it is greatly appreciated. > Did you try ctypes? >>> from ctypes import * >>> sample=cdll.sample.sample_ >>> sample.restype=None >>> sample.argtypes=[POINTER(c_int), POINTER(c_int), POINTER(c_double), POINTER(c_double)] >>> e1 = c_int(0) >>> e2 = c_int(0) >>> ain = (c_double*3)(2.0, 3.0, 4.0) >>> aout = (c_double*4)() >>> sample(e1, e2, ain, aout) >>> aout[:] [6.0, 9.0, 8.0, 12.0] >>> e1.value 0 >>> e2.value 0 I compile the SAMPLE example with mingw g77 3.4.5: g77 -shared -o sample.dll sample.for I had to take out the "INTENT(OUT)"s because g77 didn't like them. And "SAMPLE" became "sample_" in the dll. Also note that argument passing to Fortran subroutines is strictly pass-by-reference. Thus the ain pointer. Lenard Lindstrom From apardon at forel.vub.ac.be Fri Apr 13 10:43:04 2007 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 13 Apr 2007 14:43:04 GMT Subject: tuples, index method, Python's design References: <1175953520.316208.241490@o5g2000hsb.googlegroups.com> <7xzm5igbrb.fsf@ruckus.brouhaha.com> <1176200361.260546.280510@n76g2000hsh.googlegroups.com> <740c3aec0704100824m132c45fbi5c4c3ec0c0fa3a67@mail.gmail.com> Message-ID: On 2007-04-13, Steve Holden wrote: > Antoon Pardon wrote: >> On 2007-04-12, Carsten Haese wrote: >>> On Thu, 2007-04-12 at 14:10 +0000, Antoon Pardon wrote: >>>> People are always defending duck-typing in this news group and now python >>>> has chosen to choose the option that makes duck-typing more difficult. >>> Au contraire! The "inconsistent" behavior of "in" is precisely what >>> duck-typing is all about: Making the operator behave in a way that makes >>> sense in its context. >> >> No it isn't. Ducktyping is about similar objects using a similar >> interface to invoke similar behaviour and getting similar result. >> >> So that if you write a function you don't concern yourself with >> the type of the arguments but depend on the similar behaviour. >> > Please note that "similar" does not mean "exact". That is because I don't want to get down in an argument about whether tp[:3] and ls[:3] is similar behaviour or exact the same behaviour when tp is a tuple and ls is a list. > The behavior of str.__contains__ and list.__contains__ is similar. That would depend on how much you find things may differ and still call them similar. IMO they are not similar enough since "12" in "123" doesn't behave like [1,2] in [1,2,3] > Duck-typing allows natural access to polymorphism. You appear to be > making semantic distinctions merely for the sake of continuing this > rather fatuous thread. I gave an argument that showed that the specific way the in functionality was extended in strings makes duck-typing (and by extention natural access to polymorphism) more difficult. although it may do so in a way that is not significant to you and the other developers. Now if you don't agree with the argument presented that is fine with me. If you think the problem is not big enough to bother with, that is fine with me too. But the argument doesn't disappear simply because you think ill of my intentions. And consider that each small inconsistency in itself may be not important enough to remove. But if you have enough of them remembering all these special cases can become tedious. >> Suppose someone writes a function that acts on a sequence. >> The algorithm used depending on the following invariant. >> >> i = s.index(e) => s[i] = e >> >> Then this algorithm is no longer guaranteed to work with strings. >> > Because strings have different properties than other sequences. I can't > help pointing out that your invariant is invalid for tuples also, > because tuples don't have a .index() method. Strings have some properties that are different and some properties that are similar with other sequences. My argument is that if you want to facilitate duck typing and natural access to polymorphism in peoples functions that work with sequences in general you'd better take care that the sequence api of strings resembles the sequence api of other sequences as good as possible. You on the other hand seem to argue that since strings have properties where they differ from other sequences it no longer is so important that the sequence api of strings resembles those of other sequences. -- Antoon Pardon From gandalf at designaproduct.biz Wed Apr 4 16:08:57 2007 From: gandalf at designaproduct.biz (Laszlo Nagy) Date: Wed, 04 Apr 2007 22:08:57 +0200 Subject: calling super() In-Reply-To: References: <1175714555.413502.77390@o5g2000hsb.googlegroups.com> Message-ID: <461405D9.8040203@designaproduct.biz> Jarek Zgoda wrote: >> Hello, I have been trying to call the super constructor from my >> derived class but its not working as expected. See the code: >> >> class HTMLMain: >> def __init__(self): >> self.text = ""; >> print(self.text); >> def __del__(self): >> self.text = ""; >> print(self.text); >> >> class NewPage(HTMLMain): >> def __init__(self): >> print 'derive2 init' >> super(NewPage, self).__init__(); >> > > This should read: super(HTMLMain, self).__init__() > Definitely, this is not true. Well, it depends what the OP wanted to do here, but in 99.9% of the cases, you want to use class B(A): def method(self,*args): super(B,self).method(*args) Look at here: http://www.python.org/doc/2.3.5/lib/built-in-funcs.html#l2h-66 It tells that super(type,[self]) will """Return the superclass of type.""". So super(B) will return the superclass of B, that is A. The built-in function "super" is very useful when you have diamond-shaped inheritance and you only want each inherited method to be called only once, IN THE CORRECT ORDER. If you only have single inheritance class trees, then super(B,self).method(*args) is identical to A.method(self,*args). You only need to worry about method calling order when you use multiple inheritance. However, using super is much nicer than calling the method of the base class directly, and it is syntactically cleaner, since you will only have a single reference to the base class, in the class definition header. (E.g. you can change the base class by replacing one word in the source code...) Best, Laszlo From dwcoll01 at gmail.com Wed Apr 18 08:21:27 2007 From: dwcoll01 at gmail.com (lucidparadox) Date: 18 Apr 2007 05:21:27 -0700 Subject: X root Operator help Message-ID: <1176898887.530470.222830@p77g2000hsh.googlegroups.com> I'm currently new to Python and I haven't been able to find the operator/math function to find the square root or even the x root of a number. I'm rewriting a program that I wrote in BASIC that does the math of a quadratic equation (user puts in a, b, and c values) and tells the user whether it has 1 root, 2 roots, or no real roots and displays the roots if it has real roots. Thanks in advance, Dan From malaclypse2 at gmail.com Fri Apr 20 13:02:01 2007 From: malaclypse2 at gmail.com (Jerry Hill) Date: Fri, 20 Apr 2007 13:02:01 -0400 Subject: I need a string/list/generator/comprehension incantation. In-Reply-To: References: Message-ID: <16651e80704201002k73cb1500q848fcbd7f2347ffa@mail.gmail.com> On 4/20/07, Steven W. Orr wrote: > I really tried. I give up. > > Now I want something that's going to give me a string whose value is the > set of all of the first letters of months. Order is not important. >>> ''.join(set([s[0] for s in calendar.month_abbr[1:]])) 'ADFJMONS' > And for extra credit, I need the string whose value is the set of all of > the letters of months minus the first letter. I'm sure there must be a cleaner way to do this, but it works: >>> ''.join(set(''.join([s[1:] for s in calendar.month_abbr[1:]]))) 'acbeglonprutvy' > E.g., 'ADFJMONS', 'acbeglonprutvy' -- Jerry From howe.steven at gmail.com Thu Apr 26 13:45:22 2007 From: howe.steven at gmail.com (Steven Howe) Date: Thu, 26 Apr 2007 10:45:22 -0700 Subject: My python annoyances so far In-Reply-To: References: <1177541453.471959.120830@c18g2000prb.googlegroups.com> <59bf34F2k27v5U1@mid.individual.net> <1177603623.774892.230390@t38g2000prd.googlegroups.com> Message-ID: <4630E532.9000005@gmail.com> flifus at gmail.com wrote: >> Well, why do some things in the library have to be functions, and >> other things have to be class methods? >> Perhaps because some things are more naturally function like? For 'instance' (pardon the pun), functions shouldn't retain data. They perform an operation, return data and quit. While retaining data is a feature of an class/instance. If I'm looking up the time of day in L.A., why do I need the whole clock database of times including New York and London? Another example are with respect to 'int' and 'float' operations. Why should int(x) be a class? Did you want to save and operate on the value of x again? No, you want the integer portion of x. Ditto float(x); somebody input '5' but you want it clear it 5.0. You typecast it your way. But the float operation doesn't need to retain the last input, nor even exist after it's last use. So, without have any current values referenced inside 'float', garbage collection can recover the memory space of 'float'. And before someone get's all technical, I know everything in Python is an 'object' even None, which implies class, or is it the other way around? sph From iansan at gmail.com Fri Apr 6 19:01:22 2007 From: iansan at gmail.com (IamIan) Date: 6 Apr 2007 16:01:22 -0700 Subject: 08 and 09 in sequence create "invalid token" error?! Message-ID: <1175900482.804005.256900@l77g2000hsb.googlegroups.com> Hello all, I am confused as to why including 08 or 09 in a sequence (list or tuple) causes this error. All other numbers with a leading zero work. [01,02,03,04,05,06,07] is fine [01,02,03,04,05,06,07,10] is fine [01,02,03,04,05,06,08] produces "SyntaxError: invalid token", as does: [01,02,03,04,05,06,09] I have tried this both in a script and in the interactive interpreter. Using Python 2.3.4 Thanks! From kyosohma at gmail.com Tue Apr 10 14:35:35 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: 10 Apr 2007 11:35:35 -0700 Subject: writing my own extension In-Reply-To: <1176227546.273023.235220@p77g2000hsh.googlegroups.com> References: <1176227546.273023.235220@p77g2000hsh.googlegroups.com> Message-ID: <1176230135.057026.118730@b75g2000hsg.googlegroups.com> On Apr 10, 12:52 pm, "spohle" wrote: > hi, > > i use a lot the enumerate in my scripts and got really interested in > possibly writing my own enumerate as an extension, for which i would > want to extend it to be able to pass a start and step attribute. > > can anyone point me on my way with good examples for that and how to > write extensions ? > > thank you in advance The range() builtin has this functionality. Also check out http://docs.python.org/lib/itertools-functions.html As for writing extensions, check out the following links: http://docs.python.org/inst/tweak-flags.html http://docs.python.org/dist/describing-extensions.html http://www.geocities.com/foetsch/python/extending_python.htm http://cxx.sourceforge.net/ http://www.vrplumber.com/programming/mstoolkit/ Interesting notes on iterators with (or without) a "step()": http://mail.python.org/pipermail/python-bugs-list/2004-February/022007.html http://www.thescripts.com/forum/thread556059.html http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/498272 Mike From maxm at mxm.dk Sat Apr 28 05:01:01 2007 From: maxm at mxm.dk (Max M) Date: Sat, 28 Apr 2007 11:01:01 +0200 Subject: Cgi File Upload without Form In-Reply-To: <1177708242.553577.226530@n15g2000prd.googlegroups.com> References: <1177708242.553577.226530@n15g2000prd.googlegroups.com> Message-ID: <46330d52$0$52147$edfadb0f@dread11.news.tele.dk> Karsten.G.Weinert at googlemail.com skrev: > Hello, > > what is the simplest way to upload a file (or a long string) to a > server using cgi/python? > > Since I want to upload the data programmatically, a form based > solution is not good. I am not experienced with SOAP/WSDL and I > believe that would be more difficult than necessary. The client > program I have to use does not support FTP. Try out urllib2 -- hilsen/regards Max M, Denmark http://www.mxm.dk/ IT's Mad Science From collinstocks at gmail.com Thu Apr 5 14:20:00 2007 From: collinstocks at gmail.com (Collin Stocks) Date: Thu, 5 Apr 2007 14:20:00 -0400 Subject: Looping issues In-Reply-To: <1175796069.501575.157410@w1g2000hsg.googlegroups.com> References: <1175796069.501575.157410@w1g2000hsg.googlegroups.com> Message-ID: <4c0048df0704051120w4b487e7em5289d251bd21cdd1@mail.gmail.com> I don't know what is wrong with your code yet, but first you should clean it up. Either replace those backslashes with forward slashes, or put r before the first quote in the path string. This prevents special characters from being evaluated as such. Second, you should debug a little. Feel free to put print statements in! correct_settings = open(r"C:\Python25\Scripts\Output\correct_settings.txt","r") current_settings = open(r"C:\Python25\Scripts\Output\output.txt","r") for line in correct_settings: print "line=", line for val in current_settings: print "val=", val if val == line: print line, "found." ## please don't concatenate strings in the print statement! separate them with commas! break ## You have already found that the same line is in both files: you don't need to keep searching correct_settings.close() current_settings.close() On 5 Apr 2007 11:01:09 -0700, brochu121 at gmail.com wrote: > > What I am trying to do is compare two files to each other. > > If the 2nd file contains the same line the first file contains, I want > to print it. I wrote up the following code: > > > > correct_settings = open("C:\Python25\Scripts\Output > \correct_settings.txt","r") > current_settings = open("C:\Python25\Scripts\Output\output.txt","r") > > for line in correct_settings: > for val in current_settings: > if val == line: > print line + " found." > > > correct_settings.close() > current_settings.close() > > > For some reason this only looks at the first line of the > correct_settings.txt file. Any ideas as to how i can loop through each > line of the correct_settings file instead of just looking at the first? > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From fd0man at gmail.com Sun Apr 1 04:21:25 2007 From: fd0man at gmail.com (Michael B. Trausch) Date: Sun, 01 Apr 2007 04:21:25 -0400 Subject: Character set woes with binary data Message-ID: <1175415685.21349.79.camel@pepper.trausch.us> I am attempting to piece together a Python client for Fotobilder, the picture management server on Livejournal. The protocol calls for binary data to be transmitted, and I cannot seem to be able to do it, because I get this error: >>> sb.UploadSinglePicture('/home/mbt/IMG_2618.JPG') Traceback (most recent call last): File "", line 1, in File "scrapbook.py", line 181, in UploadSinglePicture {Request['UploadPic.Meta.Filename']: pic_mem}) File "scrapbook.py", line 237, in ComposeMIME return(self.EncodeMIME(fields, files)) File "scrapbook.py", line 226, in EncodeMIME body = eol.join(L) UnicodeDecodeError: 'ascii' codec can't decode byte 0xff in position 0: ordinal not in range(128) >>> When putting the MIME segments (listed line-by-line in a Python list) together to transmit them. The files are typically JPG or some other binary format, and as best as I understand the protocol, the binary data needs to be transmitted directly (this is evidenced by looking at the tcp-stream of an existing client for uploading files). It seems that Python thinks it knows better than I do, though. I want to send this binary data straightaway to the server. :-) This is a hex dump of what one file looks like being uploaded to the server (partial; the file is 3.8 MB): 000001CB ff d8 ff e1 3b fc 45 78 69 66 00 00 49 49 2a 00 ....;.Ex if..II*. 000001DB 08 00 00 00 09 00 0f 01 02 00 10 00 00 00 7a 00 ........ ......z. 000001EB 00 00 10 01 02 00 10 00 00 00 aa 00 00 00 12 01 ........ ........ 000001FB 03 00 01 00 00 00 01 00 00 00 1a 01 05 00 01 00 ........ ........ 0000020B 00 00 da 00 00 00 1b 01 05 00 01 00 00 00 e2 00 ........ ........ 0000021B 00 00 28 01 03 00 01 00 00 00 02 00 00 00 31 01 ..(..... ......1. 0000022B 02 00 1e 00 00 00 ea 00 00 00 13 02 03 00 01 00 ........ ........ 0000023B 00 00 02 00 00 00 69 87 04 00 01 00 00 00 54 01 ......i. ......T. 0000024B 00 00 ac 12 00 00 48 65 77 6c 65 74 74 2d 50 61 ......He wlett-Pa 0000025B 63 6b 61 72 64 00 00 00 00 00 00 00 00 00 00 00 ckard... ........ 0000026B 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ........ ........ 0000027B 00 00 00 00 00 00 50 68 6f 74 6f 73 6d 61 72 74 ......Ph otosmart 0000028B 20 4d 35 32 35 00 00 00 00 00 00 00 00 00 00 00 M525... ........ 0000029B 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ........ ........ 000002AB 00 00 00 00 00 00 e6 00 00 00 01 00 00 00 e6 00 ........ ........ 000002BB 00 00 01 00 00 00 56 65 72 73 69 6f 6e 20 31 2e ......Ve rsion 1. 000002CB 34 31 30 30 2c 53 4e 3a 43 4e 36 34 31 44 33 31 4100,SN: CN641D31 000002DB 4a 35 53 00 00 00 00 00 00 00 00 00 00 00 00 00 J5S..... ........ 000002EB 00 00 00 00 00 00 ff ff ff ff ff ff ff ff ff ff ........ ........ 000002FB ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ........ ........ 0000030B ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ........ ........ 0000031B ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ........ ........ 0000032B 27 00 9a 82 05 00 01 00 00 00 96 08 00 00 9d 82 '....... ........ Is there any way to tell Python to ignore the situation and treat the entire thing as simply a stream of bytes? I cannot seem to find one, though I have found a great many posts on this mailing list regarding issues in the past. It doesn't look like translating the file to base64 is an option for me. ? 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 paul at boddie.org.uk Wed Apr 11 09:46:14 2007 From: paul at boddie.org.uk (Paul Boddie) Date: 11 Apr 2007 06:46:14 -0700 Subject: Connection problems with irclib In-Reply-To: References: Message-ID: <1176299174.112447.57440@e65g2000hsc.googlegroups.com> On 11 Apr, 15:31, "Dropkick Punt" wrote: > Hi. I've written a bot in python, using the irclib by Joel Rosdahl. > > Works fine from my linux box at home, but when I upload it to my shell at > veritynet.net, can't seem to get it to connect to an irc server. It may well be the case that your hosting provider has blocked various IRC ports and/or traffic. > It doesn't report any errors. > > Anyone have any idea how I might go about at least diagnosing the problem? > Any suggestions might help. Check your provider's usage policy and documentation. Paul From mail at microcorp.co.za Wed Apr 11 02:57:43 2007 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Wed, 11 Apr 2007 08:57:43 +0200 Subject: tuples, index method, Python's design References: <1175867771.114540.61810@n76g2000hsh.googlegroups.com><1175884427.779950.267220@y80g2000hsf.googlegroups.com><1175953520.316208.241490@o5g2000hsb.googlegroups.com><7xzm5igbrb.fsf@ruckus.brouhaha.com><1176200361.260546.280510@n76g2000hsh.googlegroups.com> <1176214831.3430.49.camel@dot.uniqsys.com> Message-ID: <01af01c77c09$b04043a0$03000080@hendrik> "Carsten Haese" wrote: > I'm just a user with no influence on the development of Python itself, > but in my humble opinion, the non-existence of tuple.index is more > pythonic than its existence would be. I really cannot follow the logic behind this statement. I can write: L = [a,b,c,d,e,f] T= (a,b,c,d,e,f) The difference between the two things is that I can add to and change L, but not T. Now it seems to me that whatever argument is used to justify the existence of: n = L.index(d) can be used to justify the existence of: n = T.index(d) and vice versa. Cut down to these basics, it seems to me that the arguments against the latter construct are simply knee jerk reactions to preserve the status quo. If an index method for tuples is such a very bad thing, then the same arguments can be used to justify the removal of the list index method from the language. I happen to agree with Antoon - there is a LOT of merit in consistency, as it makes things easy to learn and remember. And I would heretically go even further, and argue that it should be possible to write stuff like: T = T.append(x) And get back a new tuple bound to the old name... - Hendrik From theller at ctypes.org Wed Apr 18 14:24:57 2007 From: theller at ctypes.org (Thomas Heller) Date: Wed, 18 Apr 2007 20:24:57 +0200 Subject: subprocess "handle is invalid" error In-Reply-To: <132cdrpqsmnvpa7@corp.supernews.com> References: <132cdrpqsmnvpa7@corp.supernews.com> Message-ID: <46266279.5050105@ctypes.org> Grant Edwards schrieb: > I'm trying to use the py-gnuplot module on windows, and have > been unable to get it to work reliably under Win2K and WinXP. > > By default, it uses popen(gnuplotcmd,'w'), but in some > situations that consistently gets an "invalid operand" IOError > when write() is called on the pipe. > > So I switched to subprocess. It works fine when executed > "normally" (e.g. "python progname.py"), but when bundled by > py2exe, it always does this: > > Traceback (most recent call last): > File "surfedit.py", line 28, in ? > File "Gnuplot\_Gnuplot.pyc", line 178, in __init__ > File "Gnuplot\gp_win32.pyc", line 117, in __init__ > File "subprocess.pyc", line 533, in __init__ > File "subprocess.pyc", line 607, in _get_handles > File "subprocess.pyc", line 634, in _make_inheritable > WindowsError: [Errno 6] The handle is invalid > > How does one troubleshoot errors that happen three layers deep > in the subprocess module? > I think this is a subprocess bug. It is often attributed to py2exe because usually developers do never run the script in pythonW.exe instead of python.exe, and later build a *windows* program with py2exe (the *windows* program has no console, and that triggers the bug). Consider ths little script: """ import os, sys, subprocess sys.stderr = open("errors.txt", "w") if os.path.exists("output.txt"): os.remove("output.txt") proc = subprocess.Popen("dir", shell=True, stdout=subprocess.PIPE, ## stderr=subprocess.PIPE, ## stdin=subprocess.PIPE, ) ##proc.stderr.close() ##proc.stdin.close() data = proc.stdout.read() open("output.txt", "w").write(data) """ It calls 'dir' in the current directory, and writes the output to the file 'output.txt'. Any errors are written to 'errors.txt'. When you run this script with python.exe, everything works. If the script is run with pythonW.exe, nothing works and 'errors.txt' contains this: c:\svn\theller>type errors.txt Traceback (most recent call last): File "test_subproc.py", line 9, in stdout=subprocess.PIPE, File "c:\python25\lib\subprocess.py", line 586, in __init__ errread, errwrite) = self._get_handles(stdin, stdout, stderr) File "c:\python25\lib\subprocess.py", line 699, in _get_handles p2cread = self._make_inheritable(p2cread) File "c:\python25\lib\subprocess.py", line 744, in _make_inheritable DUPLICATE_SAME_ACCESS) WindowsError: [Error 6] Das Handle ist ung?ltig c:\svn\theller> The error message, translated to english, is 'the handle is invalid'. The script can be made to work correctly even with pythonW.exe (and also as py2exe'd windows program, I just checked it out) when the 4 commented out lines are uncommented. subprocess cannot inherit the standard handles when the process has no console, you have to create pipes for all 3 channels, and close those that are not needed. I thought that this bug was fixed in Python2.5.1 (the release candidate), but it seems it wasn't. The bug is at http://sourceforge.net/tracker/index.php?func=detail&aid=1124861&group_id=5470&atid=105470 If all this is correct, I hope that someone adds a section to the py2exe wiki; and reopens the above bug report. Thomas From apardon at forel.vub.ac.be Wed Apr 25 06:10:46 2007 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 25 Apr 2007 10:10:46 GMT Subject: Would You Write Python Articles or Screencasts for Money? References: <462DCCE6.9060908@taupro.com> <1hx2dvj.10ek1v51noh1otN%aleax@mac.com> Message-ID: On 2007-04-24, Anton Vredegoor wrote: > Steve Holden wrote: >>> When cash is involved, it's important to avoid even the slightest >>> hint of a suggestion of a suspicion of a conflict of interest; >>> that, I guess, is why firms that run contests with cash prizes >>> always declare employees and their families "not eligible", and why >>> I think the PSF should do likewise in this case. >>> >> That's a good point, and also a valid reason for restricting the >> voting community to PSF members. Thanks, Alex. > > So in order to avoid a suspicion of a conflict of interest you want to > turn the whole thing into private property of the PSF? > > That is the most ridiculous suggestion I have ever I kind of understand why they would want to do this. If you have no limitations on who may vote, such a contest can easily turn into a contest of who can mobilize the biggest clan of supporters. Now maybe there are better ways to avoid this kind of unwanted effect but I wouldn't call Steve's suggestion ridiculous. -- Antoon Pardon From bbxx789_05ss at yahoo.com Thu Apr 5 17:31:03 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: 5 Apr 2007 14:31:03 -0700 Subject: elementary tuple question. (sorry) In-Reply-To: References: Message-ID: <1175808663.261249.175970@n76g2000hsh.googlegroups.com> On Apr 5, 3:08 pm, "Steven W. Orr" wrote: > I have a tuple that I got from struct.unpack. Now I want to pass the data > from the returned tuple to struct.pack > > >>> fmt > > 'l 10l 11i h 4h c 47c 0l'>>>struct.pack(fmt, tup) > > Traceback (most recent call last): > File "", line 1, in ? > struct.error: required argument is not an integer > > What's the idiom to pass the data in tup? > > TIA > import struct fmt = "l l" result = struct.pack(fmt, 12, 4) t = (12, 4) result = struct.pack(fmt, *t) --------- The * unpacks the tuple. From steve at holdenweb.com Thu Apr 19 12:49:10 2007 From: steve at holdenweb.com (Steve Holden) Date: Thu, 19 Apr 2007 12:49:10 -0400 Subject: Python COM iterator In-Reply-To: <46279B56.4020901@websafe.com> References: <46279B56.4020901@websafe.com> Message-ID: Larry Bates wrote: > Carsten Haese wrote: [iterative acess to COM objects] > I tested in VB and by golly it works! What is odd is that this looks > NOTHING like what we got from the docs earlier. No GetEnumerator > method, no MoveNext method. I'm glad it works, but I'm a little > puzzled as to why it works. > Presumably the magic of mark Hammond's wrapper classes providing adaptation between Python iteration and COM enumerable collection objects. win32all is *very* Pythonic. Jim Hugunin, the author of IronPython (and of J[P]ython before that) has commented that Microsoft users are frequently surprised by the small amount of code required in IronPython to manipulate .NET objects. 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 tsuraan at gmail.com Mon Apr 2 14:46:21 2007 From: tsuraan at gmail.com (tsuraan) Date: Mon, 2 Apr 2007 13:46:21 -0500 Subject: zip files as nested modules? In-Reply-To: <84fb38e30704010845t13f6785ag270df1254c1a87db@mail.gmail.com> References: <84fb38e30704010845t13f6785ag270df1254c1a87db@mail.gmail.com> Message-ID: <84fb38e30704021146w13292e82v89b1221d0cf80b4d@mail.gmail.com> > and b.py has some method (let's call it d) within it. I can, from python, > do: That should be c.py, of course. Is this message getting no replies because it's confusing, it's poorly worded, it's a dumb question, or is it just that nobody knows the answer? I'm stuck on this, so any suggestions at all would be very appreciated. -------------- next part -------------- An HTML attachment was scrubbed... URL: From ZhaoYingpu at gmail.com Tue Apr 17 22:11:07 2007 From: ZhaoYingpu at gmail.com (Yingpu Zhao) Date: 17 Apr 2007 19:11:07 -0700 Subject: How to Passs NULL as a IDispatch Pointer to method? In-Reply-To: <462529A4.40507@websafe.com> References: <1176783870.081696.278100@l77g2000hsb.googlegroups.com> <462529A4.40507@websafe.com> Message-ID: <1176862267.482764.73530@b58g2000hsg.googlegroups.com> Thanks to Larry. I want to pass the IDispatch pointer of other COM object to AddShapeInfo or pass null to tell x do nothing. for example. Rect= Dispatch("Rect.Document") ShapeSet = Dispatch("xxx.Document") ShapeSet.AddShapeInfo("Rect", 0, Shape) or ShapeSet.AddShapeInfo("EmptyShape", 0, None) From carsten at uniqsys.com Tue Apr 10 09:16:00 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Tue, 10 Apr 2007 09:16:00 -0400 Subject: tuples, index method, Python's design In-Reply-To: References: <1175867771.114540.61810@n76g2000hsh.googlegroups.com> <1175884427.779950.267220@y80g2000hsf.googlegroups.com> Message-ID: <1176210960.3430.20.camel@dot.uniqsys.com> On Tue, 2007-04-10 at 12:29 +0000, Antoon Pardon wrote: > On 2007-04-10, Carsten Haese wrote: > > On 10 Apr 2007 07:31:13 GMT, Antoon Pardon wrote > >> On 2007-04-06, Carsten Haese wrote: > >> > If you have a use case for tuple.index, please show it to me, and I'll > >> > show you what you should be using instead of a tuple. > >> > >> No wonder no convincing use cases for tuples have shown up. You just > >> defined use cases of tuples as unconvincing. > > > > It's not a definition, it's an observation. I'm simply saying that all use > > cases I've seen for tuple.index could be written in a clearer fashion by using > > something else. Please prove me wrong by supplying a use case of tuple.index > > that can not be improved by rewriting. > > No it is a defintion because it states this can be done for every > possible case, even cases you have no idea about. That would be a theorem or conjecture, not a definition. You can call it definition or banana or screwdriver if you like, but that's not going to disprove it. > > Note that I have proved elsewhere on this thread that any real use case for > > tuple.index will involve an operation to explicitly use an index different > > from the one obtained by the call to tuple.index(). I'd like to hear your > > opinion on this. > > And what relevance would such a proof have? It proves at that every conceivable use case for tuple.index, including the ones I am not thinking of, will never directly use the index obtained from calling tuple.index(). Such a use case will be poorly self-documented, and a clearer implementation can be found by avoiding tuple.index(). I'll illustrate this on the one concrete use case that was suggested on this thread: In a game where the sequence of players is given by the tuple p, find the opponents of the current player. One hypothetical solution is to find the index if the current player and then slice and reassemble the tuple: i = p.index(current_player) opponents = p[:i-1] + p[i+1:] An alternative is this: opponents = tuple(x for x in p if x is not current_player) You may disagree, but in my opinion, the alternative is better because it is a more natural translation of the concept that the opponents of the current player are all players that are not the current player. > Adding the index method to tuples is not adding a feature. It is > removing a limitation. The non-existence of tuple.index is only a limitation if there is a need for the method to exist. Please prove that this need exists. -Carsten From kay.schluehr at gmx.net Thu Apr 26 04:15:49 2007 From: kay.schluehr at gmx.net (Kay Schluehr) Date: 26 Apr 2007 01:15:49 -0700 Subject: Coding conventions for class names In-Reply-To: References: <1177492705.232244.312520@c18g2000prb.googlegroups.com> Message-ID: <1177575349.010881.174590@c18g2000prb.googlegroups.com> On 25 Apr., 12:32, Michael Hoffman wrote: > Kay Schluehr wrote: > > My question is: does anyone actually follow guidelines here > > Yes. > > > and if yes > > which ones and are they resonable ( e.g. stable with regard to > > refactoring etc. )? > > All of them that I know of. What does it mean to be "stable with regard > to refactoring etc."? > -- > Michael Hoffman What happens when an enthusiast re-implements a stdlib module e.g. decimal s.t. it becomes a builtin module? Will the stdlib module serve as a wrapper to conform the current API or will the builtin module conform to the current interface. BTW the distinction between builtins and non-builtins seems to be an artifact of the particular runtime implementation. Application level / interpreter level becomes pretty fluent with regard to PyPy for example. Not sure about these distinctions in Jython and IronPython. Note that I do like all these lower case builtin classes, so it is not about my personal taste, but making coding conventions depended on how something is right now implemented seems to miss the point. From larry.bates at websafe.com Fri Apr 20 13:28:00 2007 From: larry.bates at websafe.com (Larry Bates) Date: Fri, 20 Apr 2007 12:28:00 -0500 Subject: When to clear a dictionary... In-Reply-To: References: Message-ID: <6sCdnXnrw_aAZbXbnZ2dnUVZ_sOknZ2d@comcast.com> Bill Jackson wrote: > What is the benefit of clearing a dictionary, when you can just reassign > it as empty? If you have objects that point to the dictionary (something like a cache) then you want to clear the existing dictionary instead of just assigning it to empty. If nothing points to it, assigning it to empty is fast and you can let garbage collection do the rest. > Similarly, suppose I generate a new dictionary b, and need > to have it accessible from a. What is the best method, under which > circumstances? > >>>> import some_function > >>>> a = {1:2,3:4} >>>> b = {1:2:4:3} >>>> a.clear() >>>> a.update(b) > >>>> a = {1:2,3:4} >>>> b = {1:2,4:3} >>>> for key in b: > ... a[key] = b[key] > >>>> a = {1:2,3:4} >>>> b = {1:2,4:3} >>>> a = b > Syntax error in the first example but if you fix that the first two are equivalent (but I would suspect that the second would be faster for large dictionaries). The third example both a and b point to the same dictionary after the a=b which you can see from: >>> a is b True >>> id(a) 31760224 >>> id(b) 31760224 >>> -Larry From multani at free.fr Sun Apr 15 14:13:12 2007 From: multani at free.fr (Jonathan Ballet) Date: Sun, 15 Apr 2007 20:13:12 +0200 Subject: Standardizing XML References: <1176625793.392269.24060@n59g2000hsh.googlegroups.com> <462215bc$1@griseus.its.uu.se> <1176660139.990518.239470@l77g2000hsb.googlegroups.com> Message-ID: <20070415201312.7b3dd2d7@localhost.localdomain> Le 15 Apr 2007 11:02:20 -0700, "ZeeGeek" a ?crit : > Thanks for correcting me. I worded it inproperly. For example, in > the code returned by Live Space, they use
instead of
so > that Blogger will complain that this tag is not valid because it > doesn't have a closing tag. Another example is that the contents of a > lot of the tag attributes like "color" and "size" are not surrounded > by quotes. Maybe you can try BeautifulSoup module which aims to handle things like that : http://www.crummy.com/software/BeautifulSoup/ - Jonathan From cam.ac.uk at mh391.invalid Mon Apr 16 15:31:22 2007 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Mon, 16 Apr 2007 20:31:22 +0100 Subject: C++ extension problem In-Reply-To: <1176741526.541997.52100@e65g2000hsc.googlegroups.com> References: <1176741526.541997.52100@e65g2000hsc.googlegroups.com> Message-ID: pythoncurious at gmail.com wrote: > I'm having a bit of trouble when writing a python extension. I can't > seem to figure out what I did wrong. > I tried to make a minimal example, but it's still quite a bit of > code. > It would be very appreciated if anyone could tell me what I've done > wrong. I can't answer your question since I have no experience writing extension types. I know this is at least partially a learning exercise for you, but might I suggest that your time might be better spent learning Boost.Python instead? It is "a C++ library which enables seamless interoperability between C++ and the Python programming language." http://www.boost.org/libs/python/doc/ -- Michael Hoffman From sender at sender.send Thu Apr 12 07:36:51 2007 From: sender at sender.send (Passer By) Date: Thu, 12 Apr 2007 11:36:51 GMT Subject: NLTK, Random Sentence Generators? References: <87slb8d3uj.fsf@localhost.localdomain> <3CJSh.7608$u03.3757@newssvr21.news.prodigy.net> <87k5wkcuv6.fsf@localhost.localdomain> Message-ID: <87k5wh25b3.fsf@localhost.localdomain> James Stroud writes: > Passer By wrote: > > James Stroud writes: > > > >>Passer By wrote: > >> > >> > >>>Has any created or not of examples of random sentence generators > >>>using n-gram models (or other models might be interesting). I > >>>know of one example from a course at MIT, but besides that > >>>nothing. Any help would be great. > >>> > >> > >>Best is to just cull text from your spam folder as these are often > >>generated by similar means--but somehow I think you knew that. > >> > > Emotive on Usenet? Thats original. > > > Anonimity on usenet? That's suspiscious. Paranoid Plunk? From trevis.crane at gmail.com Tue Apr 24 11:36:39 2007 From: trevis.crane at gmail.com (T.Crane) Date: 24 Apr 2007 08:36:39 -0700 Subject: noob questions Message-ID: <1177428999.023481.98160@b40g2000prd.googlegroups.com> I'm new to python and I seem to get different behavior depending on... well who knows what. Here's my question concerning importation of packages/modules. I want to use scipy. So at the prompt (using iPython, installed with Enthought edition on Windows XP) I type: ln [1]: from scipy import * Now, I know integrate is a package this is in scipy. I want to use the ode class/module that's in integrate. So I type: ln [2]: from integrate import * And I'm told ImportError: No module named integrate In order to get access to the ode class, I end up having to type: ln [3]: from scipy.integrate import * Then it works. Will someone explain to me what I'm misunderstanding? I don't understand why after importing everything in scipy (which includes integrate), I was told there was no module named integrate. What gives? I there are sevarl functions (modules) that I want to use that are a few levels down from the root package, what's the most economical method of importing them? Any clarification would be appreciated. trevis From dillonco at comcast.net Thu Apr 19 23:43:47 2007 From: dillonco at comcast.net (DillonCo) Date: Thu, 19 Apr 2007 23:43:47 -0400 Subject: Better dict of dicts In-Reply-To: <1177038139.635788.10340@e65g2000hsc.googlegroups.com> References: <1177038139.635788.10340@e65g2000hsc.googlegroups.com> Message-ID: <200704192343.47100.dillonco@comcast.net> On Thursday 19 April 2007, Paddy wrote: > Martins earlier local_intern function would work for tuples as well as > strings. It certainly would. I had written that class, though, primarily to offer a performance improvement in the __eq__ and perhaps __hash__ methods. However, I ended up being rather surprised by just how much overhead there was in calling the Python methods vs. the builtin ones. So really mine only ends up being useful if the tuple consists of a couple (i.e. 2+) of objects with Python __eq__ methods. Oh well. As an interesting aside: >>> class A(object): ... def __eq__(self, o): ... return False ... >>> a=A() >>> a==a False >>> t=(a,) >>> t==t True Apparently the tuple's __eq__ assumes: "a is b" => "a==b" Bug? Or am I creating evil corner cases ;)? From ecir.hana at gmail.com Sun Apr 15 20:42:25 2007 From: ecir.hana at gmail.com (ecir.hana at gmail.com) Date: 15 Apr 2007 17:42:25 -0700 Subject: yield, curry, mix-in, new.function, global, closure, .... what will work? In-Reply-To: <7xy7ktmrzn.fsf@ruckus.brouhaha.com> References: <1176657848.944538.169780@p77g2000hsh.googlegroups.com> <7xy7ktmrzn.fsf@ruckus.brouhaha.com> Message-ID: <1176684145.537202.68090@p77g2000hsh.googlegroups.com> On Apr 15, 8:07 pm, Paul Rubin wrote: > That is total madness. Just use a normal object or dictionary with a lock. Please, can you elaborate further, I'm not sure if I understood. Should I lock global variables i, j during the execution of run()? In that case I have to apologize, I showed rather simplified version of the actual problem I have - in fact changer() and run() will be a bit more complex thus executing a bit longer and perhaps causing a dead- lock. From bbxx789_05ss at yahoo.com Sun Apr 22 08:54:53 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: 22 Apr 2007 05:54:53 -0700 Subject: serializable object references In-Reply-To: <1242622.P0zHLAfcMH@beaureve.gmx.net> References: <1242622.P0zHLAfcMH@beaureve.gmx.net> Message-ID: <1177246493.838787.180280@b75g2000hsg.googlegroups.com> Martin Drautzburg wrote: > Is it possible to convert an object into a string that identifies the > object in a way, so it can later be looked up by this string. > Technically this should be possible, because things like > > <__main__.Foo instance at 0xb7cfb6ac> > > say everything about an object. But how can I look up the real object, > when I only have this string? > > I know such a thing can be achieved with a dictionary that holds > reference-object pairs. Is there another way? How about: class Dog(object): def __init__(self, name): self.name = name d = Dog("Spot") print globals()["d"].name From steven.bethard at gmail.com Tue Apr 10 11:51:45 2007 From: steven.bethard at gmail.com (Steven Bethard) Date: Tue, 10 Apr 2007 09:51:45 -0600 Subject: Why is __getslice__ still implemented? In-Reply-To: References: Message-ID: Jean-Paul Calderone wrote: > On Tue, 10 Apr 2007 08:35:56 -0600, Steven Bethard > wrote: >> Yes, you do still need to implement __getslice__ if you're subclassing >> a class (like unicode or list) which provides it. The __getslice__ >> method can't be removed entirely for backwards compatibility reasons >> (though it is being removed in Python 3000). > > Why does this mean that the unicode type has to implement __getslice__? Because code could exist like:: >>> class C(list): ... def __getslice__(self, start, stop): ... return C(list.__getslice__(self, start, stop)) ... >>> type(C([1, 2, 3, 4])[:2]) For similar examples, see: http://www.google.com/codesearch?q=list.__getslice__ I couldn't find any real instances of unicode.__getslice__: http://www.google.com/codesearch?q=unicode.__getslice__ But I suspect python-dev wouldn't think it was worth it to remove just unicode.__getslice__ and not all the other ones... STeVe From see_signature at nospam.nowire.org Sun Apr 15 14:14:54 2007 From: see_signature at nospam.nowire.org (=?ISO-8859-1?Q?Thomas_Kr=FCger?=) Date: Sun, 15 Apr 2007 20:14:54 +0200 Subject: Authenticating clients and servers In-Reply-To: References: Message-ID: Chaz Ginger schrieb: > I am writing a distributed server system using Python. I need to support > authentication and was wondering what approaches are available under > Python and what are the best practices. Well, there are many ways of client authentication. To narrow it down it would be nice if your tell us something about the protocol you are planning to use. Many protocols support an additional SSL/TLS-Layers (e.g. HTTP -> HTTPS). There you can use SSL certificate authentication. It may berequired to set up a small CA, but done right it is pretty secure. Thomas -- sinature: http://nospam.nowire.org/signature_usenet.png From rasmussen.bryan at gmail.com Sun Apr 22 06:42:22 2007 From: rasmussen.bryan at gmail.com (bryan rasmussen) Date: Sun, 22 Apr 2007 12:42:22 +0200 Subject: service for file monitoring In-Reply-To: <462956EE.9000503@v.loewis.de> References: <1177099611.498274.323180@y5g2000hsa.googlegroups.com> <1177103856.200965.139840@b75g2000hsg.googlegroups.com> <462956EE.9000503@v.loewis.de> Message-ID: <3bb44c6e0704220342r5d5335f1q55e20c1138d917a9@mail.gmail.com> use WMI event monitoring objWMIService.ExecNotificationQuery http://msdn2.microsoft.com/en-us/library/aa393864.aspx , then pass the event and the file starting the event to your application via the command line, what I tend to do (so I keep one monitor running that starts applications at event occurrence) drawback but also a strength, the application cannot know for sure that the event has actually happened - this is a possible strength because then you can have other applications that redefine the occasion of the event on a file just by starting your application for handling that event and passing it a file asserted as having been the object receiving the event (probably too loosely coupled for lots of people or scenarios though, if this can be a security problem for your application have to protect against it etc. ) if you absolutely need monitoring and application tightly coupled then use Python and WMI to do it, using the same method. http://tgolden.sc.sabren.com/python/wmi.html Cheers, Bryan Rasmussen On 4/21/07, "Martin v. L?wis" wrote: > > well i tried reading that but that way i'll have to make the program > > monitor each and every directory. > > when a file is created or deleted or filename modified , a call must > > be made to the os kernel . > > isn't there any way i can utilize that with any api or package > > functions so that i can monitor the whole filesystem but at lesser > > expense of cpu n memory > > On Windows W2k+, you can use the USN journal: > > http://msdn2.microsoft.com/en-us/library/aa364586.aspx > > You may have to use ctypes or write an extension module to access that > journal. > > Regards, > Martin > -- > http://mail.python.org/mailman/listinfo/python-list > From andy.rockford at gmail.com Fri Apr 27 03:50:37 2007 From: andy.rockford at gmail.com (Andy) Date: 27 Apr 2007 00:50:37 -0700 Subject: List objects are un-hashable Message-ID: <1177660237.470851.170200@s33g2000prh.googlegroups.com> Hi, I'm trying to search and print any no# of Python keywords present in a text file (say - foo.txt), and getting the above error. Sad for not being able to decipher such a simple problem (I can come up with other ways - but want to fix this one FFS). Any help is appreciated. Thanks!! import keyword, re, sys, string inp = open("foo.txt", "r") words,lines = 0, 0 for line in inp: lines +=1 # a list of words tempwords = line.split(None) if keyword.iskeyword(tempwords): print tempwords inp.close() From time.swift at gmail.com Wed Apr 4 21:04:57 2007 From: time.swift at gmail.com (ts-dev) Date: 4 Apr 2007 18:04:57 -0700 Subject: Prevent Modification of Script? Message-ID: <1175735097.856840.177510@e65g2000hsc.googlegroups.com> Is it possible to prevent modification of a python file once its been deployed? File permissions of the OS could be used..but that doesn't seem very secure. The root of my question is verifying the integrity of the application and the scripts being run. Is this possible, if so, how? From bjourne at gmail.com Thu Apr 5 21:43:17 2007 From: bjourne at gmail.com (=?ISO-8859-1?Q?BJ=F6rn_Lindqvist?=) Date: Fri, 6 Apr 2007 01:43:17 +0000 Subject: Easy question: More items in a For loop? In-Reply-To: <1175820988.988878.18940@p77g2000hsh.googlegroups.com> References: <1175820988.988878.18940@p77g2000hsh.googlegroups.com> Message-ID: <740c3aec0704051843x6cdce073qeaf6429432f0192b@mail.gmail.com> > Here is some sample tuna: > ['[7:55pm] My teachings goes back to the last iceage.\r\n', > '[7:55pm] <%Zack> ahh now it does\r\n', '[7:55pm] <%Zack> ok\r\n', > '[7:55pm] Or it is down just for you.\r\n', '[7:55pm] <@FC3> > which one? that -12000 ice age or the one before\r\n', '[7:55pm] > the earliest..\r\n', '[7:56pm] so.. 12000 quite long..\r > \n', '[7:56pm] <@FC3> the one created by the meteor then\r\n', > '[7:57pm] did not know that.. this is just a new teory I am > folding.\r\n', '[7:57pm] * P0ke test test test\r\n'] You use the split method: for j in tuna: time, text = j.split(' ', 1) if text.startswith('<%'): print 'Will be yellow' elif text.startswith('<@'): print 'Will be pink' elif text.startswith('*'): print 'Will be dark pink' First each line in tuna is looped through. Then you split the line into two pieces so that it becomes easier to manage. Then you just check if the line begins with the searched after pattern. If it does, you color it appropriately. -- mvh Bj?rn From g.brandl at gmx.net Mon Apr 9 03:46:13 2007 From: g.brandl at gmx.net (Georg Brandl) Date: Mon, 09 Apr 2007 09:46:13 +0200 Subject: Unicode problem In-Reply-To: <4619B124.6040707@v.loewis.de> References: <1175975209.261304.183220@p77g2000hsh.googlegroups.com> <4619B124.6040707@v.loewis.de> Message-ID: Martin v. L?wis schrieb: >> Thanks! That's a nice little stumbling block for a newbie like me ;) Is >> there a way to make utf-8 the default encoding for every string, so that >> I do not have to encode each string explicitly? > > You can make sys.stdout encode each string with UTF-8, with > > sys.stdout = codecs.getwriter('utf-8')(sys.stdout) > > Make sure that you then that *all* strings that you print > are Unicode strings. BTW, any reason why an EncodedFile can't act like a Unicode writer/reader object if one of its encodings is explicitly set to None? IMO the docs don't make it clear that getwriter() is the correct API to use here. I've wanted to write "sys.stdout = codecs.EncodedFile(sys.stdout, 'utf-8')" more than once. Georg From kyosohma at gmail.com Mon Apr 16 12:18:48 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: 16 Apr 2007 09:18:48 -0700 Subject: Python and SSL In-Reply-To: <1176737058.203036.53170@n59g2000hsh.googlegroups.com> References: <1176737058.203036.53170@n59g2000hsh.googlegroups.com> Message-ID: <1176740328.792836.201280@n59g2000hsh.googlegroups.com> On Apr 16, 10:24 am, "billiejoex" wrote: > Hi, > I developed an ftp-server library and now I would like to add support > for SSL/TLS as described in RFC 2228:http://tools.ietf.org/html/rfc2228 > Currenlty I'm searching for documentation about this subject and I > would like to start to ask some questions: > > - I noticed that socket module provides an SSL class (socket.ssl) but > even if documentation reports that it does not do any certificate > verification a lot of stdlib modules (imaplib, poplib, smtplib, > httplib and urllib2) provides SSL extension classes wherein socket.ssl > is used. What does it mean? > > - On top of that why such extension classes [examples: 1, 2, 3] > accepts key-files and cert-files as optional argouments if no > certificate verification occurs? > [1] poplib.POP3_SSL( host[, port[, keyfile[, certfile]]]) > [2] imaplib.IMAP4_SSL( [host[, port[, keyfile[, certfile]]]]) > [3] smtplib.starttls( [keyfile[, certfile]]) > > - By searching through the web I found some daemons supporting SSL > such as this one:http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/442473 > By looking at the code I notice that pyopenssl package is used and > that a certificate file is required. Why do I need to use pyopenssl > and how do I generate the cert file? > > Could someone point me in the right direction? > > Thanks in advance. I don't know if this will help you or not, but we use the httplib module's "HTTPSConnection" method to connect with SSL. We use urlencode from the urllib module to encode the username and password we send to a server. Since I didn't write this particular bit of code, I don't completely understand it. But I hope it will give you some ideas. Mike From afaNOSPAM at neuf.fr Wed Apr 11 18:36:37 2007 From: afaNOSPAM at neuf.fr (Amaury Forgeot d'Arc) Date: Thu, 12 Apr 2007 00:36:37 +0200 Subject: help building debug .pyd files In-Reply-To: <1176329238.588406.144210@w1g2000hsg.googlegroups.com> References: <1176329238.588406.144210@w1g2000hsg.googlegroups.com> Message-ID: joshusdog at gmail.com a ?crit : > The installation of Python 2.5 comes with a bunch of built-in > extension modules (.pyd files) under the DLLs directory. I've > downloaded the Python source code and am trying to build the debug > versions of all of these files. However, some of the projects won't > build because they are looking for header files that don't exist > anywhere. Specifically, the non-building projects are: > > _bsddb > _sqlite3 > _ssl > _tkinter > bz2 > > Additionally, the project for the _hashlib module seems to be entirely > missing from the Python source. Any idea where I can find it? > > Is there a set of pre-built debug versions of all of these modules I > can download somewhere? It would save me a lot of time trying to > figure out where all these missing files are supposed to come from... You should read the file PCBuild/readme.txt. It explains how to build python from source, and has long explanations about the same list of modules you are asking for. And it works: I regularly use the debug build of python for my own projects. -- Amaury Forgeot d'Arc From c-cheung at northwestern.edu Tue Apr 17 13:41:36 2007 From: c-cheung at northwestern.edu (Chi Yin Cheung) Date: Tue, 17 Apr 2007 12:41:36 -0500 Subject: Binary file output using python Message-ID: <462506D0.6020605@northwestern.edu> Hi, Is there a way in python to output binary files? I need to python to write out a stream of 5 million floating point numbers, separated by some separator, but it seems that all python supports natively is string information output, which is extremely space inefficient. I'd tried using the pickle module, but it crashed whenever I tried using it due to the large amount of data involved. Thanks for your help! From DJStunks at gmail.com Mon Apr 2 20:35:27 2007 From: DJStunks at gmail.com (DJ Stunks) Date: 2 Apr 2007 17:35:27 -0700 Subject: Any "consumer review generators" available? In-Reply-To: <0sfp03d9epf50d1o9jj22ni1al4o69ut9k@4ax.com> References: <1175225665.929475.183360@n59g2000hsh.googlegroups.com> <0sfp03d9epf50d1o9jj22ni1al4o69ut9k@4ax.com> Message-ID: <1175560526.986876.297460@o5g2000hsb.googlegroups.com> On Mar 30, 1:46 am, nullified wrote: > On 29 Mar 2007 20:34:26 -0700, "Evil Otto" wrote: > > >On Mar 29, 2: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 really, really hope that you're looking to generate test data or > >filler text. > > >If you're not, then DIAF. > > Die In A Fire? Drop In A Fryer? Doug Is A Fucker? Drown In A Fart? You knew Doug too? I could tell he was a fucker right from the moment I met him. -jp From bearophileHUGS at lycos.com Wed Apr 4 16:46:53 2007 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 4 Apr 2007 13:46:53 -0700 Subject: How can I make sure my python exit In-Reply-To: <1175716891.317710.292710@l77g2000hsb.googlegroups.com> References: <1175716731.915570.236820@w1g2000hsg.googlegroups.com> <1175716891.317710.292710@l77g2000hsb.googlegroups.com> Message-ID: <1175719613.199242.288980@o5g2000hsb.googlegroups.com> > Typically when the last piece of code executes, the program ends. You > could import sys and explicitly exit by calling sys.exit(0). > Mike raise SystemExit works too. Bye, bearophile From spradml at gmail.com Wed Apr 11 13:28:07 2007 From: spradml at gmail.com (Pradnyesh Sawant) Date: Wed, 11 Apr 2007 22:58:07 +0530 Subject: doubt with importing module, given module name Message-ID: <80628d680704111028k790404cfy798629cc10072628@mail.gmail.com> > module_name = "module" > mod = __import__(module_name) > class_name = module_name.capitalize() > cls = getattr(mod, class_name) > inst = cls() > Worked like a magic charm :) Also helped me understand the concept of getattr :D Thanks a million! -- warm regards, Pradnyesh Sawant -- Be yourself......everyone else is taken. --Anon From fuzzyman at gmail.com Sun Apr 1 15:24:58 2007 From: fuzzyman at gmail.com (Fuzzyman) Date: 1 Apr 2007 12:24:58 -0700 Subject: Which will come first: Perl 6 or Python 3000? Message-ID: <1175455498.638021.189030@d57g2000hsg.googlegroups.com> http://home.inklingmarkets.com/market/show/4018 (Interesting site by the way - although a bit heavily weighted towards US politics for my tastes). Anyway, I know which way my money is going :-) Fuzzyman http://www.voidspace.org.uk/python/articles.shtml From aleax at mac.com Sat Apr 28 17:05:45 2007 From: aleax at mac.com (Alex Martelli) Date: Sat, 28 Apr 2007 14:05:45 -0700 Subject: Numbers and truth values References: Message-ID: <1hxa95b.13zrrmv1wucw71N%aleax@mac.com> John Nagle wrote: ... > I'd have to consider that a bug. > > Some very early FORTRAN compilers allowed you to redefine > integer constants: > > > CALL SET(25,99) > WRITE (6,100) 25 > 100 FORMAT(I6) > > SUBROUTINE SET(IVAR, INEWVAL) > IVAR = INEWVAL > > would print > > 99 > > It was generally agreed by 1970 or so that this was a bad idea, > and was taken out of the language. It was still perfectly legal in the Fortran 1977 standard for a compiler to cause this effect, because the Fortran source you quote has *undefined behavior* -- the compiler doesn't have to diagnose this error and can cause any effects as a consequence. The point of Fortran is to let the compiler generate the fastest code it can, NOT to "tenderly hold your hand" lest scary bugs disturb your blessed and dreamy innocence. If this has changed in the Fortran 1990 standard or later, then I can only say I'm happy I stopped using Fortran heavily before such standards became widespread in commonly available compilers -- by the late '90s, when I was still using _some_ Fortran, it was Fortran '77, as that was the version that was widely available and well optimized. Python is not particularly focused on coddling the programmer lest he or she (horrors!) make a mistake, either; rather, it embodies well 4 of the 5 principles that make up the "Spirit of C" according to the Preface to C's ISO Standard -- "trust the programmer", "don't stop the programmer from doing what needs to be done", "keep the language small and simple" (the 4th one, "offer only one way to perform an operation", is not germane here). Making the language more complicated (e.g., with more reserved words) because you _don't_ trust the programmer and badly wants to stop him/her from doing something is not well consistent with these principles. Maybe somebody assigning a value to True or False is a common error, but much of my livelihood over the last 10 years has been about mentoring/coaching programmers in Python, and that's one error I have *NEVER* observed, so I'd need a lot of empirical evidence to convince me it's worth adding two more reserved words to Python's reasonably short list (I feel much the same way about None, by the way). pychecker, pylint, and friends, are a much better way to detect and warn about all sort of anomalies of this kind. Alex From sjmachin at lexicon.net Sun Apr 29 20:45:35 2007 From: sjmachin at lexicon.net (John Machin) Date: Mon, 30 Apr 2007 10:45:35 +1000 Subject: Any Good tools to create CSV Files? In-Reply-To: References: <1177811756.255774.315260@q75g2000hsh.googlegroups.com> Message-ID: <46353C2F.8060401@lexicon.net> On 30/04/2007 6:29 AM, Aahz wrote: > In article , > Carsten Haese wrote: >> On Sat, 2007-04-28 at 18:55 -0700, johnny wrote: >>> Any Good tools to create CSV Files? ReportLab only creates pdf >>> files. I need something to create CSV files. >> You mean something like the csv module that is part of Python's standard >> library? >> >>>>> import csv > > In all fairness, the csv module is new in Python 2.3, and I'm sure I'm > not the only person still using Python 2.2 for production. In all fairness to those making ironic comments, the OP has given no indication that he is bound to an old version of Python. The Object-Craft csv extension module (ancestor of the Python csv module) has been available since October 2000. It still shows up in Google [it's the 3rd result if one searches for "python csv"] and has the source available for download -- there are even Windows binaries (.pyd) for Python 2.1 and 2.2. In all fairness to the OP, perhaps he has never heard of search engines, or perhaps he has no ARPA^H^H^H^HInternet access. From duncan.booth at invalid.invalid Tue Apr 24 06:55:45 2007 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 24 Apr 2007 10:55:45 GMT Subject: Getting python script to write to input box on another window References: <1177406151.797865.141440@r30g2000prh.googlegroups.com> Message-ID: sophie_newbie wrote: > I'm wondering if there is a way to get a python script to write text > to an input box in a window of another program that is running? For > example a text box in a web browser window? > Yes there is, but the solution depends on the operating system and the program so you'll have to be more specific. For Windows and IE you could use COM to connect to the running application and you can then manipulate the DOM: see http://groups.google.co.uk/group/comp.lang.python/browse_frm/thread/74e6e3d1321677fc/e2359e3ff6b905ca for an example. From apardon at forel.vub.ac.be Thu Apr 26 05:11:56 2007 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 26 Apr 2007 09:11:56 GMT Subject: Tutorial creates confusion about slices References: <1177496078.319400.324720@r30g2000prh.googlegroups.com> Message-ID: On 2007-04-25, Steve Holden wrote: > Antoon Pardon wrote: >> On 2007-04-25, Ant wrote: >>> On Apr 23, 1:38 pm, Antoon Pardon wrote: >>>> The following is part of the explanation on slices in the >>>> tutorial: >>>> >>>> The best way to remember how slices work is to think of the indices as >>> ... >>>> +---+---+---+---+---+ >>>> | H | e | l | p | A | >>>> +---+---+---+---+---+ >>>> 0 1 2 3 4 5 >>>> -5 -4 -3 -2 -1 >>> For a tutorial this is sound advice. A tutorial is designed to give >>> readers an easy intro to a topic, which is what this achieves. At this >>> stage the target audience has no idea that extended slices even exist, >>> let alone that you can use negative indices with them. >> >> OK. But eventually they will come into contact with negative indexes. >> If they still rely on the above representation for understanding slices >> that may cause confusions. It is possible that the time lost in clearing >> up these later confusions will be bigger than the time gained by using >> this simplification in the tutorial. >> >> So I'm not so sure it is sound advice in this case. >> >> If the consensus is that something like this should remain, I would >> suggest replacing: >> >> "The best way to remember how slices work is" >> >> with: >> >> "A way to remember how slices work, it is not entirly correct >> but may be usefull, is" >> >> Or something similar. >> >> >> Wording to that effect makes it more clear that it is a crutch >> that can be usefull now but that it should be discarded later. >> > Most people reading a tutorial are aware that they are being given the > knowledge they need to put the subject matter to immediate use, and that > there may well be refinements that are glossed over or covered in detail > later or elsewhere. I agree with that. However there is a difference between information that will help you on the way now that will be refined later and information that will help you on the way now and will be contradicted later. I also understand that the line between the two is rather fuzzy. In my opinion the text in the tutorial as it stands now, is more of the latter than of the former type and that is why I would prefer a change. -- Antoon Pardon From ecir.hana at gmail.com Mon Apr 16 21:51:26 2007 From: ecir.hana at gmail.com (ecir.hana at gmail.com) Date: 16 Apr 2007 18:51:26 -0700 Subject: yield, curry, mix-in, new.function, global, closure, .... what will work? In-Reply-To: <1176743127.450980.236610@o5g2000hsb.googlegroups.com> References: <1176657848.944538.169780@p77g2000hsh.googlegroups.com> <7xy7ktmrzn.fsf@ruckus.brouhaha.com> <1176684145.537202.68090@p77g2000hsh.googlegroups.com> <7xbqhp6sdu.fsf@ruckus.brouhaha.com> <1176730099.467774.212440@q75g2000hsh.googlegroups.com> <1176737762.629412.189270@y80g2000hsf.googlegroups.com> <1176743127.450980.236610@o5g2000hsb.googlegroups.com> Message-ID: <1176774686.328834.296410@e65g2000hsc.googlegroups.com> I'm reading the docs now and I stumbled upon something: section "15.3 threading -- Higher-level threading interface" mensions a class "local", in which "... Thread-local data are data whose values are thread specific. ..." Does it mean, I can create global variables whose changing is thread- safe? More specific: import threading def change_i(arg): global k k.i = arg def change_j(arg): global k k.j = arg def changer(): change_i('changed_i') change_j('changed_j') def run(i='', j=''): global k k = threading.local() k.i = i k.j = j changer() i = k.i j = k.j return i, j print run() == ('changed_i', 'changed_j') Is this ok? From silverburgh.meryl at gmail.com Mon Apr 30 14:24:51 2007 From: silverburgh.meryl at gmail.com (silverburgh.meryl at gmail.com) Date: 30 Apr 2007 11:24:51 -0700 Subject: How to pass in argument to timeit.Timer In-Reply-To: References: <1177786091.049008.278400@o5g2000hsb.googlegroups.com> Message-ID: <1177957491.046839.318270@o5g2000hsb.googlegroups.com> On Apr 28, 3:37 pm, "Gabriel Genellina" wrote: > En Sat, 28 Apr 2007 15:48:11 -0300, silverburgh.me... at gmail.com > escribi?: > > > I have a function in my python like this: > > def callFunc(line, no): > > # some code > > > And I want to do a performance test like this: > > for line in f: > > for i in range(int(count)): > > t1 = timeit.Timer("callFunc(line, i)","from __main__ > > import callFunc") > > r1 = t1.timeit(); > > print r1; > > > but when I run it, it can't recognize the parameter 'line' and 'i', > > can you please tell me how to fix it? i get this error: > > They go in the "setup" parameter, like this: > > t1 = timeit.Timer("callFunc(line, i)","from __main__ import callFunc; > line=%r; i=%d" % (line, i)) > Thanks I try it: def stressTest(): for line in f: for i in range(int(count)): print i; t1 = timeit.Timer("callFunc(line, i)","from __main__ import callFunc; line=%r; i=%d" % (line, i)) r1 = t1.timeit(); times.append(r1); print r1; But it keeps calling callFunc() and it never returns from my loop. The value of 'count' is 2. Thank you. > If it gets much longer, try this: > > setup = """ > from __main__ import callFunc > line = %r > i = %d""" % (line, i) > stmt = "callFunc(line, i)" > t1 = timeit.Timer(stmt, setup) > > -- > Gabriel Genellina > > PS: Please leave out the final ; - this is Python, not C nor ... > PS2: Perhaps the only place where I've used ; is with timeit. And even > then you can avoid them as in the last example. From nagle at animats.com Sun Apr 22 05:28:08 2007 From: nagle at animats.com (John Nagle) Date: Sun, 22 Apr 2007 09:28:08 GMT Subject: Python "robots.txt" parser broken since 2003 In-Reply-To: References: Message-ID: Terry Reedy wrote: > "John Nagle" wrote in message > news:FvtWh.11824$YL5.6282 at newssvr29.news.prodigy.net... > | This was reported in 2003, and a patch was uploaded in 2005, but the > patch > | never made it into Python 2.4 or 2.5. > > If the patch is still open, perhaps you could review it. > I tried it on Python 2.4 and it's in our production system now. But someone who regularly does check-ins should do this. John Nagle From a.schmolck at gmail.com Wed Apr 4 05:08:04 2007 From: a.schmolck at gmail.com (Alexander Schmolck) Date: 04 Apr 2007 10:08:04 +0100 Subject: zip list with different length References: <1175673207.231212.28310@n76g2000hsh.googlegroups.com> Message-ID: s99999999s2003 at yahoo.com writes: C> hi > suppose i have 2 lists, a, b then have different number of elements, > say len(a) = 5, len(b) = 3 > >>> a = range(5) > >>> b = range(3) > >>> zip(b,a) > [(0, 0), (1, 1), (2, 2)] > >>> zip(a,b) > [(0, 0), (1, 1), (2, 2)] > > I want the results to be > [(0, 0), (1, 1), (2, 2) , (3) , (4) ] > can it be done? map(lambda *t: filter(lambda x: x is not None,t),a,b) 'as From mzafrullah at usa.net Tue Apr 17 10:32:54 2007 From: mzafrullah at usa.net (Muhammad) Date: 17 Apr 2007 07:32:54 -0700 Subject: ??? POLICE AND CITY/UNIVERSITY OFFICIALS INCOMPETENCE LEADS TO 33 KILLED BY KOREAN-ALQAEDA TERRORIST ??? In-Reply-To: <1176818165.135834.214220@y80g2000hsf.googlegroups.com> References: <1176818165.135834.214220@y80g2000hsf.googlegroups.com> Message-ID: <1176820374.597357.315110@b75g2000hsg.googlegroups.com> On Apr 17, 7:56 am, therm... at india.com wrote: > We know that the city officials are corrupt. Instead of applying the > city codes and pursuing violations, they let the cases fester and turn > into civil disputes when there are clear code violations. And when > they apply, that is at the instigation of evil neocons and their boss > george w bus and neil bush who had adulterous sex with asian women > while married to sharon. These Bibble waving evil criminals are > ultimately the real culprits for the social and civil society > breakdown. There are terrible neighbor to neighbor disputes in the > country stemming from simple ignored code violations such as uncleaned > trash and other irritants. > > --------- > BLACKSBURG, VA (WIS/AP) - Virginia Tech's president says an Asian > university student killed 30 people in a campus building before > turning the gun on himself. > > And though Charles Steger did not explicitly say the student was also > the gunman in the first shooting, he told CNN that he did not believe > there was another shooter. > > Administrators at Virginia Tech are being subjected to some second- > guessing over how long it took to get out a campus-wide warning in > yesterday's shooting rampage. > > The first killings occurred in a dorm. More than two hours later, the > gunmen opened fire in a classroom building, killing 30 more people and > ultimately himself. > > The only alert was sent by e-mail, telling people there'd been a > shooting and urging caution. > > Steger defended the delay in warning students about the gunman. > > Steger says the university was trying to notify students who were > already on campus, not those who were commuting in. He says he thought > the best way to keep students safe was to confine them to their > classrooms. > > Security officials at other big schools are sympathetic. And they're > also looking at ways to speed up communications in a crisis. UC > Berkeley is considering sirens or an outdoor PA system. The University > of Florida is already working with police on an auto-dialing phone > system for emergencies. > > And Virginia Tech itself has been working on a system to warn people > via cell-phone text messaging. > > One of the first victims shot at Virginia Tech was just a month away > from graduation. > > Bryan Clark says his brother, Ryan, was a resident adviser on the > fourth floor of the dormitory where the rampage began yesterday. > > Ryan Clark was 22 and from Martinez, Georgia. Known as "Stack" to his > friends, he majored in psychology, biology and English. A Web site > says he was personnel officer for the Marching Virginians band and > intended to pursue a PhD in psychology. > > Another victim had ties to Georgia as well. Colleagues say German > professor Christopher Bishop was among those killed. Bishop earned > undergraduate and master's degrees in German at the > University of Georgia. > > The deadly shootings at Virginia Tech are touching families around the > world. Among those killed were a Romanian-born professor with > emigrated from Israel and a professor from India. > > Joe Librescu of Tel Aviv says his father, an engineering science and > mathematics professor, tried to stop the gunman from entering his > classroom by blocking the door before he was shot to death. > > Another victim was a man from southern India who lectured in the > Department of Civil and Environmental Engineering. The victim's > brother says he was a guiding force in their family. > > Condolences have poured in from Britain to China but there also has > been condemnation of US gun laws. The prime minister of Australia says > America's "gun culture" is a negative force, while > commentators in India say the laws must be made stricter. > > And the White House confirmed this morning that the Bushes would > travel to Blacksburg, Virginia, to attend the afternoon convocation. > > In his remarks yesterday, the president said schools should be "places > of safety, sanctuary and learning." > > Until Monday, the deadliest campus shooting in US history took place > in 1966 at the University of Texas, where Charles Whitman killed 16 > people from the observation deck of a clock tower. > > At Columbine High in 1999, two teen-agers killed 12 fellow students > and a teacher, then took their own lives. > > It's the second time in less than a year that the campus was closed > because of a shooting. > > Last August, the opening day of classes was canceled and the campus > closed when an escaped jail inmate allegedly killed a hospital guard > off campus and fled to the Tech area. > > Virginia Tech is nestled in the Blue Ridge Mountains of southwestern > Virginia, about 160 miles west of Richmond. The campus is centered > around the Drill Field, a grassy field where military cadets once > practiced. The dorm and the classroom building where the victims were > shot are on opposites sides of the Drill Field. > > Copyright 2007 Raycom Media. All rights reserved. This material may > not be published, broadcast, rewritten or redistributed. AP > contributed to this report. You mentioned "Korean Al-Qaeda Terrorist" in the title! Honesty demands that you establish it as a fact that the person was connected to Al-Qaeda and that he was a terrorist and not some mentally sick fellow. Muhammad From jasen at free.net.nz Sat Apr 28 19:52:02 2007 From: jasen at free.net.nz (jasen) Date: 28 Apr 2007 23:52:02 GMT Subject: *** Dr G Polya BRILLIANTLY analyses the Virgina Shooting Incident *** References: <1177266754.126153.202760@b58g2000hsg.googlegroups.com> <1177287460.376404.323520@b58g2000hsg.googlegroups.com> <1177416547.394200.314950@r3g2000prh.googlegroups.com> <1177430456.620057.190820@n15g2000prd.googlegroups.com> <1177771570.535837.199190@p77g2000hsh.googlegroups.com> Message-ID: On 2007-04-28, Quadibloc wrote: > Australia - Tasmania included - would today be under the iron heel of > Imperial Japan had it not been for the armed might of the United > States of America! Please do not feed the trolls. Bye. Jasen From hg at nospam.org Mon Apr 23 06:03:58 2007 From: hg at nospam.org (hg) Date: Mon, 23 Apr 2007 12:03:58 +0200 Subject: pyserial ... timeout on write References: Message-ID: hg wrote: > Hi, > > I notice that pyserial will hang on a write (even with timeout on) if > rts/cts are one. > > Anyway to get around that ? > > Thanks > > hg PS: on windows From whamil1 at entergy.com Wed Apr 25 08:45:52 2007 From: whamil1 at entergy.com (Hamilton, William ) Date: Wed, 25 Apr 2007 07:45:52 -0500 Subject: Tutorial creates confusion about slices In-Reply-To: Message-ID: <588D53831C701746A2DF46E365C018CE01D2CA78@LITEXETSP001.etrsouth.corp.entergy.com> > -----Original Message----- > From: python-list-bounces+whamil1=entergy.com at python.org [mailto:python- > list-bounces+whamil1=entergy.com at python.org] On Behalf Of Antoon Pardon > Sent: Tuesday, April 24, 2007 7:40 AM > To: python-list at python.org > Subject: Re: Tutorial creates confusion about slices > > On 2007-04-24, Michael Bentley wrote: > > > > On Apr 24, 2007, at 6:35 AM, Antoon Pardon wrote: > > > >> People don't read tutorials in a strictly linear fashion. They can > >> continue to later subjects and then come back here to see how things > >> tie together. So the fact that it is only confusing to those who > >> know more than is already presented doesn't seem a very good reason > >> to leave it in. > > > > Yet they understand that earlier in the document, there is likely to > > be a less complete coverage of a given topic. There is in fact, a > > link on that page that includes a more complete coverage of that > > topic (which I mentioned to you in an earlier message IIRC). > > That there is more complete coverage elsewhere is no good reason > to come with an explanation that suggests things working in > a way that will be contradicted by that more complete coverage. > > Even after people have read the more complete coverage it is > still very possible that they will come back to this part of > the text and get the wrong idea of how things work. That's how everything I've ever learned has been taught. Start with a simple explanation that may not be completely accurate but is functional, then fill in the details later when there is a context to put them in. The tutorial could start out by explaining everything at the implementation level; it doesn't because it is a _tutorial_, intended to give new users the context they need to understand the more complicated nuances of the language. If it covered every fiddly little detail, it wouldn't be a tutorial. It would be a language reference document instead. > A more complete coverage elsewhere is not an adequate remedy > for a tekst suggesting things working differently than they > actually do. Sure in the long run people will figger out how > things actually work and that the explanation given in that > section is totally inadequate for negative steps. But I > prefer that people don't loose too much time figgering out > that a particular explanation only works for particular cases > and not in general. > > > Submit a patch if you want it changed. I'm sure your valuable > > insights will greatly improve the quality of the python documentation. > > Fat chance, if they reason like you. So you're saying your insights aren't valuable? --- -Bill Hamilton From steve at holdenweb.com Tue Apr 24 08:10:43 2007 From: steve at holdenweb.com (Steve Holden) Date: Tue, 24 Apr 2007 08:10:43 -0400 Subject: Catching a specific IO error In-Reply-To: References: Message-ID: Thomas Kr?ger wrote: > Tina I schrieb: >> Now, this works but of course it catches every IOError, and I can not >> figure out how to restrict it to only catch the "[Errno 2]"? > > There's an example that uses the error number: > http://docs.python.org/tut/node10.html#SECTION0010300000000000000000 > So what you'll need to do is catch all IOError exceptions, then test to see if you've got (one of) the particular one(s) you are interested in. If not then you can re-raise the same error with a bare "raise" statement, and any containing exception handlers will be triggered. If there are none then you will see the familiar traceback termination message. regards Steve -- Steve Holden +1 571 484 6266 +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 gigs at hi.t-com.hr Tue Apr 24 11:40:16 2007 From: gigs at hi.t-com.hr (Gigs_) Date: Tue, 24 Apr 2007 17:40:16 +0200 Subject: tkinter paint program Message-ID: I'm working on tkinter paint program, mostly to learn tkinter canvas. I have method which create buttons for oval, rectangle, line, polygon etc. How to make oval button to be sunken when i click it and to remain sunken until i click on another button (like rectangle and than is another button sunken)? thanks From carl at personnelware.com Fri Apr 27 00:45:06 2007 From: carl at personnelware.com (Carl K) Date: Thu, 26 Apr 2007 23:45:06 -0500 Subject: mysql "rows affected" In-Reply-To: References: <1bCdnU80YoYXpazbnZ2dnUVZ_gKdnZ2d@comcast.com> Message-ID: <7smdndHDecdU4qzbnZ2dnUVZ_hSdnZ2d@comcast.com> John Nagle wrote: > Carl K wrote: >> using MySQLdb, I do cursor.execute("update...") >> >> How can I tell how many rows were affected ? >> >> Carl K > > cursor = db.cursor() # get cursor > cursor.execute(sqlstatement, argtuple) # do command > rowsaffected = cursor.rowcount # get count of rows affected > cursor.close() # close cursor > db.commit() # commit transaction > > John Nagle cursor.rowcount - bingo. Thanks a bunch. Carl K From bbxx789_05ss at yahoo.com Sat Apr 7 06:25:05 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: 7 Apr 2007 03:25:05 -0700 Subject: tuples, index method, Python's design In-Reply-To: References: <1175867771.114540.61810@n76g2000hsh.googlegroups.com> <1175884427.779950.267220@y80g2000hsf.googlegroups.com> Message-ID: <1175941505.845330.12780@w1g2000hsg.googlegroups.com> On Apr 6, 1:24 pm, Carsten Haese wrote: > Except that that wasn't the only justification. GvR also said: > > """ > For tuples, I suspect such a function would rarely be used; I think > that is most cases where x.index() would be useful, x is generally a > list, whose contents varies in time, rather than a tuple (which cannot > change easily). > """ > Touche. From kyosohma at gmail.com Mon Apr 9 10:02:45 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: 9 Apr 2007 07:02:45 -0700 Subject: Classes with initialization In-Reply-To: <1176103583.032209.304710@p77g2000hsh.googlegroups.com> References: <1176103583.032209.304710@p77g2000hsh.googlegroups.com> Message-ID: <1176127365.448101.224930@n76g2000hsh.googlegroups.com> On Apr 9, 2:26 am, mariano.suarezalva... at gmail.com wrote: > Hi all, > > I'm currently using code similar to this: > > class ClassWithInitialization(type): > def __init__(cls, name, bases, dict): > type.__init__(name, bases, dict) > dict['__class_init__'](cls) > > class A: > __metaclass__ = ClassWithInitialization > > def __class_init__(cls): > cls.some_attribute = ... > ... > > in order to get class attributes initialized (since the values of > these attributes > need non trivial work to be computed, putting the code that does that > computation in the class scope ends up with the class having extra > attributes---the `local' variables used in the computation of the > values of class attribute; so I'm using __class_init__'s scope to > contain those variables) > > I was wondering: is there a simpler approach to this? > > Also: can someone enlighten me as to when code in class scope is run, > exactly? > if a class A has a metaclass M, then M.__init__ does not seem to get > the code in A's class scope in its arguments AFAICS, so I guess that > code is run before the class is created? > > Cheers, > > -- m As I understand it, class code doesn't get run until you create an instance of the class and call a method with that instance. I don't know how to answer your other question though. Mike From silverburgh.meryl at gmail.com Sat Apr 28 23:14:17 2007 From: silverburgh.meryl at gmail.com (silverburgh.meryl at gmail.com) Date: 28 Apr 2007 20:14:17 -0700 Subject: How to get HTTP error when using urlretrieve() Message-ID: <1177816457.190845.100980@l77g2000hsb.googlegroups.com> Hi, I use urlretrieve to retrieve resources from a http server. Can you please tell me how can I get the HTTP error (whenever happens)? And what kind of different exception urlretrieve will throw? e.g. unknown host? connection timeout? HTTP error? Thank you. From bdesth.quelquechose at free.quelquepart.fr Sat Apr 21 15:32:25 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sat, 21 Apr 2007 21:32:25 +0200 Subject: class __getitem__ when item is not a sequence ??? In-Reply-To: <1177026475.610239.22720@q75g2000hsh.googlegroups.com> References: <1177026475.610239.22720@q75g2000hsh.googlegroups.com> Message-ID: <462a5d57$0$4231$426a74cc@news.free.fr> cfriedalek at gmail.com a ?crit : > Sorry for the vague subject. Not sure what the right terminology is. > > How can I use an instance's data by reference to the instance name, > not the instance attribute? OK the question is probably really poor > but hopefully an example will make it clear. > > >>x=1 >>type(x) > > > >>x.__add__(1) > > 2 > >>print x > > 1 > >>3*x > > 3 > > In this case x is an integer. My understanding is that x in an > instance of an integer class. Since it refers to only a single value > things like print x, 3*x etc operate on the instance name which seems > to refer to the instance data, not the instance itself. I want to do > the same for my own classes. http://docs.python.org/ref/specialnames.html From andmarti at gmail.com Mon Apr 23 20:39:06 2007 From: andmarti at gmail.com (andmarti at gmail.com) Date: Tue, 24 Apr 2007 00:39:06 +0000 Subject: getting scancodes Message-ID: <20070424003906.GA20969@lacordilleraandina.com.ar> Anyone knows if its possible to get scan codes ??? I tried with getch () but with no success, just keycodes. May be using the something in the sys.stdin module ?? Pleasee, any help would be very appreciated. -- Andr?s M. --------------------------------------------- .--. |o_o | |:_/ | // \ \ (| | ) /'\_ _/`\ \___)=(___/ --------------------------------------------- From Martin.Drautzburg at web.de Sun Apr 22 14:26:26 2007 From: Martin.Drautzburg at web.de (Martin Drautzburg) Date: Sun, 22 Apr 2007 20:26:26 +0200 Subject: Namespaces/introspection: collecting sql strings for validation References: <1921780.hifcbgjtIO@beaureve.gmx.net> Message-ID: <2075208.bSjua6qmHG@beaureve.gmx.net> Peter Otten wrote: > Martin Drautzburg wrote: > >> I would like to validate sql strings, which are spread all over the >> code, i.e. I run ("prepare") them against a database to see if it >> happy with the statements. Spelling errors in sql have been a major >> pain for me. > > def validateSQL(filename=None): > if filename is None: > # by default operate on the calling module > filename = sys._getframe(1).f_globals["__file__"] > for s in strings(filename): > print "validating", repr(s) This involves parsing the file. I can see that it would even work on a pyc file and it actually does solve the problem. Still (for the glory of the human mind) I would like to do this without parsing a file, but just the python internal memory. > Another option would be to mark SQL statements similar to gettext by > enclosing them in a function call > > sql = SQL("select * from...") > > and then defining SQL() as either a no-op in production or an actual > validation while you are debugging. Even simpler and safer would be to > always validate once: > > def SQL(sql, checked=set()): > if sql in checked: > return True > if not valid_sql(sql): raise ValueError > checked.add(sql) > return sql No this does not do the trick. I will not be able to validate an sql statement bofore I run over the piece of code that uses it. Or I would have to define all my sql = SQL stuff on module level, isn't id. I mean, the problem is: when are those sql = SQL statement really ececuted? From rowen at cesmail.net Mon Apr 30 14:42:01 2007 From: rowen at cesmail.net (Russell E. Owen) Date: Mon, 30 Apr 2007 11:42:01 -0700 Subject: Re-running script from Tk shell References: <1177944662.957393.306620@h2g2000hsg.googlegroups.com> Message-ID: In article <1177944662.957393.306620 at h2g2000hsg.googlegroups.com>, gtb wrote: > I am testing a simple script by running it in the Tk shell. It imports > a class from another module. I edit and save the file from which I > import. When I want to re-run I delete the Tk window and run the > module from the Edit window (F5 - Run Module). The script that does > the importing does not see the changes to the imported class, even if > I delete the compiled files. For it to see the changes I must close > all the edit windows and re-open an Idle edit. > > Perhaps I need to de-import the class, but I have not found a method > in the tutorial or the reference (yet). Try having your script first import the library and then reload it, e.g.: import foo reload(foo) It will load foo more slowly the first time (and a clever if statement could avoid that) but it will always use the latest foo. Warning: this will not work if you use from foo import... -- Russell From Eric_Dexter at msn.com Sun Apr 15 09:49:08 2007 From: Eric_Dexter at msn.com (Eric_Dexter at msn.com) Date: 15 Apr 2007 06:49:08 -0700 Subject: Getting started with python In-Reply-To: <1176598011.463543.96990@q75g2000hsh.googlegroups.com> References: <1176598011.463543.96990@q75g2000hsh.googlegroups.com> Message-ID: <1176644948.309287.63680@b75g2000hsg.googlegroups.com> On Apr 14, 7:46 pm, "Eric" wrote: > Hello, after reading some of the book Programming Python it seems that > python is something I would like to delve deeper into. The only thing > is, I have no idea what I should try and write. So I was hoping that > someone here could help point me to a group/project that would be a > good starting place for a person with limited python knowledge, but > that is willing to learn whatever is necessary. I'm hoping that with a > goal I can start to learn python instead of just playing around with > it. Thanks. If you want to play around with simple graphics and writing simple ascii files to disk then dex tracker may be a good project for you. I am currently playing around with generating random sounds to disk and random rythoms. (I also have a harder graphics problem that when I solve will break the music program wide open). https://sourceforge.net/projects/dex-tracker You would go to the (project homepage) website for dependencies http://www.stormpages.com/edexter/csound.html (not all are required for all sub-programs but you do want wxwindows). It would probily be cool to expand the idea into non-random series of numbers and I have just started to code this particular tool. I can upload it to my google groups if you are intrested From szhorvat at gmail.com Mon Apr 23 04:15:26 2007 From: szhorvat at gmail.com (Szabolcs) Date: 23 Apr 2007 01:15:26 -0700 Subject: Two syntax questions (newbie) Message-ID: <1177316126.432039.232300@o5g2000hsb.googlegroups.com> I used Mathematica for data processing a lot and I got spoiled by its functional programming possibilities. I was drawn to Python because it also allows for a similar programming style (and, more importantly, it has an interactive shell, ipython, and a lot of libraries that are useful to me, like scipy). I am still learning the language, so please be gentle :-) And here comes the first question: Mathematica allows writing result = processData at Reverse@Sort at data or even result = data//Sort//Reverse//processData instead of result = processData[Reverse[Sort[data]]] In Python this would be something like result = processData(list(reversed(sorted(data)))) The first two Mma alternatives are both easier to read (especially when part of a bigger expression) and easier to type (an re-type, if working interactively) because I don't have to jump with the cursor to the beginning and end of the expression to insert the brackets when adding another function call. Is there a way to avoid typing all the parentheses in Python? Is it possible to define a different syntax for function calls or define a function composition operator for functions that take a single argument? The second question: Of course Python is not Mathematica and not as friendly with this style as Mma is. Sometimes it forces me to use some temporary variables (e.g. because lines get too long and breaking lines with a backslash is ugly). I like to get rid of these variables as soon as they aren't needed, e.g.: temp = data[:] temp.sort() temp.reverse() result = processData(temp) del temp Is it possible to avoid the explicit del temp? In C/C++ I would simply enclose the piece of code in curly brackets. Is it possible to somehow separate a block of code from the rest of the program and make variables local to it? Of course none of these two things would allow me do to something that I can not already do, but they would make work easier. And I am curious if they are possible. Thanks for your replies in advance, Szabolcs From jeba.ride at gmail.com Thu Apr 19 15:03:03 2007 From: jeba.ride at gmail.com (Clement) Date: 19 Apr 2007 12:03:03 -0700 Subject: NFS Help In-Reply-To: References: <1177007562.103413.310390@o5g2000hsb.googlegroups.com> Message-ID: <1177009383.764076.286710@b58g2000hsg.googlegroups.com> On Apr 19, 11:44 pm, Larry Bates wrote: > Clement wrote: > > how to get the file from NFS share in python...... > > NFS share is mounted on your local directory, you get to it > the same way you would any other file (e.g. go to the mount > point and get the file). > > -Larry I want to know how to do it programatically From python-url at phaseit.net Mon Apr 23 11:39:17 2007 From: python-url at phaseit.net (Cameron Laird) Date: Mon, 23 Apr 2007 15:39:17 +0000 (UTC) Subject: Python-URL! - weekly Python news and links (Apr 23) Message-ID: QOTW: "The users." - Ali, answering a question on what's special about Emacs. "Dynamic languages look at WSDL and shrug - another example of the hoops that static typing forces humans to go through." - Gordon Weakliem http://lists.community.tummy.com/pipermail/frpythoneers/2007-April/001342.html The current issue of the rather prestigious *Computing in Science and Engineering* journal is devoted to Python (!): http://csdl2.computer.org/persagen/DLAbsToc.jsp?resourcePath=/dl/mags/cs/&toc=comp/mags/cs/2007/03/c3toc.xml Python is just as capable--and more!--as JavaScript, VBScript, ... for controlling COM. Here's a little chatter on expression of "Array" data: http://groups.google.com/group/comp.lang.python/browse_thread/thread/af1a19a4e3541060/ Despite "Python-URL!"'s habitual ... reserve about regular expressions, there *are* places they fit perfectly. Steven Bethard and Peter Otten show off how good a simple RE can be: http://groups.google.com/group/comp.lang.python/browse_thread/thread/870b46f0e4bc02c6/ Python 2.5.1 "is the first bugfix release of Python 2.5": http://groups.google.com/group/comp.lang.python/msg/2e58fab5387e1b77 Michael Hoffman correctly explains the so-often-misunderstood semantics of '*' (for example) in subprocess invocations. Notice use of the little-known expanduser(), expandvars(), and check_call(): http://groups.google.com/group/comp.lang.python/msg/639cc8af04a91595 Carsten Haese supplies a model for construction in Python of a VB/Delphi iterator: http://groups.google.com/group/comp.lang.python/msg/557e1358aa92c5d3 ======================================================================== 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, Planet Python indexes much of the universe of Pybloggers. http://www.planetpython.org/ 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/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 should get through. To receive a new issue of this posting in e-mail each Monday morning (approximately), ask 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 pandiyan.gpandi at gmail.com Mon Apr 16 04:00:50 2007 From: pandiyan.gpandi at gmail.com (pandiyan.gpandi at gmail.com) Date: 16 Apr 2007 01:00:50 -0700 Subject: DO YOU HAVE ERROR IN PC SCAN AND DOWNLOAD FOR FREE Message-ID: <1176710450.730137.215360@w1g2000hsg.googlegroups.com> * A Slow System? * Harassed by DLL errors? * Plagued by constant Blue Screens? * Receiving error messages and don't know why? Did you know that most of these issues are easily repairable? Don't pay a technician loads of money for an issue that you can easily repair yourself! scan your pc now http://hnl520.regfix.hop.clickbank.net/ From ptmcg at austin.rr.com Thu Apr 12 21:47:34 2007 From: ptmcg at austin.rr.com (Paul McGuire) Date: 12 Apr 2007 18:47:34 -0700 Subject: Lists and Tuples and Much More In-Reply-To: References: Message-ID: <1176428854.502455.12330@e65g2000hsc.googlegroups.com> On Apr 12, 5:38 pm, "Scott" wrote: > I'm going to start grouping all my questions in one post as this is my > second today, and sorta makes me feel dumb to keep having to bother you all > with trivial questions. You might also investigate the python tutorial mailing list, which covers many of these basic topics without seeming to be bothered by much of anything. -- Paul From carsten at uniqsys.com Thu Apr 12 08:56:22 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Thu, 12 Apr 2007 08:56:22 -0400 Subject: sqlite3 question In-Reply-To: References: Message-ID: <1176382582.4220.13.camel@dot.uniqsys.com> On Thu, 2007-04-12 at 13:43 +0200, Marc 'BlackJack' Rintsch wrote: > In , Jorgen Bodde > wrote: > > >>>> r = c.execute('select * from song where id = 1') > >>>> for s in r: > > ... print s > > ... > > (1, u'Spikedrivers Blues', u'Mississippi John Hurt') > > > > That works. But when I can't restore the row by e.g. an ID that does > > not exist, I cannot see any method in 'r' (which is a SQLite.Cursor) > > that can tell me if I have rows. As explained in the help, r.rowcount > > does not give a valid result because it can't determine how many rows > > are restored in advance. > > This should not work because `r` should not be a `Cursor` object. The > `execute()`-Method returns an integer with the number of "affected rows". It does work if 'c' is a connection object with a poorly chosen name. According to http://docs.python.org/lib/sqlite3-Connection-Objects.html , sqlite3 connection objects have a non-standard execute method that creates a cursor, executes a query on that cursor, and returns that cursor. Anyway, if you expect a query to return at most one row, such as when you're filtering on the table's primary key, this is how I would do it: cur.execute("select * from song where id = ?", (wanted_id,) ) song_row = cur.fetchone() if song_row: # Do something with song_row else: # Song not found HTH, Carsten. From maney at two14.net Wed Apr 11 10:29:28 2007 From: maney at two14.net (Martin Maney) Date: Wed, 11 Apr 2007 14:29:28 +0000 (UTC) Subject: is asynchat broken or just not intended to work like other dispatchers? [PATCH] Message-ID: Simple asyncore application where I wanted to use an explicit map (1) rather than the automagic default. Worked fine until I tried to use asynchat to handle an interactive status and control connection (3) and found it had no notion about using a non-default map. After convincing myself that this must be a simple oversight in asynchat, I applied the following patch to a local copy. Of course now I have to carry around this hacked-up version of asynchat, which sort of defeats the "batteries included" simplicity thing. :-( Anyway, in hopes that maybe in a few years I can lose that ugly duplication, I offer this patch for what I assume was an oversight: --- my_chat.py (revision 6) +++ my_chat.py (working copy) @@ -59,11 +59,11 @@ ac_in_buffer_size = 4096 ac_out_buffer_size = 4096 - def __init__ (self, conn=None): + def __init__ (self, conn=None, map=None): self.ac_in_buffer = '' self.ac_out_buffer = '' self.producer_fifo = fifo() - asyncore.dispatcher.__init__ (self, conn) + asyncore.dispatcher.__init__ (self, conn, map) def collect_incoming_data(self, data): raise NotImplementedError, "must be implemented in subclass" (rev 6 was the checkin of the stock asynchat.py under a different name, of course) For the docs I cannot make a specific suggestion: it depends on what is intended to be exposed and what would be better ignored outside the implementation. It's at moments like this that I miss the explicit declaration of things as public/protected/private from C++ a little. Sure, it's rather officious, but it has value in reflecting some important design criteria in the code... it's better than nothing. (1) maybe I guessed wrong on this score about what was the yuckier un-or-incompletely-documented bit to use, but non-default maps are at least mentioned in asyncore's docs, and when you dig into the code (2) to see what's going on that's not documented (4) it's obvious that at least the dispatchers defined in asyncore.py are careful to allow for the optional map argument, so I think it was reasonable to prefer to use my own mapping with this interface rather than reaching in and frobbing asyncore's socket_map... especially after puzzling over the mysterious way it's defined (maybe?) in asyncore. (2) code is NOT documentation, dammit. Well, it's not *good* documentation, and everyone knows it, as Python's docstrings and XP's "no written docs, but we have to talk and talk about what's not written down" (aren't oral traditions grand? not to mention fragile...) stand in proof of, just to cite a couple obvious examples. (3) actually it was the other way around: I had that working just fine using the default mapping, and it was when I moved from the "playing around to see if asyn* is suitable" to something a little more useful that I ran into the problem. Whatever. (4) del_channel was another gem - that seems to be the clean way for a channel to shut itself down from within its input handling code, as for example that simple interactive status and control thing when it gets the "quit" command. Not so much as a hint of it in the docs. I hope that's not because using it is in fact a bad idea - I had to guess from looking at the code, so I can't know what the design intent was. :-( -- I personally refuse to use inferior tools because of ideology. In fact, I will go as far as saying that making excuses for bad tools due to ideology is _stupid_, and people who do that think with their gonads, not their brains. -- Linus From gagsl-py2 at yahoo.com.ar Thu Apr 12 04:30:24 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 12 Apr 2007 05:30:24 -0300 Subject: sqlite3 question References: <11e49df10704120038v17df487au402a6d9f88e28568@mail.gmail.com> Message-ID: En Thu, 12 Apr 2007 04:38:06 -0300, Jorgen Bodde escribi?: > I am using sqlite3 in python, and I wonder if there is a way to know > if there are valid rows returned or not. For example I have a table > song with one entry in it. The ID of that entry is 1, so when I do; > >>>> r = c.execute('select * from song where id = 1') >>>> for s in r: > ... print s > ... > (1, u'Spikedrivers Blues', u'Mississippi John Hurt') > > That works. But when I can't restore the row by e.g. an ID that does > not exist, I cannot see any method in 'r' (which is a SQLite.Cursor) > that can tell me if I have rows. As explained in the help, r.rowcount > does not give a valid result because it can't determine how many rows > are restored in advance. If you are only interested on how many songs there are, use count(*): c.execute('select count(*) from song where id = 1') print c.fetchone()[0] If you are going to process the results, just iterate over the rows as in your example. Or, use the fetchone method; it returns the first row, or None if no data is available (don't forget to process that row too). If you don't expect many rows, you can use rows = list(c), or rows = c.fetchall(), and check len(rows). > I am pretty new with Python, maybe there are some properties of an > iterator / sqlite3 I am not aware of that can tell me how many rows > are there? As with many "generic" iterators, unfortunately, you have to consume the elements in order to know its length. -- Gabriel Genellina From gb at ccicon.com Tue Apr 3 18:00:38 2007 From: gb at ccicon.com (Geoff Bjorgan) Date: Tue, 03 Apr 2007 16:00:38 -0600 Subject: trying to check the creation date of a file Message-ID: Nice going way to help! gb -------------- next part -------------- An HTML attachment was scrubbed... URL: From luismgz at gmail.com Fri Apr 13 21:30:40 2007 From: luismgz at gmail.com (=?iso-8859-1?q?Luis_M._Gonz=E1lez?=) Date: 13 Apr 2007 18:30:40 -0700 Subject: BaseHTTPServer and Apache In-Reply-To: References: Message-ID: <1176514240.915684.11410@y5g2000hsa.googlegroups.com> On Apr 13, 8:44 pm, Ron Garret wrote: > In article , > Ron Garret wrote: > > > Does > > anyone know of a straightforward way to get Apache to "forward" requests > > to a given path to another HTTP server running on a different port? > > Never mind, I think I figured it out. Apparently what I need is the > ProxyPassReverse directive. > > I'd still be interested in hearing about people's experience using > BaseHTTPServer for real applications. > > Thanks, > rg Some python web frameworks use the aproach you described by means of mod_rewrite. For example, Karrigell and Cherrypy (although they offer also other ways of deployment). This page in Karrigell's docs show how: http://karrigell.sourceforge.net/en/apache.htm From newsgroups at nospam.nowire.org Mon Apr 2 02:28:58 2007 From: newsgroups at nospam.nowire.org (=?ISO-8859-1?Q?Thomas_Kr=FCger?=) Date: Mon, 02 Apr 2007 08:28:58 +0200 Subject: Sorting a multidimensional array by multiple keys In-Reply-To: <1hvww1d.1k8ozo312a7yazN%aleax@mac.com> References: <1hvww1d.1k8ozo312a7yazN%aleax@mac.com> Message-ID: Alex Martelli schrieb: > Thomas Kr?ger wrote: >> def sorter(a, b): >> return cmp(a.id, b.id) >> >> obj_lst.sort(sorter) > > A MUCH better way to obtain exactly the same semantics would be: > > def getid(a): > return a.id > > obj_list.sort(key=getid) Frankly speaking the purpose of the example was to show how to pass a function as argument for the sort method. Your code may be more efficient but it explains something different. Thomas From mail at timgolden.me.uk Mon Apr 16 09:48:06 2007 From: mail at timgolden.me.uk (Tim Golden) Date: Mon, 16 Apr 2007 14:48:06 +0100 Subject: Writing Log CSV (Efficiently) In-Reply-To: <000c01c7802a$08e42660$1aac7320$@rawlins@thinkbluemedia.co.uk> References: <000c01c7802a$08e42660$1aac7320$@rawlins@thinkbluemedia.co.uk> Message-ID: <46237E96.8070209@timgolden.me.uk> Robert Rawlins - Think Blue wrote: > I'm looking to write a Log file which will be CSV based, and there is a good > possibility that it'll get quite busy once its up and running, so I'm > looking for the most efficient way to achieve it. [... snip ...] > myfile = open("Logs/Application.txt", "w") > > myfile.write('col1, col2, col3, col4, col5') > > myfile.close [.. snip ...] > But I'm a little apprehensive that open() and close() on a very regular > basis is just going to cause issues. I'm also a little worried that we'll > end up with 'race' type conditions and things going missing. > So my next thought was to just have an open object for the file, and then > perform multiple rights, until I need to send the report file somewhere > else, at which point I would close it. This in itself causes more issues as > we're running in a buffer which is just going to eat my memory, and as this > is on an embedded system which may lose power, we'd be kissing good bye to > all the logs until that point. I'm sure you'll get this same advice from everyone on the list, but: 1) Use the csv module which comes with Python to avoid reinventing the wheel. (Not to do with your main question, but worth it anyway). 2) Don't optimize too soon. It's hard to predict what effect things are likely to have on performance. A *lot* depends on your operating system, the environment, the frequency of updates etc. etc. One obvious factor is the whether multiple processes are writing to the file, what the damage would be if the process crashed and the buffer didn't get written /closed. 3) If you really worry about the performance, do some profiling / timing. It's surely not too hard to generate a stream of csv writes comparable to your target system (or at least proportional). Use the timeit or hotshot modules to see what difference the open/close makes. TJG From soren.skou.nielsen at gmail.com Wed Apr 18 08:45:43 2007 From: soren.skou.nielsen at gmail.com (Soren) Date: 18 Apr 2007 05:45:43 -0700 Subject: Python crash after using weave inline Message-ID: <1176900343.605337.42230@y5g2000hsa.googlegroups.com> Hi, I have a strange and very annoying problem when using weave in scipy.. when I run the code below.. the first time it needs to compile.. it says and then python.exe crashes! and no result is shown.. the second time i run it, it does not compile but gives the completely wrong answer.. prints a matrix of all zeros except for point 1,1 in the matrix which seems to have some random high number like -5.39403959e+08. .... !!?? Basicly I run through a 10 by 10 matrix do some calculations with respect to some center values x_c and y_c and insert the result into the empty numpy matrix array "res". Any help is appreciated! Thanks, Sroren from numpy import * from scipy import weave from scipy.weave import converters def cartPolFast(xlen, ylen, x_c, y_c): res = zeros((xlen,ylen)) code = """ { int xlen, ylen, x_c, y_c; double rel_x, rel_y; int x, y; for( x = 0; x == xlen; x++) for( y = 0; y == ylen; y++) rel_x = x-x_c; rel_y = y_c-y; res(x,y) = rel_y*rel_y; } """ weave.inline(code,['xlen','ylen','x_c','y_c','res'], type_converters=converters.blitz, compiler="gcc") return res if __name__ == "__main__": tst = cartPolFast(10,10,5,5) print tst From python at hope.cz Tue Apr 24 15:12:03 2007 From: python at hope.cz (Johny) Date: 24 Apr 2007 12:12:03 -0700 Subject: PIL and font colour Message-ID: <1177441923.378487.210310@r3g2000prh.googlegroups.com> I use PIL to write some text to a picture.The text must be seen wery clearly. I write the text to different pictures but to the same position. As pictures maybe different, colour, in the position where I write the text, is also different. Is there a way how to set the font colour so that it will be seen very clearly in the picture? For example, if the picture is bright ( for example yellow), the font colour should be dark( e.g. black) and vice versa. Can anyone help? Thanks L. From vbr at email.cz Wed Apr 18 15:56:40 2007 From: vbr at email.cz (vbr at email.cz) Date: Wed, 18 Apr 2007 21:56:40 +0200 (CEST) Subject: =?us-ascii?Q?Re=3A=20unicode=20data=20=2D=20accessing=20codepoints=20=3E=20FFFF=20on=20narrow=20python=20builts?= In-Reply-To: Message-ID: <1369.3085-30170-964688013-1176926200@email.cz> Hi, thanks for the answer, > From: Gabriel Genellina > Subj: Re: unicode data - accessing codepoints > FFFF on narrow python builts > Datum: 18.4.2007 21:33:11 > ---------------------------------------- > > py> x=u"\N{GOTHIC LETTER AHSA}" > py> ord(x) > Traceback (most recent call last): > File "", line 1, in > TypeError: ord() expected a character, but string of length 2 found > py> unicodedata.name(x) > Traceback (most recent call last): > File "", line 1, in > TypeError: need a single Unicode character as parameter > py> len(x) > 2 > py> list(x) > [u'\ud800', u'\udf30'] > > That looks like UTF-16 (?) but seen as two characters instead of one. > Probably in a 32bits build Python should refuse to use such character (and > limit Unicode support to the basic plane?) (or not?) (if not, what's the > point of sys.maxunicode?) (enough parenthesis for now). > > -- > Gabriel Genellina > Yes, this is a UTF-16 surrogate pair, which is, as far as I know the usual way the characters outside the basic plane are handled on narrow python builds. There are some problems with it, but most things (I need) with non-basic plane characters can be done this way (GUI display, utf-8 text saving) - thus I wouldn't be happy, if this support were removed. The problem is the access to unicodedata, which requires "a string of length 1"; I thought, it could also accept the codepoint number, but it doesn't seem to be possible. Thanks again. vbr - Vlastimil Brom From elicriffield at gmail.com Mon Apr 9 15:11:47 2007 From: elicriffield at gmail.com (Eli Criffield) Date: 9 Apr 2007 12:11:47 -0700 Subject: recursively removing files and directories In-Reply-To: <1176144250.874365.141820@n59g2000hsh.googlegroups.com> References: <1176144250.874365.141820@n59g2000hsh.googlegroups.com> Message-ID: <1176145907.548336.28790@l77g2000hsb.googlegroups.com> On Apr 9, 1:44 pm, "bahoo" wrote: > Hi, > > I found a message on Jan 16, 2006 regarding the same topic, except > that I wanted to remove only certain files that satisfy the format > "ABC_XXX_XXX.dat", but not the other files. Once the files are > removed, if a folder becomes empty, I want to remove the folder as > well. > > The solution to the Jan 16 2006 message required many lines of python > code. I was wondering if there is a simpler solution to my problem at > hand, perhaps by using more specialized functions? > > Thanks! > bahoo Something like import os import re def processFiles(args,dir,fileList): for thisFile in fileList: if re.match(r'REGEXPATTERN',thisFile): os.unlink("%s%s"dir,thisFile) os.path.walk("/",processFiles,None) But thats just off the top of my head, so that mite not be exact. Eli Criffield From anton.vredegoor at gmail.com Sat Apr 14 13:26:32 2007 From: anton.vredegoor at gmail.com (Anton Vredegoor) Date: Sat, 14 Apr 2007 19:26:32 +0200 Subject: Simple integer comparison problem In-Reply-To: References: Message-ID: Bart Willems wrote: > I have a feeling that there's a Python-solution that is shorter yet > better readable, I just can't figure it out yet... Shorter (and faster for big lists): Yes. More readable: I don't know, I guess that depends on ones familiarity with the procedure. import bisect def grader(score): c = bisect.bisect([60,70,80,90],score) return 'FDCBA'[c] A. From martin at v.loewis.de Mon Apr 23 01:14:19 2007 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Mon, 23 Apr 2007 07:14:19 +0200 Subject: Python's handling of unicode surrogates In-Reply-To: <1177271301.924370.101450@q75g2000hsh.googlegroups.com> References: <4628532B.5060104@v.loewis.de> <1177051493.468698.176740@b75g2000hsg.googlegroups.com> <4629591a$0$13629$9b622d9e@news.freenet.de> <1177122874.524447.85130@p77g2000hsh.googlegroups.com> <1177271301.924370.101450@q75g2000hsh.googlegroups.com> Message-ID: <462C40AB.9070900@v.loewis.de> > IMHO what is really needed is a bunch of high level methods like > .graphemes() - iterate over graphemes > .codepoints() - iterate over codepoints > .isword() - check if the string represents one word > etc... This doesn't need to come as methods, though. If anybody wants to provide a library with such functions, they can do so today. I'd be hesitant to add methods to the string object with no proven applications. IMO, the biggest challenge in Unicode support is neither storage nor iteration, but it's output (rendering, fonts, etc.), and, to some degree, input (input methods). As Python has no "native" GUI library, we currently defer that main challenge to external libraries already. Regards, Martin From bbxx789_05ss at yahoo.com Mon Apr 2 00:03:34 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: 1 Apr 2007 21:03:34 -0700 Subject: can a method access/set another's variables? In-Reply-To: <1175478965.803665.15040@o5g2000hsb.googlegroups.com> References: <1175477764.549115.159410@n59g2000hsh.googlegroups.com> <1175478965.803665.15040@o5g2000hsb.googlegroups.com> Message-ID: <1175486614.620104.226300@d57g2000hsg.googlegroups.com> On Apr 1, 7:56 pm, "wswilson" wrote: > I am parsing a document which contains some lines with code I want to > eval or exec. However, due to the complexity of the parsing, I am > splitting it among different methods. So, if I eval something in one > method, it won't be there if I try to access its value a few lines > later since I happen to be in a different method in the parser. Thanks > for the help! val = None class A(object): def early_parse(self): global val self.result1 = val = eval("10 + 5") def later_parse(): global val val += eval("20*2") a = A() a.early_parse() later_parse() a.result2 = val print a.result1 print a.result2 From inq1ltd at verizon.net Wed Apr 18 15:43:44 2007 From: inq1ltd at verizon.net (jim-on-linux) Date: Wed, 18 Apr 2007 15:43:44 -0400 Subject: PY shutil on win xp home version In-Reply-To: References: <1176898887.530470.222830@p77g2000hsh.googlegroups.com> Message-ID: <200704181543.44889.inq1ltd@verizon.net> python help, A client is using win xp home. my program contains; shutil.copyfile(n, 'prn') This runs fine on win xp pro but they are getting the following traceback. File "LOP_PRT_10.pyc", line 170, in __init__ ? File "LOP_PRT_10.pyc", line 188, in Fprint1 ? File "shutil.pyc", line 47, in copyfile IOError: [Errno 2] No such file or directory: 'prn' Since this runs ok on win xp pro, does this have something to do with the home version of xp. I'm thinking of changeing 'prn' to 'lpt1' and trying again but I don't want to use the client as a testor. Or is there some other explaination for the problem. jim-on-linux From michael at jedimindworks.com Fri Apr 27 15:17:34 2007 From: michael at jedimindworks.com (Michael Bentley) Date: Fri, 27 Apr 2007 14:17:34 -0500 Subject: editing scripts on a mac In-Reply-To: References: Message-ID: <395541E7-C830-4CC3-8F43-CF237051EAAD@jedimindworks.com> On Apr 27, 2007, at 11:08 AM, Steve Holden wrote: > I am teaching someone Python by email, and part of our conversation > recently ran as follows: > > him> How do I save a script and run it? > > me > Do you have a text editor? If so, edit the script in that, then > save it > me > in your home directory (the place you can see when you open the > terminal > > him> I do not have a text editor, but here are the answers to > him> questions 1-5. > > Now, frankly, I don't think this answer is correct, since I know OS > X is > a UNIX derivative, but I am loathe to involve a programming noob > with vi > or something similar. So I wondered if one of the c.l.py mac users > could > give brief instructions for firing up a visual text editor of some > sort > and saving a file somewhere it can easily be accessed from a terminal > window (which I presume starts up in his home directory). As Thomas mentioned, Text Edit is in the Applications folder. And as Tommy mentioned, OS X does come with emacs. The default emacs on OS X is terminal based (and I've never figured out what key is supposed to be the Meta key). Other terminal based text editors include vi (of course) and nano. The IMHO better emacs Tommy suggested: Aquamacs is *really* good, and unlike the non-emacs editors mentioned so far -- has syntax highlighting for Python (and most everything else). But both Text Edit and nano are dead easy for noobs. BTW, the Terminal application is in Applications->Utilities hth, Michael From bbxx789_05ss at yahoo.com Sun Apr 15 23:26:39 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: 15 Apr 2007 20:26:39 -0700 Subject: pyparsing Catch-22 In-Reply-To: <1hwmo7x.lydgndjr9awfN%aleax@mac.com> References: <1176686782.270354.164630@l77g2000hsb.googlegroups.com> <1176692031.142326.134710@y80g2000hsf.googlegroups.com> <1hwmo7x.lydgndjr9awfN%aleax@mac.com> Message-ID: <1176693999.503571.104870@l77g2000hsb.googlegroups.com> On Apr 15, 9:16 pm, a... at mac.com (Alex Martelli) wrote: > 7stud wrote: > > 1) Even though the download at sourceforge said the file name was: > > > pyparsing-1.4.6.tar.gz > > > it was downloaded to my Desktop as: > > > pyparsing-1.4.6.tar > > > Did os x 10.4.7 automatically unzip it for me? .gz means the file was > > compressed with gzip, but I didn't have to do any unzipping. > > You probably have Safari, the browser, set up to do that upon download > (but not set up to also untar the tarfile) -- I believe that those are > its default settings. Still, Safari's just an application, even though > Apple reasonably chooses to bundle it into the OS; you might use > Firefox, Opera, Camino, or any other browser, and the issue of what that > given browser does upon download (and how to change those settings) will > be different each time. It's not really a question at OS level, rather > it depends on each specific browser. > > Alex Thanks. From bruno.42.desthuilliers at wtf.websiteburo.oops.com Fri Apr 27 06:52:15 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Fri, 27 Apr 2007 12:52:15 +0200 Subject: My python annoyances so far In-Reply-To: <1177599046.406827.5210@t38g2000prd.googlegroups.com> References: <1177541453.471959.120830@c18g2000prb.googlegroups.com> <1177599046.406827.5210@t38g2000prd.googlegroups.com> Message-ID: <4631d5be$0$2132$426a74cc@news.free.fr> 7stud a ?crit : > flifus at gmail.com wrote: >> Annoyances: >> > > Every language has annoyances. Python is no exception. Sure. But we may disagree on what are actually Python's annoyances !-) > Post away. > Anyone that is offended can go drink a Guinness. > >> 1. Underscores! What's the deal with that? Especially those double >> underscores. The best answer I read on this is that the double >> underscores denotes special methods that the interpreter may >> automatically use. For example, 4+4 get expanded by the interpreter to >> 4.__add__(4). >> > > I thought those were pretty ugly myself. Now, I am used to them. FWIW, you shouldn't have to directly use __magic__ methods - or only in very special corner cases. From will at willNOmcguganSPAM.com Sun Apr 22 15:53:05 2007 From: will at willNOmcguganSPAM.com (Will McGugan) Date: Sun, 22 Apr 2007 20:53:05 +0100 Subject: Vector classes In-Reply-To: <1177245233.573675.274580@n59g2000hsh.googlegroups.com> References: <1177245233.573675.274580@n59g2000hsh.googlegroups.com> Message-ID: <462bbd24$0$6956$fa0fcedb@news.zen.co.uk> Mizipzor wrote: > During my coding Ive found two vector classes on the internet. Ive > modified them both a little but the do both have advantages and > disadvantages. > I'm working on a vector class at the moment, in my 'gameobjects' library. It's not really ready for public consumption, but feel free to take a look... http://www.willmcgugan.com/game-objects/ -- blog: http://www.willmcgugan.com From kelvin.you at gmail.com Mon Apr 30 06:10:33 2007 From: kelvin.you at gmail.com (=?utf-8?B?5Lq66KiA6JC95pel5piv5aSp5rav77yM5pyb5p6B5aSp5rav5LiN6KeB5a62?=) Date: 30 Apr 2007 03:10:33 -0700 Subject: How do I parse a string to a tuple?? In-Reply-To: <1177926452.830059.269230@n59g2000hsh.googlegroups.com> References: <1177926452.830059.269230@n59g2000hsh.googlegroups.com> Message-ID: <1177927833.918042.237930@y5g2000hsa.googlegroups.com> On Apr 30, 5:47?pm, Soren wrote: > Hi! > > I have a string that contains some text and newline characters. I want > to parse the string so that the string just before a newline character > goes in as an element in the tuple. > > ex: > > "text1 \n text2 \n text3 \n text4" ? --> (text1, text2, text3, text4) > > Is there an easy way to do this? > > Thanks!, > Soren tuple("text1 \n text2 \n text3 \n text4".split('\n')) From KDawg44 at gmail.com Fri Apr 27 14:05:53 2007 From: KDawg44 at gmail.com (KDawg44) Date: 27 Apr 2007 11:05:53 -0700 Subject: Learning to use wxPython In-Reply-To: References: <1177690277.346950.120860@u32g2000prd.googlegroups.com> Message-ID: <1177697153.100118.179260@o40g2000prh.googlegroups.com> On Apr 27, 11:25 am, Michele Petrazzo wrote: > KDawg44 wrote: > > Hi, > > Hi, > > > I downloaded the wxPython demo and did an emerge wxpython (gentoo) to > > install. When I run the demo, I am getting this error: > > > # python demo.py Traceback (most recent call last): File > > "/usr/lib/python2.4/site-packages/wx-2.6-gtk2-ansi/wx/ _misc.py", > > line 1286, in Notify > > From here, I read that you are using the wx version 2.6 and the demo > that you are tring are for the 2.8.3! (the last as now). > So: > 1) install the new 2.8 > 2) download the demo for the 2.6! :) > > Bye, > Michele ahhh my bad i did not realize that. Thanks! From b.r.willems at gmail.com Sun Apr 29 07:24:25 2007 From: b.r.willems at gmail.com (Bart Willems) Date: Sun, 29 Apr 2007 07:24:25 -0400 Subject: I have a chance to do somting diffrent way not Python ?! In-Reply-To: <1177777623.038902.108590@y5g2000hsa.googlegroups.com> References: <1177777623.038902.108590@y5g2000hsa.googlegroups.com> Message-ID: anders wrote: > So basicly i like advice about interac with os, compiler etc. > Nice webblinks to read more > and do/don't things. Hello Anders, OS Support for Windows in Python is excellent. I suggest you download the latest version, and don't forget to download Mark Hammond's win32 library as well. Although it is mainly about COM support and you probably don't need it, it is always good to have. After that, work your way through the tutorial. It should give you enough information to create the scripts that you need. I used the Manning book to learn Python, but I hear a lot of good stories over here from 'Python for dummies' as well. The modules (included in the installation package) that you will need in your scripts are probably os, sys, and maybe some of the date modules. I can't think of any "don'ts" - except maybe for the warning that you should not try to write java or c++ code in Python. So, if there is anything that seems to me missing, consider a different approach in your code (a good example is the switch statement...) Best regards, Bart From johnjsal at NOSPAMgmail.com Tue Apr 17 23:51:32 2007 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Tue, 17 Apr 2007 23:51:32 -0400 Subject: Any way to refactor this? In-Reply-To: <461fe75c$0$11278$c3e8da3@news.astraweb.com> References: <461fe75c$0$11278$c3e8da3@news.astraweb.com> Message-ID: <46259617$0$23354$c3e8da3@news.astraweb.com> John Salerno wrote: > Setting aside, for the moment, the utility of this method or even if > there's a better way, I'm wondering if this is an efficient way to do > it. I admit, there was some copying and pasting, which is what prompts > me to ask the question. Here's the method. (I hope it looks ok, because > it looks really weird for me right now) Thanks guys. I'm going to look over all this and see what I can do. From spamtrap at dot-app.org Thu Apr 5 17:52:27 2007 From: spamtrap at dot-app.org (Sherm Pendley) Date: Thu, 05 Apr 2007 17:52:27 -0400 Subject: Why NOT only one class per file? References: <1175721799.714907.52770@o5g2000hsb.googlegroups.com> <46142acc$0$7532$426a34cc@news.free.fr> <4614b40e$0$26843$426a74cc@news.free.fr> <46154952$0$23907$426a74cc@news.free.fr> Message-ID: Bruno Desthuilliers writes: > Sherm Pendley a ?crit : > > In my book, it's huge classes and methods that are usually a smell of > a design problem. Obviously we're reading different books. But that's OK - I'm not on a crusade to convince everyone to work my way. If "one class per file" doesn't work well for you, don't write that way. All I'm saying is, what works well for you isn't necessarily what works well for everyone. sherm-- -- Web Hosting by West Virginians, for West Virginians: http://wv-www.net Cocoa programming in Perl: http://camelbones.sourceforge.net From liupeng at 18mail.cn Wed Apr 11 11:35:47 2007 From: liupeng at 18mail.cn (liupeng) Date: Wed, 11 Apr 2007 23:35:47 +0800 Subject: UnicodeEncodeError - a bit out of my element... In-Reply-To: <1176304567.142673.69710@y5g2000hsa.googlegroups.com> References: <1176304567.142673.69710@y5g2000hsa.googlegroups.com> Message-ID: <20070411153547.GB10342@pworld.org> I cut from Sam Python Phrasebook "Converting Unicode to Local Strings" import string locStr = "El " uniStr = u"Ni\u00F1o" print uniStr.encode('utf-8') print uniStr.encode('utf-16') print uniStr.encode('iso-8859-1') #Combine local and unicode results #in new unicode string newStr = locStr+uniStr print newStr.encode('iso-8859-1') #ascii will error because character '\xF1' #is out of range asciiStr = newStr.encode('iso-8859-1') asciiStr =asciiStr.translate(\ string.maketrans('\xF1','n'), '') print asciiStr.encode('ascii') print newStr.encode('ascii') unicode_str.py Ni??o ?N|I|?|o Ni?o El Ni?o El Nino Traceback (most recent call last): File "C:\books\python\CH2\code\unicode_str.py", line 19, in ? print newStr.encode('ascii') UnicodeEncodeError: 'ascii' codec can't encode character u'\xf1' in position 5: ordinal not in range(128) On Wed, Apr 11, 2007 at 08:16:07AM -0700, erikcw wrote: > Hi all, > > I'm trying to parse an email message, but am running into this > exception. > > Traceback (most recent call last): > File "wa.py", line 336, in ? > main() > File "wa.py", line 332, in main > print out['msg'] > UnicodeEncodeError: 'ascii' codec can't encode character u'\xd6' in > position 238: ordinal not in range(128) > > How can I decode/encode this string to print to stdout and send again > in another email? Do I have to know what language the email is in? > > Thanks! > Erik > > -- > http://mail.python.org/mailman/listinfo/python-list > > -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 196 bytes Desc: Digital signature URL: From matthewperpick at gmail.com Tue Apr 17 11:06:03 2007 From: matthewperpick at gmail.com (matthewperpick) Date: 17 Apr 2007 08:06:03 -0700 Subject: strange behaviour with keyword arguments and inheritance In-Reply-To: <1176801382.872769.66460@d57g2000hsg.googlegroups.com> References: <1176771364.964642.209300@b75g2000hsg.googlegroups.com> <1176801382.872769.66460@d57g2000hsg.googlegroups.com> Message-ID: <1176822363.452854.33740@b58g2000hsg.googlegroups.com> cool .. thanks everyone. here is the aforementioned faq. http://www.python.org/doc/faq/general/#why-are-default-values-shared-between-objects On Apr 17, 5:16 am, Arnaud Delobelle wrote: > matthewperpick wrote: > > Check out this toy example that demonstrates some "strange" behaviour > > with keyword arguments and inheritance. > > > ================================= > > > class Parent: > > def __init__(self, ary = []): > > self.ary = ary > > [snip] > > As pointed out earlier, default values for arguments are evaluated > when the function is defined, not when it is called. This creates > confusion if this value is mutable and later mutated; I got confused > by it when I started python. So it is often not a good idea to use > mutable objects as default arguments. > > A simple fix: > > def __init__(self, ary=None): > if ary is None: ary = [] > self.ary = ary > > -- > Arnaud From saif.shakeel at gmail.com Tue Apr 24 07:01:29 2007 From: saif.shakeel at gmail.com (saif.shakeel at gmail.com) Date: 24 Apr 2007 04:01:29 -0700 Subject: adjust Message-ID: <1177412489.683970.45320@u32g2000prd.googlegroups.com> Hi, How do i right adjust my output using python.I need a output something like this: DID= 0x01,0x02,0x03,0x05,0x06,0x07,0x2B,0x30,0x31,0x4D,0x4E, 0x51,0x52,0x53,0x55, minlength= 3, 3, 4, 2, 10, 10, 40, 2, 150, 4, 1, 2, 2, 1, 2, 1, 6, 3, 17, 1, maxlength= 3, 3, 4, 2, 10, 10, 40, 2, 150, 4, 1, 2, 2, 1, 2, 30, 6, 3, 17, 20 I am printing from a list, and the values shld print below each id like shown. Thx From lobais at gmail.com Tue Apr 17 09:42:39 2007 From: lobais at gmail.com (Thomas Dybdahl Ahle) Date: Tue, 17 Apr 2007 15:42:39 +0200 Subject: Compare regular expressions References: Message-ID: Den Mon, 16 Apr 2007 11:50:40 +0200 skrev Thomas Dybdahl Ahle: > Hi, I'm writing a program with a large data stream to which modules can > connect using regular expressions. > > Now I'd like to not have to test all expressions every time I get a > line, as most of the time, one of them having a match means none of the > others can have so. > > But ofcource there are also cases where a regular expression can > "contain" another expression, like in: "^strange line (\w+) and (\w+)$" > and "^strange line (\w+) (?:.*?)$" in which case I'd like to first test > the seccond and only if it mathces test the seccond. > > Do anybody know if such a test is possible? if exp0.contains(exp1): ... I found this link: http://terpstra.ca/compare.html which seams to compare expressions. Not python expressions though. Sadly it writes nothing about the way it does the thing, and if it will always work. From kw at codebykevin.com Fri Apr 13 15:13:23 2007 From: kw at codebykevin.com (Kevin Walzer) Date: Fri, 13 Apr 2007 15:13:23 -0400 Subject: mac IDLE problems In-Reply-To: <1176488992.439341.226340@q75g2000hsh.googlegroups.com> References: <1176441305.802719.105520@q75g2000hsh.googlegroups.com> <461FAF55.9090109@codebykevin.com> <1176488992.439341.226340@q75g2000hsh.googlegroups.com> Message-ID: 7stud wrote: > On Apr 13, 10:27? am, Kevin Walzer wrote: >> 7stud wrote: >>> Hi, >>> In the IDLE, I can't get most shortcut keys that are listed next to >>> the menu items to work. ? For instance, under the Format menu item only >>> the shortcuts for "indent region" and "undent region" work. ? If I >>> highlight some text and use Shift+3 to comment out the region I >>> highlighted, the code is erased and I get the # symbol. ? When I use >>> the option(alt key) and type a character, I get things like this: >>> ??,??,??,?? >>> I looked under Options/Configure IDLE/Keys and tried the various built >>> in key sets, and none seem to work. >>> I also can't use my mouse to copy(or cut) and paste. ? When I highlight >>> something and right click(in an attempt to bring up the context menu >>> that has copy, cut, paste, etc.), the text that is highlighted is >>> doubled when I right click, e.g.: >>> ? ? ? some text >>> becomes: >>> ? ? ? some textsome text >>> And, sometimes when I try to highlight a line, the line 7 lines below >>> the cursor gets highlighted. >>> intel mac, os 10.4.7, python 2.4.4 >> IDLE under 2.5 has been much improved on the Mac; all the standard Mac >> keyboard shortcuts are supported, and in general it's more stable. With >> 2.5, IDLE replaces the old PythonIDE that used to ship with MacPython. >> Can you update to 2.5? >> >> -- >> Kevin Walzer >> Code by Kevinhttp://www.codebykevin.com > > Thanks for the info. I just updated to 2.4.4 because the download > said there were more packages for the mac than with 2.5. I think I'll > probably just stick to vim for an editor. > You realize that packages are trivial to build for 2.5, assuming you have the developer tools installed? Usually it's sudo easy_install foo (if you have setuptools installed) or sudo python setup.py. -- Kevin Walzer Code by Kevin http://www.codebykevin.com From duncan.booth at invalid.invalid Fri Apr 13 03:39:11 2007 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 13 Apr 2007 07:39:11 GMT Subject: Calling private base methods References: <1176374675.347453.89340@n76g2000hsh.googlegroups.com> <1176404325.211501.26610@w1g2000hsg.googlegroups.com> <1176428856.998080.13470@n76g2000hsh.googlegroups.com> Message-ID: "Dan Bishop" wrote: > I have a job as a C++ programmer and once tried this trick in order to > get at a private member function I needed. Didn't work: Apparently, VC > ++ includes the access level in its name mangling, so you get linker > errors. > I don't have a copy of VC to hand to test, but I might have tried something along these lines: somheader contains: class Whatever { private: void ohnoyoudont(int); } My C file: #define ohnoyoudont blah(){};public: \ inline void sneak(int x){this.ohnoyoudont(x);};private:void ohnoyoudont #include #undef ohnoyoudont ... Whatever foo = new Whatever(); int ohyesido = 42; foo.sneak(ohyesido); I don't think injecting another couple of non-virtual methods into the class ought to break anything. From paul at subsignal.org Mon Apr 2 11:49:15 2007 From: paul at subsignal.org (paul) Date: Mon, 02 Apr 2007 17:49:15 +0200 Subject: I18n issue with optik In-Reply-To: References: Message-ID: Thorsten Kampe schrieb: [snipp] > I got the tip to set a different encoding by > sys.stdout = codecs.EncodedFile(sys.stdout, 'utf-8') > > but unfortunately this does not change the encoding of any Terminal. > So my question is: how can I set a different encoding to sys.stdout > (or why can I set it without any error but nothing changes?) AFAIK you can't. If the terminal is limited to ascii it won't be able to display anything else; it might not even have the right font, so how are you supposed to fix that? The .encode(encoding, "replace") ensures safe downgrades though. cheers Paul From eddie at holyrood.ed.ac.uk Fri Apr 20 07:34:46 2007 From: eddie at holyrood.ed.ac.uk (Eddie Corns) Date: Fri, 20 Apr 2007 11:34:46 +0000 (UTC) Subject: Calculating CIDR blocks References: <1177032744.375099.248380@q75g2000hsh.googlegroups.com> Message-ID: Look at: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/466298 it handles most of the logic of combining IP ranges. Eddie From andrew-news at andros.org.uk Sun Apr 1 20:12:53 2007 From: andrew-news at andros.org.uk (Andrew McLean) Date: Mon, 02 Apr 2007 01:12:53 +0100 Subject: Measureing memory used by a subprocess Message-ID: I want to script the benchmarking of some compression algorithms on a Windows box. The algorithms are all embodied in command line executables, such as gzip and bzip2. I would like to measure three things: 1. size of compressed file 2. elapsed time (clock or preferably CPU) 3. memory used The first is straightforward, as is measuring elapsed clock time. But how would I get the CPU time used by a sub-process or the memory used? I'm guessing that the Windows Performance Counters may be relevant, see the recipe http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/303339 But I don't see any obvious way to get the process id of the spawned subprocess. - Andrew From gheorghe.postelnicu at gmail.com Sun Apr 29 21:08:50 2007 From: gheorghe.postelnicu at gmail.com (Gheorghe Postelnicu) Date: Sun, 29 Apr 2007 21:08:50 -0400 Subject: Stopping pythoncom.PumpMessages in a windows service Message-ID: <8094b1b60704291808p784d9824qf73fde657af8d2ff@mail.gmail.com> Hi, I am trying to create a windows service that will process some keyboard events. For that, i am trying to use pyHook and pythoncom, which work great in a stand-alone application. However, when in a service, the first problem I encounter is that the SvcStop part doesn't seem to be responding. Any suggestions? Thanks, -- Gheorghe Postelnicu, PhD From facundo at taniquetil.com.ar Wed Apr 25 14:03:26 2007 From: facundo at taniquetil.com.ar (Facundo Batista) Date: Wed, 25 Apr 2007 18:03:26 +0000 (UTC) Subject: File not read to end References: <1177522730.327454.121120@s33g2000prh.googlegroups.com> Message-ID: andrew.jefferies at gmail.com wrote: > My log is around 200,000 lines but it is stopping at line 26,428. I > checked that line and there aren't any special characters. Are you in Windows? Just in case, put "rb" as the mode of the open. Regards, -- . Facundo . Blog: http://www.taniquetil.com.ar/plog/ PyAr: http://www.python.org/ar/ From user at example.net Sat Apr 7 21:22:12 2007 From: user at example.net (cyb) Date: Sat, 07 Apr 2007 21:22:12 -0400 Subject: Is http://cheeseshop.python.org/pypi/ having issues In-Reply-To: <1175967418.642658.46930@l77g2000hsb.googlegroups.com> References: <1175967418.642658.46930@l77g2000hsb.googlegroups.com> Message-ID: RobJ wrote: > Has any one noticed any issues with http://cheeseshop.python.org/pypi/ > ? I have been trying for hours to install packages (using > easy_install) but the connection keeps timing out. > > Any Help would be a appreciated. > > Rob J > I'm having issues still. Wiki too From cam.ac.uk at mh391.invalid Tue Apr 24 15:18:46 2007 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Tue, 24 Apr 2007 20:18:46 +0100 Subject: Catching a specific IO error In-Reply-To: References: Message-ID: Steven Howe wrote: > Steve Holden wrote: >> Thomas Kr?ger wrote: >> >>> Tina I schrieb: >>> >>>> Now, this works but of course it catches every IOError, and I can not >>>> figure out how to restrict it to only catch the "[Errno 2]"? >>>> >>> There's an example that uses the error number: >>> http://docs.python.org/tut/node10.html#SECTION0010300000000000000000 >>> >>> >> So what you'll need to do is catch all IOError exceptions, then test >> to see if you've got (one of) the particular one(s) you are interested >> in. If not then you can re-raise the same error with a bare "raise" >> statement, and any containing exception handlers will be triggered. If >> there are none then you will see the familiar traceback termination >> message. >> >> regards >> Steve >> > you could also use some pre-testing of the filename os.path.isfile, > os.path.isdir, os.path.split are good > functions to test file/directory existence. Also to verify that you have > permission to manipulate a file, os.access is a good function. The try first approach is better for at least two reasons: 1) It saves you an extra stat() on the disk, which can be really important for some filesystems I use :) 2) It is atomic. If os.path.isfile() returns True but the file is deleted before you open it, you are still going to have to handle the exception. -- Michael Hoffman From nagle at animats.com Sun Apr 22 17:12:43 2007 From: nagle at animats.com (John Nagle) Date: Sun, 22 Apr 2007 21:12:43 GMT Subject: Python "robots.txt" parser broken since 2003 In-Reply-To: References: Message-ID: Steven Bethard wrote: > John Nagle wrote: > >> Terry Reedy wrote: >> >>> "John Nagle" wrote in message >>> news:FvtWh.11824$YL5.6282 at newssvr29.news.prodigy.net... >>> | This was reported in 2003, and a patch was uploaded in 2005, but >>> the patch >>> | never made it into Python 2.4 or 2.5. >>> >>> If the patch is still open, perhaps you could review it. >>> >> I tried it on Python 2.4 and it's in our production system now. >> But someone who regularly does check-ins should do this. > > > If you post such a review (even just the short sentence above) to the > patch tracker, it often increases the chance of someone committing the > patch. > > Steve OK, updated the tracker comments. John Nagle From steve at holdenweb.com Fri Apr 27 13:52:32 2007 From: steve at holdenweb.com (Steve Holden) Date: Fri, 27 Apr 2007 13:52:32 -0400 Subject: http pipelining In-Reply-To: References: Message-ID: swq22 at yahoo.com wrote: > Which python module is capable of pipelining http requests? > > (I know httplib can send mulitple requests per tcp connection, but in > a strictly serial way. ) > Oops, sorry, you meant sending requests in parallel, right? You'll need to use either urllib or urllib2 for the web, and the threading module is one way to run parallel requests. It's fairly easy to use as long as you keep your tasks properly isolated form each other. regards Steve -- Steve Holden +1 571 484 6266 +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 andre.roberge at gmail.com Sun Apr 29 19:32:20 2007 From: andre.roberge at gmail.com (=?iso-8859-1?B?QW5kcuk=?=) Date: 29 Apr 2007 16:32:20 -0700 Subject: Launching an independent Python program in a cross-platform way (including mac) Message-ID: <1177889540.489960.176380@u30g2000hsc.googlegroups.com> I would like to find out how I can launch an independent Python program from existing one in a cross-platform way. The result I am after is that a new terminal window should open (for io independent of the original script). The following seems to work correctly under Ubuntu and Windows ... but I haven't been able to find a way to make it work under Mac OS. def exec_external(code, path): """execute code in an external process currently works under: * Windows NT (tested) * GNOME (tested) [January 2nd and 15th change untested] This also needs to be implemented for OS X, KDE and some form of linux fallback (xterm?) """ if os.name == 'nt': current_dir = os.getcwd() target_dir, fname = os.path.split(path) filename = open(path, 'w') filename.write(code) filename.close() if os.name == 'nt': os.chdir(target_dir) # change dir so as to deal with paths that # include spaces Popen(["cmd.exe", ('/c start python %s'%fname)]) os.chdir(current_dir) elif os.name == 'posix': try: os.spawnlp(os.P_NOWAIT, 'gnome-terminal', 'gnome- terminal', '-x', 'python', '%s'%path) except: raise NotImplementedError else: raise NotImplementedError ========================== Any help would be greatly appreciated. Andr? From bruno.42.desthuilliers at wtf.websiteburo.oops.com Mon Apr 16 04:28:37 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Mon, 16 Apr 2007 10:28:37 +0200 Subject: File DB instead of real database? In-Reply-To: <1176524076.446204.70730@w1g2000hsg.googlegroups.com> References: <1176524076.446204.70730@w1g2000hsg.googlegroups.com> Message-ID: <462333b4$0$29859$426a74cc@news.free.fr> Jia Lu a e'crit : > Hello all > > I donot want to use a real DB like MySQL ... Whether MySQL is qualifies as a "real DB" is still an open question. But you can use SQLite, which is an embedded SQL database. From jzgoda at o2.usun.pl Wed Apr 4 17:33:14 2007 From: jzgoda at o2.usun.pl (Jarek Zgoda) Date: Wed, 04 Apr 2007 23:33:14 +0200 Subject: Why NOT only one class per file? In-Reply-To: <1175721799.714907.52770@o5g2000hsb.googlegroups.com> References: <1175721799.714907.52770@o5g2000hsb.googlegroups.com> Message-ID: Chris Lasher napisa?(a): > A friend of mine with a programming background in Java and Perl places > each class in its own separate file in . I informed him that keeping > all related classes together in a single file is more in the Python > idiom than one file per class. He asked why, and frankly, his valid > question has me flummoxed. > > I tried to rationalize this Python idiom by claiming a file--a single > module--makes for a great container of code which is logically tied > together, such as a class and its subclasses. He posited that > directories (packages) can tie the files together just as well, and by > having the classes as separate files, he can "diff" them to see how > they differ, something he wouldn't be able to do with the code all in > one file. I'd not try to rationalize it, it's just natural. The requirement to have only one public class per module needs rationalization (other than limitation of compiler), not the freedom to have as much of classes in module as is needed by program's architecure. -- Jarek Zgoda http://jpa.berlios.de/ From steve at holdenweb.com Fri Apr 27 12:08:11 2007 From: steve at holdenweb.com (Steve Holden) Date: Fri, 27 Apr 2007 12:08:11 -0400 Subject: editing scripts on a mac Message-ID: I am teaching someone Python by email, and part of our conversation recently ran as follows: him> How do I save a script and run it? me > Do you have a text editor? If so, edit the script in that, then save it me > in your home directory (the place you can see when you open the terminal him> I do not have a text editor, but here are the answers to him> questions 1-5. Now, frankly, I don't think this answer is correct, since I know OS X is a UNIX derivative, but I am loathe to involve a programming noob with vi or something similar. So I wondered if one of the c.l.py mac users could give brief instructions for firing up a visual text editor of some sort and saving a file somewhere it can easily be accessed from a terminal window (which I presume starts up in his home directory). regards Steve -- Steve Holden +1 571 484 6266 +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 holdenweb.com Wed Apr 25 10:09:30 2007 From: steve at holdenweb.com (Steve Holden) Date: Wed, 25 Apr 2007 10:09:30 -0400 Subject: Python un-plugging the Interpreter In-Reply-To: References: <1hwu415.1yyvbo61efn1uqN%aleax@mac.com> <1hx2dgy.zizz7ir95hlgN%aleax@mac.com> Message-ID: <462F611A.8000904@holdenweb.com> John Nagle wrote: > Alex Martelli wrote: >> Jorgen Grahn wrote: >> ... >> >>>> Perhaps the current wave of dual-core and quad-core CPUs in cheap >>>> consumer products would change people's perceptions -- I wonder... > >> IronPython would appear to be coming along nicely and getting acceptance >> in the Windows community, and I believe the underlying dotNet CLR does >> do threads nicely; we'll see what develops on that front, I guess. > > Thus we now have a demonstration that Python implementations need > not be as slow as CPython. And that Microsoft is beating open source > on Python. > Well, let's remember that a) IronPython was originally developed independently of Microsoft, and b) it's still open source or close to it (I.'m not familiar with the OSI's opinion on the license Microsoft use to distribute IronPython, but the fact it can be included in the FePy distribution bodes well). > Python as a language is in good shape. But the CPython > implementation is holding back progress. What we need are better > and faster implementations of the language we've got. > Hear, hear! > PyPy, ShedSkin, and Jython all were steps in the right > direction, but none had enough momentum to make it. > Jython hasn't had a release since 2002, ShedSkin is basically > one guy, and the EU pulled the plug on PyPy. > Hey there, loose talk costs lives, you know. That is a complete mischaracterization of the true position. Progress on Jython may not have been stellar, but it has occurred and is ongoing. Yes, Shedskin is "one guy", but so was Psyco and that was (and remains) a useful tool. As far as I am aware the PyPy project has come to the end of its initial EU funding, and they chose to focus on producing deliverables close to the end of the project phase rather that divert effort into securing ongoing funding. So nobody has "pulled the plug", and I believe there is every possibility of a further round of funded research and development in the future. Certainly the results to date would justify that action on the part of the EU. I don't know if and when the request for further funding will be submitted. > Now what? > Work continues. Rome wasn't built in a day, you know. regards Steve -- Steve Holden +1 571 484 6266 +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 collinstocks at gmail.com Sat Apr 21 10:34:52 2007 From: collinstocks at gmail.com (subscriber123) Date: 21 Apr 2007 07:34:52 -0700 Subject: Suggestion: str.itersplit() In-Reply-To: <1177160280.784224.53460@b58g2000hsg.googlegroups.com> References: <1177160280.784224.53460@b58g2000hsg.googlegroups.com> Message-ID: <1177166092.614602.81530@n59g2000hsh.googlegroups.com> On Apr 21, 8:58 am, Dustan wrote: > >From my searches here, there is no equivalent to java's > > StringTokenizer in python, which seems like a real shame to me. > > However, str.split() works just as well, except for the fact that it > creates it all at one go. I suggest an itersplit be introduced for > lazy evaluation, if you don't want to take up recourses, and it could > be used just like java's StringTokenizer. > > Comments? That would be good, because then you could iterate over strings the same way that you iterate over files: for line in string.itersplit("\n"): ## for block ## From rehceb at no.spam.plz Sun Apr 1 20:59:49 2007 From: rehceb at no.spam.plz (Rehceb Rotkiv) Date: Sun, 01 Apr 2007 19:59:49 -0500 Subject: Overlapping matches References: Message-ID: Both methods work well, thank you! From sjmachin at lexicon.net Sat Apr 7 22:42:46 2007 From: sjmachin at lexicon.net (John Machin) Date: 7 Apr 2007 19:42:46 -0700 Subject: beginner - py unicode Q In-Reply-To: <46182E68.34A35F01@braindead.com> References: <46182E68.34A35F01@braindead.com> Message-ID: <1176000166.218763.283980@q75g2000hsh.googlegroups.com> On Apr 8, 9:51 am, enquiring mind wrote: > I read the posting by Rehceb Rotkiv and response but don't know if it > relates to my problem in any way. > > I only want to write German to the screen/console for little German > programs/exercises in python. No file w/r will be used. > > #! /usr/bin/env python > # -*- coding: utf-8 -*- > # Filename: 7P07png.py > # SUSE Linux 10 Python 2.4.1 gedit 2.12.0 > > print 'Ich z?hle zw?lf wei? H?te.' > print 'Wollen Sie' > verbs = ( 'k?mmen' , 'essen' , 'trinken' ) > print verbs[:3] Note: the [:3] is redundant. "print verbs" would have the same effect. When you do print list_tuple_dict_etc, Python prints the repr() of each element. You are seeing repr('k?mmen'). This is great for debugging, to see exactly what you've got (\xc3\xb6 is the utf8 encoding for small o with diaeresis (aka umlaut)) but no so great for presentation to the user. To see the difference, insert here: for v in verbs: print v print str(v) print repr(v) > > print ' program ends ' > > console display is: Ich z?hle zw?lf wei? H?te. > Wollen Sie > ('k\xc3\xb6mmen', 'essen', 'trinken') > program ends > > The first 2 print statements in German print perfectly to screen/console > but not the 3rd. > > I ran it with these lines below from Rehceb Rotkiv's code but it did not > fix problem. > import sys > import codecs Importing modules without using them is pointless. > > I also tried unicode string u'k?mmen', but it did not fix problem. > Any help/direction would be appreciated. Thanks in advance. > > I found this reference section but I am not sure it applies or how to > use it to solve my problem.: It doesn't solve your problem. Forget you ever read it. > > This built in setdefaultencoding(name) sets the default codec used to > encode and decode Unicode and string objects (normally ascii)and is > meant to be called only from sitecustomize.py at program startup; the > site module them removes this attribute from sys. You can call > reload(sys) to make this attriute available again but this is not a good > programming practice. > > I just thought of this. I suppose because this is py source code, it > should not be German but a reference/key to u'strings' to print German > text to the screen? It's "German" only to a human who reads the console output and recognizes the bunches of characters as representing German words/ phrases/sentences. Python and your computer see only utf8 encoding (which can be used to represent multiple languages all at once on the same screen or in the same paragraph of a document). Your console is quite happy rendering utf8 e.g. it printed "Ich z?hle zw?lf wei? H?te" OK, didn't it? Try this: print "blahblah" print u"blahblah".encode('utf8') print u"blahblah" and see what happens. HTH, John From pythoncurious at gmail.com Tue Apr 17 11:16:54 2007 From: pythoncurious at gmail.com (pythoncurious at gmail.com) Date: 17 Apr 2007 08:16:54 -0700 Subject: C++ extension problem In-Reply-To: <4623EE59.7020800@v.loewis.de> References: <1176741526.541997.52100@e65g2000hsc.googlegroups.com> <4623EE59.7020800@v.loewis.de> Message-ID: <1176823014.623736.134960@l77g2000hsb.googlegroups.com> On Apr 16, 11:44 pm, "Martin v. L?wis" wrote: > > Now this is what confuses me: Why does it say that I have the wrong > > type when it's the same type as it suggests? > > When referring to the type, you must *always* form the address of the > type structure, including, but not limited to, the line > > > if (!PyArg_ParseTuple(args, "O!", SillyStringType, &o)) > > HTH, > Martin Yes, that did help. Thanks. I assumed that the compiler would warn me about that kind of problem, but I know better know. :) Still, the error message is somewhat confusing. From cam.ac.uk at mh391.invalid Thu Apr 26 07:36:48 2007 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Thu, 26 Apr 2007 12:36:48 +0100 Subject: Access to raw command line? In-Reply-To: <1177571070.229968.155710@t39g2000prd.googlegroups.com> References: <1177571070.229968.155710@t39g2000prd.googlegroups.com> Message-ID: Pieter Edelman wrote: > Hi, > > I'm currently writing a command-line program in Python, which takes > commands in the form of: > ./myprog.py [OPTIONS] ARGS > So pretty standard stuff. In my case, ARGS is a list of image files. > > One of the possible options is to specify a file holding information > about the photos. You'd specify it with (in this particular case) the - > t switch, and you can specify multiple files by repeating this switch: > ./myprog.py -t info1.gpx -t info2.gpx -t info3.gpx *jpg > > Now, one of the users has quite a lot of info files, and asked me if > it's possible to use a wildcard in specifying these, so he would just > have to do: > ./myprog.py -t *.gpx *.jpg > > This seems like a sensible option at first sight, but it's difficult > to implement because the wildcard is expanded by the shell, so > sys.argv gets a list containing "-t", all .gpx files and all .jpg > files. With this list, there's no way to tell which files belong to > the "-t" switch and which are arguments (other than using the > extension). > > One possible way to work around this is to get the raw command line > and do the shell expansions ourselves from within Python. Ignoring the > question of whether it is worth the trouble, does anybody know if it > is possible to obtain the raw (unexpanded) command line? > Alternatively, does anybody have suggestion of how to do this in a > clean way? One option would be to accept a directory argument to -t and to recursively inlcude all the gpx files in that directory. Another option would be to use some sort of optional separator, like ./myprog.py -t *.gpx -j *.jpg where everything between -t and -j would be considered a -t option. I think this breaks the usual UNIX options paradigm though. Of course UNIX itself does that--dd is an example of a program that doesn't follow it. Another option would be to accept a list of gpx files from a file: find . -name '*.gpx' > gpxlist.txt ./myprog.py --gpx-file=gpxlist.txt *.jpg Or to accept more than one file per argument: ./myprog.py -t "$(echo *.gpx)" *.jpg Personally I would prefer the file list approach. If you start expanding wildcards yourself, then if someone stupidly wants to use a wildcard character, they'll have to triple-escape things, and it'll just be messy. -- Michael Hoffman From rdm at rcblue.com Sat Apr 7 12:14:51 2007 From: rdm at rcblue.com (Dick Moores) Date: Sat, 07 Apr 2007 09:14:51 -0700 Subject: Saving output of Turtle Graphics? In-Reply-To: References: Message-ID: <20070407161455.7B3EC1E4009@bag.python.org> At 08:48 AM 4/7/2007, =?ISO-8859-2?Q?Wojciech_Mu=B3a?= wrote: >Dick Moores wrote: > >> Turtle module uses Tk canvas element to draw graphics ('_canvas' > >> attribute). I've written module, that exports canvas graphics to SVG > >> file: http://wmula.republika.pl/proj/canvas2svg/ -- it may be useful > >> for you. > > > > I afraid I'm totally unfamiliar with SVG. Would it be possible for you > > or someone else on the list to show how to use your module to export the > > simple product of this simple script to an SVG file? > > > > =============================================== > > import turtle as T >import canvasvg > > from random import randint > > T.setup(width=1000, height=700, startx=0, starty=0) > > T.color(1, .5, .5) > > T.begin_fill() > > # 2 connected lines will fill as a triangle > > for x in range(2): > > coord = (randint(-500,500), randint(-350,350)) > > T.goto(coord) > > T.end_fill() > >canvasvg.saveall("image.svg", T._canvas) > > > T.done() > > ================================================ OK, thanks, now I've got =========================================================== ============================================================ What do I do to see this? Dick From tjreedy at udel.edu Sat Apr 7 13:40:24 2007 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 7 Apr 2007 13:40:24 -0400 Subject: Checking whether list element exists References: Message-ID: "Rehceb Rotkiv" wrote in message news:pan.2007.04.07.15.25.04 at no.spam.plz... |I want to check whether, for example, the element myList[-3] exists. So | far I did it like this: | | index = -3 | if len(myList) >= abs(index): | print myList[index] # Note that tabs gets lost in some newsreaders. Spaces are better for posting A full test of the index, equivalent to the try below, is as follows: n = len(myList) if -n <= index < n # same as <= n-1, but avoids subtraction This works for empty lists also (-0 <= i < 0 is never true!). | Another idea I had was to (ab-?)use the try...except structure: | | index = -3 | try: | print myList[index] | except: | print "Does not exist!" Follow Gary Herron's comment on this. | Is it ok to use try...except for the test Both idioms are acceptible. Some people would chose based on whether they expect bad indexes to be a normal occurence or an exceptional occurrence. One rule-of-thumb division point is 10% frequency. More expensive tests would push this higher. Terry Jan Reedy From maxime.p at gmail.com Mon Apr 2 13:51:18 2007 From: maxime.p at gmail.com (Ulysse) Date: 2 Apr 2007 10:51:18 -0700 Subject: Launch script on Linux using Putty In-Reply-To: References: <1175467029.572354.138930@y66g2000hsf.googlegroups.com> Message-ID: <1175536278.510176.183360@l77g2000hsb.googlegroups.com> On Apr 2, 12:56 am, Michael Hoffman wrote: > Ulysse wrote: > > Hello, > > > I have a python script which runs all the time (using of library > > threading). I would like this scipt to run on a remote linux Os using > > Putty. The problem is, when I close Putty command line window running > > on my Win PC, the python script stops to run too. > > > I tried to use cron tables instead. By setting the time and restart > > cron process, but it's not practical. > > > Do you know the right way to do this ? > > There are a few ways to do this, in order of easiest to most involved: > > 1. The easiest is to run nohup on your script in the background: > > $ nohup myscript.py > output.txt 2> error.txt & > > Then you can disconnect but your script will keep running. Try man nohup > for more information. > > 2. Use GNU screen on your remote terminal, and detach the screen instead > of logging off. > > 3. Set up your script to fork as a daemon. Google for ["python cookbook" > fork daemon] to find a few recipes for this. > -- > Michael Hoffman Thanks a lot but in my situation : 1. nohup seems not to be installed on my "reduced linux distribution". It's a OpenWrt tunning on my WRT54GL Broadband router. 2. I have looked for the way I can "detach the screen" with Putty but I've not found (May be you can precise ?) 3. The "fork daemon" script found on http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/278731 seems to be as huge as my own script and little bit hard to undestand. So maybe "detach the screen" ? Thanks From grahn+nntp at snipabacken.dyndns.org Fri Apr 13 07:29:48 2007 From: grahn+nntp at snipabacken.dyndns.org (Jorgen Grahn) Date: 13 Apr 2007 11:29:48 GMT Subject: Shebang or Hashbang for modules or not? References: <1176308951.932721.197630@y80g2000hsf.googlegroups.com> <461d56e9$0$27586$426a74cc@news.free.fr> Message-ID: On 13 Apr 2007 10:54:18 GMT, Jorgen Grahn wrote: > On Thu, 12 Apr 2007 00:24:12 +0200, Bruno Desthuilliers wrote: >> Chris Lasher a ?crit : >>> Should a Python module not intended to be executed have shebang/ >>> hashbang (e.g., "#!/usr/bin/env python") or not? >> >> The shebang is only useful for files that you want to make directly >> executable on a *n*x system. They are useless on Windows, > > Probably (unless setup.py uses them for something meaningful there, > too). There's another, secondary, reason to use a shebang on Python source which isn't executable: the Unix file(1) command and friends can see that it's Python code. (Of course, such files will almost always be named foo.py.) /Jorgen -- // Jorgen Grahn R'lyeh wgah'nagl fhtagn! From nagle at animats.com Sat Apr 21 19:36:04 2007 From: nagle at animats.com (John Nagle) Date: Sat, 21 Apr 2007 23:36:04 GMT Subject: No speedup on multi-processor machine? In-Reply-To: <1177197885.077863.314470@n59g2000hsh.googlegroups.com> References: <1177189332.916296.205280@d57g2000hsg.googlegroups.com> <1177197885.077863.314470@n59g2000hsh.googlegroups.com> Message-ID: Caleb Hattingh wrote: > On Apr 21, 11:02 pm, danfan1... at yahoo.com wrote: > >>Hi, >>I am using Python Thread library for my parallel processing course >>project. I am doing matrix convolution on a multi-processor machine >>running Solaris. I just found out that no speed-up is obtained with >>threading. It is probably because of something called GIL in Python. >>How can I get around >>that GIL and get speed-up? >>Thanks in advance. >>Daniel If you're actually doing the convolution in Python, you need optimization before you need more CPUs. There's a numerics library for Python called NumPy, but it doesn't have a convolution function, although it has an FFT, which may be useful. But this is just homework. Do something reasonable and turn it in. A high performance solution to this problem is probably more work than it's worth. John Nagle From per9000 at gmail.com Thu Apr 12 03:18:19 2007 From: per9000 at gmail.com (per9000) Date: 12 Apr 2007 00:18:19 -0700 Subject: reaching hidden methods + casting Message-ID: <1176362298.986221.280520@n59g2000hsh.googlegroups.com> Hi, can I reach a hidden method when doing ugly inheritance in python? >>> class A: ... def spin(self, n): print "A", n ... >>> class B: ... def spin(self, m): print "B", m ... >>> class C(A,B): ... def spin(self, k): print "C", k ... >>> myC = C() >>> dir(myC) ['__doc__', '__module__', 'spin'] In f.x. the C-family of languages I guess something like this would call B.spin: ((B)myC).spin("Lancelot"); // almost forgot the ';' Please correct me I am wrong (which I likely am) but as I understand it this example calls the constructor of int instead of casting it, right? >>> leet = int('1337') >>> leet 1337 So is there another way of digging into the past of a class? Or can/ should I create constructors for the classes A, B and C that takes objects of the other classes? Or should I have thought about getting unique names before I implemented the ugly inheritance graph? /Per -- Per Erik Strandberg blog: http://www.pererikstrandberg.se/blog/ From ptmcg at austin.rr.com Wed Apr 25 21:57:38 2007 From: ptmcg at austin.rr.com (Paul McGuire) Date: 25 Apr 2007 18:57:38 -0700 Subject: Feedback on Until recipe In-Reply-To: <1177430903.027128.86480@o40g2000prh.googlegroups.com> References: <1177430903.027128.86480@o40g2000prh.googlegroups.com> Message-ID: <1177552658.029194.19710@u32g2000prd.googlegroups.com> On Apr 24, 11:08 am, Thomas Nelson wrote: > Occasionally someone posts to this group complaining about the lack of > "repeat ... until" in python. I too have occasionally wished for such > a construct, and after some thinking, I came up with the class below. > I'm hoping to get some feedback here, and if people besides me think > they might use it someday, I can put it on the python cookbook. I'm > pretty happy with it, the only ugly thing is you have to use a > lambda. Ideally i'd like to just see > while Until(i<3) > but that doesn't work. > Please tell me what you think, and thanks for your time. > > Tom > > class Until: > """ > >>> i = 0 > >>> while Until(lambda: i<3): > ... print "hello" > ... i += 1 > hello > hello > hello > >>> while Until(lambda: i<2): #note i still equals 3 here > ... print "hello" > hello > """ > yet = True > def __init__(self, mybool): > if self.__class__.yet or mybool(): > self.__class__.yet = False > self.ans = True > else: > self.__class__.yet = True > self.ans = False > > def __nonzero__(self): > return self.ans Class-level "yet" variable not a good idea. Loops can be nested: i = 0 # this should loop once, since test is logically at the end of the loop while Until(lambda : i < 0 ): print "hello" i += 1 j = 0 while Until(lambda : j < 0 ): print "byebye" j += 1 This loops forever. After tinkering with this a bit, I can see why you need a class variable. In your outer loop, "Until(lambda : i < 0)" is evaluated every time around the loop, creating a new Until object, so you can't preserve looping state in the object, you have to do it in the class. I used your idea to create an instance-level Until that survives looping, but the requirements for construction are still onerous. In essence, the instance-level util defers the break-on-condition by one loop iteration. class Until: """ >>> i = 0 >>> while Until(lambda: i<3): ... print "hello" ... i += 1 hello hello hello >>> while Until(lambda: i<2): ... print "hello" hello """ def __init__(self, mybool): self.lastTest = True self.mybool = mybool def __nonzero__(self): ret,self.lastTest = self.lastTest,self.mybool() return ret i = 0 uCond1 = Until(lambda : i < 0 ) uCond2 = Until(lambda : j < 0 ) while uCond1: print "hello" i += 1 j = 0 while uCond2: print "byebye" j += 1 -- Paul From robert.kern at gmail.com Thu Apr 12 16:44:03 2007 From: robert.kern at gmail.com (Robert Kern) Date: Thu, 12 Apr 2007 15:44:03 -0500 Subject: tuples, index method, Python's design In-Reply-To: References: Message-ID: Alan Isaac wrote: > I am still puzzled by this discussion. > > As I said: > I doubt that *anyone* who programs in Python > has not encountered the situation where they change > a tuple to a list *solely* for the purpose of getting > access to the index method. This suggests a missing > method, does it not? Who has not done this? > Name yourself! I'm pretty sure I've never done this either. -- 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 robert.kern at gmail.com Fri Apr 20 14:44:52 2007 From: robert.kern at gmail.com (Robert Kern) Date: Fri, 20 Apr 2007 13:44:52 -0500 Subject: matplotlib basic question In-Reply-To: References: <1177016327.543985.34500@o5g2000hsb.googlegroups.com> <1177092157.763869.77600@o5g2000hsb.googlegroups.com> Message-ID: Colin J. Williams wrote: > I'm not sure that scipy has been updated to Python 2.5 ? scipy certainly works with 2.5. Are you referring to something else perhaps? -- 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 gagsl-py2 at yahoo.com.ar Sun Apr 1 05:09:24 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sun, 01 Apr 2007 06:09:24 -0300 Subject: Character set woes with binary data References: <1175415685.21349.79.camel@pepper.trausch.us> Message-ID: En Sun, 01 Apr 2007 05:21:25 -0300, Michael B. Trausch escribi?: > I am attempting to piece together a Python client for Fotobilder, the > picture management server on Livejournal. > > The protocol calls for binary data to be transmitted, and I cannot seem > to be able to do it, because I get this error: > >>>> sb.UploadSinglePicture('/home/mbt/IMG_2618.JPG') > Traceback (most recent call last): > File "", line 1, in > File "scrapbook.py", line 181, in UploadSinglePicture > {Request['UploadPic.Meta.Filename']: pic_mem}) > File "scrapbook.py", line 237, in ComposeMIME > return(self.EncodeMIME(fields, files)) > File "scrapbook.py", line 226, in EncodeMIME > body = eol.join(L) > UnicodeDecodeError: 'ascii' codec can't decode byte 0xff in position 0: > ordinal not in range(128) >>>> What's scrapbook.py? Where do you find it? > When putting the MIME segments (listed line-by-line in a Python list) > together to transmit them. The files are typically JPG or some other > binary format, and as best as I understand the protocol, the binary data > needs to be transmitted directly (this is evidenced by looking at the > tcp-stream of an existing client for uploading files). But I think your problem has nothing to do with MIME: you are mixing unicode and string objects; from your traceback, either the "L" list or "eol" contain unicode objects that can't be represented as ASCII strings. > It seems that Python thinks it knows better than I do, though. I want > to send this binary data straightaway to the server. :-) You don't appear to be using the standard email package (which includes MIME support) so don't blame Python... -- Gabriel Genellina From zefria at gmail.com Sun Apr 15 15:00:15 2007 From: zefria at gmail.com (Daniel Gee) Date: 15 Apr 2007 12:00:15 -0700 Subject: is laziness a programer's virtue? In-Reply-To: <1176654319.273907.167280@q75g2000hsh.googlegroups.com> References: <1176654319.273907.167280@q75g2000hsh.googlegroups.com> Message-ID: <1176663615.592055.45720@l77g2000hsb.googlegroups.com> You fail to understand the difference between passive laziness and active laziness. Passive laziness is what most people have. It's active laziness that is the virtue. It's the desire to go out and / make sure/ that you can be lazy in the future by spending just a little time writing a script now. It's thinking about time economically and acting on it. From steven.bethard at gmail.com Tue Apr 3 14:11:48 2007 From: steven.bethard at gmail.com (Steven Bethard) Date: Tue, 03 Apr 2007 12:11:48 -0600 Subject: File Object behavior In-Reply-To: References: Message-ID: Michael Castleton wrote: > When I open a csv or txt file with: > > infile = open(sys.argv[1],'rb').readlines() > or > infile = open(sys.argv[1],'rb').read() > > and then look at the first few lines of the file there is a carriage return > + > line feed at the end of each line - \r\n > This is fine and somewhat expected. My problem comes from then writing > infile out to a new file with: > > outfile = open(sys.argv[2],'w') > outfile.writelines(infile) > outfile.close() > > at which point an additional carriage return is inserted to the end of each > line - \r\r\n Maybe because you're reading the file as binary ('rb') but writing it as text ('w'):: >>> open('temp.txt', 'w').write('hello\r\n') >>> open('temp.txt', 'rb').read() 'hello\r\r\n' >>> open('temp.txt', 'wb').write('hello\r\n') >>> open('temp.txt', 'rb').read() 'hello\r\n' >>> open('temp.txt', 'w').write('hello\r\n') >>> open('temp.txt', 'r').read() 'hello\r\n' Looks like if you match your writes and reads everything works out fine. STeVe From howachen at gmail.com Thu Apr 19 12:40:09 2007 From: howachen at gmail.com (howa) Date: 19 Apr 2007 09:40:09 -0700 Subject: Compiling python from soruce vs RPM ? In-Reply-To: <1176976152.885919.139080@n76g2000hsh.googlegroups.com> References: <1176911689.026633.230390@l77g2000hsb.googlegroups.com> <1176934250.650536.239040@p77g2000hsh.googlegroups.com> <1176950392.192425.90980@b58g2000hsg.googlegroups.com> <1176976152.885919.139080@n76g2000hsh.googlegroups.com> Message-ID: <1177000809.846880.323090@l77g2000hsb.googlegroups.com> On 4?19?, ??5?49?, Paul Boddie wrote: > On 19 Apr, 04:39, howa wrote: > > > > > One more question: > > > How to uninstall using the source package? > > > the source package doesn't come with `make uninstall`? > > Right. That's another pitfall of most source distributions (ie. the > Python sources from python.org) compared to system packages (ie. the > package built from a source RPM or equivalent system source package). > If you want a really quick solution to this which seems to work much > of the time, look at checkinstall: > > http://asic-linux.com.mx/~izto/checkinstall/ > > This tool will make system packages by taking control of the usual > build process, and you can then install and uninstall those system > packages. > > Paul but i have the source package being installed...so any method/script to remove them? since finally i want to install via RPM ... thanks anyway From surekap at gmail.com Sat Apr 21 23:13:44 2007 From: surekap at gmail.com (Prateek) Date: 21 Apr 2007 20:13:44 -0700 Subject: Support for new items in set type Message-ID: <1177211624.069474.3960@y5g2000hsa.googlegroups.com> I have a bit of a specialized request. I'm reading a table of strings (specifically fixed length 36 char uuids generated via uuid.uuid4() in the standard library) from a file and creating a set out of it. Then my program is free to make whatever modifications to this set. When I go back to save this set, I'd like to be able to only save the new items. Currently I am creating a copy of the set as soon as I load it and then when I go back to save it, i'm calculating the difference and saving just the difference. There are many problems with this approach so far: 1) Calculating the difference via the standard set implementation is not very scalable -> O(n) I presume 2) Maintaining a copy wastes memory 3) I don't have a good solution if I delete items from the set (calculating the difference will return an empty set but I need to actually delete stuff). I was thinking of writing a specialized set implementation (I have no idea how to start on this) which tracks new items (added after initialization) in a separate space and exposes a new API call which would enable me to directly get those values. This is kind of ugly and doesn't solve problem 3. I also thought of using a hastable but I'm storing many ( > 1 million) of these sets in the same file (most of them will be empty or contain just a few values but a few of them will be very large - excess of 10,000 items). The file is already separated into tablespaces. Does anyone have any ideas? Thanks in advance. Prateek PS: Yes - I need blazing fast performance - simply pickling/unpickling won't do. Memory constraints are important but definitely secondary. Disk space constraints are not very important. From tjreedy at udel.edu Sun Apr 22 00:51:39 2007 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 22 Apr 2007 00:51:39 -0400 Subject: Python "robots.txt" parser broken since 2003 References: Message-ID: "John Nagle" wrote in message news:FvtWh.11824$YL5.6282 at newssvr29.news.prodigy.net... | This was reported in 2003, and a patch was uploaded in 2005, but the patch | never made it into Python 2.4 or 2.5. If the patch is still open, perhaps you could review it. tjr From titogarcia_nospamplease_ at gmail.com Mon Apr 2 09:20:55 2007 From: titogarcia_nospamplease_ at gmail.com (=?ISO-8859-1?Q?Ernesto_Garc=EDa_Garc=EDa?=) Date: Mon, 02 Apr 2007 15:20:55 +0200 Subject: Cascading ifs Message-ID: Hi experts, How would you do this without the more and more indenting cascade of ifs?: match = my_regex.search(line) if match: doSomething(line) else: match = my_regex2.search(line) if match: doSomething2(line) else: match = my_regex3.search(line) if match: doSomething3(line) etc. Thanks in advance and regards, Ernesto From gagsl-py2 at yahoo.com.ar Thu Apr 12 15:31:59 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 12 Apr 2007 16:31:59 -0300 Subject: wrap_EncryptByteArray argument 1 must be string without null bytes, not str References: <1176401490.277552.318630@q75g2000hsh.googlegroups.com> Message-ID: En Thu, 12 Apr 2007 15:11:30 -0300, abcd escribi?: > Has anyone seen this error before: > > wrap_EncryptByteArray() argument 1 must be string without null bytes, > not str > > I am having a hard time finding anything about it. I have no idea what wrap_EncryptByteArray does, but it appears to be a C function expecting a C NUL-terminated string, and got a string with embedded zeros in it. Forcing my crystall ball range, that name ...ByteArray implies that it should handle NULs OK, so the error may come from a wrong Python wrapper. Maybe it's using "s" format instead of "s#" in PyArg_Parse, but that is absolutely out of range for my limited crystall ball, sorry. -- Gabriel Genellina From stj911 at rock.com Fri Apr 6 12:47:32 2007 From: stj911 at rock.com (stj911 at rock.com) Date: 6 Apr 2007 09:47:32 -0700 Subject: The news that your govt wants you not to see: http://www.linktv.org/mosaic/streamsArchive/index.php4?episode_date=20070405 Re: *** It is IMPOSSIBLE to create a RABBIT FARM using the hat a MAGICIAN pulls a rabbit out of *** In-Reply-To: <1175713650.228538.165920@p77g2000hsh.googlegroups.com> References: <1175713650.228538.165920@p77g2000hsh.googlegroups.com> Message-ID: <1175878052.842166.224820@o5g2000hsb.googlegroups.com> http://www.linktv.org/mosaic/streamsArchive/index.php4?episode_date=20070405 Bookmark it. and to avoid a little form to submit, just remember this URL and change the date 20070405 20070406 .............. On Apr 4, 12:07 pm, stj... at rock.com wrote: > Please visitwww.nkusa.org,www.911blogger.com,www.stj911.org: > > I am surprised at the number of un-informed, ill-informed sheeple on > earth as well as politically correct hypocrites. > > Several polls have consistently shown that about 84% of the American > people believe that 911 was an inside job. The fact is the 911 was a > RACIST AND HEINOUS CRIME by a group of criminal and racist Americans > themselves. There is no video that Federal Bureau of Incompetence > could produce of plane hitting the Pentagon. On the contrary, they > acted as Foolish PATSIES for the criminal operators of 911 by > confiscating and destroying all other camera footage from buildings > around Pentagon. Next, WTC7 just committed suicide. Thermate residue > has been found as finger print left by the criminals. Please visit > 911blogger.com, st911.org and many other sites. > > 911 official story is a forgery like the protocols of the learned > elders of zion. It is as fake as a magician pulling a rabbit out of > his hat, and does that mean you can have a rabbit farm from that hat? > I cant believe how many idiots that we have. > > And the most interesting thing is that most lead researchers of the > movement are either Christian or Jewish. The MIT engineer, Jeff King > does not sound like an Arab name. > > Now what is the connection with Europe? Note the very first post in > this discussion starts with Islamophobia. Its probably a patsy of the > criminal cabal that pulled off 911. We have a strong feeling that > almost ALL THE INTELLIGENCE CHIEFS of EUROPE knew instantly that 911 > was a fraud. President Putin himself had carried out such a false flag > operation based on blowing Moscow apartment buildings to enter the > second Chechen war. > > Jon Carlson has written an excellent investigative piece entitled > "Russia Watched 9/11 In Real Time On Satellite" which you can find via > google using these clues. > > Racists of Europe, such as in France, Holland were immediately ready > to take full advantage of 911 hoax. India, immediately understood that > 911 was a hoax and staged its own fake terrorist attacks to harass > Pakistan. Bush used it to harass Pakistan into submitting the father > of their nuclear bomb, Dr Abdul Qadeer Khan to CIA interrogation. > There was another goal of 911. Scare Muslim leader into becoming > patsies to destroy their society from within. Once it is internally > weak, then a stone can be shattered by one blow. Iraq was thus first > weakened by sanctions, and then attack to shatter it. > > By God, they will not succeed. Elohim has power over all things. The > universe has hidden dimension and God watches everything from there. > That is what is happening. They can conspire but they will be > defeated. All those who have died in Iraq from crimes are going to go > to heaven. All the Americans who have committed atrocities will go to > hell. All Americans or Iraqis who will do good deeds will be judged > accordingly. God has absolutely no partiality towards any religion or > race. > > You are seeing events move extremely fast. > > Iran has brought UK to a stalemate. Hezbollah has essentially defeated > Israel, in the sense that the latter has failed to obtain its > objectives of the war. The racist and heinous crime of the 911 > operators has been exposed. This is the lynchpin from which will > follow a large change in the world, but not in the way the 911 > operators of controlled demolition intended, but totally opposite. The > wife cheaters, the newt gingrichs, the pedophiles reagans herbert > bush, as in the video "conspiracy of silence" where FBI criminals > tried to criminally coverup is now exposed. This is never going to go > away. The video evidence is far and wide dispersed on earth and > archived. > > The true believers from all faiths have joined hands and will not be > divided by pedophile, sex crazed, wife cheaters and genocidal > murderers and their deception and lies based on psychological tactics > of Edward Bernays. > > I ask you all for a moment of silence in the honor of 911 truth > movement people, Alex Jones, Dr Steven Jones, Dr Fetzer, Dr Jeff King > and many others I am failing to mention but God knows them and their > reward is with Him. From aleax at mac.com Sat Apr 28 21:01:45 2007 From: aleax at mac.com (Alex Martelli) Date: Sat, 28 Apr 2007 18:01:45 -0700 Subject: Numbers and truth values References: <1hxa95b.13zrrmv1wucw71N%aleax@mac.com> Message-ID: <1hxakko.1fyi3we13mgvo9N%aleax@mac.com> Szabolcs wrote: > But I still think that it is an inconsistency to allow to redefine a > _value_ like True or False (not a built-in function that may have been > missing in earlier versions). Saying True = 2 is just like saying 3 = 2. True and False were *ALSO* missing in earlier versions of Python (2.2.1 and back -- they were introduced in 2.2.2, smack in the middle of a minor release cycle, a release engineering error which Guido has vowed never to repeat). There's a lot of code around that starts with False = 0 True = not False (or similar), so it can run just as well on (e.g) 2.2.1 (and earlier) as 2.2.2 (and later) -- breaking all of that code which always worked fine is a decision not to be taken as lightly as you appear to imply. Alex From irstas at gmail.com Mon Apr 2 15:56:17 2007 From: irstas at gmail.com (irstas at gmail.com) Date: 2 Apr 2007 12:56:17 -0700 Subject: How do you escape % when formatting a string? In-Reply-To: <1175543551.433867.223590@p15g2000hsd.googlegroups.com> References: <1175543459.131630.96650@y80g2000hsf.googlegroups.com> <1175543551.433867.223590@p15g2000hsd.googlegroups.com> Message-ID: <1175543777.721294.64590@b75g2000hsg.googlegroups.com> On Apr 2, 10:52 pm, irs... at gmail.com wrote: > On Apr 2, 10:50 pm, "erikcw" wrote: > > > Hi, > > > I'm trying to format a string like so: > > > string = "You have a 75% chance of success with %s, don't use %s" %(a, > > b) > > > This gives me: > > TypeError: not enough arguments for format string > > > I've tried 75\%, but that doesn't seem to help. What am I missing? > > > Thanks! > > Erik > > Use %%. > > >>> "%d%%" % 75 > > "75" Oups, I made a typo in the result which should've been "75%" From __peter__ at web.de Mon Apr 23 02:07:14 2007 From: __peter__ at web.de (Peter Otten) Date: Mon, 23 Apr 2007 08:07:14 +0200 Subject: Namespaces/introspection: collecting sql strings for validation References: <1921780.hifcbgjtIO@beaureve.gmx.net> <2075208.bSjua6qmHG@beaureve.gmx.net> Message-ID: Martin Drautzburg wrote: > > def SQL(sql, checked=set()): > >?????if?sql?in?checked: > >?????????return?True > >?????if?not?valid_sql(sql):?raise?ValueError > >?????checked.add(sql) > >?????return?sql > > No this does not do the trick. I will not be able to validate an sql > statement bofore I run over the piece of code that uses it. Or I would > have to define all my sql = SQL stuff on module level, isn't id. I > mean, the problem is: when are those sql = SQL statement really > ececuted? Let's see: >>> def SQL(sql): ... print sql ... >>> a = SQL("module") module # that one was obvious >>> class A: ... b = SQL("class") ... def method(self, c=SQL("default arg")): ... d = SQL("method") ... class # ha, class statements are executed, too... default arg # ...as are default arguments Peter From KDawg44 at gmail.com Tue Apr 10 11:37:43 2007 From: KDawg44 at gmail.com (KDawg44) Date: 10 Apr 2007 08:37:43 -0700 Subject: Parsing log in SQL DB to change IPs to hostnames Message-ID: <1176219463.407804.315560@y80g2000hsf.googlegroups.com> Hi, I am brand new to Python. In learning anything, I find it useful to actually try to write a useful program to try to tackle an actual problem. I have a syslog server and I would like to parse the syslog messages and try to change any ips to resolved hostnames. Unfortunately, I am not getting any matches on my regular expression. A message will look something like this: Apr 10 2007 00:30:58 DEVICE : %DEVICEINFO: 1.1.1.1 Accessed URL 10.10.10.10:/folder/folder/page.html I would like to change the message to have the hostnames, or even better actually, have it appear as hostname-ip address. So a changed message would look like: Apr 10 2007 00:30:58 DEVICE : %DEVICEINFO: pcname-1.1.1.1 Accessed URL www.asite.com-10.10.10.10:/folder/folder/page.html or some equivalent. Here is what i have so far. Please be kind as it is my first python program.... :) #! /usr/bin/python import socket import re import string import MySQLdb ipRegExC = r"\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}" ipRegEx = re.compile(ipRegExC) try: conn = MySQLdb.connect(host="REMOVED", user="REMOVED", passwd="REMOVED", db="REMOVED") except MySQLdb.Error, e: print "Error connecting to the database: %d - %s " % (e.args[0], e.args[1]) sys.exit(1) cursor = conn.cursor() cursor.execute("SELECT msg, seq FROM `logs` WHERE seq = 507702") # one specific message so that it doesn't parse the whole DB during testing... while(1): row = cursor.fetchone() if row == None: break if ipRegEx.match(row[0]): print "regex match!" + ipRegEx.match(row[0]) # does not make it here..... newMsg = ipRegEx.sub(query(ipRegEx.match(row[0])), row[0]) if newMsg != 0: cursor.execute("" "UPDATE logs SET msg = %s WHERE seq = &d""", (newMsg,row[1])) def query(ipAddress): try: return socket.gethostbyaddr(ipAddress)[0] except: return 0 This is built to sub the name... I would like to change it to the hsotname-ipaddress instead since ip's can resolve to many hostnames.... it runs but does not pass the if statements so it quietly does absolutely nothing.... :) Thanks so much for any advice.... From steve at holdenweb.com Mon Apr 23 14:41:43 2007 From: steve at holdenweb.com (Steve Holden) Date: Mon, 23 Apr 2007 14:41:43 -0400 Subject: Socket exceptions aren't in the standard exception hierarchy In-Reply-To: References: Message-ID: John Nagle wrote: > Dennis Lee Bieber wrote: >> On Sun, 22 Apr 2007 23:20:25 -0700, John Nagle >> declaimed the following in comp.lang.python: >> >> >>> 2. File "D:\Python24\lib\socket.py", line 295, in read >>> data = self._sock.recv(recv_size) >>> error: (10054, 'Connection reset by peer') >>> >> That looks like M$ Windows version of UNIX/Linux error number 54 >> (pretty much all Windows socket errors are UNIX number+10000) >> >> Errors coming from Windows may not be mapped to specific Python >> exceptions, but rather to some general error conditions. {hypothesis} As >> such, the Windows errors may not match what UNIX/Linux report. > > Actually, that's not what's happening. The socket module is > explicitly raising "socket.error" in C code. It's not an OSError or > a WindowsError, although the text makes it look like one. > > The problem is not that socket errors aren't entirely portable. > It's that they're not even in the Python exception hierarchy. > See "http://docs.python.org/lib/module-exceptions.html". > They have their own hierarchy, which starts at "socket.error". > All built-in exceptions were supposed to be converted to the > standard exception hierarchy back before Python 2.0, but these > weren't. > > Either they should be under IOError, or there should be > "NetworkError" under EnvironmentError, and they should be under > that. "NetworkError", alongside IOError in the hierarchy, > would be useful. All the things that go wrong in networking > belong under there. Socket-level errors, SSL/TLS-level errors, > and HTTP/FTP/etc. level errors all belong under NetworkError. > > This has to be fixed before PEP 352, when the exception > hierarchy is enforced, or the socket exceptions won't even work > right. > John: Where did you get this information? If true it would certainly need to be logged as a bug, but under Windows on 2,4 I see >>> issubclass(socket.gaierror, Exception) True >>> and the same under Cygwin 2.5. I am presuming most other users will see the same thing. regards Steve -- Steve Holden +1 571 484 6266 +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 lycka at carmen.se Fri Apr 20 09:12:10 2007 From: lycka at carmen.se (Magnus Lycka) Date: Fri, 20 Apr 2007 15:12:10 +0200 Subject: Future Python Gui? In-Reply-To: References: <1176859699.906386.326720@b75g2000hsg.googlegroups.com> <1176863948.526051.186210@n76g2000hsh.googlegroups.com> <1176909848.455264.174730@e65g2000hsc.googlegroups.com> Message-ID: <4628BC2A.6060407@carmen.se> Jarek Zgoda wrote: > I am not a hacker, just a software developer, but I'd have no problems > in either installing PyGTK on Ubuntu box (sudo apt-get install > python-gtk2, but it's installed by default anyway) or on Windows XP > machine (double click on installer icon). "Simple user" is not an idiot > either and if she can read English, she wouldn't have hard time too. > > The rumours on "problems installing GUI toolkits" are greatly exagerated > IMO. It might not be a big deal for your own computer, but if you are distributing software professionally to a bunch of customers, things get more complex. Let's say your customers use RHEL4 for instance. If you would like to use a recent PyGTK, this means that the GTK libs in RHEL4 aren't new enough. Upgrading GTK will force you to upgrade a bunch of other libraries as well. That means that the system will no longer be the vanilla RHEL4 with your additions. Bugs might pop up in other applications on the system than yours, because they assumed other versions of shared objects. You can (perhaps) install the newer versions of the libs in non-standard locations and set LD_LIBRARY_PATH to that location for your program, but that means that things brake fairly easy, and if you for instance have a larger system, where Python scripts relying on this new PyGTK are started from a Python interpreter embedded in some big application, this big application will also see the newer versions of all those shared objects that PyGKT pulled in. Unless you are very careful, other programs that you start up from within your application (maybe it's possible to spawn a new shell from your app with the embedded Python interpreter and start arbitrary applications from there) will also get the non-standard shared objects. If you just install the shared objects the new PyGTK rely on in the standard locations, you have probably removed security patches and bug fixes added to the software by Red Hat from the system. Any application might cease to work, and the customer might have problem getting support from Red Hat on the system. You might end up with a lot more support and maintenance work than intended, or get very unhappy customers. Now imagine that you have half a dozen other platforms besides RHEL4 on x86_64 that you need to support... This is a problem you need to deal with if you develop software for Unix. It's not impossible to solve all these problems, but there is certainly a cost in this. If you handle it well, there is a cost in testing and adapting the systems. If you don't handle it well, there might be a big cost in handling emergencies and dealing with unhappy customers or users. From justin.mailinglists at gmail.com Wed Apr 11 06:29:29 2007 From: justin.mailinglists at gmail.com (Justin Ezequiel) Date: 11 Apr 2007 03:29:29 -0700 Subject: UDT wrappers Message-ID: <1176287369.307707.94310@d57g2000hsg.googlegroups.com> Found a couple of papers that mention Python wrappers for UDT have been written but Google fails me. Do any of you know of such wrappers? Have downloaded UDT SDK but source is in C++. http://udt.sourceforge.net/ From fsckedagain at gmail.com Wed Apr 11 16:24:31 2007 From: fsckedagain at gmail.com (fscked) Date: 11 Apr 2007 13:24:31 -0700 Subject: ValueError: too many values to unpack In-Reply-To: <1176322478.868786.214270@o5g2000hsb.googlegroups.com> References: <1176311618.617765.120560@p77g2000hsh.googlegroups.com> <1176319688.666986.183980@o5g2000hsb.googlegroups.com> <1176322478.868786.214270@o5g2000hsb.googlegroups.com> Message-ID: <1176323071.245392.165910@b75g2000hsg.googlegroups.com> You guys have given me some great ideas, I am going to try them all out and let you guys know how it turns out. On a side note, thanks for nto bashing a noob like me who isn't the greatest pythonista around. I am trying to learn and you guys are how I learn my mistakes. Well you, and the fact the stuff occasionally doesn't work. :) Thanks again and I will report back in a couple hours (meetings). From antroy at gmail.com Wed Apr 25 06:14:38 2007 From: antroy at gmail.com (Ant) Date: 25 Apr 2007 03:14:38 -0700 Subject: Tutorial creates confusion about slices In-Reply-To: References: Message-ID: <1177496078.319400.324720@r30g2000prh.googlegroups.com> On Apr 23, 1:38 pm, Antoon Pardon wrote: > The following is part of the explanation on slices in the > tutorial: > > The best way to remember how slices work is to think of the indices as ... > +---+---+---+---+---+ > | H | e | l | p | A | > +---+---+---+---+---+ > 0 1 2 3 4 5 > -5 -4 -3 -2 -1 For a tutorial this is sound advice. A tutorial is designed to give readers an easy intro to a topic, which is what this achieves. At this stage the target audience has no idea that extended slices even exist, let alone that you can use negative indices with them. > This is all very well with a simple slice like: > > "HelpA"[2:4] => "lp" > > But it give the wrong idea when using the following extended slice: > > "HelpA"[4:2:-1] => "Ap" But that is fine. Extended slice notation (let alone using negative indices) is beyond the scope of the tutorial. Once you start to experiment with extended slices, it is time to look beyond the simplified tutorial information, and to the official documentation in the Library and Language references. The library docs (http:// docs.python.org/lib/typesseq.html) say this: (5) The slice of s from i to j with step k is defined as the sequence of items with index x = i + n*k such that 0 <= n < (j-i/k) Which is exactly how it works, and describes exactly why your extended slice example works as it does. From robert.rawlins at thinkbluemedia.co.uk Mon Apr 30 06:12:54 2007 From: robert.rawlins at thinkbluemedia.co.uk (Robert Rawlins - Think Blue) Date: Mon, 30 Apr 2007 11:12:54 +0100 Subject: Dict Copy & Compare In-Reply-To: <4635B38E.5020606@timgolden.me.uk> References: <00da01c78b01$3e80b900$bb822b00$@rawlins@thinkbluemedia.co.uk> <4635AB95.4010309@timgolden.me.uk> <000601c78b06$b9fb0950$2df11bf0$@rawlins@thinkbluemedia.co.uk> <4635B38E.5020606@timgolden.me.uk> Message-ID: <000701c78b10$1e8aa9d0$5b9ffd70$@rawlins@thinkbluemedia.co.uk> Hello Tim, Sorry, that 'value' was a slip up on my part, we're just dealing with keys here. I get that a dict stores unique keys only but we're comparing the two dicts, so when I say 'unique keys in dict 1' I basically mean all those keys that are in dict one but not in dict 2. So imagine my 2 dicts with the following keys. Dict 1 Dict 2 ------ ------- 00:00:00:00 00:00:00:00 11:11:11:11 11:11:11:11 22:22:22:22 33:33:33:33 44:44:44:44 44:44:44:44 55:55:55:55 Now, 22:22:22:22 and 55:55:55:55 is unique to dict one, and 33:33:33:33 is unique to dict 2, does that make sense? Sorry for not explaining this stuff very well, being so new to dicts its easy to get confused with my terms. I then want to pass those keys as a string value into my function as an argument, like. thisFunction('22:22:22:22') thisFunction('55:55:55:55') thatFunction('33:33:33:33') I'm hoping that your method will work for me, I've just got to spend my time understanding what each step of it does. Thanks again for all your help Tim, Rob -----Original Message----- From: python-list-bounces+robert.rawlins=thinkbluemedia.co.uk at python.org [mailto:python-list-bounces+robert.rawlins=thinkbluemedia.co.uk at python.org] On Behalf Of Tim Golden Sent: 30 April 2007 10:15 Cc: python-list at python.org Subject: Re: Dict Copy & Compare Robert Rawlins - Think Blue wrote: > I have two dicts, one named 'this' and the other named 'that'. > > I want to get all the unique keys from 'this' and log them into a file, I > then want to take all the unique values from 'that' and log them into a > separate file. Couple of points which are confusing me: 1) Any dict can *only* have unique keys, ie you can't have a key appearing more than once in a dictionary by definition. 2) You speak of unique keys in "this" but unique values in "that". Is that deliberate on your part? Might be, but I'm not quite clear. > I have functions set up for the logging, so I can call it like > logThis(uniquekey) and logThat(uniquekey). Here you refer to "uniquekey" in both cases, so maybe a mistake above? > So it's just a case of firstly returning a list of all keys that are in > 'this' but NOT in 'that' and then visa versa, then loop over them performing > the function. OK, well following by example earlier: d1 = dict (a=1, b=2, c=3) d2 = dict (b=4, c=5, d=6) s1 = set (d1) # => set of 'a', 'b', 'c' s2 = set (d2) # => set of 'b', 'c', 'd' s1_not_in_s2 = s1 - s2 # => set of 'a' s2_not_in_s1 = s2 - s1 # => set of 'd' for key in s1_not_in_s2: print key, "=>", d1[key] for key in s2_not_in_s1: print key, "=>", d2[key] Obviously there are more concise ways of representing this; I'm just spelling the whole thing out to make it clearer (I hope). If this approach seems fruitful, have a look at the set typeit's a recentish addition to Python but very useful for this kind of thing: http://docs.python.org/lib/types-set.html TJG -- http://mail.python.org/mailman/listinfo/python-list From sjmachin at lexicon.net Wed Apr 11 17:11:08 2007 From: sjmachin at lexicon.net (John Machin) Date: 11 Apr 2007 14:11:08 -0700 Subject: text file vs. cPickle vs sqlite a design question In-Reply-To: <461d4561$0$6091$426a34cc@news.free.fr> References: <461d4561$0$6091$426a34cc@news.free.fr> Message-ID: <1176325868.370542.21160@o5g2000hsb.googlegroups.com> On Apr 12, 7:09 am, Bruno Desthuilliers wrote: > Dag a ?crit : > > > > > I have an application which works with lists of tuples of the form > > (id_nr,'text','more text',1 or 0). I'll have maybe 20-50 or so of these > > lists containing anywhere from 3 to over 30000 tuples. The actions I > > need to do is either append a new tuple to the end of the list, display > > all the tuples or display all the tuples where the last element is a 1 > > > Basically what I'm wondering is the best way to store these data stuctures > > to disc. As the subject mentioned I've basically got three approaches. > > Store each list as a text file, pickle each list to file or shove the > > whole thing into a bunch of database tables. I can see pros and cons > > with each approach. Does anybody have any advice as to whether any of > > these approaches is obviously better than any other? On one hand I like > > the text file approach since it lets me append without loading > > everything into memory, on the other hand the sqlite approach makes it > > easy to select stuff with SELECT * FROM foo WHERE... which could be > > handy if ever need to add more advanced filtering. s/if/when/ > > Given your specs, I'd go for SQLite without any hesitation. Your data > structure is obviously relational (a list of tuples is a pretty good > definition of a relation), so a relational DBMS is the obvious solution, > and you'll get lots of other benefits from it (SQL being only one of > them - you can also think about free optimization, scalability, and > interoperability). And if you don't like raw SQL and prefer something > more pythonic, then you have SQLAlchemy and Elixir. > > My 2 cents... ... and a few more cents: There are *two* relations/tables involved (at least): a "tuple" table and a "list" table. The 20-50 or so lists need a unique name or number each, and other attributes of a list are sure to come out of the woodwork later. Each tuple will need a column containing the ID of the list it belongs to. It's a bit boggling that (1) each tuple has an id_nr but there's no requirement to query on it (2) req. only to "append" new tuples w/o checking id_nr already exists (3) req. to "display" all of 30,000 tuples ... From steve at holdenweb.com Thu Apr 19 08:18:30 2007 From: steve at holdenweb.com (Steve Holden) Date: Thu, 19 Apr 2007 08:18:30 -0400 Subject: comparison with None In-Reply-To: <462709FB.9020607@gmail.com> References: <_JAVh.1700$jR5.897@trnddc08> <462709FB.9020607@gmail.com> Message-ID: Steven Howe wrote: > Alan Isaac wrote: [type comparison stuff] > I love scripting languages ... but sometimes an explicit evaluation that > one would find in > a compiled language is better. "better" in what sense? > Which is why I suggested using the explicit type(x) == types.NoneType as > opposed to > x is None > > This seems to go entirely against the spirit of the language. It's about as sensible as writing (3 > 4) == True The language *guarantees* that there is only one instance of types.NoneType, so why not just test for it directly? Among other things this avoids the need for an explicit import of the types library just so you can access the namespace. For extra marks, please explain why you prefer type(x) == type(None) # or types.NoneType to type(x) is type(None) The canonical test is, as has already been explained, x is None and to use anything else hinders the readability of your code. 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 Fri Apr 13 16:45:50 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: 13 Apr 2007 13:45:50 -0700 Subject: function/method assigment In-Reply-To: <1176480852.643836.121930@p77g2000hsh.googlegroups.com> References: <1176480852.643836.121930@p77g2000hsh.googlegroups.com> Message-ID: <1176497150.163519.244420@d57g2000hsg.googlegroups.com> On Apr 13, 10:14 am, viscr... at gmail.com wrote: > what is the > meaning of 'None'? > It's a value just like any other python value: 2, 7.5, "red", and it evaluates to false in a conditional: my_var = None if not my_var: print "bad data" From ianare at gmail.com Fri Apr 6 14:44:34 2007 From: ianare at gmail.com (=?iso-8859-1?B?aWFuYXLp?=) Date: 6 Apr 2007 11:44:34 -0700 Subject: real time updating of popen, bufsize=0 problems Message-ID: <1175885074.694737.261430@e65g2000hsc.googlegroups.com> hey all, I'm trying to get real time updates of batch file output. Here is my batch file: @echo off echo 1 @ping 127.0.0.1 -n 2 -w 1500 > nul echo 2 @ping 127.0.0.1 -n 2 -w 1500 > nul echo 3 If I run it in cmd.exe it will print "1", wait 15sec, print "2", wait 15sec, print "3". I tried doing it like this: r, w, e = popen2.popen3('"C:/path/to/test.bat"',bufsize=0) for line in r: self.display.WriteText(line) ... but get: ValueError: popen3() arg 3 must be -1 If I use -1, then it waits for the batch file to complete, and prints out all 3 lines at once. So I tried subprocess: proc = subprocess.Popen('"C:/path/to/test.bat"', bufsize=0, stdout=subprocess.PIPE) for line in proc.stdout: self.display.WriteText(line) No error message, but no real time printing either. info: self.display is a wx.TextCtrl - not that it should matter,as 'WriteText()' behaves basically like 'print' winXP pro SP2, python 2.5, wxPython 2.6.3.3 You help is appreciated. From cook_jim at yahoo.com Mon Apr 9 09:19:12 2007 From: cook_jim at yahoo.com (Jim) Date: 9 Apr 2007 06:19:12 -0700 Subject: Database in memory Message-ID: <1176124752.172926.129850@w1g2000hsg.googlegroups.com> I have an application that will maintain an in-memory database in the form of a list of lists. Does anyone know of a way to search for and retreive "records" from such a structure? Many thanks, bootkey From scott.daniels at acm.org Thu Apr 19 09:03:47 2007 From: scott.daniels at acm.org (Scott David Daniels) Date: Thu, 19 Apr 2007 06:03:47 -0700 Subject: Question about Tkinter MenuOption variable In-Reply-To: <1176968589.524252.70540@b58g2000hsg.googlegroups.com> References: <1176955769.756104.59440@y80g2000hsf.googlegroups.com> <1176968589.524252.70540@b58g2000hsg.googlegroups.com> Message-ID: <132eq45astuf0e0@corp.supernews.com> Rob Wolfe wrote: > Chad wrote: >> ... I have a menu option(code is below).... I would like to have >> corresponding values of 01, 02, 03 and so on.... > > What about using dictionary? For example: .... > OPTIONS = dict(Jan=1, Feb=2, Mar=3, Apr=4, May=5, June=6, July=7, > Aug=8, Sep=9, Oct=10, Nov=11, Dec=12) > # or > #OPTIONS = dict(Jan="01", Feb="02", Mar="03", Apr="04", May="05", > June="06", July="07", > # Aug="08", Sep="09", Oct="10", Nov="11", Dec="12") or OPTIONS = dict((m, n + 1) for n, m in enumerate( 'Jan Feb Mar Apr May June July Aug Sep Oct Nov Dec'.split())) -- --Scott David Daniels scott.daniels at acm.org From timr at probo.com Thu Apr 19 02:21:57 2007 From: timr at probo.com (Tim Roberts) Date: Thu, 19 Apr 2007 06:21:57 GMT Subject: How to communicate via USB "port" References: <1176875664.555559.259840@y80g2000hsf.googlegroups.com> Message-ID: "robinp.la at gmail.com" wrote: > >Can someone explain how I would read the data from the USB "port"? I >don't know if it matters, but I am trying to read the data from a GPS >plugged in to the USB port. USB is a "protocol" bus. It isn't like a serial port, where you can just start reading bits. Each device has one or more "interfaces", and each interface has one or more "pipe" for transmitting data. You have to know which "pipe" to talk to, what kind of pipe it is, and how to force the device to send before you can talk to it. On the other hand, as someone else pointed out, many types of USB devices fall into standard device classes, and the operating system supplies drivers for those classes. If your GPS device is in the communication class, you might be able to pretend it is a serial device. -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From sjmachin at lexicon.net Sun Apr 29 08:13:20 2007 From: sjmachin at lexicon.net (John Machin) Date: 29 Apr 2007 05:13:20 -0700 Subject: if __name__ == 'main': & passing an arg to a class object In-Reply-To: References: <1177708104.277756.245360@t38g2000prd.googlegroups.com> Message-ID: <1177848800.530548.87780@p77g2000hsh.googlegroups.com> On Apr 29, 9:32 pm, Bart Willems wrote: > gtb wrote: > > appear at the end of many examples I see. Is this to cause a .class > > file to be generated? > > This might be obvious, but no one else mentioned it: the Python > interpreter cannot execute code that it hasn't compiled yet, which is > why the "if __name__ ..." code is always at the end of the module - to > guarantee that the entire file is scanned first. I make no claims about the following code; it is merely presented for examination :-) 8< --- namemain.py ----------- # code used both in import mode and script mode def greet(whom): print "Hello, %s" % whom if __name__ == "__main__": # code used only in script mode import sys, namemain tgt = sys.argv[1] greet(tgt) namemain.farewell(tgt) else: # code used only in import mode def farewell(whom): print "Goodbye, %s" % whom 8<------------------------------------------------------ From bruno.desthuilliers at gmail.com Mon Apr 2 07:08:21 2007 From: bruno.desthuilliers at gmail.com (bruno.desthuilliers at gmail.com) Date: 2 Apr 2007 04:08:21 -0700 Subject: Web App Framework with PostgreSQL + fast + easy In-Reply-To: References: Message-ID: <1175512101.198364.34760@n76g2000hsh.googlegroups.com> On 2 avr, 11:23, Ben wrote: > I'm looking for a web application framework with a good interface to > PostgreSQL. > > The app I'm developing is relatively simple, but I'm new to coding, so it > needs to be easy. > > What I'm making is a wiki-like system that could be thought of as similar > to MediaWiki, but with each word editable separately - ie. edit locks > would be one word at a time. > > Features I need: > * works well with PostgreSQL - fast and powerful with support/awareness > of MVCC > * easy to use > * fast > > Features I want: > * flexible options for user accounts, with some reasonable non HTTPS > security > * support for internationalisation. > > I am a happy Plone user, but I'm concerned it or even Zope on its > own wouldn't be fast enough as they have a whole lot of functionality I > really don't need and aren't built for a RDBMS. > > Ben The three leadings Python Web/MVC frameworks are Django, Turbogears and Pylons. Django is perhaps the most easy to geat started with, but it's a bit monolithic IMHO. Turbogears and Pylons may be a bit more complex to get started with, but are also much more flexible. My personal favorite is Pylons. From parimala.kalavala at gmail.com Tue Apr 17 00:06:25 2007 From: parimala.kalavala at gmail.com (PARIMALA KALAVALA) Date: Tue, 17 Apr 2007 09:36:25 +0530 Subject: regarding tree iterators Message-ID: <67eb1c790704162106n7b96de29v6e5e0fbd77ef39a@mail.gmail.com> hi , I wanted to know how to move data from one row to another row or how to copy contents of one row to another row if we click any button in a table in pygtk. Do we need to use get value and set value methods in tree iterators. pls reply to this as early as possible. Thank you. -------------- next part -------------- An HTML attachment was scrubbed... URL: From turbana at gmail.com Thu Apr 26 19:59:37 2007 From: turbana at gmail.com (Ian Clark) Date: Thu, 26 Apr 2007 16:59:37 -0700 Subject: mysql "rows affected" In-Reply-To: <1bCdnU80YoYXpazbnZ2dnUVZ_gKdnZ2d@comcast.com> References: <1bCdnU80YoYXpazbnZ2dnUVZ_gKdnZ2d@comcast.com> Message-ID: Both cursor.execute() and cursor.executemany() return the number of rows affected. Here is a link to the documentation: http://mysql-python.sourceforge.net/MySQLdb-1.2.2/public/MySQLdb.cursors.BaseCursor-class.html#execute Ian On 4/26/07, Carl K wrote: > > using MySQLdb, I do cursor.execute("update...") > > How can I tell how many rows were affected ? > > Carl K > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From deets at nospam.web.de Tue Apr 17 14:05:06 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 17 Apr 2007 20:05:06 +0200 Subject: Queue enhancement suggestion In-Reply-To: References: <7x4pngluel.fsf_-_@ruckus.brouhaha.com> Message-ID: <58kgilF2h6d55U1@mid.uni-berlin.de> > The problem is that sometimes the gui thread has something to show > too. With the added problem that the code wanting to show something > doesn't know when it is executing the gui thread or an other. So > it is very difficult to avoid the gui thread putting things on the > queue. But since the gui thread is the single reader, it will dead > lock if the queue happens to be full at the moment the gui thread > want to add another item. This sounds like a pretty constructed case to me. After all, it's not too hard to determine that the thread running is the gui-thread. Combine this with a simple thread-local "put-my-event-in-the-queue"-function and you can either stuff it in the queue in worker threads, or create a toolkit event in case of the gui-thread. Diez From BjornSteinarFjeldPettersen at gmail.com Fri Apr 6 05:56:55 2007 From: BjornSteinarFjeldPettersen at gmail.com (thebjorn) Date: 6 Apr 2007 02:56:55 -0700 Subject: Looping issues In-Reply-To: <1175796069.501575.157410@w1g2000hsg.googlegroups.com> References: <1175796069.501575.157410@w1g2000hsg.googlegroups.com> Message-ID: <1175853415.185610.228750@y66g2000hsf.googlegroups.com> On Apr 5, 8:01 pm, brochu... at gmail.com wrote: > What I am trying to do is compare two files to each other. > > If the 2nd file contains the same line the first file contains, I want > to print it. I wrote up the following code: > > correct_settings = open("C:\Python25\Scripts\Output > \correct_settings.txt","r") > current_settings = open("C:\Python25\Scripts\Output\output.txt","r") > > for line in correct_settings: > for val in current_settings: > if val == line: > print line + " found." > > correct_settings.close() > current_settings.close() > > For some reason this only looks at the first line of the > correct_settings.txt file. Any ideas as to how i can loop through each > line of the correct_settings file instead of just looking at the first? I'm not entirely sure I understand what you're trying to do, but in case you're trying to walk through the two files in lockstep printing the lines that correspond, here's a way to do that: # note the r'..' syntax correct = open(r'c:\python25\scripts\output\correct_settings.txt') current = open(r'c:\python25\scripts\output\output.txt') for correct_line, current_line in zip(correct, current): if correct_line == current_line: print correct_line, 'found.' correct.close() current.close() hth, -- bjorn From aisaac at american.edu Sat Apr 7 22:40:52 2007 From: aisaac at american.edu (Alan Isaac) Date: Sun, 08 Apr 2007 02:40:52 GMT Subject: tuples, index method, Python's design References: <1175867771.114540.61810@n76g2000hsh.googlegroups.com><1175884427.779950.267220@y80g2000hsf.googlegroups.com><1175953520.316208.241490@o5g2000hsb.googlegroups.com> Message-ID: "Carsten Haese" wrote in message news:mailman.6146.1175956040.32031.python-list at python.org... > Adding useless features always makes a product worse. What's your use > case for tuple.index? I find this question odd for the following reason: I doubt that *anyone* who programs in Python has not encountered the situation where they change a tuple to a list *solely* for the purpose of getting access to the index method. There is simply no conflict between the index method and immutability, but at the moment you are forced to choose. Anyway, for a simple use case, consider a game, where the fixed set p of players have a fixed order. A tuple is natural. Now for a player you want to construct the opponents. If I had the index i it wd be p[:i]+p[i+1:], but how to get the index? Cheers, Alan Isaac From bdesth.quelquechose at free.quelquepart.fr Wed Apr 4 19:32:31 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Thu, 05 Apr 2007 01:32:31 +0200 Subject: calling super() In-Reply-To: References: <1175714555.413502.77390@o5g2000hsb.googlegroups.com> Message-ID: <46142ca0$0$14488$426a34cc@news.free.fr> Jarek Zgoda a ?crit : > Finger.Octopus at gmail.com napisa?(a): > > (snip) >>class NewPage(HTMLMain): >> def __init__(self): >> print 'derive2 init' >> super(NewPage, self).__init__(); > > > This should read: super(HTMLMain, self).__init__() Nope. It's just how it should be. From mensanator at aol.com Sun Apr 15 16:39:08 2007 From: mensanator at aol.com (mensanator at aol.com) Date: 15 Apr 2007 13:39:08 -0700 Subject: combination function in python In-Reply-To: References: <1176615838.830315.160210@b75g2000hsg.googlegroups.com> <1176629911.409257.149780@l77g2000hsb.googlegroups.com> Message-ID: <1176669548.436118.176300@e65g2000hsc.googlegroups.com> On Apr 15, 11:34???am, Anton Vredegoor wrote: > Jussi Piitulainen wrote: > >> There's probably even a really clever way to avoid that final > >> division, but I suspect that would cost more in time and memory than > >> it would save. > > We're getting closer and closer to something I already posted a few > times here. This implementation was unfortunate because I consistently > used an uncommon name for it so people couldn't easily find it But then, who's looking for it? > (mea culpa), and maybe also because it uses the despised reduce builtin. > > def noverk(n,k): > ? ? ?return reduce(lambda a,b: a*(n-b)/(b+1),xrange(k),1) > > BTW I hereby give up the strange name for this and request a better name > that everybody will use so there will be no confusion anymore. Maybe > comb(n,k) ? No, that name's already used by gmpy. And a single function doesn't replace all of gmpy's other functionality, many of which are needed in the same applications where comb() is used, so there's really no need for your function. Your time is better spent applying the tools provided by gmpy rather than trying to re-invent the wheel. > > > Here's one non-clever one for integers n, k that uses n^k / k^k > > (falling powers) with the smaller of k and n - k as lower index: > > > def choose(n, k): > > ? ?if 0 <= k <= n: > > ? ? ? ?ntok = 1 > > ? ? ? ?ktok = 1 > > ? ? ? ?for t in xrange(1, min(k, n - k) + 1): > > ? ? ? ? ? ntok *= n > > ? ? ? ? ? ktok *= t > > ? ? ? ? ? n -= 1 > > ? ? ? ?return ntok // ktok > > ? ?else: > > ? ? ? ?return 0 > > Ha, my function uses smaller subproducts :-) > > A. From john106henry at hotmail.com Thu Apr 26 19:13:07 2007 From: john106henry at hotmail.com (John Henry) Date: 26 Apr 2007 16:13:07 -0700 Subject: statistical functions for Date/Time data series Message-ID: <1177629187.700142.102600@t38g2000prd.googlegroups.com> I am looking for a simple Python function for handling a set of time series data. For instance, I might have the following raw data (year's worth): 1/1/2005 12:00 AM 11.24 1/1/2005 12:10 AM 12.31 1/1/2005 12:20 AM 12.06 1/1/2005 12:30 AM 11.61 1/1/2005 12:40 AM 11.12 1/1/2005 12:50 AM 11.74 1/1/2005 1:00 AM 12.59 1/1/2005 1:10 AM 11.46 1/1/2005 1:20 AM 12.51 1/1/2005 1:30 AM 12.78 1/1/2005 1:40 AM 12.43 1/1/2005 1:50 AM 11.87 1/1/2005 2:00 AM 12.42 1/1/2005 2:10 AM 12.11 1/1/2005 2:20 AM 12.11 1/1/2005 2:30 AM 10.06 1/1/2005 2:40 AM 10.44 1/1/2005 2:50 AM 10.19 1/1/2005 3:00 AM 10.34 1/1/2005 3:10 AM 10.28 1/1/2005 3:20 AM 9.88 1/1/2005 3:30 AM 9.85 ..... and I want to know, for instance, what's the average value between 1:00AM and 2:00AM everyday for winter months, or average value every 15 minutes..... Does anybody know if there is a package that can do rudimentary time- series statistical analysis before I roll my own? Thanks, From bbxx789_05ss at yahoo.com Wed Apr 4 13:20:50 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: 4 Apr 2007 10:20:50 -0700 Subject: Indentifying the LAST occurrence of an item in a list In-Reply-To: References: <1175702329.330032.250750@w1g2000hsg.googlegroups.com> Message-ID: <1175707250.349825.223470@p77g2000hsh.googlegroups.com> On Apr 4, 10:55 am, "Terry Reedy" wrote: > wrote in message > > news:1175702329.330032.250750 at w1g2000hsg.googlegroups.com... > | For any list x, x.index(item) returns the index of the FIRST > | occurrence of the item in x. Is there a simple way to identify the > | LAST occurrence of an item in a list? My solution feels complex - > | reverse the list, look for the first occurence of the item in the > | reversed list, and then subtract its index from the length of the list > | - 1, i.e. > | > | LastOcc = len(x) - 1 - x[::-1].index(item) > | > | Is there a simpler solution? > How about: l = [1, 2, 1, 3, 1, 5] target = 1 for index, val in enumerate(l): if val==1: lastIndexOf = index print lastIndexOf From bbxx789_05ss at yahoo.com Wed Apr 11 22:00:59 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: 11 Apr 2007 19:00:59 -0700 Subject: Nested dictionaries trouble In-Reply-To: <1176341288.631317.235660@y5g2000hsa.googlegroups.com> References: <1176317876.917874.58040@n59g2000hsh.googlegroups.com> <461d427e$0$18058$426a74cc@news.free.fr> <1176339709.998807.32990@e65g2000hsc.googlegroups.com> <1176341288.631317.235660@y5g2000hsa.googlegroups.com> Message-ID: <1176343259.884902.320020@n59g2000hsh.googlegroups.com> On Apr 11, 7:28 pm, "7stud" wrote: > On Apr 11, 7:01 pm, "7stud" wrote: > > > On Apr 11, 2:57 pm, Bruno Desthuilliers > > > wrote: > > > IamIan a ?crit : > > > > yearTotals = dict([(year, dict.fromkeys(months, 0)) for year in years]) > > > > HTH > > > List comprehensions without a list? What? Where? How? > > Ooops. I copied the wrong one. I was looking at this one: > > yearTotals = dict((year, monthTotals) for year in years) Never mind. I found this PEP: http://www.python.org/dev/peps/pep-0289/ From nagle at animats.com Thu Apr 26 21:18:57 2007 From: nagle at animats.com (John Nagle) Date: Thu, 26 Apr 2007 18:18:57 -0700 Subject: mysql "rows affected" In-Reply-To: <1bCdnU80YoYXpazbnZ2dnUVZ_gKdnZ2d@comcast.com> References: <1bCdnU80YoYXpazbnZ2dnUVZ_gKdnZ2d@comcast.com> Message-ID: Carl K wrote: > using MySQLdb, I do cursor.execute("update...") > > How can I tell how many rows were affected ? > > Carl K cursor = db.cursor() # get cursor cursor.execute(sqlstatement, argtuple) # do command rowsaffected = cursor.rowcount # get count of rows affected cursor.close() # close cursor db.commit() # commit transaction John Nagle From whamil1 at entergy.com Wed Apr 18 15:15:22 2007 From: whamil1 at entergy.com (Hamilton, William ) Date: Wed, 18 Apr 2007 14:15:22 -0500 Subject: Iterate through a dictionary of lists one "line" at a time In-Reply-To: <1176921542.567121.248820@b58g2000hsg.googlegroups.com> Message-ID: <588D53831C701746A2DF46E365C018CE01D2CA71@LITEXETSP001.etrsouth.corp.entergy.com> > -----Original Message----- > From: python-list-bounces+whamil1=entergy.com at python.org [mailto:python- > list-bounces+whamil1=entergy.com at python.org] On Behalf Of wswilson > Sent: Wednesday, April 18, 2007 1:39 PM > To: python-list at python.org > Subject: Iterate through a dictionary of lists one "line" at a time > > Here is my code: > > listing = {'id': ['a', 'b', 'c'], 'name': ['Joe', 'Jane', 'Bob']} > > I need to output: > > id name > a Joe > b Jane > c Bob > > I could do: > > print 'id', 'name' > for id, name in zip(listing['id'], listing['name']): print id, name > > but that only works if there are two entries in the dictionary, id and > name, and I know what they are. My problem is I don't know how many of > these entries there will be. Thanks for any help you can give! > >>> for x in xrange(len(listing['id'])): ... print "" ... for key in listing.keys(): ... print listing[key][x], a Joe b Jane c Bob --- -Bill Hamilton From cam.ac.uk at mh391.invalid Mon Apr 16 21:41:58 2007 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Tue, 17 Apr 2007 02:41:58 +0100 Subject: strange behaviour sys.argv In-Reply-To: <1176772070.349541.80890@y5g2000hsa.googlegroups.com> References: <1176772070.349541.80890@y5g2000hsa.googlegroups.com> Message-ID: schnupfy wrote: > I am not used to python and I am wondering about this thing: This is not a Python question. It is a question about how to use bash. I would try to help anyway, but I am unsure what results you actually want. Your example is too complicated as well. You should strip down your example to only the arguments that change. In doing this you may solve the problem on your own. -- Michael Hoffman From louise.hoffman at gmail.com Thu Apr 26 13:16:00 2007 From: louise.hoffman at gmail.com (Louise Hoffman) Date: 26 Apr 2007 10:16:00 -0700 Subject: Dedicated CPU core for Python? Message-ID: <1177607759.916727.180950@t39g2000prd.googlegroups.com> Dear readers, I was wondering, if Python in the foerseeable future will allocate one CPU core just for the interpreter, so heavy Python operations does slow down the OS? It seams to me like a perfect use for a CPU core =) Lots of love, Louise From jstroud at mbi.ucla.edu Sun Apr 29 17:17:08 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Sun, 29 Apr 2007 14:17:08 -0700 Subject: Counting In-Reply-To: <1177877775.780666.222080@p77g2000hsh.googlegroups.com> References: <1177873864.502180.283390@u30g2000hsc.googlegroups.com> <1177877775.780666.222080@p77g2000hsh.googlegroups.com> Message-ID: rockmode at gmail.com wrote: > That's a short, abridged version of my code :) But, what I want is to > count total# of keywords per line and print 'em. Rather than > printing : > > The word 'and' belongs in line num: 1 > The word 'del' belongs in line num: 1 > The word 'from' belongs in line num: 1 > > I want to print " Line #1 has 3 keywords" > > ;) > I think it would be obvious how to write this: for i,line in enumerate(linelist): line = line.split() for k in line: if keyword.iskeyword(k): c = line.count(k) total += line.count(k) print "Line #%d has %d keywords." % (i+1, c) break print "Total keyords are: %d" % total From webraviteja at gmail.com Sat Apr 28 16:42:38 2007 From: webraviteja at gmail.com (Ravi Teja) Date: 28 Apr 2007 13:42:38 -0700 Subject: Interop between C# and Python In-Reply-To: <1177730757.208859.274790@q75g2000hsh.googlegroups.com> References: <1177722543.098518.192840@h2g2000hsg.googlegroups.com> <1177730289.935376.167590@e65g2000hsc.googlegroups.com> <1177730757.208859.274790@q75g2000hsh.googlegroups.com> Message-ID: <1177792958.040386.263660@p77g2000hsh.googlegroups.com> On Apr 27, 8:25 pm, urielka wrote: > thx i will try this. > > i am also trying XML-RPC,i wrote a basic generator(in python) that > genrate a Interface from the XML-RPC service module,but maybe with > soaplib i don`t need this if i use wsdl as Visual Studio can generate > the code from the wsdl Typed remoting mechanisms (SOAP, CORBA, ICE etc) tend to be less work with statically typed languages like C#. Untyped remoting mechanisms are more convenient to work with dynamic languages (XML-RPC, JSON-RPC etc). When combining them, typed one are more convenient because working with typed systems is more convenient in dynamic languages than it is to work with untyped systems in typed languages. Of course, if the project is really small, none of this really matters. Pick your poison. Ravi Teja. From b83503104 at yahoo.com Mon Apr 9 14:44:10 2007 From: b83503104 at yahoo.com (bahoo) Date: 9 Apr 2007 11:44:10 -0700 Subject: recursively removing files and directories Message-ID: <1176144250.874365.141820@n59g2000hsh.googlegroups.com> Hi, I found a message on Jan 16, 2006 regarding the same topic, except that I wanted to remove only certain files that satisfy the format "ABC_XXX_XXX.dat", but not the other files. Once the files are removed, if a folder becomes empty, I want to remove the folder as well. The solution to the Jan 16 2006 message required many lines of python code. I was wondering if there is a simpler solution to my problem at hand, perhaps by using more specialized functions? Thanks! bahoo From ann at toqm.com Sat Apr 14 03:48:23 2007 From: ann at toqm.com (ann) Date: 14 Apr 2007 00:48:23 -0700 Subject: How to get a forum for your free site? In-Reply-To: <1176536341.202549.241010@o5g2000hsb.googlegroups.com> References: <1176518288.373349.237050@w1g2000hsg.googlegroups.com> <1176533345.247060.206320@b75g2000hsg.googlegroups.com> <1176536341.202549.241010@o5g2000hsb.googlegroups.com> Message-ID: <1176536903.210706.310900@e65g2000hsc.googlegroups.com> On 4?14?, ??3?39?, "Ann" wrote: > On 4?14?, ??2?49?, "Eric_Dex... at msn.com" wrote: > > > Normaly I would consider this way way off topic but I did notice that > > you offer unlimited space so I suppose it could be usefull for those > > of us that distribute software.. what else do I get some of the add > > space?? If you are after killer apps you should consider allowing > > combination of other boards between websites... (I had a provider > > that went down in the .com bust that did that) > > Don't be doubtful of our space .We can sure to provide you unlimited > free space forever. If you need add your space ,we could support > too.If you have the intention, you can leave the link, or contact with > me ,my MSN : xuxu_1... at hotmail.com . > thank you. What's your account on our forum ? So we could contact you convenience. From mensanator at aol.com Thu Apr 12 20:46:26 2007 From: mensanator at aol.com (mensanator at aol.com) Date: 12 Apr 2007 17:46:26 -0700 Subject: Lists and Tuples and Much More In-Reply-To: References: Message-ID: <1176425186.096019.167430@w1g2000hsg.googlegroups.com> On Apr 12, 5:38 pm, "Scott" wrote: > I'm going to start grouping all my questions in one post as this is my > second today, and sorta makes me feel dumb to keep having to bother you all > with trivial questions. I'll just seperate my questions with: > ---------------------------------------------------------------------------?---------------- > Now onto the issue: > List's and Tuple's > I don't see the distinction between the two. I mean, I understand that a > list is mutable and a tuple is immutable. > The thing that I dont understand about them is what, besides that, seperates > the two. I did a little experimentation to try to understand it better, but > only confused myelf more. > > A list looks like this: > > >>>my_list = [1, 2, 3, 4, 5, 6] > > and a tuple looks like this: > > >>>my_tuple = (1, 2, 3, 4, 5, 6) > > Now you can add to a list, but not a tuple so: > > >>>my_list.append(my_tuple) #or extend for that matter right? > > [1, 2, 3, 4, 5, 6, (1, 2, 3, 4, 5, 6)] > > Is that pretty much accurate? And which is better on resources....I'm > guessing a tuple seeing as it doesn't change. > > And the last example brings up another question. What's the deal with a > tupple that has a list in it such as: > > >>>my_tupple = (1, 2, 3, 4, 5, [6, 7, 8, 9]) > > Now I read somewhere that you could change the list inside that tupple. But > I can't find any documentation that describes HOW to do it. The only things > I CAN find on the subject say, "Don't do it because its more trouble than > it's worth." But that doesn't matter to me, because I want to know > everything. > ---------------------------------------------------------------------------?------------------ > > Now there comes append. I read everywhere that append only add's 1 element > to the end of your list. But if you write:>>> my_list = [1, 2, 3, 4, 5, 6] > >>> my_list.append([7, 8, 9, 10]) > >>> my_list > > [1, 2, 3, 4, 5, 6, [7, 8, 9, 10]] > > Is that because list's, no matter what they contain, are counted as 1 > element? Right, but I didn't see the following mentioned elsewhere, so note that: What you probably wanted to use to add [7,8,9,10] to your list was .extend() not .append(). >>> my_list = [1, 2, 3, 4, 5, 6] >>> my_list.extend([7, 8, 9, 10]) >>> my_list [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] > > And how would you sort the list that's in the list? I guess that goes in > conjunction with the section above, but still:>>> my_list = [6, 4, 3, 5, 2, 1] > >>> my_list.append([7, 9, 8, 10]) > >>> my_list.sort() > >>> my_list > > [1, 2, 3, 4, 5, 6, [7, 9, 8, 10]] > > This is, again, something I'm finding nothing on. > ---------------------------------------------------------------------------?------------------ > > Maybe I'm just not looking in the right spots. The only things I have as > learning aids are: this newsgroup ;p,http://diveintopython.org,http://python.org/, Beggining Python: From Novice to Professional, and (now > don't laugh) Python for Dummies. From mike.terrell at earthlink.net Sun Apr 29 18:29:40 2007 From: mike.terrell at earthlink.net (Michael A. Terrell) Date: Sun, 29 Apr 2007 22:29:40 GMT Subject: Video: Professor of Physics Phd at Cal Tech says: 911 Inside Job References: <1177467203.719625.93920@u32g2000prd.googlegroups.com> <1177780530.539758.275660@c35g2000hsg.googlegroups.com> <1177788032.971421.65550@c35g2000hsg.googlegroups.com> Message-ID: <46351C76.33D802DF@earthlink.net> Mitchell Jones wrote: > If I seem to be ignoring you, consider the possibility > that you are in my killfile. --MJ Ditto. -- Service to my country? Been there, Done that, and I've got my DD214 to prove it. Member of DAV #85. Michael A. Terrell Central Florida From mirandacascade at yahoo.com Wed Apr 18 14:27:17 2007 From: mirandacascade at yahoo.com (mirandacascade at yahoo.com) Date: 18 Apr 2007 11:27:17 -0700 Subject: SSLCrypto package Message-ID: <1176920837.102271.258690@n59g2000hsh.googlegroups.com> When I review: - the site that describes the SSLCrypto package: http://www.freenet.org.nz/python/SSLCrypto/ - the documention for SSLCrypto: http://www.freenet.org.nz/python/SSLCrypto/Doco/ - the examples provided http://www.freenet.org.nz/python/SSLCrypto/#examples It appears as though: a) SSLCrypto package replaces ezPyCrypto package b) the ezPyCrypto package provided a wrapper for the PyCrypto package c) most of the heavy lifting in the SSLCrypto package happens in the key class Since SSLCrypto replaced ezPyCrypto and since ezPyCrypto provides a wrapper for PyCrypto, I guessed (perhaps incorrectly) that one can use SSLCrypto to accomplish the functions that can be accomplished in PyCrypto package. I looked at the documentation for all of SSLCrypto in general, and for the key() class in particular, yet I am unable to determine from the material that I reviewed whether certain functionality can be accomplished in SSLCrypto, specifically: a) can one use the SSLCrypto package to perform an HMAC message digest calculation (accomplished in PyCrypto package via Crypto.Hash.HMAC class)? b) can one use the SSLCrypto package to perform an SHA256 hash (accomplished in PyCrypto package via Crypto.Hash.SHA256 class)? Thank you. From aleax at mac.com Sun Apr 22 22:23:05 2007 From: aleax at mac.com (Alex Martelli) Date: Sun, 22 Apr 2007 19:23:05 -0700 Subject: recursion depth problem References: <1177267774.416169.276780@e65g2000hsc.googlegroups.com> <1177271382.859369.104790@q75g2000hsh.googlegroups.com> <1177278499.378120.246560@o5g2000hsb.googlegroups.com> Message-ID: <1hwzkey.19hmuyn1tebhe7N%aleax@mac.com> Steven Bethard wrote: ... > >>>>> import sys > >>>>> def ch4(item, n=0): > >>>>> if n < len(item): > >>>>> if item[n] == '0': > >>>>> item[n] = '1' > >>>>> print ''.join(item) > >>>>> ch4(item) > >>>>> elif item[n] == '1': > >>>>> item[n] = '0' > >>>>> ch4(item, n+1) > >>>>> ch4(list(sys.argv[1])) ... > > for interest sake: is my method unredeemable? > > Let's just say that I don't currently see an obvious way of redeeming > it. ;-) Change the outer if into a while, and the recursive calls into proper assignments to n. They're both tail-recursive calls, so this won't change the semantics, as it happens. Alex From gagsl-py2 at yahoo.com.ar Fri Apr 6 00:51:47 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: 5 Apr 2007 21:51:47 -0700 Subject: Extract zip file from email attachment In-Reply-To: <1175821421.265541.120440@w1g2000hsg.googlegroups.com> References: <1175815907.434721.274190@w1g2000hsg.googlegroups.com> <65fge4-j15.ln1@athlon.my> <1175821421.265541.120440@w1g2000hsg.googlegroups.com> Message-ID: <1175835107.288163.139050@b75g2000hsg.googlegroups.com> erikcw wrote: > resp = p.retr(msg_num) > if resp[0].startswith('+OK'): You don't have to check this; errors are transformed into exceptions. > fileObj = StringIO.StringIO() cStringIO is faster > fileObj.write( part.get_payload() ) You have to reset the file pointer to the beginning: fileObj.seek(0), else ZipFile will not be able to read the contents. -- Gabriel Genellina From C.delete_this.Sanders at BoM.GOv.AU Wed Apr 25 21:34:52 2007 From: C.delete_this.Sanders at BoM.GOv.AU (Charles Sanders) Date: Thu, 26 Apr 2007 11:34:52 +1000 Subject: Python not giving free memory back to the os get's me in real problems ... In-Reply-To: <132v2rbgjm66d24@corp.supernews.com> References: <1177510121.882503.145560@n15g2000prd.googlegroups.com> <_LidnenBcrz7-rLbnZ2dnUVZ_tCtnZ2d@comcast.com> <59990rF2ja6c7U3@mid.dfncis.de> <132uv54ncsspm91@corp.supernews.com> <132v2rbgjm66d24@corp.supernews.com> Message-ID: <463001bd$0$44860$c30e37c6@lon-reader.news.telstra.net> Grant Edwards wrote: > Assuming the python interpreter free()s the memory, my > understanding is that on Unixes the memory is returned to the > pool used by malloc(), but is not returned to the OS since > there isn't a practical way to ensure that the memory at the > "end" of the data segment is not used. http://www.dent.med.uni-muenchen.de/~wmglo/malloc-slides.html > Large chunks are allocated via mmap(). The threshold is set > through the environment variable MALLOC_MMAP_THRESHOLD_. > The maximum number of chunks allocated in this way is limited > through MALLOC_MMAP_MAX_. I think these large chunks are returned to the OS when freed. > Trimming occurs when the size of the top chunk exceeds > MALLOC_TRIM_THRESHOLD_. I think this means that memory for small chunks is returned to the OS if the free space at the top of the heap exceeds the threshold. > Asking on the gnu libc mailing list would probably provide a > more authoritative answer. I'd wager that they even know what > other non-Gnu libc implementations do. Agreed, they would be authoritative for GNU libc. Charles From carsten at uniqsys.com Fri Apr 27 17:00:06 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Fri, 27 Apr 2007 17:00:06 -0400 Subject: Memory addressing In-Reply-To: <1177703803.179501.95300@n35g2000prd.googlegroups.com> References: <1177702902.156596.52510@n35g2000prd.googlegroups.com> <1177703803.179501.95300@n35g2000prd.googlegroups.com> Message-ID: <1177707606.5467.16.camel@dot.uniqsys.com> On Fri, 2007-04-27 at 12:56 -0700, Simon Berube wrote: > When you call certain objects __repr__() strings in python you often > get the : happen. I am simply trying to > understand how that information can be used to recreate a certain > object that failed as per the given purpose of the __repr__() > functions. It's not a requirement of repr() that the resulting string be suitable for recreating the object. For many built-in object types, calling eval() on their repr() will result in a copy of the object, but in general eval(repr(obj))==obj will not be true. > In short, how do I used strings to recreate > a an object. You don't. What you should do instead depends on what you actually need to do, which you haven't said yet. Do you want to pass an object to another function, do you want to make a copy of an object, or do you want to serialize/unserialize an object to send it through time and/or space? -Carsten From hq4ever at gmail.com Mon Apr 9 19:23:27 2007 From: hq4ever at gmail.com (Maxim Veksler) Date: Tue, 10 Apr 2007 02:23:27 +0300 Subject: ulimit on open sockets ? Message-ID: Hi, I've written this code, the general idea was to listen on all 65535 port of tcp for connection. """ #!/usr/bin/env python import socket, select def get_non_blocking_socket(port_number): s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.setblocking(0) s.bind(('0.0.0.0', port_number)) s.listen(1) return s all_sockets = map(get_non_blocking_socket, xrange(10000, 15000)) while 1: ready_to_read, ready_to_write, in_error = select.select(all_sockets, [], [], 0) for nb_active_socket in all_sockets: if nb_active_socket in ready_to_read: conn, addr = nb_active_socket.accept() while 1: data = conn.recv(1024) if not data: break conn.send(data) conn.close() """ The thing is that when I tried to run this at first I got """ python non_blocking_range.py Traceback (most recent call last): File "non_blocking_range.py", line 12, in ? all_sockets = map(get_non_blocking_socket, xrange(10000, 15000)) File "non_blocking_range.py", line 6, in get_non_blocking_socket s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) File "/usr/lib/python2.4/socket.py", line 148, in __init__ _sock = _realsocket(family, type, proto) socket.error: (24, 'Too many open files') """ So I set ulimit -n 500000, now I'm getting """ python non_blocking_range.py Traceback (most recent call last): File "non_blocking_range.py", line 15, in ? ready_to_read, ready_to_write, in_error = select.select(all_sockets, [], [], 0) ValueError: filedescriptor out of range in select() """ Should I be using a different version of select or something? Or should I implement this the other way around, if so please suggest how. Thank you very much, (enthusiastically learning python) Maxim. -- Cheers, Maxim Veksler "Free as in Freedom" - Do u GNU ? From Bulkan at gmail.com Thu Apr 26 03:34:49 2007 From: Bulkan at gmail.com (placid) Date: 26 Apr 2007 00:34:49 -0700 Subject: Would You Write Python Articles or Screencasts for Money? In-Reply-To: References: <462DCCE6.9060908@taupro.com> Message-ID: <1177572889.671360.308700@r30g2000prh.googlegroups.com> On Apr 25, 12:00 am, Steve Holden wrote: > Jeff Rush wrote: > > There is discussion by the Python Software Foundation of offering cash > > bounties or perhaps periodic awards to the "best of" for magazine articles, > > video/screencast clips and such. I would like to see more screen-casts on python modules out there, like CherryPy, Zope and Twisted. Sometimes documentation just seems "dry" to read when you're just trying to learn. > > > If YOU would be swayed to get involved in producing content in exchange for > > cash, please speak up on the advocacy mailing list and also drop an email to > > Steve Holden , current champion of this idea and looking > > for encouragement. Ideas on how to evaluate contributions, how frequently to > > do this and critical thresholds of cash amounts necessary to induce YOUR > > participation are wanted. I would write an article for a t-shirt with the python logo on it.... ;) Cheers From bcwhite at pobox.com Thu Apr 19 22:16:33 2007 From: bcwhite at pobox.com (bcwhite at pobox.com) Date: 19 Apr 2007 19:16:33 -0700 Subject: How To Find Currently Selected Tile.Notebook Tab? Message-ID: <1177035392.983733.68240@n76g2000hsh.googlegroups.com> How can I determine what tab is currently selected in a Tile.Notebook widget? The best suggestion I've been able to find via Google is "mynotebook.index('current')", but that gets an exception from Tcl. Any ideas? -- Brian From oliver at obeattie.com Tue Apr 3 03:02:44 2007 From: oliver at obeattie.com (oliver at obeattie.com) Date: 3 Apr 2007 00:02:44 -0700 Subject: Opening Photoshop EPS with PIL? In-Reply-To: <460fd449$0$27399$ba4acef3@news.orange.fr> References: <1175350344.418087.288320@q75g2000hsh.googlegroups.com> <460fd449$0$27399$ba4acef3@news.orange.fr> Message-ID: <1175583764.252501.89710@o5g2000hsb.googlegroups.com> On Apr 1, 12:01 pm, "M?ta-MCI" wrote: > .eps ==> vector ; not bitmap I was under the impression that .eps could be opened with PIL (and by the way, their contents are actually raster (but with a work path which shouldn't be displayed anyway) Any ideas? From horpner at yahoo.com Thu Apr 26 09:47:41 2007 From: horpner at yahoo.com (Neil Cerutti) Date: 26 Apr 2007 15:47:41 +0200 Subject: Tutorial creates confusion about slices References: <1177535739.431386.77300@s33g2000prh.googlegroups.com> Message-ID: On 2007-04-25, Ant wrote: > On Apr 23, 1:38 pm, Antoon Pardon wrote: >> The following is part of the explanation on slices in the >> tutorial: >> >> The best way to remember how slices work is > ... >> +---+---+---+---+---+ >> | H | e | l | p | A | >> +---+---+---+---+---+ >> 0 1 2 3 4 5 >> -5 -4 -3 -2 -1 >> >> This is all very well with a simple slice like: >> >> "HelpA"[2:4] => "lp" >> >> But it give the wrong idea when using the following extended >> slice: >> >> "HelpA"[4:2:-1] => "Ap" > > I think that the tutorial example is absolutely fine as it is. I object only to the word "best". I don't like the above model because it divorces the indexes that appear in subscripts from those that appear in slices. I 't find it complicated to think: a[2:4] is the contiguous slice of elements starting at the gap between element 1 and 2, and ending at the gap between element 3 and 4. I've always found thinking of [2:4] as a half-open range much easier. I suppose the above model could avoid this notational problem if you say that a[k] means the one element slice a[k:k+1] (technically true for strings, but false for lists), rather than ever thinking of item indexes as pointing directly at an item. So I vote that the word "best" be removed. -- Neil Cerutti When "yearn" was sung, the performers ounded like they were in a state of yearning. --Music Lit Essay From anton.vredegoor at gmail.com Thu Apr 19 11:38:01 2007 From: anton.vredegoor at gmail.com (Anton Vredegoor) Date: Thu, 19 Apr 2007 17:38:01 +0200 Subject: multirember&co In-Reply-To: References: <1176768854.720234.23320@w1g2000hsg.googlegroups.com> <1176790588.024371.119360@n76g2000hsh.googlegroups.com> <1176850352.999231.79260@n59g2000hsh.googlegroups.com> <1176921030.330467.76860@o5g2000hsb.googlegroups.com> <1176925857.535835.130010@b58g2000hsg.googlegroups.com> Message-ID: Anton Vredegoor wrote: > attn.steven.kuo at gmail.com wrote: > >> Try it with >> >> def test(): >> L = 'a', 1, 2, 'a' >> it1, it2 = xsplitter(L, lambda x: x == 'a') >> print it1.next() >> print it2.next() >> print it1.next() >> print it2.next() >> >> >> The last print statement raises StopIteration... >> We, however, expected each iterator to contain >> two elements (one yielding 'a' then 'a', and >> the other yielding 1 then 2). > > Ouch! I never understood much about generators anyway. How about this one? from collections import deque class sentinel(object): pass class myiter(object): def __init__(self,seq): self.seq = seq self.index = -1 def __iter__(self): return self def next(self): self.index +=1 if self.index < len(self.seq): return self.seq[self.index] else: return sentinel def mygen(seq): for x in seq: if x is sentinel: #way past bedtime raise StopIteration yield x def xsplitter(seq, pred): Q = deque(),deque() it = myiter(seq) def gen(p): for x in it: while Q[p]: yield Q[p].popleft() if pred(x) == p: yield x else: Q[~p].append(x) for x in gen(p): yield x return map(mygen,[gen(1),gen(0)]) def test(): L = 'a', 1, 2, 'a' it1, it2 = xsplitter(L, lambda x: x == 'a') print it1.next() print it2.next() print it1.next() print it2.next() if __name__=='__main__': test() A. From stj911 at rock.com Tue Apr 24 22:13:23 2007 From: stj911 at rock.com (stj911 at rock.com) Date: 24 Apr 2007 19:13:23 -0700 Subject: Video: Professor of Physics Phd at Cal Tech says: 911 Inside Job Message-ID: <1177467203.719625.93920@u32g2000prd.googlegroups.com> Cal Tech is the ELITE of ELITE in physics. If Feynman were alive, he would point his finger straight at the 911 criminal operators, the yank bastards themselves ....... http://www.911blogger.com/node/8101 No self-respecting scientist should keep his mouth shut. Its a fundamental challenge to the method of science, a detective work most demanding of INTELLECTUAL HONESTY. From collinstocks at gmail.com Wed Apr 11 18:08:43 2007 From: collinstocks at gmail.com (Collin Stocks) Date: Wed, 11 Apr 2007 18:08:43 -0400 Subject: Python Web Servers and Page Retrievers In-Reply-To: References: <4c0048df0704081442w7a25ee2bqe2b13229dc37769e@mail.gmail.com> Message-ID: <4c0048df0704111508u1fbccadbwa164b6c598f89659@mail.gmail.com> I tried it, and when checking it using a proxy, saw that it didn't really work, at least in the version that I have (urllib v1.17 and urllib2 v2.5). It just added that header onto the end, therefore making there two User-Agent headers, each with different values. I might add that my script IS able to retrieve search pages from Google, whereas both urllibs are FORBIDDEN with the headers that they use. On 4/8/07, Max Erickson wrote: > > Subscriber123 wrote: > > urllib, or urllib2 for advanced users. For example, you can > > easily set your own headers when retrieving and serving pages, > > such as the User-Agent header which you cannot set in either > > urllib or urllib2. > > Sure you can. See: > > http://www.diveintopython.org/http_web_services/user_agent.html > > (though the behavior was changed for python 2.3 to make setting the > user agent work better) > > > max > > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From grante at visi.com Mon Apr 23 15:46:36 2007 From: grante at visi.com (Grant Edwards) Date: Mon, 23 Apr 2007 19:46:36 -0000 Subject: Generate report containing pdf or ps figures? References: <132pnp6r4qg0lc2@corp.supernews.com> <1177356412.269325.85990@d57g2000hsg.googlegroups.com> Message-ID: <132q38sh8lkmr99@corp.supernews.com> On 2007-04-23, infidel wrote: >> I've looked at ReportLab's documentation, but although it >> appears to be able to use bitmap images (e.g jpeg) it doesn't >> appear to be able to use vector images (EPS/PDF/SVG). >> >> Is there a PDF generation library that can place EPS or >> PDF figures on a page? > > I've had great success using Apache's FOP utility (http:// > xmlgraphics.apache.org/fop) to generate PDFs out of XSL-FO, which can > contain SVG graphics (at least the 0.20.5 version can, the newer > rewrite version doesn't yet). FOP is a java library but has a > suitable command line interface. Unfortunately, trying to bundle a Java installation with my app is going to be harder than bundling Ghostscript or LaTeX (the other two solutions that come to mind). I should have mentioned it in my OP, but I need something that's cross-platform (At least Linux and Windows), and not difficult to bundle using something like py2exe. -- Grant Edwards grante Yow! I'm totally DESPONDENT at over the LIBYAN situation visi.com and the price of CHICKEN ... From howe.steven at gmail.com Wed Apr 18 13:28:02 2007 From: howe.steven at gmail.com (Steven Howe) Date: Wed, 18 Apr 2007 10:28:02 -0700 Subject: Newbie: import In-Reply-To: <1176914096.493758.77120@o5g2000hsb.googlegroups.com> References: <1176914096.493758.77120@o5g2000hsb.googlegroups.com> Message-ID: <46265522.4000509@gmail.com> genkuro at gmail.com wrote: > I thought import used relative paths from either the python executable > or the script being executed. I have a script pulling in code from an > arbitrary directory. How is this happening? > > It's a RHEL 4 environment by the way. I couldn't find any relevant > environment variables. > > Thanks from a newbie for any insight. > > See .... http://docs.python.org/tut/node8.html#SECTION008110000000000000000 6.1.1 The Module Search Path When a module named spam is imported, the interpreter searches for a file named spam.py in the current directory, and then in the list of directories specified by the environment variable PYTHONPATH. This has the same syntax as the shell variable PATH, that is, a list of directory names. When PYTHONPATH is not set, or when the file is not found there, the search continues in an installation-dependent default path; on Unix, this is usually .:/usr/local/lib/python. Actually, modules are searched in the list of directories given by the variable |sys.path| which is initialized from the directory containing the input script (or the current directory), PYTHONPATH and the installation-dependent default. This allows Python programs that know what they're doing to modify or replace the module search path. Note that because the directory containing the script being run is on the search path, it is important that the script not have the same name as a standard module, or Python will attempt to load the script as a module when that module is imported. This will generally be an error. See section 6.2 , ``Standard Modules,'' for more information. Then try import sys sys.path -------------- next part -------------- An HTML attachment was scrubbed... URL: From gregpinero at gmail.com Tue Apr 10 14:48:03 2007 From: gregpinero at gmail.com (gregpinero at gmail.com) Date: 10 Apr 2007 11:48:03 -0700 Subject: exec statement Syntax Error on string pulled from MySQL In-Reply-To: <1176229141.124962.73110@o5g2000hsb.googlegroups.com> References: <1176191064.840339.247160@d57g2000hsg.googlegroups.com> <1176229141.124962.73110@o5g2000hsb.googlegroups.com> Message-ID: <1176230883.100211.215080@d57g2000hsg.googlegroups.com> On Apr 10, 2:19 pm, "gregpin... at gmail.com" wrote: > Now I just have to figure out how the '\r' are getting in > there. I entered that piece of code using PHPMyAdmin so that could be > doing it, or MySQLdb could be doing it when returning it, or it could > be something about the DB encoding! I'll post back if I find out. > Hmm, searches didn't turn up anything. The best I can figure is that the HTML textarea / browser combination is sending the text in that way. I can check for sure on that later. -Greg From gagsl-py2 at yahoo.com.ar Fri Apr 20 23:25:16 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sat, 21 Apr 2007 00:25:16 -0300 Subject: comparison with None References: <3IqdnfRnCNWPC7vbnZ2dnUVZ_jqdnZ2d@rcn.net> <2qzVh.7373$xL6.982@trnddc05> <_JAVh.1700$jR5.897@trnddc08> <1hwu26k.oyynyowsbxvcN%aleax@mac.com> <1hwuyed.1pfg5y31tp64kmN%aleax@mac.com> <1hwvw04.btbo2u17yso3sN%aleax@mac.com> Message-ID: En Fri, 20 Apr 2007 23:48:02 -0300, Alex Martelli escribi?: > Gabriel Genellina wrote: > >> Reference Manual, 5.9 Comparisons >> >> "The objects need not have the same type. If both are numbers, they are >> converted to a common type. Otherwise, objects of different types always >> compare unequal, and are ordered consistently but arbitrarily." >> >> (Apart from the latter not menctioning string types too, looks good to >> me). > > Right. However, it might be worth underscoring that this applies to > _built-in_ types, and user-defined types are free to implement different > comparison semantics, although that should be done with care and good > taste; for example, one might have a collection type defining __eq__ to > mean "the same set of items as the other [iterable] operand in any > order", though that might cause weird behavior such as a==b but b!=a > (unfortunately there's no __req__, and __coerce__ is not involved in > comparisons either). BTW, I think that the relationship between __eq__ and __hash__ (a==b => hash(a)==hash(b), when hashable) should be more clearly stated too. I almost got insane some time ago because of a faulty Rational numbers implementation where hash(1/2)!=hash(2/4) (so dictionaries didn't work at all). -- Gabriel Genellina From nospam at nospam.com Fri Apr 27 06:59:28 2007 From: nospam at nospam.com (Fred Bloggs) Date: Fri, 27 Apr 2007 10:59:28 GMT Subject: *** Dr G Polya BRILLIANTLY analyses the Virgina Shooting Incident *** References: <1177266754.126153.202760@b58g2000hsg.googlegroups.com> <1177287460.376404.323520@b58g2000hsg.googlegroups.com> <1177416547.394200.314950@r3g2000prh.googlegroups.com> <1177447632.371289.38180@r30g2000prh.googlegroups.com> Message-ID: <4631D78D.5050700@nospam.com> bill.sloman at ieee.org wrote: > On Apr 24, 2:09 pm, Quadibloc wrote: > >>The Real Andy wrote: >> >>>Makes me wonder about the credibility of any statement Dr Gideon Polya >>>makes. >> >>. >>I never thought that I would feel the urge to call someone an >>edelweiss-eating Tanzanian devil, but Dr. Polya proved that I lacked >>imagination. >> >>(Note that "Tanzanian" is pronounced Tan.zan._ee_.yan, not >>Tan._zayn_.ee.an; one wouldn't want to spoil the effect.) > > > What really spoils the effect is that Dr. Polya lives in Tasmania, a > state of Australia, and not in Tanzania, which is a country in East > Africa. > > Semi-literate Americans do tend to confuse the two places, as they > also tend confuse Australia and Austria. Oddly enough, edelweiss grows > in Austria, so Dr. Polya would have to import it from Europe if he > were in the habit of dining on edelweiss - which would be an eccentric > habit, even in Austria, where the flower doesn't form part of the > normal diet. > > -- > Bill Sloman, Nijmegen > Is there any civilized life in Tasmania? It looks like just another natural wonderland that was raped, pillaged, exploited for its resources, and left behind. Even the official tourism site makes the place seem dull and bereft of any kind of enthusiasm, warning the prospective visitor that life is slow there. I did not know Erol Flynn was from there. That's something anyway. They might consider making his boyhood home a museum or something. And was that Gunn Forestry you know so well? From robert.kern at gmail.com Wed Apr 4 18:12:49 2007 From: robert.kern at gmail.com (Robert Kern) Date: Wed, 04 Apr 2007 17:12:49 -0500 Subject: BeautifulSoup vs. real-world HTML comments In-Reply-To: <1175724136.054215.249970@p77g2000hsh.googlegroups.com> References: <1175711322.448629.20300@y80g2000hsf.googlegroups.com> <1175717833.872281.6300@l77g2000hsb.googlegroups.com> <1175724136.054215.249970@p77g2000hsh.googlegroups.com> Message-ID: Carl Banks wrote: > On Apr 4, 4:55 pm, Robert Kern wrote: >> Carl Banks wrote: >>> On Apr 4, 2:43 pm, Robert Kern wrote: >>>> Carl Banks wrote: >>>>> On Apr 4, 2:08 pm, John Nagle wrote: >>>>>> BeautifulSoup can't parse this page usefully at all. >>>>>> It treats the entire page as a text chunk. It's actually >>>>>> HTMLParser that parses comments, so this is really an HTMLParser >>>>>> level problem. >>>>> Google for a program called "tidy". Install it, and run it as a >>>>> filter on any HTML you download. "tidy" has invested in it quite a >>>>> bit of work understanding common bad HTML and how browsers deal with >>>>> it. It would be pointless to duplicate that work in the Python >>>>> standard library; let HTMLParser be small and tight, and outsource the >>>>> handling of floozy input to a dedicated program. >>>> Well, BeautifulSoup is just such a dedicated library. >>> No, not really. >> Yes, it is. Whether it succeeds in all particulars is besides the point. The >> only mission of BeautifulSoup is to handle bad HTML. > > I think the authors of BeautifulSoup have the right to decide what > their own mission is. Yes, and he's stated it pretty clearly: """You didn't write that awful page. You're just trying to get some data out of it. Right now, you don't really care what HTML is supposed to look like. Neither does this parser.""" -- 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 usenet-mail-0306.20.chr0n0ss at spamgourmet.com Fri Apr 27 16:35:49 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Fri, 27 Apr 2007 22:35:49 +0200 Subject: Memory addressing References: <1177702902.156596.52510@n35g2000prd.googlegroups.com> <1177703803.179501.95300@n35g2000prd.googlegroups.com> Message-ID: <59f555F2k70baU1@mid.individual.net> Simon Berube wrote: > When you call certain objects __repr__() strings in python you > often get the : happen. I am simply > trying to understand how that information can be used to recreate > a certain object that failed as per the given purpose of the > __repr__() functions. It cannot. The string returned by repr is supposed to be unique. In C Python, it just happens to be the object's memory address that's used to make this string unique. > In short, how do I used strings to > recreate a an object. Not at all :) Objects that can't be recreated using their __repr__ information just provide an unique identifier string if you call repr on them, no more and no less. Regards, Bj?rn -- BOFH excuse #202: kernel panic: write-only-memory (/dev/wom0) capacity exceeded. From care02 at gmail.com Tue Apr 3 13:21:59 2007 From: care02 at gmail.com (care02 at gmail.com) Date: 3 Apr 2007 10:21:59 -0700 Subject: How can I kill a running thread when exiting from __main__ Message-ID: <1175620919.478708.292150@p77g2000hsh.googlegroups.com> Hi! I have the following problem: I have written a short Python server that creates an indefinite simulation thread that I want to kill when quitting (Ctrl-C) from Python. Googling around has not given me any hints on how to cleanly kill running threads before exiting. Any help is appreciated! Carl ### CODE EXTRACT ### import pythoncom class QueueThread( threading.Thread): def __init__(self, command): threading.Thread.__init__(self) self.command = command def run(self): pythoncom.CoInitialize() try: object = Dispatch('application') execute = getattr(object, 'Execute') execute(self.command ) finally: object = None pythoncom.CoUnitialize() queuethread = QueueThread("queuehandler") queuethread.setDaemon(True) queuethread.start() ## How can I kill "queuethread" when exiting (Ctrl-C)? From bcwhite at pobox.com Fri Apr 20 22:38:55 2007 From: bcwhite at pobox.com (bcwhite at pobox.com) Date: 20 Apr 2007 19:38:55 -0700 Subject: wx.TextCtrl.SetDefaultStyle not working? Message-ID: <1177123135.263882.238100@y5g2000hsa.googlegroups.com> I'm running Python2.5 with wxPython v2.8.3.0 under WinXP and I cannot get the SetDefaultStyle method to work. I'm trying: self.output.SetDefaultStyle(wx.TextAttr(wx.RED)) self.output.AppendText(text) self.output.SetDefaultStyle(wx.TextAttr()) where "self.output" is a TextCtrl window. The text appears, but it's always black. If I print the output of self.output.GetDefaultStyle().GetTextColour() before resetting it back to default, I see "(255, 0, 0, 255)". After reset, it's "(-1, -1, -1, 255)". The font in that window is the system default. Am I doing something wrong? -- Brian From ptmcg at austin.rr.com Fri Apr 13 12:46:11 2007 From: ptmcg at austin.rr.com (Paul McGuire) Date: 13 Apr 2007 09:46:11 -0700 Subject: Problem with algorithm In-Reply-To: References: <1176434160.047703.214600@q75g2000hsh.googlegroups.com> <1176434937.258002.162220@p77g2000hsh.googlegroups.com> <1176448576.047996.12930@d57g2000hsg.googlegroups.com> Message-ID: <1176482771.267327.247940@e65g2000hsc.googlegroups.com> On Apr 13, 8:53 am, Steve Holden wrote: > > I'm pretty sure you could give a separate name to each atom ont he known > universe with a scheme like this. Do you really need 20-byte strings? > Steve, Based on the Wikipedia article's estimate of 10**79 atoms in the observable universe (is that all?), we would need a string of about 57 characters long to give each one a separate name. (And I'll bet you've typed on an old Royal or two in your time...) -- Paul From bodemory at gmail.com Mon Apr 9 07:12:59 2007 From: bodemory at gmail.com (Brice-Olivier Demory) Date: 9 Apr 2007 04:12:59 -0700 Subject: Memory allocation problem with python 2.4.3 Message-ID: <1176117179.200754.234610@o5g2000hsb.googlegroups.com> Hi, I'm encountering an odd problem while running a python script which calls a C program called 'st_time' : Traceback (most recent call last): File "ccdd.py", line 177, in ? answer=proc_request(conn,addr,request) # proc the request File "ccdd.py", line 69, in proc_request answer = '1&%s'%(ccd.exec_function(fct,arg)) File "/opt/OFXB/lib/python2.4/site-packages/ccdlib.py", line 204, in exec_function return apply(self.funcs[name],args) File "/opt/OFXB/lib/python2.4/site-packages/ccdlib.py", line 731, in mpose answer = self.download() File "/opt/OFXB/lib/python2.4/site-packages/ccdlib.py", line 1152, in download st = libastro.st_time(ut,LON) File "/opt/OFXB/lib/python2.4/site-packages/libastro.py", line 169, in st_time raise e OSError: [Errno 12] Cannot allocate memory This error is far from appearing each time I invoke st_time. To debug this problem, a friend of mine tried to get memory information as soon as this error is raised. Here, it returns : MemTotal: 774856 kB MemFree: 22952 kB Buffers: 3656 kB Cached: 127600 kB SwapCached: 6308 kB Active: 626132 kB Inactive: 75452 kB HighTotal: 0 kB HighFree: 0 kB LowTotal: 774856 kB LowFree: 22952 kB SwapTotal: 1116476 kB SwapFree: 647064 kB Dirty: 12 kB Writeback: 0 kB Mapped: 621524 kB Slab: 28268 kB CommitLimit: 1503904 kB Committed_AS: 1146312 kB PageTables: 2472 kB VmallocTotal: 245752 kB VmallocUsed: 8992 kB VmallocChunk: 236384 kB Nothing indicates a lack of memory. I'm running the following version of python : Python 2.4.3 (#2, Apr 27 2006, 14:43:58) [GCC 4.0.3 (Ubuntu 4.0.3-1ubuntu5)] Does somebody has an idea about what's happening ? Many thanks for your time, Brice From gagsl-py2 at yahoo.com.ar Fri Apr 20 22:20:39 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 20 Apr 2007 23:20:39 -0300 Subject: Significance of "start" parameter to string method "endswith" References: <1177016236.700474.16170@n59g2000hsh.googlegroups.com> <1177107716.353954.223460@p77g2000hsh.googlegroups.com> Message-ID: En Fri, 20 Apr 2007 23:13:23 -0300, Steven D'Aprano escribi?: > On Fri, 20 Apr 2007 15:21:56 -0700, John Machin wrote: > >> On Apr 20, 9:12 am, Steven D'Aprano >> wrote: >>> >>> You can do this: >>> >>> p = 0 >>> while text: >>> p = text.find('parrot', p) >>> do_something_with(buffer, p) >>> >>> which avoids copying text unnecessarily. >> >> ... but increases the care and attention required when coding: > > There are always trade-offs. ... and you still need more attention when replying - read again your own reply :) -- Gabriel Genellina From apardon at forel.vub.ac.be Mon Apr 23 09:31:41 2007 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 23 Apr 2007 13:31:41 GMT Subject: Tutorial creates confusion about slices References: <1177334277.241487.142430@b75g2000hsg.googlegroups.com> Message-ID: On 2007-04-23, Rob Wolfe wrote: > > Antoon Pardon wrote: >> The following is part of the explanation on slices in the >> tutorial: >> >> The best way to remember how slices work is to think of the indices as >> pointing between characters, with the left edge of the first character >> numbered 0. Then the right edge of the last character of a string of n >> characters has index n, for example: >> >> +---+---+---+---+---+ >> | H | e | l | p | A | >> +---+---+---+---+---+ >> 0 1 2 3 4 5 >> -5 -4 -3 -2 -1 >> >> This is all very well with a simple slice like: >> >> "HelpA"[2:4] => "lp" >> >> >> But it give the wrong idea when using the following extended slice: >> >> "HelpA"[4:2:-1] => "Ap" >> >> So this doesn't result in the reverse of the previous expression while >> the explanation above suggest it does. > > Clearly I understand that differently: > >>>> "HelpA"[-2:-4:-1] > 'pl' This is not about what you understand. This is about what the tutorial seems to suggest here and whether or not that corresponds with how python actually works. Read the explanation and look at the picture. The -2 is to the right of "l" the -4 is to the left of "e". So the picture IMO suggests that "HelpA"[-2:-4:-1] would result in "le" -- Antoon Pardon From steven.bethard at gmail.com Sun Apr 15 20:36:18 2007 From: steven.bethard at gmail.com (Steven Bethard) Date: Sun, 15 Apr 2007 18:36:18 -0600 Subject: working of round() In-Reply-To: <1176682019.215351.114560@y80g2000hsf.googlegroups.com> References: <1176682019.215351.114560@y80g2000hsf.googlegroups.com> Message-ID: Krishna.K.1900 at gmail.com wrote: > Does round() always perfectly return the output expected or are there > some artifacts which don't allow perfect functionality > > Using python 2.5: >>>> round(12.234, 2) > 12.23 >>>> round(12.234, 3) > 12.234 >>>> round(12.234, 1) > 12.199999999999999 > > but was expecting 12.2 > > Also, for round(x,n), can't 'x' be an expression > > round(5.25/2, 2) > > was expecting 2.62 , but > >>>> round(5.25/2, 2) > 2.6299999999999999 You're running into floating-point issues (e.g. it's impossible to represent 2.63 perfectly in binary). What are you really trying to do? If you just want to format these with only two decimal places, use string formatting:: >>> '%.2f' % 12.234 '12.23' >>> '%.2f' % (5.25 / 2) '2.63' I'm not sure why you would have expected 2.62 for the latter when:: >>> 5.25 / 2 2.625 STeVe From paul at boddie.org.uk Sun Apr 1 14:09:02 2007 From: paul at boddie.org.uk (Paul Boddie) Date: 1 Apr 2007 11:09:02 -0700 Subject: Character set woes with binary data In-Reply-To: References: <1175415685.21349.79.camel@pepper.trausch.us> Message-ID: <1175450942.280035.204390@o5g2000hsb.googlegroups.com> Michael B. Trausch wrote: > > I never said it did. It just happens to be the context with which I am > working. I said I wanted to concatenate materials without regard for > the character set. I am mixing binary data with ASCII and Unicode, for > sure, but I should be able to do this. The problem is that Unicode has no default representation for mixing with binary data and ASCII. What you should therefore ask yourself is, "Which encoded representation of Unicode should I be using to mix my text with those things?" Then, you should choose an encoding, call the encode method on your Unicode objects, take the result, and mix away! [...] > In short: How do I create a string that contains raw binary content > without Python caring? Is that possible? All strings can contain raw binary content without Python caring. Unicode objects, however, work on a higher level of abstraction: characters, not bytes. Thus, you need to make sure that your Unicode objects have been converted to bytes (ie. encoded to strings) in order for the content to be workable at the same level as that binary content. Paul From silverburgh.meryl at gmail.com Sat Apr 28 14:48:11 2007 From: silverburgh.meryl at gmail.com (silverburgh.meryl at gmail.com) Date: 28 Apr 2007 11:48:11 -0700 Subject: How to pass in argument to timeit.Timer Message-ID: <1177786091.049008.278400@o5g2000hsb.googlegroups.com> Hi, I have a function in my python like this: def callFunc(line, no): # some code And I want to do a performance test like this: for line in f: for i in range(int(count)): t1 = timeit.Timer("callFunc(line, i)","from __main__ import callFunc") r1 = t1.timeit(); print r1; but when I run it, it can't recognize the parameter 'line' and 'i', can you please tell me how to fix it? i get this error: File "/usr/lib/python2.4/timeit.py", line 161, in timeit timing = self.inner(it, self.timer) File "", line 6, in inner NameError: global name 'line' is not defined Thank you. From redtiger84 at googlemail.com Fri Apr 6 07:02:52 2007 From: redtiger84 at googlemail.com (Christoph Krammer) Date: 6 Apr 2007 04:02:52 -0700 Subject: Using os.popen3() to get binary data Message-ID: <1175857372.585042.239310@y80g2000hsf.googlegroups.com> Hello everybody, I need to get the different frames from a GIF image in my python script and want to use the giftopnm program from netpbm to get the frames and directly convert them to pnm files. I tried to use the following code: for image in images: if (image[0:3] == 'GIF'): (si, so, se) = os.popen3('giftopnm -image=all', 'b') si.write(image) frame = so.readlines() But with this code the script just hangs. When I interrupt the script, I get the following error message: Traceback (most recent call last): File "/home/tiger/stock-spam/scripts/all_in_one.py", line 46, in ? frames = so.readlines() KeyboardInterrupt close failed: [Errno 32] Broken pipe Can somebody tell me, which command I have to use that the pipe will be closed when the giftopnm returns? This program just prints the converted images to stdout and terminates. Thanks in advance, Christoph From inq1ltd at verizon.net Thu Apr 19 20:04:22 2007 From: inq1ltd at verizon.net (jim-on-linux) Date: Thu, 19 Apr 2007 20:04:22 -0400 Subject: PY shutil on win xp home version In-Reply-To: <46268782.60204@timgolden.me.uk> References: <1176898887.530470.222830@p77g2000hsh.googlegroups.com> <200704181543.44889.inq1ltd@verizon.net> <46268782.60204@timgolden.me.uk> Message-ID: <200704192004.22604.inq1ltd@verizon.net> On Wednesday 18 April 2007 17:02, Tim Golden wrote: > jim-on-linux wrote: > > python help, > > > > A client is using win xp home. > > > > my program contains; > > shutil.copyfile(n, 'prn') > > > > This runs fine on win xp pro but they are > > getting the following traceback. > > > > File "LOP_PRT_10.pyc", line 170, in __init__ > > File "LOP_PRT_10.pyc", line 188, in Fprint1 > > File "shutil.pyc", line 47, in copyfile > > IOError: [Errno 2] No such file or directory: > > 'prn' > > > > Since this runs ok on win xp pro, does this > > have something to do with the home version of > > xp. > > > > I'm thinking of changeing 'prn' to 'lpt1' > > and trying again but I don't want to use the > > client as a testor. Or is there some other > > explaination for the problem. > > Not that this is your question, but if you're > trying to print under Windows have you looked > at: > > > http://tgolden.sc.sabren.com/python/win32_how_d >o_i/print.html > > for alternatives? > > TJG Thanks for the response, I got the following to work on windows. win32api.ShellExecute ( 0, 'print', filename, None, ".", 0 ) However it prints the name of the file at the top and adds a page number on the bottom. Is there some way of eliminating the filename and page number. jim-on-linux From grante at visi.com Wed Apr 18 11:21:29 2007 From: grante at visi.com (Grant Edwards) Date: Wed, 18 Apr 2007 15:21:29 -0000 Subject: subprocess "handle is invalid" error Message-ID: <132cdrpqsmnvpa7@corp.supernews.com> I'm trying to use the py-gnuplot module on windows, and have been unable to get it to work reliably under Win2K and WinXP. By default, it uses popen(gnuplotcmd,'w'), but in some situations that consistently gets an "invalid operand" IOError when write() is called on the pipe. So I switched to subprocess. It works fine when executed "normally" (e.g. "python progname.py"), but when bundled by py2exe, it always does this: Traceback (most recent call last): File "surfedit.py", line 28, in ? File "Gnuplot\_Gnuplot.pyc", line 178, in __init__ File "Gnuplot\gp_win32.pyc", line 117, in __init__ File "subprocess.pyc", line 533, in __init__ File "subprocess.pyc", line 607, in _get_handles File "subprocess.pyc", line 634, in _make_inheritable WindowsError: [Errno 6] The handle is invalid How does one troubleshoot errors that happen three layers deep in the subprocess module? -- Grant Edwards grante Yow! I'm a fuschia bowling at ball somewhere in Brittany visi.com From ptmcg at austin.rr.com Fri Apr 27 11:32:21 2007 From: ptmcg at austin.rr.com (Paul McGuire) Date: 27 Apr 2007 08:32:21 -0700 Subject: conditional print statement ? In-Reply-To: References: <2c923$462fb3e0$d443bb3a$18429@news.speedlinq.nl> <1177590681.015153.67800@b40g2000prd.googlegroups.com> <1177683110.005910.99250@t38g2000prd.googlegroups.com> Message-ID: <1177687940.935269.111840@r35g2000prh.googlegroups.com> On Apr 27, 9:45 am, Duncan Booth wrote: > Paul McGuire wrote: > > The Enable/Disable decorators on the Python wiki (http:// > > wiki.python.org/moin/PythonDecoratorLibrary?highlight=%28decorator > > %29#head-8298dbf9ac7325d9ef15e7130e676378bbbda572) help you do > > something very similar, without having to replicate the function being > > enabled/disabled. > > > @(disabled,enabled)[Print_Info] > > def printOrNot(arg): > > print arg > > Pardon me for asking, but isn't that a syntax error? Decorator syntax is: > > "@" dotted_name ["(" [argument_list [","]] ")"] NEWLINE > > and you don't have a dotted_name. My bad. The wiki example assigns the appropriate decorator to another name, and then uses that name, like this: debugFlag = int(False) state = (disabled,enabled)[debugFlag] # <-- proper way to do this @state def debugPrint(s): print s print "here comes some debug output" debugPrint("xyzzy is the secret word") print "that was it" I think early in the decorator syntax discussions, there were some proposals that decorators could be expressions, but I guess I forgot which way that was decided. The example in this post does work (and so does the one on the wiki) . -- Paul From martin at v.loewis.de Sat Apr 14 03:27:20 2007 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sat, 14 Apr 2007 09:27:20 +0200 Subject: tuples, index method, Python's design In-Reply-To: <7x8xd2iq53.fsf@ruckus.brouhaha.com> References: <1175867771.114540.61810@n76g2000hsh.googlegroups.com> <1175884427.779950.267220@y80g2000hsf.googlegroups.com> <1175953520.316208.241490@o5g2000hsb.googlegroups.com> <7xzm5igbrb.fsf@ruckus.brouhaha.com> <7x8xd2iq53.fsf@ruckus.brouhaha.com> Message-ID: <46208258$0$14430$9b622d9e@news.freenet.de> > The use case has already been discussed. Removing the pointless > inconsistency between lists and tuples means you can stop having to > remember it, so you can free up brain cells for implementing useful > things. That increases your programming productivity. So to increase consistency, the .index method should be removed from lists, as well, IMO. If you find yourself doing a linear search, something is wrong. Regards, Martin From lialie at gmail.com Thu Apr 5 02:35:34 2007 From: lialie at gmail.com (lialie) Date: Thu, 05 Apr 2007 14:35:34 +0800 Subject: Why does my callback funtion collapse? Message-ID: <461498B6.109@gmail.com> Hi,all I try to callback from a thread in C. But it collapsed. I can't figure it out. My test files attached. Thanks. -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: callback.c URL: -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: setup.py URL: -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: test_callback.py URL: From admin at loial.co.uk Mon Apr 16 09:43:37 2007 From: admin at loial.co.uk (loial) Date: 16 Apr 2007 06:43:37 -0700 Subject: More newbie help required with dictionaries Message-ID: <1176731017.008097.21590@o5g2000hsb.googlegroups.com> The following code only returns the last row(222222) added to the machines dictionary. presumably I need some additional syntax to add rows to the dictionary rather than overwrite. What do I need to add? machinekey = "111111" machines = { machinekey:[1,0,0,0,0,0,0,0,0,0,0,0,0] } machinekey = "222222" machines = { machinekey:[0,1,0,0,0,0,0,0,0,0,0,0,0] } for machine in machines.keys(): print machine From steveo at syslang.net Mon Apr 23 09:20:56 2007 From: steveo at syslang.net (Steven W. Orr) Date: Mon, 23 Apr 2007 09:20:56 -0400 (EDT) Subject: Shebang or Hashbang for modules or not? In-Reply-To: References: <1176308951.932721.197630@y80g2000hsf.googlegroups.com> Message-ID: On Saturday, Apr 21st 2007 at 19:18 +0100, quoth Michael Hoffman: =>Chris Lasher wrote: =>> Should a Python module not intended to be executed have shebang/ =>> hashbang (e.g., "#!/usr/bin/env python") or not? I'm used to having a =>> shebang in every .py file but I recently heard someone argue that =>> shebangs were only appropriate for Python code intended to be =>> executable (i.e., run from the command line). => =>Personally I include it in all of them, as part of boilerplate in a =>template. I'd recommend againt it. The shebang doesn't do you any good unless it's also in the presence of a file that has its executable bit set. For example, let's leave python out for a second: I have a shell script. And I also have lots of files which are not intended to be executed which are also shell scripts, but which are sucked in by the shell "." or "source" command (which is *somewhat* analogous to python's import). Lots of these shell "library" scripts can't execute as standalone. The same thing is possible with pything scripts. Of course, anything that has if __name__ == "__main__": in it should always have a shebang and be executable. -- 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 gagsl-py2 at yahoo.com.ar Wed Apr 4 20:24:33 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 04 Apr 2007 21:24:33 -0300 Subject: CRC CCITT UPDATE in Python References: <1175393727.233247.254500@n76g2000hsh.googlegroups.com> <460F4E6C.9050308@v.loewis.de> <73b38a6e0704010610o719d1651w518045ce59559b66@mail.gmail.com> Message-ID: En Sun, 01 Apr 2007 10:10:04 -0300, [Py Thorneiro] escribi?: [Py Thorneiro] >> > uint16_t >> > crc_ccitt_update (uint16_t crc, uint8_t data) >> > { >> > data ?= lo8 (crc); >> > data ?= data << 4; >> > return ((((uint16_t)data << 8) | hi8 (crc)) ? (uint8_t)(data >> 4) >> > ? ((uint16_t)data << 3)); >> > } [Martin v. L?wis] >> Most likely, lo8(crc) == crc & 0xFF, and hi8(crc) == (crc >> 8) & 0xFF >> (the last bit masking might be redundant, as crc should not occupy more >> than 16 bits, anyway). [Py Thorneiro] > Please, could you help me? :-) How to port this hi8 and lo8 to > Python, > is there some function similar? That's exactly what MvL said. To put it more clearly: def lo8(i16): return i16 & 0xff def hi8(i16): return (i16 >> 8) & 0xff -- Gabriel Genellina From nogradi at gmail.com Wed Apr 25 05:36:17 2007 From: nogradi at gmail.com (Daniel Nogradi) Date: Wed, 25 Apr 2007 11:36:17 +0200 Subject: If Dict Contains... In-Reply-To: <6667263534486737469@unknownmsgid> References: <6667263534486737469@unknownmsgid> Message-ID: <5f56302b0704250236v44e3329am5a56979c5208ec49@mail.gmail.com> > Looking to build a quick if/else statement that checks a dictionary for a > key like follows. > > If myDict contains ThisKey: > > Do this... > > Else > > Do that... > > > > Thats the best way of doing this? if key in myDict: Do this..... else: Do that.... HTH, Daniel From steve at REMOVE.THIS.cybersource.com.au Sun Apr 8 23:30:29 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Mon, 09 Apr 2007 13:30:29 +1000 Subject: tuples are useless??? References: Message-ID: On Mon, 09 Apr 2007 02:26:37 +0000, James Stroud wrote: > Bart Willems wrote: >> James Stroud wrote: >>> ... It boils down to the fact that tuples are useless as a result >>> unless you know you really need them--and you never really NEED them. >> >> Could you clarify that for me? I use tuples *a lot* and I really *NEED* >> them - I'm building a lot of multi-tier reports where detail-level data >> is pulled out of a dictionary based on a composed key. It is impossible >> to build those dictionaries *without* using tuples. > > > "Impossible" is a strong word, as is "need" (especially when in all caps). > > py> import md5 > py> class HashedList(list): > ... def __hash__(self): > ... h = md5.new() > ... for item in self: > ... h.update(str(hash(item))) > ... return int(h.hexdigest(), 16) > ... > py> hl = HashedList('bob', 'carol', 'ted') > py> {hl:3} > {['bob', 'carol', 'ted']: 3} > > Impossible? I wouldn't even say that this was all that difficult. Possible, if by possible you mean "broken". >>> D = {hl: 3} >>> D {['bob', 'carol', 'ted']: 3} >>> hl[0] = 'Bob' >>> D {['Bob', 'carol', 'ted']: 3} >>> D.keys()[0] is hl True >>> D[hl] Traceback (most recent call last): File "", line 1, in KeyError: ['Bob', 'carol', 'ted'] -- Steven. From nate.finch at gmail.com Thu Apr 5 08:33:30 2007 From: nate.finch at gmail.com (Nate Finch) Date: 5 Apr 2007 05:33:30 -0700 Subject: Not understanding absolute_import Message-ID: <1175776410.788058.309080@w1g2000hsg.googlegroups.com> I've been trying to use from absolute_import and it's giving me a hell of a headache. I can't figure out what it's *supposed* to do, or maybe rather, it doesn't seem to be doing what I *think* it's supposed to be doing. For example (actual example from my code, assume all files have "from __future__ import absolute_import"): /project /common guid.py (has "class Guid") __init__.py (has "from .guid import Guid") /relate relatable.py (has "from .common import Guid" and "class Relatable(Guid)") __init__.py (has "from .relatable import Relatable") Now, this all compiles ok and if I change the imports, it does not. So obviously this is working. However, I can't figure out *why* it works. In relatable.py, shouldn't that need to be "from ..common import Guid"? from . should import stuff from the current directory, from . should import stuff from module foo in the current directory. to go up a directory, you should need to use .. but if I do that, python complains that I've gone up too many levels. So, I don't understand... if the way I have above is correct, what happens if I put a common.py in the relate directory? How would you differentiate between that and the common package? I don't understand why .common works from relatable. According to the docs and according to what seems to be common sense, it really seems like it should be ..common. -Nate From mail at timgolden.me.uk Wed Apr 18 17:02:58 2007 From: mail at timgolden.me.uk (Tim Golden) Date: Wed, 18 Apr 2007 22:02:58 +0100 Subject: PY shutil on win xp home version In-Reply-To: <200704181543.44889.inq1ltd@verizon.net> References: <1176898887.530470.222830@p77g2000hsh.googlegroups.com> <200704181543.44889.inq1ltd@verizon.net> Message-ID: <46268782.60204@timgolden.me.uk> jim-on-linux wrote: > python help, > > A client is using win xp home. > > my program contains; > shutil.copyfile(n, 'prn') > > This runs fine on win xp pro but they are getting > the following traceback. > > File "LOP_PRT_10.pyc", line 170, in __init__ > File "LOP_PRT_10.pyc", line 188, in Fprint1 > File "shutil.pyc", line 47, in copyfile > IOError: [Errno 2] No such file or directory: > 'prn' > > Since this runs ok on win xp pro, does this have > something to do with the home version of xp. > > I'm thinking of changeing 'prn' to 'lpt1' and > trying again but I don't want to use the client > as a testor. Or is there some other explaination > for the problem. Not that this is your question, but if you're trying to print under Windows have you looked at: http://tgolden.sc.sabren.com/python/win32_how_do_i/print.html for alternatives? TJG From arnodel at googlemail.com Tue Apr 17 05:16:22 2007 From: arnodel at googlemail.com (Arnaud Delobelle) Date: 17 Apr 2007 02:16:22 -0700 Subject: strange behaviour with keyword arguments and inheritance In-Reply-To: <1176771364.964642.209300@b75g2000hsg.googlegroups.com> References: <1176771364.964642.209300@b75g2000hsg.googlegroups.com> Message-ID: <1176801382.872769.66460@d57g2000hsg.googlegroups.com> matthewperpick wrote: > Check out this toy example that demonstrates some "strange" behaviour > with keyword arguments and inheritance. > > ================================= > > class Parent: > def __init__(self, ary = []): > self.ary = ary > [snip] As pointed out earlier, default values for arguments are evaluated when the function is defined, not when it is called. This creates confusion if this value is mutable and later mutated; I got confused by it when I started python. So it is often not a good idea to use mutable objects as default arguments. A simple fix: def __init__(self, ary=None): if ary is None: ary = [] self.ary = ary -- Arnaud From hq4ever at gmail.com Sun Apr 29 15:48:31 2007 From: hq4ever at gmail.com (Maxim Veksler) Date: Sun, 29 Apr 2007 22:48:31 +0300 Subject: I can't inherit from "compiled" classes ? Message-ID: Hello list, I'm trying to subclass socket and select, for both I get: """ TypeError: Error when calling the metaclass bases module.__init__() takes at most 2 arguments (3 given) """, I don't understand this error. Why would python try to pass 3 arguments (what are they) ? Googling for this error gave random results talking about try to inherit a "Package" but socket is definitely a class, (/usr/lib/python2.4/socket.py). Not sure about select thought. I've did the following to receive the error: """ In [1]: import socket In [2]: class PollingSocket(socket): ...: pass ...: --------------------------------------------------------------------------- exceptions.TypeError Traceback (most recent call last) /home/hq4ever/ TypeError: Error when calling the metaclass bases module.__init__() takes at most 2 arguments (3 given) """ What am I breaking wrong? Thank you, Maxim. -- Cheers, Maxim Veksler "Free as in Freedom" - Do u GNU ? From nospam at nospam.com Mon Apr 23 09:07:20 2007 From: nospam at nospam.com (Gilles Ganault) Date: Mon, 23 Apr 2007 15:07:20 +0200 Subject: [SQLite] Recommended wrapper? Message-ID: Hello I browsed through the SQLite archives at Gname, but most threads regarding wrappers for Python date back to 2005, and for this ng, Google returns stuff from 2006 as the most relevant posts, so I figured I should ask here before diving in. There are several wrappers listed in the wiki (http://www.sqlite.org/cvstrac/wiki?p=SqliteWrappers), so I'd like some feedback about which you would recommend to use SQLite from Python (2.4, but I can upgrade to 2.5 if need be). Thank you GG. From larry.bates at websafe.com Tue Apr 17 17:54:50 2007 From: larry.bates at websafe.com (Larry Bates) Date: Tue, 17 Apr 2007 16:54:50 -0500 Subject: Python COM iterator Message-ID: Does anyone know if there is a way to make a Python COM object act like a proper iterator in VB/Delphi? Example: Python COM object class foo: _public_methods_=['next'] def __init__(self): self.numbers=[1,2,3,4,5,6,7,8] def next(self): try: return self.numbers.pop(0) except IndexError: # # Normally in Python I would do this, but that raises a # COMexception when used in a COM object. # raise StopIteration def __iter__(self): return self I want to be able to write something like (VB): oFOO=foo() for each n in oFOO ' ' Do something with n ' next Seems like there should be a way. Hope explanation is clear enough. Regards, Larry From bronger at physik.rwth-aachen.de Tue Apr 10 05:15:30 2007 From: bronger at physik.rwth-aachen.de (Torsten Bronger) Date: Tue, 10 Apr 2007 11:15:30 +0200 Subject: Why is __getslice__ still implemented? Message-ID: <87irc4wpxp.fsf@wilson.homeunix.com> Hall?chen! According to , __getslice__ is deprecated. At the moment, I derive an own class from unicode and want to implement my own slicing. I found that I have to override __getslice__ since __getitem__ isn't called when I have something like my_instance[a:b] in my code. According to , this may have efficiency reasons, however, I agree with news:1102645919.114898.139820 at f14g2000cwb.googlegroups.com that this is quite confusing. It forces people to implement a deprecated function after all. I think the docs should say that you still have to override __getslice__ when subclassing from a built-in type, unless I really don't understand the issue correctly. Tsch?, Torsten. -- Torsten Bronger, aquisgrana, europa vetus Jabber ID: bronger at jabber.org (See http://ime.webhop.org for ICQ, MSN, etc.) From pekka.jarvinen at gmail.com Fri Apr 20 09:16:07 2007 From: pekka.jarvinen at gmail.com (=?iso-8859-1?q?Pekka_J=E4rvinen?=) Date: 20 Apr 2007 06:16:07 -0700 Subject: Calculating CIDR blocks In-Reply-To: References: <1177032744.375099.248380@q75g2000hsh.googlegroups.com> Message-ID: <1177074967.900881.256280@n76g2000hsh.googlegroups.com> On 20 huhti, 14:34, e... at holyrood.ed.ac.uk (Eddie Corns) wrote: > Look at:http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/466298 > it handles most of the logic of combining IP ranges. > > Eddie I'm getting error: Traceback (most recent call last): File "ipr.py", line 5, in x = ipv4.IP4Range(ips) File "IP4Range.py", line 119, in __init__ raise TypeError("Invalid argument.") TypeError: Invalid argument. From bbxx789_05ss at yahoo.com Thu Apr 5 00:14:17 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: 4 Apr 2007 21:14:17 -0700 Subject: shelve error Message-ID: <1175746456.995618.186190@e65g2000hsc.googlegroups.com> test1.py: -------------------- import shelve s = shelve.open("/Users/me/2testing/dir1/aaa.txt") s['x'] = "red" s.close() --------output:------ $ python test1.py Traceback (most recent call last): File "test1.py", line 3, in ? s = shelve.open("/Users/me/2testing/dir1/aaa.txt") File "/System/Library/Frameworks/Python.framework/Versions/2.3/lib/ python2.3/shelve.py", line 231, in open return DbfilenameShelf(filename, flag, protocol, writeback, binary) File "/System/Library/Frameworks/Python.framework/Versions/2.3/lib/ python2.3/shelve.py", line 212, in __init__ Shelf.__init__(self, anydbm.open(filename, flag), protocol, writeback, binary) File "/System/Library/Frameworks/Python.framework/Versions/2.3/lib/ python2.3/anydbm.py", line 80, in open raise error, "db type could not be determined" anydbm.error: db type could not be determined Exception exceptions.AttributeError: "DbfilenameShelf instance has no attribute 'writeback'" in ignored --------------------- What should I do to correct that error? From rhc28 at cornell.edu Thu Apr 19 22:52:10 2007 From: rhc28 at cornell.edu (Rob Clewley) Date: Thu, 19 Apr 2007 22:52:10 -0400 Subject: matplotlib basic question In-Reply-To: <1177024423.742103.194750@p77g2000hsh.googlegroups.com> References: <1177016327.543985.34500@o5g2000hsb.googlegroups.com> <1177024423.742103.194750@p77g2000hsh.googlegroups.com> Message-ID: On 19 Apr 2007 16:13:43 -0700, cfriedalek at gmail.com wrote: > > > So, first off, what's up with the [ > at 0x017C38C8>] line that shows up after my plot command? And second, > > when I call show(), a new figure pops up with my sin wave -- seems all > > right, yes? But I'm not given another >>> prompt in IDLE until or > > unless I close the figure that popped up with the show() call. > This may not be strictly correct but thats a reference to the plot > instance which is subsequently passed to show(). > If you don't want to see it put a semicolon at the end of your command > eg. plot(range(5)); My understanding is that the semicolon trick is specific to IPython, and does not work in IDLE. I don't know about in other environments. You can just assign the list of returned plot objects to a variable to make it invisible at the command line although these return values (like all return values) are not "shown in the command window" (i.e. passed to stdout) if they are returned from calls made in a script. > The issue with IDLE is to due with lack of connection between the > python interpreter event loop and the event loop of matplotlib (I > think). For me the solution was to install the ipython shell (http:// > ipython.scipy.org/moin/). If you run ipython with the -pylab flag then > you can matplotlib interactively. For example > > plot(range(5),'bo') > show() > clf() > plot([1,2,3,4,5],range(0,10,2),'r-') > (no need for another show() command since the graphics display is > already visible ... unless of course I deleted it in between plot > commands) The OP appears to be using IDLE, for which the things to try are: In site-packages/matplotlib/backends/backend_tkagg.py uncomment the line #os.environ['PYTHONINSPECT'] = '1' Set interactive=True in share/matplotlib/.matplotlibrc Start IDLE with the -n flag In site-packages/matplotlib/backends/backend_tkagg.py comment out the line Tk.mainloop() in the function "show" -Rob From tjreedy at udel.edu Wed Apr 4 13:54:40 2007 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 4 Apr 2007 13:54:40 -0400 Subject: try... except SyntaxError: unexpected EOF while parsing References: <1175708304.034078.139020@e65g2000hsc.googlegroups.com> Message-ID: "oscartheduck" wrote in message news:1175708304.034078.139020 at e65g2000hsc.googlegroups.com... |I have a small script for doing some ssh stuff for me. I could have | written it as shell script, but wanted to improve my python skills | some. | | RIght now, I'm not catching a syntax error as I'd like to. | | Here's my code: | | #!/usr/bin/env python | import sys | import os | | port = input("Please enter a port to connect on. If you're unsure or | just want the default of port 2024 just hit enter -- ") | | | try: | if port > 65535: | print "That's not a valid port number, sorry. Between 0 and 65535 | is cool." | sys.exit() | else: | cmd = 'su root -c "/usr/sbin/sshd -p %s"' % port | except SyntaxError: | cmd = 'su root -c "/usr/sbin/sshd -p 2024;exit"' | | os.system(cmd) | | | I'm under the impression that the except should catch the syntax error | and execute the "default" command, but hitting enter at the input | value doesn't lead to that. Any ideas what's going wrong? Try putting the input statement after the try statement. From cjames at callone.net Tue Apr 10 08:26:15 2007 From: cjames at callone.net (c james) Date: Tue, 10 Apr 2007 07:26:15 -0500 Subject: "Plugin" architecture - how to do? In-Reply-To: <1176124020.074341.144740@o5g2000hsb.googlegroups.com> References: <1175785055.668181.308140@b75g2000hsg.googlegroups.com> <1175867963.727762.321170@l77g2000hsb.googlegroups.com> <1176124020.074341.144740@o5g2000hsb.googlegroups.com> Message-ID: Take a look at Trac. This might give you some ideas. http://trac.edgewall.org/wiki/TracDev/ComponentArchitecture From gagsl-py2 at yahoo.com.ar Mon Apr 23 04:55:10 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 23 Apr 2007 05:55:10 -0300 Subject: Two syntax questions (newbie) References: <1177316126.432039.232300@o5g2000hsb.googlegroups.com> Message-ID: En Mon, 23 Apr 2007 05:15:26 -0300, Szabolcs escribi?: > Mathematica allows writing > result = processData at Reverse@Sort at data > or even > result = data//Sort//Reverse//processData > instead of > result = processData[Reverse[Sort[data]]] > > In Python this would be something like > result = processData(list(reversed(sorted(data)))) > > The first two Mma alternatives are both easier to read (especially > when part of a bigger expression) and easier to type (an re-type, if > working interactively) because I don't have to jump with the cursor to > the beginning and end of the expression to insert the brackets when > adding another function call. > > Is there a way to avoid typing all the parentheses in Python? Is it > possible to define a different syntax for function calls Not a different syntax. > or define a > function composition operator for functions that take a single > argument? You could use this: def chain(*args): """Compose functions (assoc right). last argument (args[-1]): argument to last function args[0] .. args[-2]: functions taking a single argument Returns args[0](args[1](...(args[-2]))(args[-1]) """ args = list(args) data = args.pop(-1) while args: fn = args.pop(-1) data = fn(data) return data import random items = [random.randrange(100) for _ in range(20)] print chain(list, reversed, sorted, items) > Of course Python is not Mathematica and not as friendly with this > style as Mma is. Sometimes it forces me to use some temporary > variables (e.g. because lines get too long and breaking lines with a > backslash is ugly). I almost never use backslashes for line continuation. If you have an open (,[,{ continuation is implicit. If not, usually adding a heading ( is enough. That is, instead of x = a + b + \ c - d I'd use: x = (a + b + c - d) > I like to get rid of these variables as soon as > they aren't needed, e.g.: > > temp = data[:] > temp.sort() > temp.reverse() > result = processData(temp) > del temp > > Is it possible to avoid the explicit del temp? In C/C++ I would simply > enclose the piece of code in curly brackets. Is it possible to somehow > separate a block of code from the rest of the program and make > variables local to it? Python does not have block scope; use a function instead. (It's hard to define block scopes without variable declarations). Anyway that would make any difference if you are using huge structures. -- Gabriel Genellina From gagsl-py2 at yahoo.com.ar Sat Apr 7 16:19:06 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: 7 Apr 2007 13:19:06 -0700 Subject: Comments in ConfigParser module In-Reply-To: References: Message-ID: <1175977146.653832.245350@p77g2000hsh.googlegroups.com> Joel Andres Granados wrote: > The module also allows the comments to appear in the same line as the > "name = value" constructs. The only difference being that this is only > possible with ";" and not with "#" character. I did not see this in the > documentation but this is how it is behaving. Yes, it's not documented. There is only a comment in the source code: # ';' is a comment delimiter only if it follows # a spacing character I think it's either a bug in the code or in the documentation. > QUESTION...So the question is: > Can you use "#" and ";" as comment characters? and if so why does the > "#" not apply for the same situations as the ";"? If you follow the documentation, comments are ONLY allowed to start a line. The actual implementation discards any text following a ; sequence. > Just for reference: > On the RFC 822 (a document > referenced in the documentation) there is a mention of ";" being used as > comment character but not necessarily at the beginning of the line. RFC822 uses ";" to include comments in the syntax rules, not for comments in the actual message headers (parenthesis are used there). -- Gabriel Genellina From apardon at forel.vub.ac.be Mon Apr 23 05:36:15 2007 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 23 Apr 2007 09:36:15 GMT Subject: When are immutable tuples *essential*? Why can't you just use lists *everywhere* instead? References: <1177088796.622928.224890@d57g2000hsg.googlegroups.com> <1177089206.550423.288670@q75g2000hsh.googlegroups.com> <58sf33F2b1q8tU1@mid.individual.net> Message-ID: On 2007-04-20, Gabriel Genellina wrote: > En Fri, 20 Apr 2007 15:28:51 -0300, Bjoern Schliessmann > escribi?: > >> Luis M. Gonz?lez wrote: >> >>> I don't remember exactly where I read about it, but Guido said >>> once that tuples are being kept mainly for historical reasons. >> >> Weren't tuples added when lists already existed? > > Both listobject.c and tupleobject.c appear to had been checked in at the > same time: > > Revision 2167 - (view) (download) (as text) - [select for diffs] > Added Sun Oct 14 12:07:46 1990 UTC (16 years, 6 months ago) by guido > File length: 4965 byte(s) > Initial revision > > And that's before the earliest tagged release I could find on svn, Python > 0.98 But this doesn't contradict the supposed comment from guido. One can add something later and come to the conclusion that it would have been better not included but that in the mean time too much depend on it to remove it. That seems a perfect description of keeping something for historical reasons. So it is possible that one keeps something for historical reasons that is more recent than something one keeps for design reasons. -- Antoon Pardon From rw at smsnet.pl Thu Apr 19 03:43:09 2007 From: rw at smsnet.pl (Rob Wolfe) Date: 19 Apr 2007 00:43:09 -0700 Subject: Question about Tkinter MenuOption variable In-Reply-To: <1176955769.756104.59440@y80g2000hsf.googlegroups.com> References: <1176955769.756104.59440@y80g2000hsf.googlegroups.com> Message-ID: <1176968589.524252.70540@b58g2000hsg.googlegroups.com> Chad wrote: > Is there anyway to set the individual options in Tkinter to a > particular variable. For example, I have a menu option(code is below) > which has January, February, March and so on, which I would like to > have corresponding values of 01, 02, 03 and so on. Can someone please > tell me how to do that within the context of the code I have below - > or even totally modify it if you must. > > Label(self, > text = "Month" > ).grid(row = 5, column = 1, sticky = W) > OPTIONS = [ > "Jan", > "Feb", > "Mar", > "Apr", > "May", > "June", > "July", > "Aug", > "Sep", > "Oct", > "Nov", > "Dec"] > default_option = StringVar(self) > default_option.set(OPTIONS[0]) > self.month_option = OptionMenu(self, default_option, *OPTIONS) > self.month_option.grid(row = 5, column = 2, sticky = W) What about using dictionary? For example: import Tkinter as Tk def state(): print OPTIONS[default_option.get()] root = Tk.Tk() Tk.Label(root, text="Month").grid(row=1, column=1, sticky=Tk.W) OPTIONS = dict(Jan=1, Feb=2, Mar=3, Apr=4, May=5, June=6, July=7, Aug=8, Sep=9, Oct=10, Nov=11, Dec=12) # or #OPTIONS = dict(Jan="01", Feb="02", Mar="03", Apr="04", May="05", June="06", July="07", # Aug="08", Sep="09", Oct="10", Nov="11", Dec="12") default_option = Tk.StringVar() default_option.set("Jan") month_option = Tk.OptionMenu(root, default_option, *OPTIONS.keys()) month_option.grid(row=1, column=2, sticky=Tk.W) Tk.Button(root, command=state, text='state').grid(row=2, column=1) root.mainloop() -- HTH, Rob From aboudouvas at panafonet.gr Tue Apr 10 18:04:00 2007 From: aboudouvas at panafonet.gr (king kikapu) Date: 10 Apr 2007 15:04:00 -0700 Subject: About Trolltech QT OpenSource license. In-Reply-To: References: <1176233376.712861.67160@o5g2000hsb.googlegroups.com> Message-ID: <1176242640.630110.121120@y5g2000hsa.googlegroups.com> ?/? Peter Decker ??????: > There is another alternative: Dabo, which wraps the wxPython toolkit. > It has a GUI designer, although not as polished as the Qt Designer. > Check out some of their screencasts to see their tools in action. You > can find them at http://dabodev.com/documentation I am aware but i prefer to use PythonCard if i choose wxPython over Qt. I think Dadbo has a lot of work to be done, it is surely very promising, thanks! @ Kevin and Jarek : thanks for the enlightening of that GPL thing. So, if i understand, i create my Python software using Qt as my GUI, i earn the money for it with the obligation to release my source code and somewhere in my files i explicilty write that this software is under the GPL lisence, is that correct ?? And i am legal all the way out ?? So why these people at Trolltech have the word "Commercial" at their mouth all the time ?? I can understand of course that money is all about but becauce they released Qt under GPL they simply cannot prevent anyone from gaining money using it. From zhonghua.m.yang at gmail.com Tue Apr 3 00:33:58 2007 From: zhonghua.m.yang at gmail.com (ZMY) Date: 2 Apr 2007 21:33:58 -0700 Subject: python installation destination directory Message-ID: <1175574838.705561.203310@n76g2000hsh.googlegroups.com> Hi all, I am installing python 2.2 on QNX4.25 but can't get it into /usr/local/ bin/ directory. Here is what I did: 1) untar Python-2.2 into directory /openqnx/Python-2.2/ 2) use command: CONFIG_SHELL=/usr/local/bin/bash CC=cc RANLIB=: ./configure --verbose --without-gcc --with-libm="" 3) Enabled array, math, os, struct, time, cmath modules 4) use command: make SHELL=/usr/local/bin/bash and I got a python excutable in directory /openqnx/Python-2.2/ which works well with all the modules. But I really want to have it at /usr/local/bin I checked the Makefile, and it seems python should be installed in / usr/local/bin instead, since I got following lines in Makefile: # Install prefix for architecture-independent files prefix= /usr/local # Install prefix for architecture-dependent files exec_prefix= ${prefix} Do any of you know what the problem is? Thanks a lot in advance. - ZMY From cam.ac.uk at mh391.invalid Fri Apr 27 09:19:52 2007 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Fri, 27 Apr 2007 14:19:52 +0100 Subject: getting rid of EOL character ? In-Reply-To: <268cc$4631f634$83aef404$27224@news1.tudelft.nl> References: <268cc$4631f634$83aef404$27224@news1.tudelft.nl> Message-ID: stef wrote: > hello, > > In the previous language I used, > when reading a line by readline, the EOL character was removed. > > Now I'm reading a text-file with CR+LF at the end of each line, > Datafile = open(filename,'r') line = Datafile.readline() > > now this gives an extra empty line > print line > > and what I expect that should be correct, remove CR+LF, > gives me one character too much removed > print line[,-2] > > while this gives what I need ??? > print line[,-1] > > Is it correct that the 2 characters CR+LF are converted to 1 character ? > Is there a more automatic way to remove the EOL from the string ? line = line.rstrip("\r\n") should take care of it. If you leave out the parameter, it will strip out all whitespace at the end of the line, which is what I do in most cases. -- Michael Hoffman From steve at holdenweb.com Sun Apr 1 05:43:49 2007 From: steve at holdenweb.com (Steve Holden) Date: Sun, 01 Apr 2007 05:43:49 -0400 Subject: Mastering Python In-Reply-To: <000f01c771d2$2fc41940$03000080@hendrik> References: <1174045298.826137.262890@o5g2000hsb.googlegroups.com><1174052358.486071.163280@e65g2000hsc.googlegroups.com><46018fd8$0$18018$426a74cc@news.free.fr><46091cdf$0$19664$426a74cc@news.free.fr> <000f01c771d2$2fc41940$03000080@hendrik> Message-ID: Hendrik van Rooyen wrote: > "Dennis Lee Bieber" wrote: > > >> On Wed, 28 Mar 2007 07:55:20 +0200, "Hendrik van Rooyen" >> declaimed the following in comp.lang.python: > >>> Pretty obvious of course, as is the pronounciation of the >>> name: "Cholmondely" >>> >> Is that a scottish "Ch" (as in LoCH Lomond), plain hard "Ch" (as in >> CHristmas) or a soft "Ch" (as in CHicken)? > > It comes out something like "Chum-lee", with the ch like chicken... > > (that's what I have heard - but who knows - It may have been > a regional dialect, a case of the blind leading the blind, or > someone pulling the piss..) > You have been correctly informed. It's one of the least intuitive names in the English language. 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 michael at jedimindworks.com Wed Apr 11 07:22:31 2007 From: michael at jedimindworks.com (Michael Bentley) Date: Wed, 11 Apr 2007 06:22:31 -0500 Subject: Pass A Var To a Python Script? In-Reply-To: References: Message-ID: <4C842BB6-F09F-44C5-ACA1-8CCED41B349A@jedimindworks.com> On Apr 7, 2007, at 1:13 PM, Eric Price wrote: > Hi; > How do I pass a variable to a python script? Something like this > (which > doesn't work): > > ./test.py?var=hello_world The easiest thing would be to drop the '?var=': ./test.py hello_world Then in your script, use sys.argv to gather the argument (hello_world). hth, Michael From markscala at gmail.com Sun Apr 22 09:55:14 2007 From: markscala at gmail.com (markscala at gmail.com) Date: 22 Apr 2007 06:55:14 -0700 Subject: function minimization Message-ID: <1177250114.342886.160520@o5g2000hsb.googlegroups.com> Is anyone aware of python library that does function minimization a la Minuit (http://wwwasdoc.web.cern.ch/wwwasdoc/minuit/) used by CERN? thanks From paul at boddie.org.uk Wed Apr 11 05:11:38 2007 From: paul at boddie.org.uk (Paul Boddie) Date: 11 Apr 2007 02:11:38 -0700 Subject: installing pyqt4 on ubuntu 6.06 In-Reply-To: <461bcf9c$0$21364$88260bb3@free.teranews.com> References: <80628d680704100833y197473d2wb421bdec5cd79aae@mail.gmail.com> <461bcf9c$0$21364$88260bb3@free.teranews.com> Message-ID: <1176282698.114924.167700@y5g2000hsa.googlegroups.com> On 10 Apr, 20:48, "Joshua J. Kugler" wrote: > On Tuesday 10 April 2007 07:35, Pradnyesh Sawant wrote: > > > Any pointers regarding what packages should i install to get the > > system into working condition would be very helpful > > It's next to impossible, due to conflicts with SIP, and other dependencies. > See these two threads (both started by me) for more information: > > http://ubuntuforums.org/showthread.php?t=243936 > http://ubuntuforums.org/showthread.php?t=244612 Yes, so much for cutting edge packages in the bleeding edge Ubuntu releases. Anyway, I've previously made PyQt4 packages for Ubuntu Hoary based on the Debian (and possibly Ubuntu) sources plus diffs, and as far as I remember you just need to choose a version of SIP which is capable of working with both the PyQt3 and PyQt4 sources. I think I also had to upgrade my PyQt3 stuff in the process, but since the stuff shipped with Hoary is almost archaic, that was on the cards, anyway. Sadly, you'll probably get into issues with the various applications which need PyQt3, and it might be necessary to rebuild them. I'd provide some details of what I've done, but they aren't currently to hand, so I'll try and post some more information at a later time. Paul From bruno.42.desthuilliers at wtf.websiteburo.oops.com Fri Apr 20 10:03:38 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Fri, 20 Apr 2007 16:03:38 +0200 Subject: Python Feature Request: Explicit variable declarations In-Reply-To: <1176546078.934340.253810@y5g2000hsa.googlegroups.com> References: <1176546078.934340.253810@y5g2000hsa.googlegroups.com> Message-ID: <4628c819$0$2337$426a74cc@news.free.fr> samjnaa at gmail.com a ?crit : > Hello. Please tell me whether this feature request is sane (and not > done before) for python so it can be posted to the python-dev mailing > list. I should say first that I am not a professional programmer with > too much technical knowledge. > > I would like to have something like the "option explicit" statement in > Visual Basic which turns on C-like checking for declaration of > variables. This is highly helpful for people who are coming from C/C+ > +, for people who are learning programming using Python, and even > professionals, since this helps prevent typo errors like: > > sunlognitude = sunlongitude + 180.0 > > where the user has inadvertantly typed "g" before "n" and will later > wonder why his application is not working as expected. > if you find declarative static typing programmer-friendly, then Python is definitively not for you, and you'd better look for something else (Java ?). FWIW, the first and main reason for stating typing is about compiler's hint and raw performances, not "type-safety". (A professional programmer with restricted technical knowledge and absolutely no need for this kind of "help") From apardon at forel.vub.ac.be Thu Apr 12 03:37:38 2007 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 12 Apr 2007 07:37:38 GMT Subject: tuples, index method, Python's design References: <1176210960.3430.20.camel@dot.uniqsys.com> <740c3aec0704100810g5f962e8eu614fbaedecf3608e@mail.gmail.com> <1176219856.3430.76.camel@dot.uniqsys.com> <740c3aec0704101021i1fd79ef2l99eac4ced1e252d9@mail.gmail.com> <1176226682.3430.86.camel@dot.uniqsys.com> <4866bea60704101104r4600d281h135286b66378f4d4@mail.gmail.com> <740c3aec0704101534y3c65f5a7je382f97e1f6301b7@mail.gmail.com> <1176305859.581010.199600@n76g2000hsh.googlegroups.com> Message-ID: On 2007-04-11, Chris Mellon wrote: > On 11 Apr 2007 08:37:39 -0700, Paul Boddie wrote: >> On 11 Apr, 16:14, "Chris Mellon" wrote: >> > >> > If you want a language that just adds whatever methods anyone thinks >> > of, along with whatever aliases for it any can think of, to every data >> > type, you know where to find Ruby. >> >> Nobody is asking for Ruby, as far as I can see. I even submitted a >> quick patch to provide tuple.index (a method that has already been >> thought of), given the triviality of the solution, but you won't find >> me asking for a bundle of different convenience methods with all their >> aliases on every object, regardless of whether you can monkey-patch >> them after the fact or not. For example: >> > > Note that the mail I responded to was using being drunk, not knowing > any better, and having fun as use cases for the method. That sounds > like Ruby-style method proliferation to me ;) > > >> Note that, in that document, index and count are methods of >> MutableSequence. Quite why this should be from a conceptual >> perspective is baffling, but don't underestimate the legacy influence >> in such matters. >> > > Well, I'm not Guido obviously, but here's why I don't find it baffling. > > There are 2 main reasons why you'd use an immutable sequence for something: > 1) You want to make sure it's not modified by a callee. This is > unPythonic and mostly unnecessary. Pass them a copy if you're that > paranoid. Why then does python itself provide immutables? I find this reasoning more than baffling. There has been all these arguments about why it is best to use immutables as dictionary keys. But the moment the topic changes, someone else comes with the comment that wanting your sequence to be immuatble is unpythonic. I once had a problem I like to solve by having a dictionary where the keys were multidimensional points on an integer grid. For a number of reasons I thought it would be easier if I could use lists, but most people argued that would be a bad idea and that I should use tuples, because they are immutable. Of course if I now would want to find out if the point is on an axis and which axis that is, I cannot use index because that is not available. -- Antoon Pardon From 4564 at 755189.45 Thu Apr 12 05:12:00 2007 From: 4564 at 755189.45 (Enrico) Date: Thu, 12 Apr 2007 11:12:00 +0200 Subject: Calling private base methods References: Message-ID: <461df7db$0$4791$4fafbaef@reader4.news.tin.it> "Jorgen Bodde" ha scritto nel messaggio news:mailman.6393.1176367681.32031.python-list at python.org... > Hi All, > > Now that I am really diving into Python, I encounter a lot of things > that us newbies find difficult to get right. I thought I understood > how super() worked, but with 'private' members it does not seem to > work. For example; > > >>> class A(object): > ... def __baseMethod(self): > ... print 'Test' > > Deriving from A, and doing; > > >>> class D(A): > ... def someMethod(self): > ... super(A, self).__baseMethod() > ... print 'test3' > > Will not work; if you type >> dir(A) you'll get a method named _A__baseMethod >From the documentation: Private name mangling: When an identifier that textually occurs in a class definition begins with two or more underscore characters and does not end in two or more underscores, it is considered a private name of that class. Private names are transformed to a longer form before code is generated for them. The transformation inserts the class name in front of the name, with leading underscores removed, and a single underscore inserted in front of the class name. For example, the identifier __spam occurring in a class named Ham will be transformed to _Ham__spam. This transformation is independent of the syntactical context in which the identifier is used. If the transformed name is extremely long (longer than 255 characters), implementation defined truncation may happen. If the class name consists only of underscores, no transformation is done. Enrico From slm_guzel at hotmail.com Mon Apr 2 17:30:54 2007 From: slm_guzel at hotmail.com (gslm) Date: 2 Apr 2007 14:30:54 -0700 Subject: doing standart window icons unvisible in python Message-ID: <1175549454.378661.93570@y66g2000hsf.googlegroups.com> Hi! I want to do close-minimize icons unvisible in python.How can I do this?I want to do this especially for printing. And is it possible to provide .exe file for any program in python or only we can change the file as .pyw? From grante at visi.com Thu Apr 26 09:37:42 2007 From: grante at visi.com (Grant Edwards) Date: Thu, 26 Apr 2007 13:37:42 -0000 Subject: Access to raw command line? References: <1177571070.229968.155710@t39g2000prd.googlegroups.com> Message-ID: <1331ap6quirih40@corp.supernews.com> On 2007-04-26, Pieter Edelman wrote: > Hi, > > I'm currently writing a command-line program in Python, which takes > commands in the form of: > ./myprog.py [OPTIONS] ARGS > So pretty standard stuff. In my case, ARGS is a list of image files. > > One of the possible options is to specify a file holding information > about the photos. You'd specify it with (in this particular case) the - > t switch, and you can specify multiple files by repeating this switch: > ./myprog.py -t info1.gpx -t info2.gpx -t info3.gpx *jpg > > Now, one of the users has quite a lot of info files, and asked me if > it's possible to use a wildcard in specifying these, so he would just > have to do: > ./myprog.py -t *.gpx *.jpg > > This seems like a sensible option at first sight, but it's difficult > to implement because the wildcard is expanded by the shell, You should buy a new keyboard. The latest ones have quote keys -- both single _and_ double! -- Grant Edwards grante Yow! What PROGRAM are they at watching? visi.com From adam.won at gmail.com Sat Apr 21 22:16:37 2007 From: adam.won at gmail.com (=?gb2312?B?u7W1sA==?=) Date: 21 Apr 2007 19:16:37 -0700 Subject: Give me the google group address in Chinese. Message-ID: <1177208197.176088.121800@q75g2000hsh.googlegroups.com> It's really annoying to find there are all English language posts here because I wanna talk about something about the Chinese related programs. Could you give me some ? From oshecho at gmail.com Tue Apr 10 13:41:09 2007 From: oshecho at gmail.com (Echo) Date: Tue, 10 Apr 2007 13:41:09 -0400 Subject: Having trouble with relative imports In-Reply-To: <910885da0704091034u5e874dfen10d4846dae2ffc08@mail.gmail.com> References: <910885da0704091034u5e874dfen10d4846dae2ffc08@mail.gmail.com> Message-ID: <910885da0704101041m51af0461ta8f6d03fd02f911d@mail.gmail.com> On 4/9/07, Echo wrote: > Here is my setup: > rpg > -objects > --__init__.py > --gameobject.py > --material.py > -__init__.py > -run_tests.py > -stats.py > > the contents of run_test.py is: > import objects as o > > the contents of objects/__init__.py is: > from material import * > > in objects/material.py I have: > from .gameobject import GameObject > from ..stats import stats > > When I try to run run_tests.py, I get this traceback: > (1:30:59 PM) OshEcho: echo at MobileEcho ~/projects/rpg $ python run_tests.py > Traceback (most recent call last): > File "run_tests.py", line 4, in > import objects as o > File "/home/echo/projects/rpg/objects/__init__.py", line 3, in > from material import * > File "/home/echo/projects/rpg/objects/material.py", line 4, in > from ..stats import stats > ValueError: Attempted relative import beyond toplevel package > > > Could someone point out to me what I am doing wrong? > I'm running Python 2.5 on Gentoo > > -- > -Echo > Well, since I've gotten no answer and since that Python 2.5 doesn't play well with some programs on Gentoo, I will be switch back to 2.4 for now. -- -Echo From steve at holdenweb.com Fri Apr 20 16:16:16 2007 From: steve at holdenweb.com (Steve Holden) Date: Fri, 20 Apr 2007 16:16:16 -0400 Subject: Newbie question regarding string.split() In-Reply-To: <9C4465B8-6A24-4624-9593-DE18714E356E@mac.com> References: <1177095062.826018.63590@n59g2000hsh.googlegroups.com> <1177096533.564349.285930@q75g2000hsh.googlegroups.com> <9C4465B8-6A24-4624-9593-DE18714E356E@mac.com> Message-ID: Tommy Grav wrote: > On Apr 20, 2007, at 3:15 PM, kyosohma at gmail.com wrote: >> On Apr 20, 1:51 pm, kevinliu23 wrote: >>> ['', 'b34bx5b', 'c4a5a6'] >>> >>> My question is, why is the first element of projectOptions an empty >>> string? What can I do so that the first element is not an empty >>> string? but the 'b34bx5b' string as I expected? >>> >>> Thanks so much guys. :) >> The reason you have an empty string at the beginning is because you >> are "splitting" on a character that happens to include the first >> character in your string. So what you are telling Python to do is to >> split the beginning from itself, or to insert a blank so that it is >> split. > > So why does this not happen when you use the empty split() function? > > [tgrav at Thrym] /Users/tgrav --> python > Python 2.4.4 (#1, Oct 18 2006, 10:34:39) > [GCC 4.0.1 (Apple Computer, Inc. build 5341)] on darwin > Type "help", "copyright", "credits" or "license" for more information. > >>> a = " 456 556 556" > >>> a.split() > ['456', '556', '556'] > >>> a.split(" ") > ['', '456', '556', '556'] > >>> > > What exactly does .split() use to do the splitting? > Any sequence of one or more whitespace characters. This is a rather special case, quite different from .split(" "). 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 mensanator at aol.com Sun Apr 15 20:36:37 2007 From: mensanator at aol.com (mensanator at aol.com) Date: 15 Apr 2007 17:36:37 -0700 Subject: combination function in python In-Reply-To: References: <1176615838.830315.160210@b75g2000hsg.googlegroups.com> <1176629911.409257.149780@l77g2000hsb.googlegroups.com> <1176669548.436118.176300@e65g2000hsc.googlegroups.com> Message-ID: <1176683797.421863.16980@o5g2000hsb.googlegroups.com> On Apr 15, 4:16?pm, Anton Vredegoor wrote: > mensana... at aol.com wrote: > >> We're getting closer and closer to something I already posted a few > >> times here. This implementation was unfortunate because I consistently > >> used an uncommon name for it so people couldn't easily find it > > > But then, who's looking for it? > > The OP was trying to find it in the docs, assuming it was some kind of > builtin function. I can see the logic of that and I can also see the > logic of including some other smallish functions like for example fac. > Failing that, the next recourse would be the Internet, or a Usenet > search but that would imply well named Usenet posts and function names. Isn't that what docstrings are for? Can't you leave the function name noverk() and add something to the effect of "this function calculates combinations"? Then it would show up in searches, wouldn't it? > > >> (mea culpa), and maybe also because it uses the despised reduce builtin. > > >> def noverk(n,k): > >> ? ? ?return reduce(lambda a,b: a*(n-b)/(b+1),xrange(k),1) > > This is a rather concise function which has the added advantage that it > returns 0 when k>n. import gmpy print gmpy.comb(4,8) ## 0 > > >> BTW I hereby give up the strange name for this and request a better name > >> that everybody will use so there will be no confusion anymore. Maybe > >> comb(n,k) ? > > > No, that name's already used by gmpy. And a single > > function doesn't replace all of gmpy's other > > functionality, many of which are needed in the > > same applications where comb() is used, so there's > > really no need for your function. > > Actually, by proposing comb I am *honoring* gmpy and > I'm also complying with it. Perhaps you should use the name comb_works_just_like_the_gmpy_version_only_slower() > In Python we use namespaces to differentiate between such > things. Provided they get used. > You might want to read the documentation about it some time. But *I* always use namespaces, as *I've* read the documentation. But when there *is* no documentation, that becomes a problem, doesn't it? > > > Your time is better spent applying the tools provided > > by gmpy rather than trying to re-invent the wheel. > > Please let me be the judge of how to spend my time. Suit yourself. > In this case it seems rather unjustified to introduce > dependencies on external modules when only a few functions > are needed. Unless you don't know how to write the functions you need in which case you're better off relying on external modules. Have you ever wondered why Python even *has* a standard library? Why doesn't everyone just write the functionality they need? > Since I'm also interested in the > functions themselves -in this case- I'd rather have a > few lines of code in my source than importing an > optimized code library. Well, some people prefer optimized libraries because they have real work to do, not just acedemic excercizes. > There *are* > situations where such things are completely justified, > but I don't think this is one of them. So it doesn't matter whether anyone can find noverk(), does it? > You could take it up with the gmpy author and > induce him to get gmpy included in the standard distro if you are so > inclined. Alex Martelli knows more about that subject than I and it would be pointless for me to bug him about it. > > A. From nospam at noemailhere.nowhere Fri Apr 13 02:02:32 2007 From: nospam at noemailhere.nowhere (Anthony Irwin) Date: Fri, 13 Apr 2007 16:02:32 +1000 Subject: Databases with python Message-ID: Hi All, I am interested in playing with python some more and am looking at writing an app with data stored in a database. I have experience with mysql but thought that their may be other better databases that can be more easily distributed with the program does anyone have any suggestions here? I only use linux myself but I can foresee some windows people wanting to use what I create and if I am going to support windows then I might as well support mac too. (this is to say that the database should support the 3 main platforms in use) Also is wxpython the best cross platform gui library it seems to be the best I have seen so far. -- Kind Regards, Anthony Irwin http://www.irwinresources.com email: anthony at the above domain, - www. From cam.ac.uk at mh391.invalid Thu Apr 26 12:22:01 2007 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Thu, 26 Apr 2007 17:22:01 +0100 Subject: My python annoyances so far In-Reply-To: <1177603623.774892.230390@t38g2000prd.googlegroups.com> References: <1177541453.471959.120830@c18g2000prb.googlegroups.com> <59bf34F2k27v5U1@mid.individual.net> <1177603623.774892.230390@t38g2000prd.googlegroups.com> Message-ID: flifus at gmail.com wrote: > Well, why do some things in the library have to be functions, and > other things have to be class methods? They don't have to be. They just are. That's like asking why do some functions start with the letters a-m, and others with n-z. Why can't they all begin with a-m? The answer would be that it would make the language harder to use to cram concepts that should more naturally start with n-z into spellings that start with a-m. -- Michael Hoffman From steve at holdenweb.com Tue Apr 10 11:29:43 2007 From: steve at holdenweb.com (Steve Holden) Date: Tue, 10 Apr 2007 11:29:43 -0400 Subject: tuples, index method, Python's design In-Reply-To: <1176215231.002726.148960@y5g2000hsa.googlegroups.com> References: <1175867771.114540.61810@n76g2000hsh.googlegroups.com> <1175884427.779950.267220@y80g2000hsf.googlegroups.com> <1175953520.316208.241490@o5g2000hsb.googlegroups.com> <7xzm5igbrb.fsf@ruckus.brouhaha.com> <1176200361.260546.280510@n76g2000hsh.googlegroups.com> <1176215231.002726.148960@y5g2000hsa.googlegroups.com> Message-ID: Paul Boddie wrote: > On 10 Apr, 15:57, Steve Holden wrote: >> The point I am trying to make is that circumstances alter cases, and that we >> can't always rely on our intuition to determine how specific methods >> work, let alone whether they are available. > > But it's telling that by adopting precisely the implementation that we > currently have for lists, we can have a tuple method which does what > most people would reasonably expect. "Why are we suddenly getting > single characters instead of whole strings?" people have presumably > exclaimed often enough, illustrating that the sequence nature of > strings is a controversial topic. Lists and tuples, however, don't > have such controversial baggage. > You can call something non-controversial when it generates a thread like this? :-) It's really a storm in a teacup. The acid test would be to generate a patch that added the method and then see if you could get a committer to commit it. All else (including my own contributions) is mere hot air. >> I hear the screams of "just add the index() method to tuples and have >> done with it" and, to an extent, can sympathize with them. But that way >> lies creeping featurism and the next thing you know we'll have a ternary >> operator in the language - oh wait, we do now! > > Yes, but the cost of adding index to tuples is minimal, and the mental > cost to programmers is arguably negative. Meanwhile, we now have to > put up with the syntactic bodge that is the ternary operator until the > time comes when it gets deprecated as something that didn't work out > or wasn't really necessary (in Python 4000, perhaps), meaning that we > now have to read third-party code more carefully, the people writing > editors and tools have to change their lexers/parsers again, and so > on. > What can I say? Every language has warts. Some people were as anxious to see if ... else (which I regard as a wart) put in as others are to see tuple.index(). 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 holdenweb.com Fri Apr 13 12:34:15 2007 From: steve at holdenweb.com (Steve Holden) Date: Fri, 13 Apr 2007 12:34:15 -0400 Subject: function/method assigment In-Reply-To: <1176480852.643836.121930@p77g2000hsh.googlegroups.com> References: <1176480852.643836.121930@p77g2000hsh.googlegroups.com> Message-ID: viscroad at gmail.com wrote: > I have a confusion when I do some practice, the code and output are as > following, > >>>> def fun(): > print 'In fun()....' > > >>>> testfun = fun() > In fun().... >>>> print testfun > None >>>> testfun2 = fun >>>> print testfun2 > >>>> print testfun2() > In fun().... > None > > what is 'testfun'? Why it is 'None'? And print testfun2(), what is the > meaning of 'None'? > > Thanks! > > When a function does not specifically return a value then its return value is a particular value known as None, the only instance of the None type. So testfun is the result of calling the fun function, and it's None because fun() does not return a value. Since testfun2 is just another reference to the fun function, testfun2() is None for exactly the same reasons. 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 kelvin.you at gmail.com Mon Apr 9 04:45:47 2007 From: kelvin.you at gmail.com (=?utf-8?B?5Lq66KiA6JC95pel5piv5aSp5rav77yM5pyb5p6B5aSp5rav5LiN6KeB5a62?=) Date: 9 Apr 2007 01:45:47 -0700 Subject: Is there a simple function to generate a list like ['a', 'b', 'c', ... 'z']? In-Reply-To: References: <1176107364.000517.68580@q75g2000hsh.googlegroups.com> Message-ID: <1176108347.228630.126410@e65g2000hsc.googlegroups.com> On Apr 9, 4:39?pm, Thomas Kr?ger wrote: > ??????????????? schrieb: > > > Is there a simple function to generate a list like ['a', 'b', 'c', ... > > 'z']? ? The range() just can generate the numeric list. > > There is: > [ chr(i) for i in range(97, 123) ] > > Thomas Thanks you too! I'm a beginner of python. From i3dmaster at gmail.com Wed Apr 11 23:23:36 2007 From: i3dmaster at gmail.com (i3dmaster) Date: 11 Apr 2007 20:23:36 -0700 Subject: Universal Feed Parser issue In-Reply-To: References: <1176227922.910993.36910@y80g2000hsf.googlegroups.com> <1176267073.787216.80170@n76g2000hsh.googlegroups.com> <1176311235.792366.296010@b75g2000hsg.googlegroups.com> Message-ID: <1176348216.424419.65220@y80g2000hsf.googlegroups.com> On Apr 11, 12:01 pm, "Gabriel Genellina" wrote: > En Wed, 11 Apr 2007 14:07:15 -0300, i3dmaster > escribi?: > > > Hmm... well I don't know if I made my question clear then or you might > > have misread it?... Anyway, the namespace handling wasn't the issue > > of this question. feedparser handles it as expected but only when > > there is a text value associated with it. Look at the rdf file you > > will see the prism:issn element has a text value but in my case, the > > foo:timezone element DOES NOT have a text value but a Attribute or > > maybe attributes... What it looks like is feedparser simply ignores > > all the attributes when parsing it. This behavior wasn't seen from > > other xml parsers though. > > Oh, sorry! I thought you were complaining about the namespace. > You're out of luck with this parser - see my own reply on January for a > similar issue:http://mail.python.org/pipermail/python-list/2007-January/422237.html > > -- > Gabriel Genellina Ok no problem. Back to my original question, should this be considered a bug (didn't see a bug reported though) ? Do you know if the developer is considering fixing it in the future? Thanks, Jim From xellzhang at gmail.com Thu Apr 5 01:40:38 2007 From: xellzhang at gmail.com (Xell Zhang) Date: Thu, 5 Apr 2007 13:40:38 +0800 Subject: problem with my urllib.urlopen() function Message-ID: hello all, I am a newbie in Python. In my module, if I call urllib.urlopen() function like: url = "http://www.google.com/" source = urllib.urlopen(url) Then in the output there will be an exception: Exception exceptions.AttributeError: "'NoneType' object has no attribute 'print_exc'" in > ignored I do not know why, if I did something wrong? -------------- next part -------------- An HTML attachment was scrubbed... URL: From yf110 at vtn1.victoria.tc.ca Thu Apr 5 21:48:13 2007 From: yf110 at vtn1.victoria.tc.ca (Malcolm Dew-Jones) Date: 5 Apr 2007 17:48:13 -0800 Subject: Why NOT only one class per file? References: <1175721799.714907.52770@o5g2000hsb.googlegroups.com> Message-ID: <461598cd@news.victoria.tc.ca> Chris Lasher (chris.lasher at gmail.com) wrote: : A friend of mine with a programming background in Java and Perl places : each class in its own separate file in . Java doesn't actually require one class per file, it requires one public class per file. You can have any number of helper classes in the same file. Perl doesn't require anything, and files and classes are almost entirely different things (except by useful convention). I'm only just getting into python, so I have no opinions yet. From mwilson at the-wire.com Thu Apr 12 21:23:00 2007 From: mwilson at the-wire.com (Mel Wilson) Date: Thu, 12 Apr 2007 21:23:00 -0400 Subject: Lists and Tuples and Much More In-Reply-To: References: Message-ID: Scott wrote: > Now I read somewhere that you could change the list inside that tupple. But > I can't find any documentation that describes HOW to do it. The only things > I CAN find on the subject say, "Don't do it because its more trouble than > it's worth." But that doesn't matter to me, because I want to know > everything. 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. >>> aa = (1, 2, [3, 4]) >>> aa (1, 2, [3, 4]) >>> aa[2].append ((True, False)) >>> aa (1, 2, [3, 4, (True, False)]) >>> Like that. Mel. From rupole at hotmail.com Mon Apr 30 19:07:39 2007 From: rupole at hotmail.com (Roger Upole) Date: Mon, 30 Apr 2007 19:07:39 -0400 Subject: Python-URL! - weekly Python news and links (Apr 30) References: <1177963548_23061@sp12lax.superfeed.net> <961ig4-hti.ln1@lairds.us> Message-ID: <1177974549_23503@sp12lax.superfeed.net> "Cameron Laird" wrote in message news:961ig4-hti.ln1 at lairds.us... > In article <1177963548_23061 at sp12lax.superfeed.net>, > Roger Upole wrote: >>Cameron Laird wrote: >>> QOTW: "That is just as feasible as passing a cruise ship through a phone >>> line." - Carsten Haese, on transporting a COM object across a network. >>> Less vividly but more formally, as he notes, "A COM object represents a >>> connection to a service or executable that is running on one computer. >>> Transferring that connection to another computer is impossible." >>> >> >>While this is indeed a nice turn of phrase, in substance it's incorrect. >>You can marshal a live COM object and unmarshal it on a different >>machine. > . > . > . > ... but the *references* in that object are unlikely to be > meaningful on the second machine (or, in many cases, on the > original machine, if at a sufficiently later time). In practice, you can marshal and unmarshal an object as complex as Excel.Application which contains references to literally hundreds of objects. Roger ----== 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 irmen.NOSPAM at xs4all.nl Mon Apr 23 02:40:11 2007 From: irmen.NOSPAM at xs4all.nl (Irmen de Jong) Date: Mon, 23 Apr 2007 08:40:11 +0200 Subject: Select weirdness In-Reply-To: References: <462b3e47$0$326$e4fe514c@news.xs4all.nl> Message-ID: <462c54cb$0$336$e4fe514c@news.xs4all.nl> Ron Garret wrote: > I don't understand why socketserver calling select should matter. (And > BTW, there are no calls to select in SocketServer.py. I'm using > Python2.5.) You don't *need* a select at all. Socketserver just blocks on accept() and dispatches a handler on the new connection. >> Anyway, try the following instead: >> > > That won't work for POST requests. > Why not? Just add some more code to deal with the POST request body. There should be a content-length header to tell you how many bytes to read after the header section has finished. --Irmen From anbeyon at btinternet.com Thu Apr 5 09:32:11 2007 From: anbeyon at btinternet.com (Anbeyon) Date: 5 Apr 2007 06:32:11 -0700 Subject: Newbie - Boa Constructor, wxPython problem running Boa Message-ID: <1175779931.504252.75840@b75g2000hsg.googlegroups.com> Hi all I am a Newbie to the world of Python, wxPython and Boa. Please forgive me if there is a really obvious answer to this one. I am trying to get Python, wxPython and Boa all to install on my Windows XP machine. I have both Python and wxPython running. However, when I launch Boa I get an error message; An 'Error On Startup' dialog/message box is displayed that says; 'module' object has no attribute 'NotebookSizer' (Output on the console window is at the end of this message incase that helps.....) I click OK and everything closes. I have the following setup; Python2.5 --------------- installed using python-2.5.msi from http://www.python.org/download/releases/2.5/ wxPython for Python2.5 ------------------------------------ installed using http://prdownloads.sourceforge.net/wxpython/wxPython2.8-win32-unicode-2.8.3.0-py25.exe Boa Constructor ------------------------ installed using boa-constructor-0.4.4.win32.exe Does anyone have any ideas, thoughts as to what the problem might be ? The only thing I'm wondering is that instead of installing on my c: drive in installed on my d: drive ???? Thanks in advance Anbeyon >>>>>>> BELOW IS THE OUTPUT IN THE CONSOLE WINDOW WHEN I LAUNCH BOA <<<<<<<<<< Starting Boa Constructor v0.4.4 importing wxPython reading user preferences running main... importing Models.Controllers importing Models.EditorModels importing Views importing Views.SourceViews D:\Python25\Lib\site-packages\boa-constructor\Views\STCStyleEditor.py: 59: Deprec ationWarning: The wxPython compatibility package is no longer automatically gene rated or actively maintained. Please switch to the wx package as soon as possib le. import wxPython.stc # needed names from 2.4 for config files importing Explorers.ExplorerNodes importing Companions importing PropertyEditors importing Companions.FrameCompanions importing Companions.WizardCompanions importing Companions.ContainerCompanions importing Companions.SizerCompanions From trentm at activestate.com Thu Apr 5 21:07:20 2007 From: trentm at activestate.com (Trent Mick) Date: Thu, 05 Apr 2007 18:07:20 -0700 Subject: Support SSL for Solaris 10 In-Reply-To: <1175789468.487182.217750@w1g2000hsg.googlegroups.com> References: <1175789468.487182.217750@w1g2000hsg.googlegroups.com> Message-ID: <46159D48.7090604@activestate.com> campos wrote: > Last time I installed Python 2.5 by default, it didn't support SSL. > When I tried to use HTTPS, the following error occured: > AttributeError: 'module' object has no attribute 'ssl' The ActivePython 2.5 builds for Solaris on SPARC (the "solaris8-sparc" build) supports OpenSSL. Note that the Solaris on *x86* ActivePython build does not because there were build errors for that extension that haven't yet been resolved. http://www.activestate.com/products/activepython/ Cheers, Trent -- Trent Mick trentm at activestate.com From KDawg44 at gmail.com Wed Apr 11 08:39:21 2007 From: KDawg44 at gmail.com (KDawg44) Date: 11 Apr 2007 05:39:21 -0700 Subject: Parsing log in SQL DB to change IPs to hostnames In-Reply-To: <92%Sh.21541$tD2.14028@newsread1.news.pas.earthlink.net> References: <1176219463.407804.315560@y80g2000hsf.googlegroups.com> <1176221494.813800.78580@y80g2000hsf.googlegroups.com> <1176231258.626137.228220@d57g2000hsg.googlegroups.com> <92%Sh.21541$tD2.14028@newsread1.news.pas.earthlink.net> Message-ID: <1176295161.448113.253650@w1g2000hsg.googlegroups.com> On Apr 11, 1:15 am, Dennis Lee Bieber wrote: > On 10 Apr 2007 11:54:18 -0700, "KDawg44" declaimed > the following in comp.lang.python: > > > > > [----- BEGIN ERROR ---] > > Traceback (most recent call last): > > File "changeLogs.py", line 47, in ? > > cursor.execute("""UPDATE logs SET msg = %s WHERE seq = %i""", > > (newMsg,seqNum)) > > File "/usr/lib/python2.4/site-packages/MySQLdb/cursors.py", line > > 148, in execute > > query = query % db.literal(args) > > TypeError: int argument required > > [----- END ERROR ---] > > > Here is my code > > > [----- BEGIN CODE ---] > > Comments interspersed > > > > > #! /usr/bin/python > > > import socket > > import sys > > import re > > import string > > import MySQLdb > > > def resolveHost(ipAdds): > > ipDict = {} > > for ips in ipAdds: > > try: > > ipDict[ips] = socket.gethostbyaddr(ips)[0] > > except: > > ipDict[ips] = "Cannot resolve" > > return ipDict > > > ipRegExC = r"\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}" > > ipRegEx = re.compile(ipRegExC) > > > try: > > conn = MySQLdb.connect(host="REMOVED", > > user="REMOVED", > > passwd="REMOVED", > > db="REMOVED") > > > except MySQLdb.Error, e: > > print "Error connecting to the database: %s - %s " % (e.args[0], e.args[1]) > > #just use %s unless you need particular numeric formatting > #(field width and decimal places, as in %8.4f)> sys.exit(1) > > > cursor = conn.cursor() > > cursor.execute("SELECT msg, seq FROM logs WHERE seq = 507702") > #why the ` around the table name? > #I also presume at some point that 507702 becomes dynamic -- otherwise > the returned > #seq field will always be 507702,-- and if there are multiple instances, > the update > #statement below will change all of them each time > > #while(1): > # row = cursor.fetchone() > for row in cursor:> ipAddresses = [] > > resolvedDict = {} > > # if row == None: > # break> if ipRegEx.search(row[0]): > > seqNum = row[1] > > ipAddresses = ipRegEx.findall(row[0]) > > resolvedDict = resolveHost(ipAddresses) > > newMsg = row[0] > > for ip in resolvedDict.keys(): > > newMsg = newMsg.replace(ip, > > ip + "-" +resolvedDict[ip]) > > cursor.execute( > """UPDATE REMOVED SET msg = %s WHERE seq = %s""", > (newMsg, seqNum)) > #the documented parameter code for MySQLdb is %s; use of > anything > #else relies upon luck -- luck that the safety logic inside > the module > #leaves the parameter in a format compatible with the format > code! > #%s is the only code you should use with MySQLd -- > regardless of > #the type of the actual data > > -- > 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/ ohhh okay. thanks so much. I knew that it came out as strings, i guess it makes sense that I would have to send it back IN as a string. Changed that and now it works! THanks so much. I just specified once specific field so that it would not change the whole db on a test run. Thanks so much. From steve at REMOVE.THIS.cybersource.com.au Sun Apr 22 02:09:12 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Sun, 22 Apr 2007 16:09:12 +1000 Subject: Support for new items in set type References: <1177211624.069474.3960@y5g2000hsa.googlegroups.com> Message-ID: On Sat, 21 Apr 2007 20:13:44 -0700, Prateek wrote: > I have a bit of a specialized request. > > I'm reading a table of strings (specifically fixed length 36 char > uuids generated via uuid.uuid4() in the standard library) from a file > and creating a set out of it. > Then my program is free to make whatever modifications to this set. > > When I go back to save this set, I'd like to be able to only save the > new items. This may be a silly question, but why? Why not just save the modified set, new items and old, and not mess about with complicated transactions? After all, you say: > PS: Yes - I need blazing fast performance - simply pickling/unpickling > won't do. Memory constraints are important but definitely secondary. > Disk space constraints are not very important. Since disk space is not important, I think that you shouldn't care that you're duplicating the original items. (Although maybe I'm missing something.) Perhaps what you should be thinking about is writing a custom pickle-like module optimized for reading/writing sets quickly. -- Steven. From bj_666 at gmx.net Mon Apr 30 05:42:52 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Mon, 30 Apr 2007 11:42:52 +0200 Subject: I/O Operations ..... References: <1177919063.650070.321560@y80g2000hsf.googlegroups.com> <1177924784.122690.233540@p77g2000hsh.googlegroups.com> Message-ID: In <1177924784.122690.233540 at p77g2000hsh.googlegroups.com>, saif.shakeel wrote: > File writing can be done in that way,but my query is > something different.I have to rename the output file by default with > input file name(only changing the extension. Take a look at the functions in `os.path`. Ciao, Marc 'BlackJack' Rintsch From aleax at mac.com Thu Apr 19 00:09:12 2007 From: aleax at mac.com (Alex Martelli) Date: Wed, 18 Apr 2007 21:09:12 -0700 Subject: Python Threads - References: Message-ID: <1hwsajp.1by6iih10p5z9hN%aleax@mac.com> S.Mohideen wrote: > Hi All, > > Can you please suggest a technique in Python where we can spawn few number > of worker threads and later map them to a function/s to execute individual > Jobs. > > Any references would be helpful.. I believe I give some examples in the Nutshell, but the basic idea is very simple: start the N worker threads you want in your pool -- they all use .get on the same Queue.Queue instance qI which contains "work requests" (WRs). A WR could e.g. be a tuple with a Queue qO (or None to indicate that the result is not interesting), a callable, and 0+ arguments (or an empty tuple to request thread termination); the worker thread just calls the callable on the arguments and puts the result to qO (if qO is not None). Many other similar arrangements are possible, depending on your application's exact needs, but I hope the general idea is clear. Alex From kelvin.you at gmail.com Wed Apr 11 14:51:04 2007 From: kelvin.you at gmail.com (=?utf-8?B?5Lq66KiA6JC95pel5piv5aSp5rav77yM5pyb5p6B5aSp5rav5LiN6KeB5a62?=) Date: 11 Apr 2007 11:51:04 -0700 Subject: Shutting down windows using win32api In-Reply-To: References: <637903.8497.qm@web90304.mail.mud.yahoo.com> Message-ID: <1176317464.244953.86380@d57g2000hsg.googlegroups.com> On Apr 11, 7:49?pm, Tim Golden wrote: > On a whim, given the terseness of your post, I > cut-and-pasted your subject line into Google, > added "python" for good measure, and looked at > the results. > > I suggest you might do the same. Granted, maybe > this will raise more questions, but at least it > shows willing :) > > TJG use ctypes module to execute the windows api. Shutdown windows can use the follow api BOOL ExitWindowsEx( UINT uFlags, DWORD dwReason ); about the usage, u can refer to the microsoft msdn From kelvin.you at gmail.com Mon Apr 9 04:29:24 2007 From: kelvin.you at gmail.com (=?utf-8?B?5Lq66KiA6JC95pel5piv5aSp5rav77yM5pyb5p6B5aSp5rav5LiN6KeB5a62?=) Date: 9 Apr 2007 01:29:24 -0700 Subject: Is there a simple function to generate a list like ['a', 'b', 'c', ... 'z']? Message-ID: <1176107364.000517.68580@q75g2000hsh.googlegroups.com> Is there a simple function to generate a list like ['a', 'b', 'c', ... 'z']? The range() just can generate the numeric list. From steve at REMOVE.THIS.cybersource.com.au Fri Apr 6 10:15:42 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Sat, 07 Apr 2007 00:15:42 +1000 Subject: Why NOT only one class per file? References: <1175721799.714907.52770@o5g2000hsb.googlegroups.com> Message-ID: On Wed, 04 Apr 2007 14:23:19 -0700, Chris Lasher wrote: > A friend of mine with a programming background in Java and Perl places > each class in its own separate file in . I informed him that keeping > all related classes together in a single file is more in the Python > idiom than one file per class. He asked why, and frankly, his valid > question has me flummoxed. Hah! Writing one class per file is for wimps! When I program, I write one *method* per file, then import them and build the class at runtime. I have a friend who writes one *line* per file, then pulls them all together with exec(), but that's just being stupid. -- Steven. From aleax at mac.com Sat Apr 28 14:19:22 2007 From: aleax at mac.com (Alex Martelli) Date: Sat, 28 Apr 2007 11:19:22 -0700 Subject: Numbers and truth values References: Message-ID: <1hxa0lo.kkg0uo2fd6dN%aleax@mac.com> Szabolcs wrote: ... > >>>> True = 2 # DON'T DO THIS!!! > >>>> 2 == True > > True > > But shouldn't Python forbid this? Is it possible to get a warning when > unintentionally redefining built-in thing? Python can be changed to make some non-reserved builtin identifiers into reserved words, going through a stage where this is allowed but gives a warning. This happened in recent years for assignments to None, which were legal back in 2.2 and earlier: $ python2.3 -c'None=23' :1: SyntaxWarning: assignment to None $ python2.4 -c'None=23' File "", line 1 SyntaxError: assignment to None ...and, as you can see, gave syntax warnings in 2.3, becoming syntax errors in 2.4 and later versions. However, Python has a somewhat large and growing number of builtin identifiers: $ python2.3 -c'print len(__builtins__.__dict__)' 124 $ python2.4 -c'print len(__builtins__.__dict__)' 128 $ python2.5 -c'print len(__builtins__.__dict__)' 133 while keywords (reserved words) are far fewer, and more constrained in their growth: $ python2.3 -c'import keyword; print len(keyword.kwlist)' 29 $ python2.4 -c'import keyword; print len(keyword.kwlist)' 29 $ python2.5 -c'import keyword; print len(keyword.kwlist)' 31 so, making all builtins into keywords is unlikely to happen: it would break a lot of existing code in exchange for a minor benefit. It _would_ surely be possible to make Python behave this way only when a certain commandline flag or environment variable is present, e.g. by tweaking the implementation of the relevant bytecodes: >>> def f(): ... global aglobal ... aglobal = 23 ... alocal = 45 ... >>> dis.dis(f) 3 0 LOAD_CONST 1 (23) 3 STORE_GLOBAL 0 (aglobal) 4 6 LOAD_CONST 2 (45) 9 STORE_FAST 0 (alocal) 12 LOAD_CONST 0 (None) 15 RETURN_VALUE STORE_GLOBAL and STORE_FAST. However, this might slow down normal operation (by needing to check some flag at each STORE_...). Perhaps a better approach is to perform your checking with a tool that is _separate_ from "Python proper". Wouldn't it be great to have a tool to check Python sources, one which we could name, for example, pychecker, that we could run as follows...: $ cat >ba.py False = 23 $ pychecker ba.py Processing ba... Warnings... ba.py:1: (False) shadows builtin ba.py:1: Should not assign to False, it is (or will be) a builtin Rejoyce! ... There are other tools to perform such checks, such as pylint, , which is quite a bit more complicated but can perform many more checks (and can be integrated into PyDev, an Eclipse add-on which some people like to use as a Python IDE), and, I believe, a few other with slightly different slants (such as pyflakes, , which does fewer checks but does them faster and in a way that's safe against potentially-evil code). By the way, both of these tools (and many other tools, and a lot of other useful tips) are mentioned at , the Python Programming FAQ (it's a bit dated, but if you find any problem with it, just like with any other piece of official Python docs, bugs and suggested patches are welcome at the usual location, ). Perhaps one day some variant of pychecker and/or pylint can be integrated in Python itself, and executed (for example at each import) if that's indicated by some appropriate flag or environment variable; however, for us command-line dinosaurs, the people who prefer running python at a shell prompt (rather than more advanced things such as ipython, or IDEs such as PyDev, IDLE, etc, etc) this doesn't really tend to be that high a priority, as we're quite used to "not necessarily auto-integrated" tools; it's probably a higher priority to get pychecker or something like that integrated with other IDEs such as IDLE (I don't know, besides PyDev's ability to use pylint, which other such integrations currently exist -- anybody?). Alex From jstroud at mbi.ucla.edu Fri Apr 20 19:18:28 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Fri, 20 Apr 2007 16:18:28 -0700 Subject: When are immutable tuples *essential*? Why can't you just use lists *everywhere* instead? In-Reply-To: <1177109625.619171.121610@d57g2000hsg.googlegroups.com> References: <1177088796.622928.224890@d57g2000hsg.googlegroups.com> <1177089206.550423.288670@q75g2000hsh.googlegroups.com> <58sf33F2b1q8tU1@mid.individual.net> <1177103370.022138.110320@n59g2000hsh.googlegroups.com> <1177108656.291537.182560@o5g2000hsb.googlegroups.com> <1177109625.619171.121610@d57g2000hsg.googlegroups.com> Message-ID: garrickp at gmail.com wrote: > On Apr 20, 4:37 pm, John Machin wrote: > >>One inessential but very useful thing about tuples when you have a lot >>of them is that they are allocated the minimum possible amount of >>memory. OTOH lists are created with some slack so that appending etc >>can avoid taking quadratic time. > > > Speaking of inessential but very useful things, I'm also a big fan of > the tuple swap... > a = 2 > b = 3 > (a, b) = (b, a) > print a # 3 > print b # 2 You can also do a list swap. py> a = 4 py> b = 2 py> [a, b] = [b, a] py> a 2 py> b 4 From andre.roberge at gmail.com Mon Apr 30 20:36:36 2007 From: andre.roberge at gmail.com (=?iso-8859-1?B?QW5kcuk=?=) Date: 30 Apr 2007 17:36:36 -0700 Subject: Launching an independent Python program in a cross-platform way (including mac) In-Reply-To: <1177944037.400933.291060@l77g2000hsb.googlegroups.com> References: <1177889540.489960.176380@u30g2000hsc.googlegroups.com> <1177890695.308785.165580@l77g2000hsb.googlegroups.com> <838d5$4635f634$4275d90a$5047@FUSE.NET> <1177944037.400933.291060@l77g2000hsb.googlegroups.com> Message-ID: <1177979796.103422.316930@y5g2000hsa.googlegroups.com> As promised, here's the solution I came up with for launching an external python script. The function below has been edited (read simplified slightly) from the original one used in Crunchy. Note that while the original has been tested, the following has not- but it should provide a good start *if* problems are found with it. Andr? ==================== def exec_external(path): """execute code saved in file found in 'path' in an external process currently works under: * Windows NT (tested) * GNOME * OS X This also needs to be tested for KDE and implemented some form of linux fallback (xterm?) """ if os.name == 'nt': current_dir = os.getcwd() target_dir, fname = os.path.split(path) os.chdir(target_dir) # change dir so as to deal with paths that # include spaces if console: Popen(["cmd.exe", ('/c start python %s'%fname)]) else: Popen(["cmd.exe", ('/c python %s'%fname)]) os.chdir(current_dir) elif sys.platform == 'darwin': pth, fn = os.path.split(path) activate = 'tell application "Terminal" to activate' script = r"cd '\''/Users/andre/CrunchySVN/branches/ andre'\'';python '\''test.py'\'';exit" do_script = r'tell application "Terminal" to do script "%s"'%script command = "osascript -e '%s';osascript -e '%s'"%(activate, do_script) os.popen(command) elif os.name == 'posix': try: os.spawnlp(os.P_NOWAIT, 'gnome-terminal', 'gnome- terminal', '-x', 'python', '%s'%path) except: try: # untested os.spawnlp(os.P_NOWAIT, 'konsole', 'konsole', '-x', 'python', '%s'%path) except: raise NotImplementedError else: raise NotImplementedError From okyoon at stanford.edu Mon Apr 30 03:45:22 2007 From: okyoon at stanford.edu (OhKyu Yoon) Date: Mon, 30 Apr 2007 00:45:22 -0700 Subject: Qustion about struct.unpack Message-ID: Hi! I have a really long binary file that I want to read. The way I am doing it now is: for i in xrange(N): # N is about 10,000,000 time = struct.unpack('=HHHH', infile.read(8)) # do something tdc = struct.unpack('=LiLiLiLi',self.lmf.read(32)) # do something Each loop takes about 0.2 ms in my computer, which means the whole for loop takes 2000 seconds. I would like it to run faster. Do you have any suggestions? Thank you very much. OhKyu From brochu121 at gmail.com Thu Apr 5 14:25:14 2007 From: brochu121 at gmail.com (brochu121 at gmail.com) Date: 5 Apr 2007 11:25:14 -0700 Subject: Looping issues In-Reply-To: <1175797130.561115.147450@p77g2000hsh.googlegroups.com> References: <1175796069.501575.157410@w1g2000hsg.googlegroups.com> <1175797130.561115.147450@p77g2000hsh.googlegroups.com> Message-ID: <1175797514.270221.190610@n59g2000hsh.googlegroups.com> On Apr 5, 2:18 pm, "anglozaxxon" wrote: > On Apr 5, 2:01 pm, brochu... at gmail.com wrote: > > > > > What I am trying to do is compare two files to each other. > > > If the 2nd file contains the same line the first file contains, I want > > to print it. I wrote up the following code: > > > correct_settings = open("C:\Python25\Scripts\Output > > \correct_settings.txt","r") > > current_settings = open("C:\Python25\Scripts\Output\output.txt","r") > > > for line in correct_settings: > > for val in current_settings: > > if val == line: > > print line + " found." > > > correct_settings.close() > > current_settings.close() > > > For some reason this only looks at the first line of the > > correct_settings.txt file. Any ideas as to how i can loop through each > > line of the correct_settings file instead of just looking at the first? > > Instead of "for line in correct_settings", try "for line in > correct_settings.readlines()". That Still didnt fix it. Same output From bruno.42.desthuilliers at wtf.websiteburo.oops.com Fri Apr 27 09:34:30 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Fri, 27 Apr 2007 15:34:30 +0200 Subject: what python technology for my app? In-Reply-To: References: <4631dc06$0$15457$426a74cc@news.free.fr> Message-ID: <4631fbc2$0$641$426a74cc@news.free.fr> Robert Rawlins - Think Blue a ?crit : > Just thought I'd make a little suggestion about this, I don?t know how > strict you want to be with the web development side of things, but I'm a web > developer by trade and have recently started using python for my non-web > type applications. > > If you're looking for a web based server side solution, then you can't go > wrong with Adobe ColdFusion. Err... is this a troll ? From deets at nospam.web.de Tue Apr 24 10:16:05 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 24 Apr 2007 16:16:05 +0200 Subject: getting scancodes References: <132r2hb2gltbf4d@corp.supernews.com> Message-ID: <596hp5F2jf49qU1@mid.uni-berlin.de> andmarti at gmail.com wrote: > On Tue, Apr 24, 2007 at 04:40:11AM -0000, Grant Edwards wrote: >> On 2007-04-24, andmarti at gmail.com wrote: >> >> > Anyone knows if its possible to get scan codes ??? >> >> What hardware? What OS? > > Debian Sarge/Etch, i386.. > > :P Greeeeeaaaat. Now we only need to guess what scan code reader you use.... From oscartheduck at gmail.com Sat Apr 28 22:15:19 2007 From: oscartheduck at gmail.com (oscartheduck) Date: 28 Apr 2007 19:15:19 -0700 Subject: I have a chance to do somting diffrent way not Python ?! In-Reply-To: <1177777623.038902.108590@y5g2000hsa.googlegroups.com> References: <1177777623.038902.108590@y5g2000hsa.googlegroups.com> Message-ID: <1177812919.692060.308690@n59g2000hsh.googlegroups.com> Hi anders, try looking here first: http://docs.python.org/lib/module-os.html Also: http://sourceforge.net/projects/pywin32/ On Apr 28, 10:27 am, anders wrote: > Hi! > On my work we have a lot off diffrent server to make software for > diffrent os > from Windows, OS/X to Linux Solaris > > Everyting is scripted with shell, but Windows has batchfiles witch is > very > limited, compared to cshell etc. > > So my boss has told me that it okej if i want to make somting better > och smooter, > for the windows machine. > > First i looked a Ruby but didn't like it to interacting with the os, > nothinh wrong > but my eyes moved to Python becurse syntax is clean and every server > (not windows) has Python as base installed, and in the future i could > then move > the script to run on all servers. > > So basicly i like advice about interac with os, compiler etc. > Nice webblinks to read more > and do/don't things. > > best regards > Anders From aboudouvas at panafonet.gr Thu Apr 12 05:03:17 2007 From: aboudouvas at panafonet.gr (king kikapu) Date: 12 Apr 2007 02:03:17 -0700 Subject: About Trolltech QT OpenSource license. In-Reply-To: <1176364905.342440.295520@l77g2000hsb.googlegroups.com> References: <1176233376.712861.67160@o5g2000hsb.googlegroups.com> <1176237050.409742.8760@30g2000cwc.googlegroups.com> <1176285062.178372.15090@d57g2000hsg.googlegroups.com> <1176326271.183571.286710@l77g2000hsb.googlegroups.com> <1176364905.342440.295520@l77g2000hsb.googlegroups.com> Message-ID: <1176368597.018340.65680@o5g2000hsb.googlegroups.com> I dig a little bit more on the Trolltech's site and i think that this page is telling all the truth: http://www.trolltech.com/developer/downloads/qt/faq So, this tells us all the good stuff people in this thread are talking about, i think is clear enough. From bbxx789_05ss at yahoo.com Mon Apr 16 06:10:58 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: 16 Apr 2007 03:10:58 -0700 Subject: newbie question: how to read back the dictionary from a file? In-Reply-To: <1176717819.937015.9890@y80g2000hsf.googlegroups.com> References: <1176717819.937015.9890@y80g2000hsf.googlegroups.com> Message-ID: <1176718258.762366.69340@q75g2000hsh.googlegroups.com> On Apr 16, 4:03 am, "lancered" wrote: > Hi Dear all, > > I have some data here in the form of a dictionary, called "vdic". Then > I write them to a data file "f" using the write function as > f.write(str(vdic)). The keys of this dictionary are integers and > values are float numbers. Something like this: > > { 1: 0.00951486513347, 2: 0.0388123556019, ... ...} > > Now, I want to read these data back in another function. Of course, I > could parse the string little by little, e.g, first read a "{", then > loop read a int, then read a ":", then a float etc etc... Since it is > written out with standard python builtin functions, I guess there may > be some more direct method than this, say a function in some modules? > Could someone give me a hint? Try: import shelve s = shelve.open("newFile.dat") s["d"] = {"red":2, 3:"blue", 2.5:"x"} s.close() s = shelve.open("newFile.dat") print s["d"] my_dict = s["d"] print my_dict[2.5] From gagsl-py2 at yahoo.com.ar Wed Apr 11 23:50:36 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 12 Apr 2007 00:50:36 -0300 Subject: Universal Feed Parser issue References: <1176227922.910993.36910@y80g2000hsf.googlegroups.com> <1176267073.787216.80170@n76g2000hsh.googlegroups.com> <1176311235.792366.296010@b75g2000hsg.googlegroups.com> <1176348216.424419.65220@y80g2000hsf.googlegroups.com> Message-ID: En Thu, 12 Apr 2007 00:23:36 -0300, i3dmaster escribi?: > Ok no problem. Back to my original question, should this be considered > a bug (didn't see a bug reported though) ? Do you know if the > developer is considering fixing it in the future? I have no idea! The bug was reported more than a year ago: http://sourceforge.net/tracker/?func=browse&group_id=112328&atid=661937 with no comments from the developer... Why don't you switch to a more general and supported tool, like ElementTree? -- Gabriel Genellina From zondo42 at googlemail.com Fri Apr 20 02:42:49 2007 From: zondo42 at googlemail.com (Glenn Hutchings) Date: 19 Apr 2007 23:42:49 -0700 Subject: using tkinter to display html In-Reply-To: References: <1176988173.015892.273660@e65g2000hsc.googlegroups.com> Message-ID: <1177051369.897460.109980@e65g2000hsc.googlegroups.com> On 20 Apr, 02:54, "Stephen M. Gava" wrote: > yeah. i feel like i'm being forced to use wxwidgets/wxpython just because > i need pretty good html display though. You could always use a real web browser: import webbrowser webbrowser.open_new("index.html") Glenn From hugonz at gmail.com Fri Apr 13 04:07:01 2007 From: hugonz at gmail.com (hugonz at gmail.com) Date: 13 Apr 2007 01:07:01 -0700 Subject: Any Pythonistas in Mexico? In-Reply-To: <1176386191.990363.112350@y80g2000hsf.googlegroups.com> References: <1176386191.990363.112350@y80g2000hsf.googlegroups.com> Message-ID: <1176451621.552908.24780@w1g2000hsg.googlegroups.com> On Apr 12, 8:56 am, "Marcpp" wrote: > Yo vivo en Espa?a. > Usas el pyqt? Hola! no, no lo he usado, aunque ahorita estoy m?s bien haciendo mis experimentos con wxPython... Hugo From grante at visi.com Wed Apr 18 10:01:04 2007 From: grante at visi.com (Grant Edwards) Date: Wed, 18 Apr 2007 14:01:04 -0000 Subject: How to communicate via USB "port" References: <1176875664.555559.259840@y80g2000hsf.googlegroups.com> Message-ID: <132c950a4s5kacd@corp.supernews.com> On 2007-04-18, robinp.la at gmail.com wrote: > Can someone explain how I would read the data from the USB "port"? You can't. There's no such thing from a SW point of view. ;) > I don't know if it matters, but I am trying to read the data > from a GPS plugged in to the USB port. It's probably a serial device. Try using pyserial to talk to /dev/ttyUSB0. -- Grant Edwards grante Yow! Used staples are good at with SOY SAUCE! visi.com From aleax at mac.com Sun Apr 15 01:12:30 2007 From: aleax at mac.com (Alex Martelli) Date: Sat, 14 Apr 2007 22:12:30 -0700 Subject: Lists and Tuples and Much More References: <1176422546.385731.172910@d57g2000hsg.googlegroups.com> Message-ID: <1hwkyvb.jx0pp116qtbeqN%aleax@mac.com> 7stud wrote: > It sure looks like t changed, and therefore t is NOT immutable--and > the whole "tuples are immutable" mantra is a lie. However, the list """ So, "the statue that points to Hotel Belfiore" had suddenly become "the statue that points to Da Carlo"...! Amazing isn't it? Considering that marble isn't very fluid and the statue had not been moved or disturbed in any way...? """ Alex From basilisk96 at gmail.com Sat Apr 28 16:20:27 2007 From: basilisk96 at gmail.com (Basilisk96) Date: 28 Apr 2007 13:20:27 -0700 Subject: My Python annoyances In-Reply-To: <1177790269.523160.276060@l77g2000hsb.googlegroups.com> References: <1177790269.523160.276060@l77g2000hsb.googlegroups.com> Message-ID: <1177791627.691137.324780@l77g2000hsb.googlegroups.com> > Everyone know that programming is supposed to be a dark art, nearly > impossible to learn. Computer code is supposed to be something > impossible to read to the common person and yet reveal their secrets > to the initiated - just remember the code displayed in the Matrix... Hmm, on my PyCon mug there are words "Python: so easy...even your BOSS can use it!" Thankfully, my boss doesn't know the difference between directories and files, so I can easily succeed in making him think that Python really IS a black art :) Cheers -Basilisk96 From len-l at telus.net Thu Apr 5 13:12:37 2007 From: len-l at telus.net (Lenard Lindstrom) Date: Thu, 05 Apr 2007 17:12:37 GMT Subject: Calling Fortran from Python In-Reply-To: <1175783592.931018.318850@l77g2000hsb.googlegroups.com> References: <1175640339.648190.207530@y66g2000hsf.googlegroups.com> <1175685841.847487.173440@w1g2000hsg.googlegroups.com> <1175718204.410453.29510@q75g2000hsh.googlegroups.com> <1175726427.114890.7990@y80g2000hsf.googlegroups.com> <1175729338.287712.305870@e65g2000hsc.googlegroups.com> <1175783592.931018.318850@l77g2000hsb.googlegroups.com> Message-ID: <96aRh.5$Uf7.3@edtnps89> Mangabasi wrote: > A little bit of googling solved the problem. instead of > >>>> sample = cdll.sample_dll.SAMPLE > > I used > > >>>> sample = windll.sample_dll.SAMPLE > > and now it seems to be working without error messages. > > Thanks a lot. > > I remember someone on the ctypes mailing list mentioning that g77 uses the C calling convention for exported functions. Other compilers might default to standard calls. At least with ctypes one can tinker with calling convention and function arguments to make a call work. Lenard From rhamph at gmail.com Fri Apr 13 14:38:54 2007 From: rhamph at gmail.com (Rhamphoryncus) Date: 13 Apr 2007 11:38:54 -0700 Subject: tuples, index method, Python's design In-Reply-To: References: <1175953520.316208.241490@o5g2000hsb.googlegroups.com> <7xzm5igbrb.fsf@ruckus.brouhaha.com> <1176200361.260546.280510@n76g2000hsh.googlegroups.com> <740c3aec0704100824m132c45fbi5c4c3ec0c0fa3a67@mail.gmail.com> Message-ID: <1176489534.568939.249910@q75g2000hsh.googlegroups.com> On Apr 13, 1:32 am, Antoon Pardon wrote: > Suppose someone writes a function that acts on a sequence. > The algorithm used depending on the following invariant. > > i = s.index(e) => s[i] = e > > Then this algorithm is no longer guaranteed to work with strings. It never worked correctly on unicode strings anyway (which becomes the canonical string in python 3.0). The base unit exposed by the implementation is rarely what you want to operate upon. The terminology is pretty confusing, but let's see if I can lay out the relationships here: byte ? code unit ? code point ? scalar value ? grapheme cluster ~ character ? syllable ? word ? sentence ? paragraph "12" in "123" allows you to handle bytes through scalar values the same way, glossing over the implementation details (such as UTF-32 on linux and UTF-16 on windows). -- Adam Olsen, aka Rhamphoryncus From whamil1 at entergy.com Thu Apr 5 15:16:03 2007 From: whamil1 at entergy.com (Hamilton, William ) Date: Thu, 5 Apr 2007 14:16:03 -0500 Subject: Looping issues Message-ID: <588D53831C701746A2DF46E365C018CE01D2CA63@LITEXETSP001.etrsouth.corp.entergy.com> -----Original Message----- From: python-list-bounces+whamil1=entergy.com at python.org [mailto:python-list-bounces+whamil1=entergy.com at python.org] On Behalf Of brochu121 at gmail.com Sent: Thursday, April 05, 2007 1:01 PM To: python-list at python.org Subject: Looping issues What I am trying to do is compare two files to each other. If the 2nd file contains the same line the first file contains, I want to print it. I wrote up the following code: correct_settings = open("C:\Python25\Scripts\Output \correct_settings.txt","r") current_settings = open("C:\Python25\Scripts\Output\output.txt","r") for line in correct_settings: for val in current_settings: if val == line: print line + " found." correct_settings.close() current_settings.close() For some reason this only looks at the first line of the correct_settings.txt file. Any ideas as to how i can loop through each line of the correct_settings file instead of just looking at the first? ===================================== I think the problem is that it's actually only looping through current_settings once; for the remaining lines in correct_settings, current_settings is at EOF and produces nothing to be matched. for line in correct_settings: if line in current_settings: print line + "found." This may do what you want. --- -Bill Hamilton whamil1 at entergy.com From flyzone at technologist.com Fri Apr 13 04:55:05 2007 From: flyzone at technologist.com (Flyzone) Date: 13 Apr 2007 01:55:05 -0700 Subject: split and regexp on textfile In-Reply-To: <1176453634.577706.326170@y80g2000hsf.googlegroups.com> References: <1176451192.364949.8260@w1g2000hsg.googlegroups.com> <1176453634.577706.326170@y80g2000hsf.googlegroups.com> Message-ID: <1176454505.336514.90910@p77g2000hsh.googlegroups.com> On 13 Apr, 10:40, mik3l3... at gmail.com wrote: > you trying to match the date part right? if re is what you desire, > here's one example: Amm..not! I need to get the text-block between the two data, not the data! :) From ptmcg at austin.rr.com Sat Apr 7 22:55:04 2007 From: ptmcg at austin.rr.com (Paul McGuire) Date: 7 Apr 2007 19:55:04 -0700 Subject: RFC: Assignment as expression (pre-PEP) In-Reply-To: <1175807326.466842.219820@p77g2000hsh.googlegroups.com> References: <1175802680.021987.39220@p77g2000hsh.googlegroups.com> <1175807326.466842.219820@p77g2000hsh.googlegroups.com> Message-ID: <1176000904.832489.72300@o5g2000hsb.googlegroups.com> On Apr 5, 4:08 pm, "darkl... at timehorse.com" wrote: > I love event-based parsers so I have no problem with that > approach in general. You might find a pyparsing version of this to be to your liking. It is possible in the parser events (or "parse actions" as pyparsing calls them) to perform operations such as capitalization, string replacement, or string-to-integer conversion. To assign names to specific fields, one defines results names using setResultsName. A grammar for your file name might look something like (I'm just guessing from your code): from pyparsing import * def parseName2(name): """Parse filenames of the form: programmeTitle.year.series.episodeNum.episodeName.capper.ext """ capper = oneOf("JJ JeffreyJacobs").replaceWith("Jeffrey C. Jacobs").setResultsName("capper") ext = Word(alphanums).setResultsName("ext") year = Word(nums,exact=4).setResultsName("year") capitalizeAll = lambda tokens : map(str.capitalize, tokens) title = Combine( OneOrMore( ~year + Word(alphas) ).setParseAction( capitalizeAll ), joinString=" " ) \ .setResultsName("programme") seriesAndEpnum = Combine( OneOrMore( ~Literal("-") + Word(alphas) ).setParseAction( capitalizeAll ), joinString=" ").setResultsName("series") + \ Word(nums).setResultsName("episodeNum") epname = Combine( OneOrMore( ~capper + Word(alphas) ).setParseAction( capitalizeAll ), joinString=" " ) \ .setResultsName("episodeName") fileName = title + "." + year + "." + seriesAndEpnum + "." + epname + "." + capper + "." + ext parts = fileName.parseString(name) return parts.programme, parts.series, parts.episodeName, parts.episodeNum, parst.year, parts.capper, parts.ext In this example, the parse actions are capitalizeAll (easily implemented with a simple lambda), and replaceWith (which is included with pyparsing). -- Paul From chris.cavalaria at free.fr Thu Apr 5 06:20:36 2007 From: chris.cavalaria at free.fr (Christophe) Date: Thu, 05 Apr 2007 12:20:36 +0200 Subject: Why NOT only one class per file? In-Reply-To: <1175721799.714907.52770@o5g2000hsb.googlegroups.com> References: <1175721799.714907.52770@o5g2000hsb.googlegroups.com> Message-ID: <4614cd8a$0$11172$426a74cc@news.free.fr> Chris Lasher a ?crit : > A friend of mine with a programming background in Java and Perl places > each class in its own separate file in . I informed him that keeping > all related classes together in a single file is more in the Python > idiom than one file per class. He asked why, and frankly, his valid > question has me flummoxed. In Java, you HAVE to place a class in it's own file. That's how the language works. But in Java, you do not have to place each class in it's own module/package, in fact, it would be bad. It's the same in Python: you do not want to have one class per module/package. Unfortunately, in Python, a module/package is a file, and in Java, it's a directory. Also, Python doesn't really have the notion of a "root package/module". Translation: "import foo; foo.foo()" sucks so avoid having only one class per module :) From carsten at uniqsys.com Fri Apr 13 11:49:02 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Fri, 13 Apr 2007 11:49:02 -0400 Subject: Problem with algorithm In-Reply-To: References: <1176434160.047703.214600@q75g2000hsh.googlegroups.com> <1176434937.258002.162220@p77g2000hsh.googlegroups.com> <1176448576.047996.12930@d57g2000hsg.googlegroups.com> <1176473989.420067.190970@l77g2000hsb.googlegroups.com> Message-ID: <1176479342.3428.30.camel@dot.uniqsys.com> On Fri, 2007-04-13 at 10:22 -0500, Michael Bentley wrote: > On Apr 13, 2007, at 9:19 AM, Paul McGuire wrote: > > > If you just expand the length to five million* or so, one of those > > strings will contain all the works of Shakespeare. > > Not likely, even with a tiny sampling of the works of Shakespeare: Actually, the OP seems to be interested in generating *all* strings of length N. If you generate the set of *all* strings of 5 million characters length, at least one of them will contain all works of Shakespeare. That statement is utterly true and utterly impractical, which is, of course, the point of Paul's joke. -Carsten From mail at microcorp.co.za Mon Apr 2 01:56:23 2007 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Mon, 2 Apr 2007 07:56:23 +0200 Subject: socket read timeout References: <17930.25631.86693.827473@montanaro.dyndns.org> <000e01c771d2$2f3dd240$03000080@hendrik> Message-ID: <00b701c774eb$a59e4ca0$03000080@hendrik> "Bryan Olson" wrote: > Steve Holden wrote: > > Hendrik van Rooyen wrote: > >> Are sockets full duplex? > >> > > Yes. But you have to use non-blocking calls in your application to use > > them as full-duplex in your code. > > Hmmm... I'm missing something. Suppose I have one thread (or > process) reading from a blocking-mode socket while another is > writing to it? What stops it from being full duplex? > Elsewhere in this thread I wrote about my experience with a serial port, where I can show that the "file handler" only does the write once the blocking read completes - and the point at issue is if sockets are the same. We regularly get questions about "my stuff does not come out" on the group, and I wondered whether this effect is the underlying cause. But I don't know about the sockets case, which is why I asked. You raise an interesting point about a different process - my serial experience is using threads. I have never tried mixing processes on a serial port. Haven't a clue if its possible, or if the behaviour will be different. - Hendrik From soarnil at gmail.com Sun Apr 8 02:11:05 2007 From: soarnil at gmail.com (soarnil) Date: 7 Apr 2007 23:11:05 -0700 Subject: How to control files such as windows update program? In-Reply-To: <1175999310.048693.288280@e65g2000hsc.googlegroups.com> References: <1175997193.271155.144030@d57g2000hsg.googlegroups.com> <1175999310.048693.288280@e65g2000hsc.googlegroups.com> Message-ID: <1176012665.145214.69680@l77g2000hsb.googlegroups.com> On 4?8?, ??10?28?, "Gabriel Genellina" wrote: > soarnil wrote: > > I hope i could write a program to execute a range of ".exe" files. > > When there is a "Licensing Agreement", the program can choose > > "Accept",then click "Next" until "Finish".Or maybe it could use some > > function to finish this rather then really "click" the buttons. > > Some installers accept command line options to control how they > behave, and sometimes you can run the installation completely > unattended. > If there are no choices, you could use pyWinAuto to "click" the > buttons. > > -- > Gabriel Genellina Thank you very much! I really think I must write this tool by myself. Now I'll learn something about pyWinAuto. Thank you! From steve at holdenweb.com Mon Apr 23 08:26:36 2007 From: steve at holdenweb.com (Steve Holden) Date: Mon, 23 Apr 2007 08:26:36 -0400 Subject: send pictures to mobile phones - sms767 In-Reply-To: <1177311598.349112.229310@b75g2000hsg.googlegroups.com> References: <1177311598.349112.229310@b75g2000hsg.googlegroups.com> Message-ID: sms767 wrote: > Hi, > > Is there anyone interested in helping test a web service? Sending > pictures to mobile phones: > > http://www.sms767.com > Probably those list readers who are interested in having their names and cellphone numbers captured and potentially spammed to hell, as if that kind of thing doesn't already happen enough on email and newsgroups. The fact that there's no privacy policy doesn't help. 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 holdenweb.com Wed Apr 4 18:48:12 2007 From: steve at holdenweb.com (Steve Holden) Date: Wed, 04 Apr 2007 18:48:12 -0400 Subject: Newbie Question about sequence multiplication In-Reply-To: <6cOdnVFCLMXxuYnbnZ2dnUVZ_rCsnZ2d@comcast.com> References: <6cOdnVFCLMXxuYnbnZ2dnUVZ_rCsnZ2d@comcast.com> Message-ID: Scott wrote: > Alright, so I've been trying to teach myself Python which, when compared to > my attempt to learn C++, is going pretty well. > But I've come across an issue that I can't figure out, so I figured I'd ask > the pro's. > > Now it looks pretty weird in this format but it was copied exactly from IDLE > > *****code follows******* > > #What this program is suppose to do is print a sentence centered in a box > > sentence = raw_input('Sentence: ') > > screen_width = 80 > text_width = len(sentence) > box_width = text_width + 6 > left_margin = (screen_width - box_width) // 2 > > print > print ' ' * left_margin + '+' + '-' * (box_width-2) + '+' > print ' ' * left_margin + '| ' + ' ' * text_width + ' |' > print ' ' * left_margin + '| ' + ' ' sentence + ' |' ^ There's a plus sign missing just here ..| > print ' ' * left_margin + '| ' + ' ' * text_width + ' |' > print ' ' * left_margin + '+' + '-' * (box_width-2) + ' |' > print > > ****end code**** > > Now that, even though copied straight from "Beginning Python: From Novice to > Professional", returns : > There's an error in your program: invalid syntax > How on Earth are you running these programs? That doesn't look like a compiler error message! > with the word sentence highlighted (not the sentence when I'm defining the > name, the one in......uhm....the body of the code) > > > Now if i put * before sentence as it is with the rest of the variables, it > actually gets to the point where it asks me for the sentence, but after > inputting my sentence I receive: > Traceback (most recent call last): > File "D:/Programming/Python/sequence string multiplication example", line > 16, in > print ' ' * left_margin + '| ' + ' ' * sentence + ' |' > TypeError: can't multiply sequence by non-int of type 'str' > The plus sign I've indicated adds (concatenates) the sentence you've typed in to the other strings you are using. > Why can't I get it to do what it's supposed to do? What am I > missing/misunderstanding? > Very simply all its supposed to do is something like this (now bear with me > formating might distort this a bit lol) > +------------------------------------+ > | | > | Like This | > | | > +------------------------------------+ > > Any help would be greatly appreciated > Good luck! 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 python at hope.cz Thu Apr 26 03:17:05 2007 From: python at hope.cz (python at hope.cz) Date: Thu, 26 Apr 2007 09:17:05 +0200 Subject: PIL and font colour. In-Reply-To: References: <1177441923.378487.210310@r3g2000prh.googlegroups.com> Message-ID: <46306E11.30338.1CA2026C@python.hope.cz> Steve Thank you for your reply. Is there a way how to find out a complementary colour for an area where I will write the text, so that the text will be seen clearly?Is there a routine in PIL or in Python somewhere? Thank you for help Lad. > > I use PIL to write some text to a picture.The text must be seen wery > > clearly. > > I write the text to different pictures but to the same position. As > > pictures maybe different, colour, in the position where I write the > > text, is also different. > > Is there a way how to set the font colour so that it will be seen very > > clearly in the picture? > > For example, if the picture is bright ( for example yellow), the font > > colour should be dark( e.g. black) and vice versa. > > Can anyone help? > > Thanks > > L. > > > The easy way to ensure this is to paint a background rectangle of an > appropriate color to ensure good font contrast before writing the text. > Of course, this obscures rather more of the image in the background than > you might otherwise. > > Apart from that you could try averaging the pixel values in the area you > are going to paint on, and then choose a font color that contrasts well > with the average. If there are large variations in color, however, this > can give disappointing results. > > If you'd like to get some insight into color contrast you could do worse > than start at > > http://wellstyled.com/tools/colorscheme2/index-en.html > > regards > Steve > -- > Steve Holden +1 571 484 6266 +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 > > -- > http://mail.python.org/mailman/listinfo/python-list From nospam at invalid.com Thu Apr 12 22:28:10 2007 From: nospam at invalid.com (Jack) Date: Thu, 12 Apr 2007 19:28:10 -0700 Subject: Custom Python Runtime References: <2NudnVn5jsm2QIvbnZ2dnUVZ_vqpnZ2d@comcast.com> Message-ID: Gabriel, thanks for the reply. The error is that the DLL can not be found. I think the reason is that the pyd files from pywin32 do not use the python.exe directory. Instead, they expect pywintypes24.dll on the path. "Gabriel Genellina" wrote in message news:mailman.6433.1176418692.32031.python-list at python.org... > En Thu, 12 Apr 2007 19:02:53 -0300, Jack escribi?: > >> It seems that pywintypes24.dll and pythoncom24.dll have to be in >> C:\Windows\System32 directory. Otherwise I get an error. >> Any way to get around that? > > Both are part of the pywin32 extensions, better ask on the python-win32 > list: > http://mail.python.org/mailman/listinfo/python-win32 > > You don't say which error you got, but abusing again my crystall ball, try > this: > http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnsetup/html/dlldanger1.asp > > -- > Gabriel Genellina > From joshusdog at gmail.com Wed Apr 11 18:07:18 2007 From: joshusdog at gmail.com (joshusdog at gmail.com) Date: 11 Apr 2007 15:07:18 -0700 Subject: help building debug .pyd files Message-ID: <1176329238.588406.144210@w1g2000hsg.googlegroups.com> The installation of Python 2.5 comes with a bunch of built-in extension modules (.pyd files) under the DLLs directory. I've downloaded the Python source code and am trying to build the debug versions of all of these files. However, some of the projects won't build because they are looking for header files that don't exist anywhere. Specifically, the non-building projects are: _bsddb _sqlite3 _ssl _tkinter bz2 Additionally, the project for the _hashlib module seems to be entirely missing from the Python source. Any idea where I can find it? Is there a set of pre-built debug versions of all of these modules I can download somewhere? It would save me a lot of time trying to figure out where all these missing files are supposed to come from... From roy at panix.com Fri Apr 6 20:26:02 2007 From: roy at panix.com (Roy Smith) Date: Fri, 06 Apr 2007 20:26:02 -0400 Subject: SNMP agent References: <1175680387.575097.4590@e65g2000hsc.googlegroups.com> <1175686451.614022.171650@b75g2000hsg.googlegroups.com> <2vlfe4-6n.ln1@lairds.us> Message-ID: claird at lairds.us (Cameron Laird) wrote: > I understand the sentiment; in principle, it shouldn't be hard > to write a library which supports construction of SNMP agents > in Python. I'm aware of no one who has done so publicly, though. I've used pysnmp (http://pysnmp.sourceforge.net/) in a test environment for a while. Only the manager side, never tried to implement an agent. It's pure python, so it's very portable. In theory, that also means it's not very fast, but for what I've ever wanted it for, it was plenty fast enough. The latest NetSNMP release apparently now includes a python binding (http://www.net-snmp.org/docs/NEWS.html). I have not had a chance to use it, but it sounds good. From mal at egenix.com Fri Apr 27 13:35:47 2007 From: mal at egenix.com (M.-A. Lemburg) Date: Fri, 27 Apr 2007 19:35:47 +0200 Subject: Rational numbers In-Reply-To: <20070223103519.08f25af9@localhost> References: <20070223103519.08f25af9@localhost> Message-ID: <46323473.8040501@egenix.com> On 2007-02-23 16:35, Martin Manns wrote: > Hi, > > I am starting to use rationals and since I found no batteries included, > I tried out the mxNumber package. > > However, I get strange warnings on comparison operations > (which however seem to yield correct results): > > --- > $ python > Python 2.4.3 (#1, Jan 15 2007, 15:46:19) > [GCC 4.1.1 (Gentoo 4.1.1-r3)] on linux2 > Type "help", "copyright", "credits" or "license" for more information. >>>> from mx.Number import * >>>> a=Rational(0,1) >>>> a > 0/1 >>>> str(a) > '0.0' >>>> b=-5000000000000000000000000000000000000000000000000000000000 >>>> b > -5000000000000000000000000000000000000000000000000000000000L >>>> a==b > __main__:1: RuntimeWarning: tp_compare didn't return -1, 0 or 1 > False > --- > > How do I get rid of these warnings? FYI: The next version of mxNumber will have this warning removed. > Is there any rational number library around that > 1) is comparably fast for large denominators > 2) allows deriving types from Rationals without wrapping? > > Regards > > Martin > > P.S. The respective mailing list does not like me, so that I try my > luck here. Why is that ? The egenix-user mailing is open for all our users. We do require registration to stop spam from reaching the list. -- Marc-Andre Lemburg eGenix.com Professional Python Services directly from the Source (#1, Apr 27 2007) >>> Python/Zope Consulting and Support ... http://www.egenix.com/ >>> mxODBC.Zope.Database.Adapter ... http://zope.egenix.com/ >>> mxODBC, mxDateTime, mxTextTools ... http://python.egenix.com/ ________________________________________________________________________ :::: Try mxODBC.Zope.DA for Windows,Linux,Solaris,MacOSX for free ! :::: eGenix.com Software, Skills and Services GmbH Pastor-Loeh-Str.48 D-40764 Langenfeld, Germany. CEO Dipl.-Math. Marc-Andre Lemburg Registered at Amtsgericht Duesseldorf: HRB 46611 From xuxu_1009 at 163.com Sat Apr 14 03:39:01 2007 From: xuxu_1009 at 163.com (Ann) Date: 14 Apr 2007 00:39:01 -0700 Subject: How to get a forum for your free site? In-Reply-To: <1176533345.247060.206320@b75g2000hsg.googlegroups.com> References: <1176518288.373349.237050@w1g2000hsg.googlegroups.com> <1176533345.247060.206320@b75g2000hsg.googlegroups.com> Message-ID: <1176536341.202549.241010@o5g2000hsb.googlegroups.com> On 4?14?, ??2?49?, "Eric_Dex... at msn.com" wrote: > Normaly I would consider this way way off topic but I did notice that > you offer unlimited space so I suppose it could be usefull for those > of us that distribute software.. what else do I get some of the add > space?? If you are after killer apps you should consider allowing > combination of other boards between websites... (I had a provider > that went down in the .com bust that did that) Don't be doubtful of our space .We can sure to provide you unlimited free space forever. If you need add your space ,we could support too.If you have the intention, you can leave the link, or contact with me ,my MSN : xuxu_1009 at hotmail.com . thank you. From steve at holdenweb.com Wed Apr 4 10:48:42 2007 From: steve at holdenweb.com (Steve Holden) Date: Wed, 04 Apr 2007 10:48:42 -0400 Subject: Refactoring question In-Reply-To: <1175695066.405208.227670@w1g2000hsg.googlegroups.com> References: <1175661692.837687.146350@q75g2000hsh.googlegroups.com> <1175695066.405208.227670@w1g2000hsg.googlegroups.com> Message-ID: kyosohma at gmail.com wrote: > On Apr 3, 11:41 pm, "ginstrom" wrote: >>> On Behalf Of Kevin Walzer >>> What's the best way to do this? Can anyone point me in the >>> right direction? How could, for instance, the top snippet be >>> rewritten to separate the Tkinter parts from the generic stuff? >> I like to use the broadcaster/broker recipe athttp://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/81983 [lots of code that was pretty irrelevant to the reply] > > I usually put all my GUI code into their own methods(s) and call those > methods from the __init__(). I do the same with the logic (where > applicable). This makes the code easier to manipulate and/or import. > > In wxPython, you can also use XRC to define most of the common > elements of you GUI. I've found this method to be very helpful in > keeping my code short and easy to read, for GUI code. > While talking about keeping things short and easy to read, maybe you could be a bit more considerate in your quoting practices. We really didn't need to see all the code quoted to hear what you had to say ... 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 development-2006-8ecbb5cc8aREMOVETHIS at ANDTHATm-e-leypold.de Mon Apr 16 19:46:55 2007 From: development-2006-8ecbb5cc8aREMOVETHIS at ANDTHATm-e-leypold.de (Markus E Leypold) Date: Tue, 17 Apr 2007 01:46:55 +0200 Subject: is laziness a programer's virtue? References: <1176757271.282365.319740@n76g2000hsh.googlegroups.com> Message-ID: <26abx7j30w.fsf@hod.lan.m-e-leypold.de> "Xah Lee" writes: > ? Please remind yourself what is on-topic and off-topic. Unless you You, Sir, ARE off-topic. I suggest you make the experiment to post your drivel on your web site and let your fans come to you. Should be an eye opener, this experiment. Regards -- Markus From cam.ac.uk at mh391.invalid Wed Apr 18 21:27:56 2007 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Thu, 19 Apr 2007 02:27:56 +0100 Subject: Using the Python interpreter In-Reply-To: <1176942756.283173.234750@n76g2000hsh.googlegroups.com> References: <1176942756.283173.234750@n76g2000hsh.googlegroups.com> Message-ID: tkpmep at hotmail.com wrote: > Instead of starting IDLE as I normally do, I started the Python > interpreter and tried to run a program. I got a Python prompt (>>>), > and then tried unsuccessfully to run a Python script named Script1.py > that runs perfectly well in IDLE. Here's what I did: > >>>> Script1.py > Traceback (most recent call last): > File "", line 1, in ? > NameError: name Script1 is not defined > >>>> python Script1.py You need to do this from a Windows command line, not from Python. C:\Python25>python Script1.py Hello, world! -- Michael Hoffman From cam.ac.uk at mh391.invalid Tue Apr 24 09:39:43 2007 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Tue, 24 Apr 2007 14:39:43 +0100 Subject: Tutorial creates confusion about slices In-Reply-To: References: Message-ID: [Michael Hoffman] >> Personally, I do not think of slices in the way this tutorial suggests, >> but I think taking it out without replacement would not help. If you >> want to add a more accurate replacement, I think that would be better >> received than just saying that the section should be removed. Even more >> so if you provide it in the form of a patch. [Antoon Pardon] > Well people could suggest that instead of just removing the section > there should be a replacement and then we could discuss how such > a replacement should look like. Isn't that what I have done? And William Hamilton suggested an alternative way of looking at it which you could have just incorporated into your patch. > I just started with what I see as > a problem and one possible fix. Now I guess that if people would > agree that there is problem but don't agree with my fix they would > comment on my fix. Instead most reactions seem to suggest there is > not really a problem. Now I am not going to waste my time writing > a patch for something that doesn't seem to be considered a problem. Really only one person has argued that the docs do not need to be changed. The other two people seemed to think you were asking for help rather than discussing how to revise the docs. Understandable, since that's why most people come to this group in my estimation. Your time is your own and it is good to spend your efforts on what you think will be most fruitful. But if you are going to let the opposition of one person stop you from doing anything, you will not accomplish very much. -- Michael Hoffman From steve at holdenweb.com Sun Apr 15 20:48:41 2007 From: steve at holdenweb.com (Steve Holden) Date: Sun, 15 Apr 2007 20:48:41 -0400 Subject: Getting started with python In-Reply-To: <%LyUh.10121$YL5.5753@newssvr29.news.prodigy.net> References: <1176598011.463543.96990@q75g2000hsh.googlegroups.com> <1176608302.928513.274400@y5g2000hsa.googlegroups.com> <%LyUh.10121$YL5.5753@newssvr29.news.prodigy.net> Message-ID: <4622C7E9.5020802@holdenweb.com> James Stroud wrote: > Gabriel Genellina wrote: >> En Sun, 15 Apr 2007 10:46:54 -0300, Army1987 escribi?: >> >>> "Paddy" ha scritto nel messaggio >>> news:1176608302.928513.274400 at y5g2000hsa.googlegroups.com... >>> >>>> On a different tack, from: >>>> http://tickletux.wordpress.com/2007/01/24/using-fizzbuzz-to-find-developers-who-grok-coding/ >>>> >>>> It seems you need to learn how to write a Fizz-Buzz >>>> program to get a job now-a-days :-) >>> Something less idiotic? I took longer to type a program to do that >>> than to >>> figure out how to do that. >> We've used it as part of a test a few weeks ago. You'd be surprised on >> how many guys couldn't write anything remotely sensible. >> >> --Gabriel Genellina > > py> for i in xrange(1,101): > ... if not i % 15: > ... print 'fizzbuzz' > ... continue > ... if not i % 5: > ... print 'buzz' > ... continue > ... if not i % 3: > ... print 'fizz' > ... else: > ... print i > ... > > I typed this without so much as hitting delete. Didn't time it but I'm > guessing less than 2 minutes. How much am I worth a year? (Hopefully > capitalization is not important for this exercise.) > You'd be worth more if you'd used elif and omitted the continue statements, but for a first solution it's acceptable. For better readability I'd have used if i % 5 == 0 rather than if not i % 5 but that's mostly a stylistic matter. regards Steve 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 irmen.NOSPAM at xs4all.nl Wed Apr 4 14:44:35 2007 From: irmen.NOSPAM at xs4all.nl (Irmen de Jong) Date: Wed, 04 Apr 2007 20:44:35 +0200 Subject: Getting word frequencies from files which are in folder. In-Reply-To: <1175710660.753453.205000@n76g2000hsh.googlegroups.com> References: <1175710660.753453.205000@n76g2000hsh.googlegroups.com> Message-ID: <4613f24f$0$327$e4fe514c@news.xs4all.nl> krisbee1983 at gmail.com wrote: > Hello to all, > > I'm beginer in learning Python I wish somebody help me with solving > this problem. I would like to read all text files wchich are in some > folder. For this text files I need to make some word frequencies using > defined words like "buy", "red", "good". If some file don't have that > word will get "0" for this frequency. It shoud be stored in array. If > I have alredy got frequencies for every file in folder, my array wrote > to text file. This sounds suspiciously like a homework assignment. I don't think you'll get much help for this one, unless you show some code you wrote yourself already with a specific question about problems you're having.... --Irmen From Martin.Drautzburg at web.de Sun Apr 22 14:36:48 2007 From: Martin.Drautzburg at web.de (Martin Drautzburg) Date: Sun, 22 Apr 2007 20:36:48 +0200 Subject: Dictionaries and dot notation References: <23087554.X5dcTmlj7P@beaureve.gmx.net> <462b842e$0$28548$426a74cc@news.free.fr> Message-ID: <2424549.70D5anvh5e@beaureve.gmx.net> Daniel Nogradi wrote: >> > What if I want to create a datastructure that can be used in dot >> > notation without having to create a class, i.e. because those >> > objects have no behavior at all? >> >> A class inheriting from dict and implementing __getattr__ and >> __setattr__ should do the trick... > > > It can do the trick but one has to be careful with attributes that are > used by dict such as update, keys, pop, etc. Actually it's noted in a > comment at > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/361668 why the > whole idea (attribute access of dictionaries) is a bad idea and I tend > to agree. Oh thank you. So all I have to do is have my object's class implement __setattr__ and __getattr__, or derive it from a class that does so? And I could save my "attributes" anywhere within my instance variables. So I could even add a dictionary whose name does not conflict with what python uses and whose key/value pairs hold the attributes I want to access with dot notation and delegate all the python attributes to their native positions? Oh I see, thats tricky. I still need to be aware of the builtin stuff one way or the other. Interesting. From reder at ieee.org Fri Apr 13 02:50:32 2007 From: reder at ieee.org (Leonard J. Reder) Date: Fri, 13 Apr 2007 06:50:32 GMT Subject: Python and XML? Message-ID: Hello, What is the best way to process a Relax NG Schema and auto generate XML Python parser/generator code? Any suggestions? Thanks for all replies, Len -- =================================== Leonard J. Reder Home office email : reder at ieee.org Lab email : reder at jpl.nasa.gov Lab web page : http://reder.jpl.nasa.gov =================================== From bruno.42.desthuilliers at wtf.websiteburo.oops.com Thu Apr 12 04:44:42 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Thu, 12 Apr 2007 10:44:42 +0200 Subject: Newbie help with array handling In-Reply-To: <1176364734.439383.252930@o5g2000hsb.googlegroups.com> References: <1176364734.439383.252930@o5g2000hsb.googlegroups.com> Message-ID: <461df110$0$18514$426a34cc@news.free.fr> loial a ?crit : > I am new to python and am converting an awk script to python > > I need to store some data in an array/table of some form > > keyvalue1, value1, value2, value3 > keyvalue2, value1,value2, value3 > keyvalue3, value1,value2,value3 > etc data = dict( keyvalue1=[value11, value12, value13], keyvalue2=[value21, value22, value23], keyvalue3=[value31, value32, value33] ) > I will later need to sort in keyvalue order for key in sorted(data.keys()): print "%s : %s" % (key, data[key]) > and also need to be able > to check if a key already exists if somekey in data: print "somekey already exists" > It is not clear how to do this in python. All the examples I see have > just a key and a single value Everything in Python is an object, so nothing prevents you from using lists as 'values'. HTH From robert.kern at gmail.com Tue Apr 3 17:52:06 2007 From: robert.kern at gmail.com (Robert Kern) Date: Tue, 03 Apr 2007 16:52:06 -0500 Subject: Numeric compiling problem under QNX 4.25 In-Reply-To: <1175632439.676454.21830@q75g2000hsh.googlegroups.com> References: <1175578324.426293.21970@y80g2000hsf.googlegroups.com> <1175622049.939184.28670@d57g2000hsg.googlegroups.com> <1175632439.676454.21830@q75g2000hsh.googlegroups.com> Message-ID: ZMY wrote: > On Apr 3, 10:51 am, Robert Kern wrote: >> ZMY wrote: >>> Is "ld" part of make command? I am not familiar with compiling with >>> make in general. >> No, it's the linker. I takes the object files (.o) which are generated by the >> compiler (cc, I imagine) and links them together into the shared library (.so). >> make is a program that can automate builds given instructions, but Numeric >> doesn't use it, nor do most other Python packages. >> >>> Most other extensions (including math, os, struct, cPickle) from >>> Python 2.2 works when I install python on QNX. >> No, I was wondering if you could build any other third-party extension modules. >> Did you install Python from source? When building extension modules, Python uses >> whatever linker was used to build itself. >> >> -- >> 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 E > > Dear Robert, > > Looks like you are right. Here is what I got when I compile the > Python2.2 from source (or I believe so): > > $ sudo make SHELL=/usr/local/bin/bash > Password: > case $MAKEFLAGS in \ > *-s*) CC='cc' LDSHARED='ld' OPT='-DNDEBUG -O' ./python -E //6/openqnx/ > Python-2.2/setup.py -q build;; \ > *) CC='cc' LDSHARED='ld' OPT='-DNDEBUG -O' ./python -E //6/openqnx/ > Python-2.2/setup.py build;; \ > esac > running build > running build_ext > building 'regex' extension > skipping //6/openqnx/Python-2.2/Modules/regexmodule.c (build/temp.qnx- > O-PCI-2.2/regexmodule.o up-to-date) > skipping //6/openqnx/Python-2.2/Modules/regexpr.c (build/temp.qnx-O- > PCI-2.2/regexpr.o up-to-date) > ld build/temp.qnx-O-PCI-2.2/regexmodule.o build/temp.qnx-O-PCI-2.2/ > regexpr.o -L/usr/local/lib -o build/lib.qnx-O-PCI-2.2/regex.so > unable to execute ld: No such file or directory > .... > > If there is no 'ld' linker, what should be used instead?? I don't know. I've never used QNX. It looks like the Python binaries were built with a linker that you don't have on your system. Usually, you have to use the same compiler/linker combination to build extension modules that you used to build Python itself. -- 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 howe.steven at gmail.com Tue Apr 24 13:58:28 2007 From: howe.steven at gmail.com (Steven Howe) Date: Tue, 24 Apr 2007 10:58:28 -0700 Subject: If Dict Contains a particular key In-Reply-To: <1177436682.3441.15.camel@dot.uniqsys.com> References: <000001c78695$ed321540$c7963fc0$@rawlins@thinkbluemedia.co.uk> <1177436682.3441.15.camel@dot.uniqsys.com> Message-ID: <462E4544.8080807@gmail.com> Carsten Haese wrote: > On Tue, 2007-04-24 at 18:28 +0100, Robert Rawlins - Think Blue wrote: > >> Hello Guys, >> >> >> >> I?m Looking to build a quick if/else statement that checks a >> dictionary for a key like follows. >> >> >> >> If myDict contains ThisKey: >> >> Do this... >> >> Else >> >> Do that... >> > > I'm pretty sure you'll find the answer to this question somewhere in > http://docs.python.org/tut/tut.html > > -Carsten > > > or try: thedict = { 'a': 1, 'b':2, 'c':3 } if 'a' in thedict.keys(): print thedict['a'] From steve at REMOVE.THIS.cybersource.com.au Thu Apr 26 19:37:07 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Fri, 27 Apr 2007 09:37:07 +1000 Subject: My python annoyances so far References: <1177541453.471959.120830@c18g2000prb.googlegroups.com> <59bf34F2k27v5U1@mid.individual.net> <1177603623.774892.230390@t38g2000prd.googlegroups.com> Message-ID: On Thu, 26 Apr 2007 09:07:03 -0700, flifus wrote: > Well, why do some things in the library have to be functions, and > other things have to be class methods? > > Why aren't they all just either functions or class methods? like > perhaps ruby. Perhaps you should read about the Kingdom of Nouns: http://steve-yegge.blogspot.com/2006/03/execution-in-kingdom-of-nouns.html -- Steven. From szhorvat at gmail.com Sat Apr 28 08:33:23 2007 From: szhorvat at gmail.com (Szabolcs) Date: Sat, 28 Apr 2007 14:33:23 +0200 Subject: Numbers and truth values Message-ID: Newbie question: Why is 1 == True and 2 == True (even though 1 != 2), but 'x' != True (even though if 'x': works)? From robert.kern at gmail.com Mon Apr 2 20:33:18 2007 From: robert.kern at gmail.com (Robert Kern) Date: Mon, 02 Apr 2007 19:33:18 -0500 Subject: Finding a module's sub modules at runtime In-Reply-To: <461190fe$0$16311$88260bb3@free.teranews.com> References: <460ab913$0$16387$88260bb3@free.teranews.com> <1175112265.427331.93340@o5g2000hsb.googlegroups.com> <460ac66a$0$16290$88260bb3@free.teranews.com> <1hvqae5.1alie2515sbssfN%aleax@mac.com> <460c01df$0$16410$88260bb3@free.teranews.com> <1hvr2it.jmrhe215gail1N%aleax@mac.com> <461190fe$0$16311$88260bb3@free.teranews.com> Message-ID: Joshua J. Kugler wrote: > On Thursday 29 March 2007 17:58, Alex Martelli wrote: >> Sure, pydoc (which help calls under the code) does that, with a nice mix >> of inspect, os, and pkgutil.iter_modules calls. pkgutil.iter_modules >> may in fact be most of what you need: >> >>>>> help(pkgutil.iter_modules) >> Help on function iter_modules in module pkgutil: >> >> iter_modules(path=None, prefix='') >> Yields (module_loader, name, ispkg) for all submodules on path, >> or, if path is None, all top-level modules on sys.path. >> >> 'path' should be either None or a list of paths to look for >> modules in. >> >> 'prefix' is a string to output on the front of every module name >> on output. > > OK, that looks nice...but what version of Python is that? > http://docs.python.org/lib/module-pkgutil.html only shows one function (and > that's 2.5) and my python 2.4 installation is similarly lacking an > iter_modules() function for the pkgutil module. Is this a 2.6 thing? No, 2.5. The documentation is not up to date. Read the source. -- 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 syedamjad_a at yahoo.com Tue Apr 24 11:14:39 2007 From: syedamjad_a at yahoo.com (CSUIDL PROGRAMMEr) Date: 24 Apr 2007 08:14:39 -0700 Subject: RPM error Message-ID: <1177427678.916561.27800@b40g2000prd.googlegroups.com> Hi folks I am trying to write a program that will install RPM. IS there any built in Exception in python that will catch the faied dependencies in python. Also if not how can i write one ?? thanks From fatuheeva at yahoo.com Tue Apr 3 14:02:40 2007 From: fatuheeva at yahoo.com (Michael Castleton) Date: Tue, 3 Apr 2007 11:02:40 -0700 (PDT) Subject: File Object behavior Message-ID: <9821538.post@talk.nabble.com> When I open a csv or txt file with: infile = open(sys.argv[1],'rb').readlines() or infile = open(sys.argv[1],'rb').read() and then look at the first few lines of the file there is a carriage return + line feed at the end of each line - \r\n This is fine and somewhat expected. My problem comes from then writing infile out to a new file with: outfile = open(sys.argv[2],'w') outfile.writelines(infile) outfile.close() at which point an additional carriage return is inserted to the end of each line - \r\r\n The same behavior occurs with outfile.write(infile) also. I am doing no processing between reading the input and writing to the output. Is this expected behavior? The file.writelines() documentation says that it doesn't add line separators. Is adding a carriage return something different? At this point I have to filter out the additional carriage return which seems like extra and unnecessary effort. I am using Python 2.4 on Windows XP sp2. Can anybody help me understand this situation? Thanks -- View this message in context: http://www.nabble.com/File-Object-behavior-tf3520070.html#a9821538 Sent from the Python - python-list mailing list archive at Nabble.com. From apardon at forel.vub.ac.be Fri Apr 27 09:52:39 2007 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 27 Apr 2007 13:52:39 GMT Subject: Command-line option equiv of PYTHONPATH References: <1177648804.947472.112830@s33g2000prh.googlegroups.com> Message-ID: On 2007-04-27, James Stroud wrote: > Rajesh wrote: >> Hi, >> >> The '-I' option adds the path to the list of directories that >> contains modules that can be included in a script. I can use it as "#!/ >> usr/bin/perl -I" thereby not asking the user of >> the script to set the in their environment. >> >> Is there any equivalent command-line option to the python binary or a >> command-line version of PYTHONPATH? >> >> Regards >> Rajesh > > Why not just modify sys.path within the actual script? Maybe because he has multiple versions of modules he wants to test his script against. -- Antoon Pardon From deets at nospam.web.de Tue Apr 24 05:05:52 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 24 Apr 2007 11:05:52 +0200 Subject: Python Widget to read in user input box in blog References: <1177379827.873957.47760@n76g2000hsh.googlegroups.com> Message-ID: <595vjgF2jhnneU1@mid.uni-berlin.de> ecpbm765 at gmail.com wrote: > Hey, > > I am helping to develop a project that displays images based on user > input. One possible way of implementing this is via a widget that > when it is run, would read in the users input from an input text field > (probably from a blog), and replace it with the HTML that would > display those images. This is more a proof of concept, so really all > I am wondering is if there is a good way in Python to read in the text > the user has typed and change it before the user hits submit? Are you talking about a webapplication here? If yes - and the mentioning of HTML somehow implies that - you can't do that in python, as client-side code in browsers is Javascript. However there are frameworks - TurboGears, Django, Pylons - that make rapid web-application development easy, with good ajax-support. Diez From DustanGroups at gmail.com Sat Apr 21 17:18:47 2007 From: DustanGroups at gmail.com (Dustan) Date: 21 Apr 2007 14:18:47 -0700 Subject: Suggestion: str.itersplit() In-Reply-To: <1177160280.784224.53460@b58g2000hsg.googlegroups.com> References: <1177160280.784224.53460@b58g2000hsg.googlegroups.com> Message-ID: <1177190327.236981.153770@o5g2000hsb.googlegroups.com> On Apr 21, 7:58 am, Dustan wrote: > >From my searches here, there is no equivalent to java's > > StringTokenizer in python, which seems like a real shame to me. > > However, str.split() works just as well, except for the fact that it > creates it all at one go. I suggest an itersplit be introduced for > lazy evaluation, if you don't want to take up recourses, and it could > be used just like java's StringTokenizer. > > Comments? If anybody could inform me on how to get my hands on the python source code, I might even be able to come up with an example of how it could be implemented. I have no idea how to unzip that tgz or tar.bz2 file on a windows machine, though (and that's not from lack of trying). From jjl at pobox.com Wed Apr 11 18:07:40 2007 From: jjl at pobox.com (John J. Lee) Date: Wed, 11 Apr 2007 22:07:40 GMT Subject: Calling Python from Javascript? References: <87k5wi7iwi.fsf@pobox.com> Message-ID: <877isi7efj.fsf@pobox.com> jjl at pobox.com (John J. Lee) writes: > Kenneth McDonald writes: > > > I know that there's some work out there to let Python make use of > > Javascript (Spidermonkey) via (I assume) some sort of bridging C/C++ > > code. Anyone know of efforts to allow the reverse? I'd really like to > > make use of Python when doing Mozilla DOM programming, and I can never > > get a clear idea of when PyXPCOM might be available to those of us who > > don't know the ins and outs of compiling Mozilla, and its XPCOM > > structures. So if there was an easy way to simply and quickly pass > > even just strings back and forth between Python and Moz Javascript, > > that would make certain things a heck of a lot easier. > > I too wonder what happened to Mark Hammond's work on the > DOM_AGNOSTIC_2 branch a year or so back. Might be nice to be able to > write Firefox extensions in Python. > > Practically, I know that e.g. the firefox htmltidy extension (I forget > the name) contains binaries built from C code, not just JS, so I guess > you could write a Firefox extension that embeds CPython in a similar > way. There are also some compilers for generating JS from Python (or Python-like) source. The pyjamas project has one (pyjamas is currently a port of GWT to Python), and I believe PyPy has a JS backend too. Both of those are serious work but experimental. John From fff at sss.com Wed Apr 25 16:54:12 2007 From: fff at sss.com (desktop) Date: Wed, 25 Apr 2007 22:54:12 +0200 Subject: bitwise shift? Message-ID: I have found a code example with this loop. for k in range(10, 25): n = 1 << k; I have never read Python before but is it correct that 1 get multiplied with the numbers 10,11,12,12,...,25 assuming that 1 << k means "1 shift left by k" which is the same as multiplying with k. From paul at boddie.org.uk Wed Apr 11 06:30:28 2007 From: paul at boddie.org.uk (Paul Boddie) Date: 11 Apr 2007 03:30:28 -0700 Subject: tuples, index method, Python's design In-Reply-To: References: <1176210960.3430.20.camel@dot.uniqsys.com> <740c3aec0704100810g5f962e8eu614fbaedecf3608e@mail.gmail.com> <1176219856.3430.76.camel@dot.uniqsys.com> <740c3aec0704101021i1fd79ef2l99eac4ced1e252d9@mail.gmail.com> <1176226682.3430.86.camel@dot.uniqsys.com> Message-ID: <1176287428.004109.253810@y80g2000hsf.googlegroups.com> On 10 Apr, 20:04, "Chris Mellon" wrote: > > This is a rare enough use case and is easy enough to work around (convert it to > a list, write a helper function) that I don't think it's worth any > language change overhead at all. It isn't a language change: it's a change to the interface of a data type, and not a particularly big one, either. Paul From somas1 at gmail.com Sat Apr 14 21:46:33 2007 From: somas1 at gmail.com (somas1 at gmail.com) Date: 14 Apr 2007 18:46:33 -0700 Subject: Getting started with python In-Reply-To: <1176598011.463543.96990@q75g2000hsh.googlegroups.com> References: <1176598011.463543.96990@q75g2000hsh.googlegroups.com> Message-ID: <1176601593.703536.14620@l77g2000hsb.googlegroups.com> I'd like to second this request or at least find out if there are any type of Python mentorship programs I could join. From michael at jedimindworks.com Sun Apr 15 21:24:25 2007 From: michael at jedimindworks.com (Michael Bentley) Date: Sun, 15 Apr 2007 20:24:25 -0500 Subject: how to check the 'content/type' using urlopen In-Reply-To: <1176679523.382142.309220@b75g2000hsg.googlegroups.com> References: <1176679523.382142.309220@b75g2000hsg.googlegroups.com> Message-ID: <1DC93944-2B2E-40E1-AC1B-B90739E47AE3@jedimindworks.com> On Apr 15, 2007, at 6:25 PM, John wrote: > > i have the following code to open a URL address, but can you please > tell me how can I check the content type of the url response? > > Thank you. > > try: > req = Request(url, txdata, txheaders) > handle = urlopen(req) > except IOError, e: > print e > print 'Failed to open %s' % url > return 0; > > else: > data = handle.read() Not absolutely sure about this, but try handle.headers.get('Content- Type') before the read. hth, Michael --- Asking a person who he *is* ... is not Pythonic! --Anton Vredegoor From robinp.la at gmail.com Wed Apr 18 01:54:24 2007 From: robinp.la at gmail.com (robinp.la at gmail.com) Date: 17 Apr 2007 22:54:24 -0700 Subject: How to communicate via USB "port" Message-ID: <1176875664.555559.259840@y80g2000hsf.googlegroups.com> Can someone explain how I would read the data from the USB "port"? I don't know if it matters, but I am trying to read the data from a GPS plugged in to the USB port. Thank you, Robin From nogradi at gmail.com Thu Apr 26 07:37:43 2007 From: nogradi at gmail.com (Daniel Nogradi) Date: Thu, 26 Apr 2007 13:37:43 +0200 Subject: Re-ocurring Events In-Reply-To: <3891950377467154133@unknownmsgid> References: <3891950377467154133@unknownmsgid> Message-ID: <5f56302b0704260437v1e6bcecdv5d0c86ca8c0eeeaa@mail.gmail.com> > A bit more of a complex one this time, and I thought I'd get your opinions > on the best way to achieve this. Basically I'm looking for a way to describe > a re-occurring event, like a calendar event or appointment I guess. I'm > likely to use an XML file for the definition of the events, but imagine I've > got an event that looks something like this. > > /> > > Now what I want to do is be able to build a class which has a function like > 'getCurrentEvent()' which will return any events that should be occurring at > that time. So if the current system time and date is 2007-01-03 13:00:00 > then it will return THAT event to me, but if it was say 2007-01-03 16:00:00 > then it would not, as the event isn't 'due' to occur at that time. Make > sense? > > What's the best way of handling this? I'm really a little lost as to how I > might get started, checking a static date time isn't a problem, it's when it > comes to these re-occurring events that I struggle a little. The idea is > that I would have 5 core repetitions, none, daily, weekly, monthly and > annually. This will not solve all your problems, but a very convenient way of handling XML is the element tree module (that comes with python 2.5): http://docs.python.org/lib/module-xml.etree.ElementTree.html HTH, Daniel From carl at personnelware.com Fri Apr 13 15:08:39 2007 From: carl at personnelware.com (Carl K) Date: Fri, 13 Apr 2007 14:08:39 -0500 Subject: attribute save restore Message-ID: <7_ydnZt7B8WqSILbnZ2dnUVZ_uOmnZ2d@comcast.com> Is there a more elegant way of coding this: x=o.p # save .p o.p=0 o.m() o.p=x # restore .p seems very push/pop to me - like there should be a way that doesn't need a var (x) or the save/set lines should be done in one command. (personally I think .m would better be implemented by passing in a parameter, but that isn't my choice.) Carl K From kyosohma at gmail.com Thu Apr 12 11:43:25 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: 12 Apr 2007 08:43:25 -0700 Subject: wxPython, mac, wx.HSCROLL not working In-Reply-To: <586qvsF2fbq3rU1@mid.individual.net> References: <1176364597.741079.25840@n59g2000hsh.googlegroups.com> <586qvsF2fbq3rU1@mid.individual.net> Message-ID: <1176392605.298630.8210@y5g2000hsa.googlegroups.com> On Apr 12, 8:37 am, Bjoern Schliessmann wrote: > 7stud wrote: > > I'm trying to allow for a horizontal scrollbar on a textarea, but > > the scrollbar won't appear when I enter a long string of text(by > > leaning on one character on my keyboard): > > Works for me (Linux, self-built Python 2.5 and wxPython 2.8.3.0). > > Regards, > > Bj?rn > > -- > BOFH excuse #285: > > Telecommunications is upgrading. This works for me too. I'm using Python 2.4, Windows XP Pro, wxPython 2.6. You may want to post this to the wxpython users group list. It could be a Mac-specific bug. Mike From aisaac at american.edu Wed Apr 18 21:16:46 2007 From: aisaac at american.edu (Alan Isaac) Date: Thu, 19 Apr 2007 01:16:46 GMT Subject: comparison with None References: <3IqdnfRnCNWPC7vbnZ2dnUVZ_jqdnZ2d@rcn.net> Message-ID: <2qzVh.7373$xL6.982@trnddc05> "Terry Reedy" wrote in message news:mailman.6686.1176934558.32031.python-list at python.org... > Should be in the reference manual section on comparisons. Only to this extent: http://www.python.org/doc/2.4/ref/comparisons.html objects of different types always compare unequal, and are ordered consistently but arbitrarily. (This unusual definition of comparison was used to simplify the definition of operations like sorting and the in and not in operators. In the future, the comparison rules for objects of different types are likely to change.) ... Most other types compare unequal unless they are the same object; the choice whether one object is considered smaller or larger than another one is made arbitrarily but consistently within one execution of a program. This does not provide a direct answer to "why" None comparisons. (As far as I can tell, None is less than any object.) However, Gary Herron's explanation makes sense: this provides a stable sort when None is involved, and meets the criterion that objects of different types must always compare unequal. However this would also be true if None always compared greater than any object, and the current behavior does not seem to be guaranteed. Is that about right? Cheers, Alan Isaac From linusno at gmail.com Wed Apr 11 12:22:39 2007 From: linusno at gmail.com (=?ISO-8859-1?Q?Linus_Nordstr=F6m?=) Date: Wed, 11 Apr 2007 18:22:39 +0200 Subject: bittorent Message-ID: <1eb3a0e10704110922v17f83f79se5972dce07415a5@mail.gmail.com> Hello Im planing playing a bit whit bittorrent, but I'm having some trouble about where to start. So if anyone could point me in the right direction it would be much appreciated. The best would be if there are some already written modules that handle downloading and seeding torrents, but if that cant be found a good source on how one dose to build some sort of bitorrent client would be nice. thanks in advance From paul at boddie.org.uk Fri Apr 20 11:41:43 2007 From: paul at boddie.org.uk (Paul Boddie) Date: 20 Apr 2007 08:41:43 -0700 Subject: Do other Python GUI toolkits require this? In-Reply-To: References: <462697A6.6010007@codebykevin.com> <465B30B4-5BA0-459A-BE6F-1038874FA74B@jedimindworks.com> <58rq32F2fo980U1@mid.uni-berlin.de> <1177077506.429242.161690@e65g2000hsc.googlegroups.com> Message-ID: <1177083703.203360.220020@b75g2000hsg.googlegroups.com> On 20 Apr, 16:34, Antoon Pardon wrote: > On 2007-04-20, Paul Boddie wrote: > > > You could have knowledge or accomplishment > > on the X axis and effort or work on the Y axis. > > What else is effort than the time you spent on it? What's the difference between watching a television programme called "Useless Celebrity Factoids" for half an hour and spending the same amount of time studying for an exam involving useful information where you might also need to show some level of understanding of the subject matter? If that's not comparing similar measures of information, what's the difference between studying for an exam in a subject whose prerequisites are familiar to you and studying for one in an unfamiliar field, both for the same amount of time? Paul From deets at nospam.web.de Thu Apr 26 10:46:22 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 26 Apr 2007 16:46:22 +0200 Subject: Interrupting ftplib.storbinary() In-Reply-To: <1177597797.296812.226620@t39g2000prd.googlegroups.com> References: <1177597797.296812.226620@t39g2000prd.googlegroups.com> Message-ID: <59bsa3F2jpogvU1@mid.uni-berlin.de> Florian Demmer schrieb: > Hi! > > I have a number of ftp uploads running in parallel using > ftplib.storbinary and threading and in case one of them fails I need > to interrupt all the others (but not exit the program completely)... > do you guys have an idea how i could implement the interruption as > cleanly as possible? Might be a hint: http://mail.python.org/pipermail/python-list/2000-June/037692.html Diez From sjmachin at lexicon.net Tue Apr 24 20:35:19 2007 From: sjmachin at lexicon.net (John Machin) Date: Wed, 25 Apr 2007 10:35:19 +1000 Subject: Simple csv read/write In-Reply-To: <1177453628.474670.301330@t38g2000prd.googlegroups.com> References: <1177453628.474670.301330@t38g2000prd.googlegroups.com> Message-ID: <462EA247.1030708@lexicon.net> On 25/04/2007 8:27 AM, Drew wrote: > Ok, I'm trying to do the simplest read/write from one csv file to > another. For some reason, every other row on the output file is a > blank row. What am I doing wrong? > > import csv > > reader = csv.reader(open('current.csv')) > writer = csv.writer(open('new.csv','w')) > > for line in reader: > writer.writerow(line) > 1. Try reading the responses already posted to your previous questions. 2. Try reading the documentation; for each of csv.reader and csv.writer, it says "If csvfile is a file object, it must be opened with the 'b' flag on platforms where that makes a difference." From gtcopeland at gmail.com Tue Apr 17 16:12:20 2007 From: gtcopeland at gmail.com (Greg Copeland) Date: 17 Apr 2007 13:12:20 -0700 Subject: setup.py bdist_rpm help In-Reply-To: <1176833983.998563.313930@l77g2000hsb.googlegroups.com> References: <1176833983.998563.313930@l77g2000hsb.googlegroups.com> Message-ID: <1176840740.625636.235370@b58g2000hsg.googlegroups.com> Ahh. I figured it out. I resolved the issue by using a MANIFEST.in file. Greg On Apr 17, 1:19 pm, Greg Copeland wrote: > Okay, I have an application which is frozen via pyinstaller. That is > all working great. I now want to create an RPM using distutils' > bdist_rpm facilities. I seem to be running into trouble. No matter > what, I only seem to get three files within my RPM (setup.py, > README.txt, and PKG_INFO). > > My application ('app') has a configuration file ('x.cfg') and a single > directory ('data') which contains various data files used during > runtime. Can someone show me an example setup.py which will create an > RPM containing only the following: app, x.cfg, data/*? Please note > that 'app' is the frozen application and not the normal python script > (app.py). If it matters, I'm using Python 2.4.4 on Linux. > > Thanks! From zhonghua.m.yang at gmail.com Tue Apr 3 17:07:50 2007 From: zhonghua.m.yang at gmail.com (ZMY) Date: 3 Apr 2007 14:07:50 -0700 Subject: Numeric compiling problem under QNX 4.25 In-Reply-To: <1175632439.676454.21830@q75g2000hsh.googlegroups.com> References: <1175578324.426293.21970@y80g2000hsf.googlegroups.com> <1175622049.939184.28670@d57g2000hsg.googlegroups.com> <1175632439.676454.21830@q75g2000hsh.googlegroups.com> Message-ID: <1175634470.810726.304660@n76g2000hsh.googlegroups.com> On Apr 3, 1:33 pm, "ZMY" wrote: > On Apr 3, 10:51 am, Robert Kern wrote: > > > > >ZMYwrote: > > > Is "ld" part of make command? I am not familiar with compiling with > > > make in general. > > > No, it's the linker. I takes the object files (.o) which are generated by the > > compiler (cc, I imagine) and links them together into the shared library (.so). > > make is a program that can automate builds given instructions, but Numeric > > doesn't use it, nor do most other Python packages. > > > > Most other extensions (including math, os, struct, cPickle) from > > > Python 2.2 works when I install python on QNX. > > > No, I was wondering if you could build any other third-party extension modules. > > Did you install Python from source? When building extension modules, Python uses > > whatever linker was used to build itself. > > > -- > > 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 E > > Dear Robert, > > Looks like you are right. Here is what I got when I compile the > Python2.2 from source (or I believe so): > > $ sudo make SHELL=/usr/local/bin/bash > Password: > case $MAKEFLAGS in \ > *-s*) CC='cc' LDSHARED='ld' OPT='-DNDEBUG -O' ./python -E //6/openqnx/ > Python-2.2/setup.py -q build;; \ > *) CC='cc' LDSHARED='ld' OPT='-DNDEBUG -O' ./python -E //6/openqnx/ > Python-2.2/setup.py build;; \ > esac > running build > running build_ext > building 'regex' extension > skipping //6/openqnx/Python-2.2/Modules/regexmodule.c (build/temp.qnx- > O-PCI-2.2/regexmodule.o up-to-date) > skipping //6/openqnx/Python-2.2/Modules/regexpr.c (build/temp.qnx-O- > PCI-2.2/regexpr.o up-to-date) > ld build/temp.qnx-O-PCI-2.2/regexmodule.o build/temp.qnx-O-PCI-2.2/ > regexpr.o -L/usr/local/lib -o build/lib.qnx-O-PCI-2.2/regex.so > unable to execute ld: No such file or directory > .... > > If there is no 'ld' linker, what should be used instead?? > > BTW, the reason I am still using QNX4.25 is because I was trying to > install python on this legacy system. We can't move to QNX6 unless we > want to redo all other code as well, which took 3 years of a good > programmer :-( > > -ZMY I have tried to use Watcom linker 'wlink' in QNX instead of the 'ld' linker, but I still got problem with _numpymodule.o Do you have any experience with this?? ... building '_numpy' extension cc -DNDEBUG -O -IInclude -IPackages/FFT/Include -IPackages/RNG/Include -I/usr/local/include/python2.2 -c Src/_numpymodule.c -o build/temp.qnx- O-PCI-2.2/_numpymodule.o /usr/watcom/10.6/bin/wcc386 -zq -d+ -dNDEBUG -oil -i=Include - i=Packages/FFT/Include -i=Packages/RNG/Include -i=/usr/local/include/ python2.2 -ms -fo=build/temp.qnx-O-PCI-2.2/_numpymodule.o -4r -i=/usr/ watcom/10.6/usr/include -i=/usr/include Src/_numpymodule.c cc -DNDEBUG -O -IInclude -IPackages/FFT/Include -IPackages/RNG/Include -I/usr/local/include/python2.2 -c Src/arrayobject.c -o build/temp.qnx- O-PCI-2.2/arrayobject.o /usr/watcom/10.6/bin/wcc386 -zq -d+ -dNDEBUG -oil -i=Include - i=Packages/FFT/Include -i=Packages/RNG/Include -i=/usr/local/include/ python2.2 -ms -fo=build/temp.qnx-O-PCI-2.2/arrayobject.o -4r -i=/usr/ watcom/10.6/usr/include -i=/usr/include Src/arrayobject.c Src/arrayobject.c(527): Warning! W124: Comparison result always 0 cc -DNDEBUG -O -IInclude -IPackages/FFT/Include -IPackages/RNG/Include -I/usr/local/include/python2.2 -c Src/ufuncobject.c -o build/temp.qnx- O-PCI-2.2/ufuncobject.o /usr/watcom/10.6/bin/wcc386 -zq -d+ -dNDEBUG -oil -i=Include - i=Packages/FFT/Include -i=Packages/RNG/Include -i=/usr/local/include/ python2.2 -ms -fo=build/temp.qnx-O-PCI-2.2/ufuncobject.o -4r -i=/usr/ watcom/10.6/usr/include -i=/usr/include Src/ufuncobject.c wlink build/temp.qnx-O-PCI-2.2/_numpymodule.o build/temp.qnx-O-PCI-2.2/ arrayobject.o build/temp.qnx-O-PCI-2.2/ufuncobject.o -o build/lib.qnx- O-PCI-2.2/_numpy.so WATCOM Linker Version 10.6 Copyright by WATCOM International Corp. 1985, 1996. All rights reserved. WATCOM is a trademark of WATCOM International Corp. Error(3033): directive error near 'build/temp.qnx-O-PCI-2.2/ _numpymodule.o' error: command 'wlink' failed with exit status 1 From robert.kern at gmail.com Tue Apr 3 14:58:48 2007 From: robert.kern at gmail.com (Robert Kern) Date: Tue, 03 Apr 2007 13:58:48 -0500 Subject: os.popen--which one to use? In-Reply-To: References: Message-ID: Kevin Walzer wrote: > I'm confused by the number of variations on "popen" that Python offers. > > I'm using os.popen in my programs without difficulty. Is this wrong? > Should I be using popen 2, popen3, etc.? I'm not clear on what the > advantages of popen2, 3 etc. are: they seem a lot more complicated. Use the subprocess module, instead. It makes all of the popen functions more or less obsolete (it used to be called popen5 before it got moved into the standard library). -- 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 R.Brodie at rl.ac.uk Fri Apr 13 09:04:07 2007 From: R.Brodie at rl.ac.uk (Richard Brodie) Date: Fri, 13 Apr 2007 14:04:07 +0100 Subject: Arrays, Got Me Confused References: <000101c77dc3$d4152a00$7c3f7e00$@rawlins@thinkbluemedia.co.uk> <461F7712.2040201@timgolden.me.uk> Message-ID: "Robert Rawlins - Think Blue" wrote in message news:mailman.6460.1176468727.32031.python-list at python.org... > Wider fragments of code don't really exists at this moment in time No but specifying the problem too narrowly tends to get you an unidiomatic solution. > Basically I'm trying to create a class that contains an array of MAC > address, these look something like this 'FD:E4:55:00:FG:A9. You rarely want to use 'array' in the standard library; there are some use cases for it but they are rare. More often you want to use the list type. However, here you really want to use a set: having decided that, the code is so trivial, it's hardly worth making a new class. >>> s = set() >>> s.add('FD:E4:55:00:FG:A9') >>> s.remove('FD:E4:55:00:FG:A9') >>> s = set() >>> s.add('FD:E4:55:00:FG:A9') >>> 'FD:E4:55:00:FG:A9' in s True >>> s.remove('FD:E4:55:00:FG:A9') >>> 'FD:E4:55:00:FG:A9' in s False >>> s.clear() Of course, you might want to add sanity checks like 'G' is not a hex digit in a real implementation. From dsampson at NRCan.gc.ca Tue Apr 17 08:32:03 2007 From: dsampson at NRCan.gc.ca (Sampson, David) Date: Tue, 17 Apr 2007 08:32:03 -0400 Subject: PYTHON and GUIS and LOGIC... What First? (NEWBIE) Message-ID: <2FAA57395C1F914DB27CAA4C376058F2024352B9@S0-OTT-X2.nrn.nrcan.gc.ca> Hey folks, Well I read parts of the Oreily python book last night to knock me out. Unfortunately it actualy kept me awake with more questions. I am new to Python, OOP and for the fact programming. I have been a long time scriptor for basic processes using BAT shells and BASH shells... now I have dabled in VB for a while and been studying python. I have been doing various tutorials, creating small plugin widgets for python based applications and some simple scripts....... Now comes the next stage So here are today's perplexing thoughts. HOW TO START A PROGRAM FROM SCRATCH. I am not dealing with storing any data, just massive repetive processes on photos and grabbing info from a DB. I am also doing a GUI through Glade (done a few tutorials). Do I design the GUI or create the logic? Maybe it is done at the same time. So how do I decide if code should be housed in one module, a few or many modules. Do I have the GLADE XML file and then a module that organizes all the event handling and then pawn off the processing of strings to one or various modules? Should I create an object for everything or just things that will be reused. Looking at P.300 (OOP at 30,000 feet) makes me feel like that to be a good programmer I have to relate everything to everything and all code should be reused. I just want to make a nice tight and clean chunk of code and comments that can be understood by people who look at it later. AAAAAWWWWKKKKK Any thoughts, insight or philosphies? -------------- next part -------------- An HTML attachment was scrubbed... URL: From aisaac at american.edu Fri Apr 13 17:41:25 2007 From: aisaac at american.edu (Alan G Isaac) Date: Fri, 13 Apr 2007 16:41:25 -0500 Subject: vocab question In-Reply-To: References: <461fe3d0$0$11935$426a74cc@news.free.fr> Message-ID: Steven Bethard wrote: > As far as I > know, there's no official term for the first four elements of a class > statement. I'd probably call it the class statement header. That will have to do for now. Thanks! Alan Isaac From robert.kern at gmail.com Wed Apr 11 18:02:27 2007 From: robert.kern at gmail.com (Robert Kern) Date: Wed, 11 Apr 2007 17:02:27 -0500 Subject: About Trolltech QT OpenSource license. In-Reply-To: <1176326271.183571.286710@l77g2000hsb.googlegroups.com> References: <1176233376.712861.67160@o5g2000hsb.googlegroups.com> <1176237050.409742.8760@30g2000cwc.googlegroups.com> <1176285062.178372.15090@d57g2000hsg.googlegroups.com> <1176326271.183571.286710@l77g2000hsb.googlegroups.com> Message-ID: king kikapu wrote: > ?/? Robert Kern ??????: >> It's a bit more complicated than that. There are good resources for >> understanding the implications of the GPL on the FSF's site which other people >> have pointed out. > >>From what i can understand, you can sell your product and you have to > give the source. Also you must state clearly somewhere in the software > that this is under GPL. > Are there other complications that comes to the party ? All parts of the software have to be licensed compatibly with the GPL. The FSF has a fairly comprehensive list of the licenses they believe are GPL-compatible. The source that you provide needs to be the preferred form for making modifications; i.e., you can't use a tool that obfuscates the code. You need to provide the scripts that you use to build the software. You have to be careful about using patented techniques in your code. The source code must be offered at no extra charge (this part of the license is a bit tricky, so please read the license and the commentaries). > (i really like Qt but if i have chances to mess with laywers, i show > stick to wxPython and PythonCard...) You probably won't have to mess with lawyers, but with all software, even with wxPython and PythonCard, you yourself should understand the legal implications. You said that you "do not fully understand this license stuff," so I am trying to give you the resources such that you can learn. -- 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 bbxx789_05ss at yahoo.com Sat Apr 7 04:56:07 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: 7 Apr 2007 01:56:07 -0700 Subject: os.path.isfile() error Message-ID: <1175936167.548551.289600@n76g2000hsh.googlegroups.com> Here's the code: ------------ import os, os.path, pprint mydir = "/Users/me/2testing" files = [file for file in os.listdir(mydir)] pprint.pprint(files) print os.path.join(mydir, "helloWorld.py") files = [file for file in os.listdir(mydir) if os.path.isfile(os.path.join(dir, file) ) ] pprint.pprint(files) ----output:---------------- ['.DS_Store', 'cpTest', 'dir1', 'testfile1', 'xmlFile.xml'] /Users/me/2testing/helloWorld.py Traceback (most recent call last): File "test1.py", line 16, in ? files = [file File "/System/Library/Frameworks/Python.framework/Versions/2.3/lib/ python2.3/posixpath.py", line 62, in join elif path == '' or path.endswith('/'): AttributeError: 'builtin_function_or_method' object has no attribute 'endswith' From steven.bethard at gmail.com Wed Apr 4 17:49:23 2007 From: steven.bethard at gmail.com (Steven Bethard) Date: Wed, 04 Apr 2007 15:49:23 -0600 Subject: how to remove multiple occurrences of a string within a list? In-Reply-To: References: <1175624433.206953.214290@n59g2000hsh.googlegroups.com> <1175625098.269660.184790@o5g2000hsb.googlegroups.com> <1175626164.428718.267670@w1g2000hsg.googlegroups.com> <1175626674.836668.293850@b75g2000hsg.googlegroups.com> Message-ID: Ayaz Ahmed Khan wrote: > "kyosohma" typed: > >> If you want to get really fancy, you could do a list comprehension >> too: >> >> your_list = ["0024","haha","0024"] >> new_list = [i for i in your_list if i != '0024'] > > Or, just: > > In [1]: l = ["0024","haha","0024"] > In [2]: filter(lambda x: x != "0024", l) > Out[2]: ['haha'] Only if you want to make your code harder to read and slower:: $ python -m timeit -s "L = ['0024', 'haha', '0024']" "[i for i in L if i != '0024']" 1000000 loops, best of 3: 0.679 usec per loop $ python -m timeit -s "L = ['0024', 'haha', '0024']" "filter(lambda i: i != '1024', L)" 1000000 loops, best of 3: 1.38 usec per loop There really isn't much use for filter() anymore. Even in the one place I would have expected it to be faster, it's slower:: $ python -m timeit -s "L = ['', 'a', '', 'b']" "filter(None, L)" 1000000 loops, best of 3: 0.789 usec per loop $ python -m timeit -s "L = ['', 'a', '', 'b']" "[i for i in L if i]" 1000000 loops, best of 3: 0.739 usec per loop STeVe From ptmcg at austin.rr.com Wed Apr 25 22:02:49 2007 From: ptmcg at austin.rr.com (Paul McGuire) Date: 25 Apr 2007 19:02:49 -0700 Subject: Convert a string to a list In-Reply-To: References: <1177426760.164877.104990@t38g2000prd.googlegroups.com> Message-ID: <1177552969.604821.267290@c18g2000prb.googlegroups.com> On Apr 24, 12:30 pm, Nick Craig-Wood wrote: > > Someone normally chimes in with pyparsing at this point... > Well it *is* a short pyparsing routine, after all... -- Someone tests = """\ ("." ".." "cdslib_cleanup.py" "cadence.py" "cdsinit_cdsenv_cleanup.py") ("." ("cadence.py" "foo_cleanup.py") "cdslib_cleanup.py" "cadence.py" "cdsinit_cdsenv_cleanup.py") """.splitlines() import pyparsing as pp LPAR,RPAR = map(pp.Suppress,"()") list_ = pp.Forward() list_ << ( LPAR + pp.ZeroOrMore( pp.quotedString | pp.Group(list_) ) + RPAR ) for t in tests: result = list_.parseString(t) print result.asList() Prints: ['"."', '".."', '"cdslib_cleanup.py"', '"cadence.py"', '"cdsinit_cdsenv_cleanup.py"'] ['"."', ['"cadence.py"', '"foo_cleanup.py"'], '"cdslib_cleanup.py"', '"cadence.py"', '"cdsinit_cdsenv_cleanup.py"'] From steve at holdenweb.com Thu Apr 5 17:44:01 2007 From: steve at holdenweb.com (Steve Holden) Date: Thu, 05 Apr 2007 17:44:01 -0400 Subject: UNICODE mode for regular expressions - time to change the default? In-Reply-To: References: Message-ID: John Nagle wrote: > Regular expressions are compiled in ASCII mode unless > Unicode mode is specified to "rc.compile". The difference is that regular > expressions in ASCII mode don't recognize things like > Unicode whitespace, even when applied to Unicode strings. > For example, Unicode character 0x00A0 is a "NO-BREAK SPACE", which is > a form of whitespace. It's the Unicode equivalent of HTML's " ". > This can create some strange bugs. > > Is the current default good? Or is it time to compile all regular > expressions in Unicode mode by default? It shouldn't hurt processing of > ASCII strings to do that. The current setup is really a legacy of when > most things in Python didn't work in Unicode mode, and you didn't want to > introduce Unicode unnecessarily. It's another one of those obscure > Unicode "gotchas" that really should go away. > > John Nagle Personally I'd leave it to go away with Python 3.0, when all strings will be Unicode. 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 aboudouvas at panafonet.gr Tue Apr 10 16:30:50 2007 From: aboudouvas at panafonet.gr (king kikapu) Date: 10 Apr 2007 13:30:50 -0700 Subject: About Trolltech QT OpenSource license. In-Reply-To: References: <1176233376.712861.67160@o5g2000hsb.googlegroups.com> Message-ID: <1176237050.409742.8760@30g2000cwc.googlegroups.com> ?/? Jarek Zgoda ??????: > king kikapu napisa?(a): > > This is a bullsh*t. Qt is free (as in "free speech") on GPL. Nothing > stops you from using it in any commercial project if only it fits the > licensing terms (i.o.w. it's free software). This specially applies to > inhouse development, as in such case there's no "distribution". Hmmm...how a commercial software (that means i get paid for give it) it will be consider "free software" ? I ask because i surely do not understand correctly the GPL lisence and all that stuff. > Hey, there's no such statement here. Where did you get this "must buy > the commercial lisence"? Good point! I got it because at the last portion of my email, i asked for it. I asked them that: "And in the case i want to build something that i want to later sell (as an individual)..." so i got it back. > Plus, this (sales)person forgot to state clearly, that GPL covers only > distribution, not the cost of software. If you manage to get some hot > cash for selling sources of your GPL-ed program, the license would not > try to stop you from doing that. ;) As i said, i do not fully understand all this license stuff. All i want to ask is, i can make GPL software and gain money from this ? And if that so, then why they "force" you to buy the commercial lisence in such case ? From matthiasjanes at gmx.net Wed Apr 11 05:38:41 2007 From: matthiasjanes at gmx.net (matthiasjanes at gmx.net) Date: 11 Apr 2007 02:38:41 -0700 Subject: THREADS use 100 % CPU all the time Message-ID: <1176284321.528102.112740@o5g2000hsb.googlegroups.com> Hi all, I have a application where I use different threads. actually all is working - BUT I just discovered that the [b]CPU is always 100 % [/ b]used. on the 32-bit machine athlon XP, as well as on the amd 64-bit AMD Athlon(TM) 64 X2 Dual-Core. I have to admit I'm not used to threads. I actually use a thirdparty scheduler [url]http://www.webwareforpython.org/TaskKit/Docs/Source/ Docs/TaskKit.Scheduler.html[/url] but I checked and a very simple exampe with threading gives me also all the time 100% CPU. [code] import threading, time class TestThread ( threading.Thread ): def run ( self ): print 'TEST' t = TestThread() t.start() while (True): pass [/code] Does anyone know how to run this without consuming all CPU. regards, MJ From franz.steinhaeusler at gmx.at Wed Apr 18 09:07:55 2007 From: franz.steinhaeusler at gmx.at (Franz Steinhaeusler) Date: Wed, 18 Apr 2007 15:07:55 +0200 Subject: Wanted: Email Client with GUI Message-ID: Hi, although I have googled, I didn't find a Python email client program fitting to my needs. What I want is a program (it doesn't have to be so sophisticated as thunderbird) written totally in python and using a gui toolkit like pyqt, pygtk, wxpyhton or tkinter. Who knows such a program? ;) best regards, From admin at loial.co.uk Thu Apr 12 05:31:53 2007 From: admin at loial.co.uk (loial) Date: 12 Apr 2007 02:31:53 -0700 Subject: Newbie help with array handling In-Reply-To: <1176368561.245625.251270@y5g2000hsa.googlegroups.com> References: <1176364734.439383.252930@o5g2000hsb.googlegroups.com> <1176368561.245625.251270@y5g2000hsa.googlegroups.com> Message-ID: <1176370313.386948.260930@p77g2000hsh.googlegroups.com> OK, thanks for the replies One other thing...I need to update the values since they are basically totals that I am accumulating. How do I update a specific value for a specific key? From TimeHorse at gmail.com Thu Apr 5 18:10:59 2007 From: TimeHorse at gmail.com (darklord@timehorse.com) Date: 5 Apr 2007 15:10:59 -0700 Subject: RFC: Assignment as expression (pre-PEP) In-Reply-To: <%keRh.9812$M.739@news-server.bigpond.net.au> References: <1175802680.021987.39220@p77g2000hsh.googlegroups.com> <1175807326.466842.219820@p77g2000hsh.googlegroups.com> <%keRh.9812$M.739@news-server.bigpond.net.au> Message-ID: <1175811059.951111.205190@e65g2000hsc.googlegroups.com> On Apr 5, 6:01 pm, Neil Hodgson wrote: > darkl... at timehorse.com: > > > else: > > my_match = capper_re.match(f): > > if my_match: > > capper = capper_re.match(f).group(1) > > if capper == 'JJ' or capper == 'JeffreyJacobs': > > capper = 'Jeffrey C. Jacobs' > > past_title = True > > The assignment to my_match here is not used, so the test can be "if > capper_re.match(f)" which can then merge up into the previous else as an > elif dropping one level of indentation. > > Neil That was a typo. I meant to reuse my_match in the line "capper = my_match.group(1)" rather than the line above just so I would not have to evaluate the regular expression twice. Sorry for the confusion. Jeffrey. From kevinliu23 at gmail.com Sat Apr 21 17:01:25 2007 From: kevinliu23 at gmail.com (kevinliu23) Date: 21 Apr 2007 14:01:25 -0700 Subject: Newbie question regarding string.split() In-Reply-To: <462a5cd0$0$4231$426a74cc@news.free.fr> References: <1177095062.826018.63590@n59g2000hsh.googlegroups.com> <462a5cd0$0$4231$426a74cc@news.free.fr> Message-ID: <1177189285.686072.159390@b58g2000hsg.googlegroups.com> On Apr 21, 3:30 pm, Bruno Desthuilliers wrote: > kevinliu23 a ?crit :> Hey guys, > > > So I have a question regarding the split() function in the string > > module. Let's say I have an string... > > > input = "2b 3 4bx 5b 2c 4a 5a 6" > > projectOptions = (input.replace(" ", "")).split('2') Thanks for all your help everyone. :) > The parens around the call to input.replace are useless: > projectOptions = input.replace(" ", "").split('2') > > > print projectOptions > > > ['', 'b34bx5b', 'c4a5a6'] > > (snip) > > > What can I do so that the first element is not an empty > > string? but the 'b34bx5b' string as I expected? > > projectOptions = filter(None, input.replace(" ", "").split('2')) From deets at nospam.web.de Tue Apr 24 12:43:16 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 24 Apr 2007 18:43:16 +0200 Subject: q: how to output a unicode string? References: Message-ID: <596qd4F2k129kU1@mid.uni-berlin.de> Frank Stajano wrote: > A simple unicode question. How do I print? > > Sample code: > > # -*- coding: utf-8 -*- > s1 = u"h?ll? w?rld" > print s1 > # Gives UnicodeEncodeError: 'ascii' codec can't encode character > # u'\xe9' in position 1: ordinal not in range(128) > > > What I actually want to do is slightly more elaborate: read from a text > file which is in utf-8, do some manipulations of the text and print the > result on stdout. I understand I must open the file with > > f = codecs.open("input.txt", "r", "utf-8") > > but then I get stuck as above. > > I tried > > s2 = s1.encode("utf-8") > print s2 > > but got > > h??ll?? w??rld Which is perfectly alright - it's just that your terminal isn't prepared to decode UTF-8, but some other encoding, like latin1. > Then, in the hope of being able to write the string to a file if not to > stdout, I also tried > > > import codecs > f = codecs.open("out.txt", "w", "utf-8") > f.write(s2) > > but got > > UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 1: > ordinal not in range(128) Instead of writing s2 (which is a byte-string!!!), write s1. It will work. The error you get stems from f.write wanting a unicode-object, but s2 is a bytestring (you explicitly converted it before), so python tries to encode the bytestring with the default encoding - ascii - to a unicode string. This of course fails. Diez From fuzzyman at gmail.com Sun Apr 22 15:46:03 2007 From: fuzzyman at gmail.com (Fuzzyman) Date: 22 Apr 2007 12:46:03 -0700 Subject: [ANN] Pythonutils 0.3.0 Message-ID: <1177271163.678440.51370@b58g2000hsg.googlegroups.com> There is a new (and long overdue) release of the `Pythonutils module `_. This is version **0.3.0**. * `Quick Download: Pythonutils 0.3.0.zip `_ What is Pythonutils? =============== Pythonutils is a collection of general utility modules that simplify common programming tasks in Python. The modules included are : * `ConfigObj `_ 4.4.0 - Easy config file reading/writing * `validate `_ 0.2.3 - Validation and type conversion system * `StandOut `_ 3.0.0 - Simple logging and output control object * `pathutils `_ 0.2.5 - For working with paths and files * `cgiutils `_ 0.3.5 - {acro;CGI} helpers * `urlpath `_ 0.1.0 - Functions for handling URLs * `odict `_ 0.2.2 - Ordered Dictionary Class For more details, visit the `Pythonutils Homepage `_. What is New in 0.3.0? ================ Several of the modules have been updated. The major changes are: * Removed the `listquote `_ module * ConfigObj updated to 4.4.0 * StandOut updated to 3.0.0 (*Not* backwards compatible, but much improved) From donn at u.washington.edu Wed Apr 25 13:55:35 2007 From: donn at u.washington.edu (Donn Cave) Date: Wed, 25 Apr 2007 10:55:35 -0700 Subject: Python not giving free memory back to the os get's me in real problems ... References: <1177510121.882503.145560@n15g2000prd.googlegroups.com> <_LidnenBcrz7-rLbnZ2dnUVZ_tCtnZ2d@comcast.com> <59990rF2ja6c7U3@mid.dfncis.de> <132uv54ncsspm91@corp.supernews.com> Message-ID: In article , Steven Howe wrote: > Interesting questions. What happens when an object is 'cleaned' up by > using the 'del' command. Does the memory space stay in the python > process, get handed back to the OS, or some combination of both? > I remember 'C' on VMS at least, could be coerced into return memory on > block boundaries. 'C++' was suppose to have garbage collect, but I was > always doubtful it worked well. Note that UNIX (and VMS) use "virtual" memory. Real memory space gets "handed back to the OS" by default -- if you don't use it, you lose it. It isn't coercion, but it does happen on a per page basis, so fragmentation wastes space. If a Python program uses more space than it ought to need, then some knowledge of Python's reference counting allocation scheme will be useful. In particular, you need a fairly good grasp of what a "reference" is. Donn Cave, donn at u.washington.edu From fuzzyman at gmail.com Sat Apr 21 19:22:26 2007 From: fuzzyman at gmail.com (Fuzzyman) Date: 21 Apr 2007 16:22:26 -0700 Subject: CGI Script using Python In-Reply-To: References: <58our9F2fertqU1@mid.individual.net> Message-ID: <1177197746.091576.92370@o5g2000hsb.googlegroups.com> On Apr 21, 10:02 pm, Tim Roberts wrote: > "Ralf" wrote: > > >is there anybody who can help me. > >I would like to use a Python Script to download Files from a Server to the > >Client, to update the Client. > > Remember, though, that a CGI script cannot actually put files anywhere. You > can certainly download files to the client browser, but the user will have > to be involved to tell the browser where to store the incoming file. > > Doing anything else would be a security hole. But a CGI script can send a file in response to an automated request from a client application, without ever needing a browser to be involved. Sending the right headers means that existing libraries (urllib2 I guess) will know how to handle the response. Fuzzyman http://www.voidspace.org.uk/python/articles.shtml > -- > Tim Roberts, t... at probo.com > Providenza & Boekelheide, Inc. From mike.aldrich at gmail.com Fri Apr 13 07:59:30 2007 From: mike.aldrich at gmail.com (mike.aldrich at gmail.com) Date: 13 Apr 2007 04:59:30 -0700 Subject: Reading the first line of a file (in a zipfile) In-Reply-To: References: <1176318822.811661.115730@q75g2000hsh.googlegroups.com> <1176322548.710970.315610@d57g2000hsg.googlegroups.com> Message-ID: <1176465570.907000.86150@b75g2000hsg.googlegroups.com> On Apr 11, 4:20 pm, "Gabriel Genellina" wrote: > En Wed, 11 Apr 2007 17:15:48 -0300, escribi?: > > > The file contents have leading whitespace, then a number: > > 123456 \n > > I expect to return '123456' > > And nothing following the number? > > py> line = " 123456 \n" > py> print line.strip() > 123456 > > -- > Gabriel Genellina That works fine if I am using the interpreter, but I get 'cannot open file' when i try to read from an archive.. Does that make sense? Sorry, this is my 2nd python script. From saif.shakeel at gmail.com Mon Apr 30 03:44:23 2007 From: saif.shakeel at gmail.com (saif.shakeel at gmail.com) Date: 30 Apr 2007 00:44:23 -0700 Subject: I/O Operations ..... Message-ID: <1177919063.650070.321560@y80g2000hsf.googlegroups.com> Hi, I am parsing an XML file and sending the output to two files.The code asks the user to enter the input file,something like: file_input = raw_input("Enter The ODX File Path:") input_xml = open(file_input,'r') Now suppose the user enters the path as : C:\Projects\ODX Import\Sample Files\Global _A_UHP_Low_0.7.odx.xml I have 2 output files to which i have to redirect the output.The output file name should be same as input file in the same path ( the extension has to change to a format "ini" which is basically text file opened using notepad).Eg.. output files should be : C:\Projects\ODX Import\Sample Files\Global _A_UHP_Low_0.7.ini, and, C:\Projects\ODX Import\Sample Files\Global _A_UHP_Low_0.7.xls Can someone help me in this. cheers From aleax at mac.com Thu Apr 26 01:47:03 2007 From: aleax at mac.com (Alex Martelli) Date: Wed, 25 Apr 2007 22:47:03 -0700 Subject: If Dict Contains a particular key References: <000001c78695$ed321540$c7963fc0$@rawlins@thinkbluemedia.co.uk> <1177436682.3441.15.camel@dot.uniqsys.com> <1177565430.992904.149450@n35g2000prd.googlegroups.com> Message-ID: <1hx5dto.hwi9shy3mg47N%aleax@mac.com> mensanator at aol.com wrote: ... > > if 'a' in thedict: > > ... > > > > There's no need for the call to keys(). > > Why not > > if thedict.has_key('a'): > pass > elde: > pass has_key exists only for backwards compatibility; the 'in' operator is preferable. $ python -mtimeit -s'd={}' 'd.has_key(23)' 1000000 loops, best of 3: 0.289 usec per loop $ python -mtimeit -s'd={}' '23 in d' 10000000 loops, best of 3: 0.139 usec per loop Why consume twice as much time with no advantages whatever?! Alex From bbxx789_05ss at yahoo.com Mon Apr 23 18:32:21 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: 23 Apr 2007 15:32:21 -0700 Subject: Learning Python - First Project In-Reply-To: <1177367105.564414.312320@y5g2000hsa.googlegroups.com> References: <1177339942.371167.93970@b75g2000hsg.googlegroups.com> <1177352775.828143.9910@y5g2000hsa.googlegroups.com> <1177367105.564414.312320@y5g2000hsa.googlegroups.com> Message-ID: <1177367541.059834.18420@o5g2000hsb.googlegroups.com> On Apr 23, 4:25 pm, 7stud wrote: > On Apr 23, 12:26 pm, kyoso... at gmail.com wrote: > > > I am assuming you are using Tkinter for your front-end GUI. You might > > also take a gander at wxPython. It has an excellent demo you could > > download and it might give you some additional ideas for > > implementation:www.wxpython.org. > > > Mike > > Hi, > > I've heard about that excellent demo, but I downloaded wxPython, and I > don't even know where to look for it. Any pointers? Never mind. Got it: $ python /Developer/Examples/wxWidgets/wxPython/demo/demo.py From bbxx789_05ss at yahoo.com Tue Apr 10 03:23:17 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: 10 Apr 2007 00:23:17 -0700 Subject: how to get char ASCII value. In-Reply-To: <1176188274.244322.250780@e65g2000hsc.googlegroups.com> References: <1176188274.244322.250780@e65g2000hsc.googlegroups.com> Message-ID: <1176189797.515948.237310@w1g2000hsg.googlegroups.com> On Apr 10, 12:57 am, veblen.... at gmail.com wrote: > for an example: > 'a' value 0x61 > '1' value 0x31. How about: import string for char in string.lowercase: print hex(ord(char) ) From mike.klaas at gmail.com Mon Apr 16 19:12:30 2007 From: mike.klaas at gmail.com (Klaas) Date: 16 Apr 2007 16:12:30 -0700 Subject: Queue enhancement suggestion In-Reply-To: <7x4pngluel.fsf_-_@ruckus.brouhaha.com> References: <7x4pngluel.fsf_-_@ruckus.brouhaha.com> Message-ID: <1176765150.918468.207300@p77g2000hsh.googlegroups.com> On Apr 15, 11:12 pm, Paul Rubin wrote: > I'd like to suggest adding a new operation > > Queue.finish() > > This puts a special sentinel object on the queue. The sentinel > travels through the queue like any other object, however, when > q.get() encounters the sentinel, it raises StopIteration instead > of returning the sentinel. It does not remove the sentinel from > the queue, so further calls to q.get also raise StopIteration. > That permits writing the typical "worker thread" as This is a pretty good idea. However, it needs a custom __iter__ method to work... the syntax below is wrong on many levels. > for item in iter(q.get): ... Once you implement __iter__, you are left with 'for item in q'. The main danger here is that all the threading synchro stuff is hidden in the guts of the __iter__ implementation, which isn't terribly clear. There is no way to handle Empty exceptions and use timeouts, for instance. > however that actually pops the sentinel, so if there are a lot of > readers then the writing side has to push a separate sentinel for > each reader. I found my code cluttered with > > for i in xrange(number_of_worker_threads): > q.put(sentinel) > > which certainly seems like a code smell to me. Yeah, it kind of does. Why not write a Queue + Worker manager that keeps track of the number of workers, that has a .finish() method that does this smelly task for you? -Mike From iansan at gmail.com Wed Apr 11 19:20:47 2007 From: iansan at gmail.com (IamIan) Date: 11 Apr 2007 16:20:47 -0700 Subject: Nested dictionaries trouble In-Reply-To: <461d427e$0$18058$426a74cc@news.free.fr> References: <1176317876.917874.58040@n59g2000hsh.googlegroups.com> <461d427e$0$18058$426a74cc@news.free.fr> Message-ID: <1176333647.470409.62320@q75g2000hsh.googlegroups.com> Thank you everyone for the helpful replies. Some of the solutions were new to me, but the script now runs successfully. I'm still learning to ride the snake but I love this language! Ian From mad.vijay at gmail.com Fri Apr 13 05:14:02 2007 From: mad.vijay at gmail.com (SamG) Date: 13 Apr 2007 02:14:02 -0700 Subject: Try problem Message-ID: <1176455642.199343.136720@l77g2000hsb.googlegroups.com> import sys try: s=1 if s==1: sys.exit(0) else: sys.exit(1) except SystemExit,s: if (s==0): print s else: print "Hello" How come i always end up getting the "Hello" printed on the screen as logically i should a '0' printed? From jstroud at mbi.ucla.edu Tue Apr 24 07:50:07 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Tue, 24 Apr 2007 11:50:07 GMT Subject: Python Screen Scraper Message-ID: Hello, Does anyone know of an example, however modest, of a screenscraper authored in python? I am using Firefox. Basically, I am answering problems via my browser and being scored for each problem. I have a tendency to go past my peak for training efficiency, so I would like to scrape the result page for each problem I answer, compile statistics, and have a program alert me when I should stop (based on score and accuracy--assuming training value is related to changes in these metrics). I have no idea how to go about writing such a beast and I am hoping that I could get some pointers or an example that could get me going in the right direction. Parsing, etc, is not a problem, but I'm not exactly sure how I might interface python with Firefox, forwarding scraped pages to my browser (or forwarding from the browser to the scraper). Thanks in advance for any help or advice. James From pecoraREMOVE at THISanvil.nrl.navy.mil Tue Apr 17 10:58:46 2007 From: pecoraREMOVE at THISanvil.nrl.navy.mil (Lou Pecora) Date: Tue, 17 Apr 2007 10:58:46 -0400 Subject: The smallest and largest values of numeric types References: Message-ID: In article , tom at finland.com wrote: > Hi! > How can I determine the smallest and largest values of numeric types > (for example int) possible in my system? I think there exists a function > for this task but I don't know it. There is or was a module called "kinds" which was an implementation of PEP 0242. I have it and it gives the values you are looking for (and more). But I don't know where I got it. I think it was once distributed with Macpython on MacPython.org, but I'm not sure. I've searched for it, but nothing shows up except my own questions about it from many years ago and they have no clues. Does anyone know where this package is? Or what might replace it. It is very useful. From steve at holdenweb.com Tue Apr 17 07:23:29 2007 From: steve at holdenweb.com (Steve Holden) Date: Tue, 17 Apr 2007 07:23:29 -0400 Subject: Python and SSL In-Reply-To: <7xy7krbte4.fsf@ruckus.brouhaha.com> References: <1176737058.203036.53170@n59g2000hsh.googlegroups.com> <4623ECE0.3010103@v.loewis.de> <7xy7krbte4.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > "Martin v. L?wis" writes: >> It means that these modules can do encrypted communication for their >> respective protocol. They cannot validate that they are really talking >> to the server they think they talk to (so they are prone to a >> man-in-the-middle attack), however, as communication is encrypted, they >> are protected against wire-tapping. > > Unless the wiretapper is running a man-in-the-middle attack... > That's pretty unreasonable: wiretapping is normally regarded as passive listening - when the FBI tap your wire do they try and impersonate the people you are calling? - and Martin already explained that man-in-the-middle was still a risk. Why muddy the issue with this "point"? 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 mvksagar at gmail.com Mon Apr 30 04:35:30 2007 From: mvksagar at gmail.com (sagar) Date: 30 Apr 2007 01:35:30 -0700 Subject: Reading Data From an Excel Sheet Message-ID: <1177922130.251948.107740@p77g2000hsh.googlegroups.com> Hi all, I want a python script which takes in input an EXCEL sheet and then reads the data in it. Any code snippets will be fine and this i want this in windows XP . Thanks in Advance Sagar Meesala From tsm8015 at gmail.com Sat Apr 21 23:36:13 2007 From: tsm8015 at gmail.com (tsm8015 at gmail.com) Date: 21 Apr 2007 20:36:13 -0700 Subject: Problem redefining __getitem__ for str subclass Message-ID: <1177212972.973086.319990@b58g2000hsg.googlegroups.com> I do not think I am understanding how to redefine the getitem function for string. Why does the following not work: class NStr(str): def __getitem__(self,idx): print "NStr:getitem",idx,type(idx) return str.__getitem__(self,idx) s=NStr("abcde") print s[1] print s[1:4:2] print s[1:2] if I run this program (python 2.5; Mac OSX) i get: $ python strProb.py NStr:getitem 1 b NStr:getitem slice(1, 4, 2) bd b ie the last statement (s[1:2]) with a simple slice does not call the new __getitem__???? What am I missing. Thanks tom From gagsl-py2 at yahoo.com.ar Sun Apr 1 04:44:47 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sun, 01 Apr 2007 05:44:47 -0300 Subject: Pygame Q (linux) beginner References: <460F28F2.D91DB67A@braindead.com> Message-ID: En Sat, 31 Mar 2007 23:37:16 -0300, enquiring mind <"enquiring mind"@braindead.com> escribi?: > Running 2.4.1 Python (learning) > Running SUSE Linux 10 > > Am learning from a new books that mostly deals with windows python and > Pygames called "Game Programming" by Randy Harris (2007) His books > references Python 2.4.2 and Pygame 1.7.1 with these comments: > > "If you are using a Linux machine, you probably won't have the simple > installer that came with the windows version. Follow the instructions > at http://pygame.org/install. You may have to run a couple of scripts > to make everything work, but just follow the directions and you will be > fine." > > Could anybody suggest or make a helpful comment in view of what > information I have supplied. At Chapter 5 is where the Pygame module is > introduced so I have a little time before I have to figure out what I > have to download and install. First: read that page. I don't use SUSE myself, but the first hit on Google for "pygame SUSE" goes into the Novell site, and SUSE 10.1 appears to include pygame 1.7.1release14 (or at least, you should be able to download and install the RPM from Novell) -- Gabriel Genellina From tgrav at mac.com Fri Apr 20 09:53:09 2007 From: tgrav at mac.com (Tommy Grav) Date: Fri, 20 Apr 2007 09:53:09 -0400 Subject: Do other Python GUI toolkits require this? In-Reply-To: References: <462697A6.6010007@codebykevin.com> <465B30B4-5BA0-459A-BE6F-1038874FA74B@jedimindworks.com> <58rq32F2fo980U1@mid.uni-berlin.de> Message-ID: <2B05BF8C-8477-4F56-B89A-A5D58DBB53C7@mac.com> On Apr 20, 2007, at 9:22 AM, Antoon Pardon wrote: > Well if you want to do it that way, nobody can stop you, but people > in the habit of processing numbers usually put the time on the X-axis > like in time spend learning or exercising and put the other value > on the Y-axis. > > That is because people prefer a curve going up and down while moving > to the right instead of going left and right while moving up. That depends all on what you are plotting. If you are after the amount of work it was to go from uneducated to educated then a shallow slope is preferable (with amount of work on the y axis, and degree of educated on the x axis). Wether a shallow or steep slope is preferable is all dependent on what one is actually measuring. Cheers Tommy From gagsl-py2 at yahoo.com.ar Thu Apr 5 13:14:16 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 05 Apr 2007 14:14:16 -0300 Subject: Windows service and pyc files References: <1175709094.352514.64920@y66g2000hsf.googlegroups.com> <46151D34.50608@designaproduct.biz> <461528C8.9020707@designaproduct.biz> Message-ID: En Thu, 05 Apr 2007 13:50:16 -0300, Laszlo Nagy escribi?: > 1. subprocess.Popen cannot redirect stderr and stdout when called from a > win32 service. This is not documented, and makes debugging almost > impossible. Without the patch menctioned in my previous message, you must redirect all stdin, stdout AND stderr (because the child cannot inherit the handles from the parent service, as a service has no standard handles assigned usually) or none of them. > 2. sys.executable becomes "pythonservice.exe" inside a win32 service. > > If I specify r"C:\Python25\python.exe" instead of sys.executable, and > if I do not specify stdout and stderr parameters for subprocess.Popen, > then my program starts to work. Here arises the question: how can I > find r"C:\Python25\python.exe" from inside a win32 service? Can I use > this: > > interpreter = os.path.join( os.path.split(sys.executable),[0], > os.sep,os.sep,os.sep,'Python.exe' ) I think you meant to write: os.path.join(os.path.split(sys.executable)[0], os.pardir, os.pardir, os.pardir, 'python.exe') pythonservice.exe is so Windows-specific that using os.pardir only makes the code harder to read. Anyway I'd use os.path.join(sys.prefix, 'python.exe') (sys.prefix would be C:\Python25 in your case) -- Gabriel Genellina From bbxx789_05ss at yahoo.com Sat Apr 28 13:38:30 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: 28 Apr 2007 10:38:30 -0700 Subject: python function in pipe In-Reply-To: <1177781750.667445.305900@l77g2000hsb.googlegroups.com> References: <1177781750.667445.305900@l77g2000hsb.googlegroups.com> Message-ID: <1177781910.064770.150780@c35g2000hsg.googlegroups.com> > p = subprocess.Popen(["python", "6test.py"], > stdout=subprocess.PIPE, > stderr=subprocess.PIPE) The file name is wrong there; it should be: p = subprocess.Popen(["python", "moduleA.py"], stdout=subprocess.PIPE, stderr=subprocess.PIPE) From psdasilvaX at esotericaX.ptX Sun Apr 1 22:03:23 2007 From: psdasilvaX at esotericaX.ptX (Paulo da Silva) Date: Mon, 02 Apr 2007 03:03:23 +0100 Subject: Sorting a multidimensional array by multiple keys In-Reply-To: References: Message-ID: <1175479365.353572@jubilee.claranet.pt> Rehceb Rotkiv escreveu: > Hello everyone, > > can I sort a multidimensional array in Python by multiple sort keys? A > litte code sample would be nice! class MyList(list): # This is the index of the element to be compared CmpIndex=0 # Comparision methods @staticmethod def __cmp_pars(x,y): if isinstance(x,MyList): x=x[MyList.CmpIndex] if isinstance(y,MyList): y=y[MyList.CmpIndex] return x,y def __cmp__(self,other): s,o=MyList.__cmp_pars(self,other) return cmp(s,o) def __lt__(self,other): s,o=MyList.__cmp_pars(self,other) return so def __ge__(self,other): s,o=MyList.__cmp_pars(self,other) return s>=o def __eq__(self,other): s,o=MyList.__cmp_pars(self,other) return s==o def __ne__(self,other): s,o=MyList.__cmp_pars(self,other) return s!=o Use: x=MyList() MyList.CmpIndex=2 # Compare by index 2 x.sort() May be there is a better solution ... HTH Paulo From google at mrabarnett.plus.com Mon Apr 30 18:24:03 2007 From: google at mrabarnett.plus.com (MRAB) Date: 30 Apr 2007 15:24:03 -0700 Subject: regexp match string with word1 and not word2 In-Reply-To: References: <1177920984.247487.54620@c35g2000hsg.googlegroups.com> <1177946458.620210.68690@u30g2000hsc.googlegroups.com> Message-ID: <1177971843.333443.42860@y5g2000hsa.googlegroups.com> On Apr 30, 6:49 pm, Marc 'BlackJack' Rintsch wrote: > In <1177946458.620210.68... at u30g2000hsc.googlegroups.com>, Flyzone wrote: > > for y in range(0, len(skip_lst) ): > > if (re.search(skip_lst[y], line)): > > skip=1 > > break > > Please try to avoid unnecessary indexes:: > > for regexp in skip_list: > if re.search(regexp, line): > skip = True > break > > And if you don't intent to count the `skip`\s a `True` seems to be more > readable. > Also try to avoid compiling the same regex repeatedly: compiled_skip_list = [re.compile(regexp) for regexp in skip_list] ... for regexp in compiled_skip_list: if regexp.search(line): skip = True break From lorenzo at excitement.com Sun Apr 8 19:02:25 2007 From: lorenzo at excitement.com (Lorenzo) Date: Sun, 08 Apr 2007 18:02:25 -0500 Subject: How do I get a slice of a string held in a tuple? References: <25ine4-rvt.ln1@Hedley.internal.thethurmans.com> <1176050876.835238.68560@d57g2000hsg.googlegroups.com> Message-ID: In article , Georg Brandl wrote: > Lorenzo schrieb: > > >> > How do I go about it? > >> > >> Do it correctly. Post your actual example that fails > >> and the related error message. Possibnly your indexes > >> were out of range. > >> > >> > I googled this and found a couple > >> > of references, but no solution. > >> > >> Well, there wouldn't be a solution to a non-existent > >> problem, would there? > >> > >> > TIA > > > > Here's the code: > > > > elapsedTime = mydata[1] > > index = elapsedTime.find("real") > > # the index will have a value 0f 110 > > totaltime = elapsedTime[index:] > > # instead of this returning a shortened html string, i only > > # get the left angle bracket '<' > > May it be that mydata[1] doesn't contain "real" at all? In that case, > find() returns -1, and the slice elapsedTime[-1:] always contains > at most one character. > > If you replace "find" by "index", you get a ValueError exception if > "real" was not found, if that helps you. > > Whenever one calls str.find(), one has to check the return value for -1. > > Georg Oops! I sent the wrong piece of code. The above is actually the work around which actually works. The bad code is this: index = mydata[0].find("real") elapsedTime = mydata[0][index:] My apologies, but this is what fails. -- "My Break-Dancing days are over, but there's always the Funky Chicken" --The Full Monty From malaclypse2 at gmail.com Wed Apr 4 13:59:32 2007 From: malaclypse2 at gmail.com (Jerry Hill) Date: Wed, 4 Apr 2007 13:59:32 -0400 Subject: try... except SyntaxError: unexpected EOF while parsing In-Reply-To: <1175708304.034078.139020@e65g2000hsc.googlegroups.com> References: <1175708304.034078.139020@e65g2000hsc.googlegroups.com> Message-ID: <16651e80704041059s7e74ccd9t439c86f596a6a1f1@mail.gmail.com> On 4 Apr 2007 10:38:24 -0700, oscartheduck wrote: > I have a small script for doing some ssh stuff for me. I could have > written it as shell script, but wanted to improve my python skills > some. > > RIght now, I'm not catching a syntax error as I'd like to. ... > port = input("Please enter a port to connect on. If you're unsure or > just want the default of port 2024 just hit enter -- ") > > try: ... > I'm under the impression that the except should catch the syntax error > and execute the "default" command, but hitting enter at the input > value doesn't lead to that. Any ideas what's going wrong? You didn't include the full exception that you're getting, but my guess is that the line trowing the error is the one calling input(). Move your try up before that line, and it should work as you expected. On a slightly different note, input() isn't really the right function to call here. input() evaluates python commands. Instead, use raw_input() which just returns a user-entered string. Something like this (untested): sshport = raw_input('Port: ') if sshport == "": sshport = "2024" try: sshport = int(sshport) except ValueError: print "Not a valid port" sys.exit() cmd = 'su root -c "/usr/sbin/sshd -p %s"' % port -- Jerry From http Sun Apr 8 02:40:37 2007 From: http (Paul Rubin) Date: 07 Apr 2007 23:40:37 -0700 Subject: iterator interface for Queue? Message-ID: <7x64875py2.fsf@ruckus.brouhaha.com> Is there any reason Queue shouldn't have an iterator interface? I.e. instead of while True: item = work_queue.get() if item is quit_sentinel: # put sentinel back so other readers can find it work_queue.put(quit_sentinel) break process(item) with accompanying hair on the other side to create and send a sentinel, you'd just say: for item in work_queue: process(item) You'd still need hair at the writing end to tell the readers when to finish, either by directly inserting a sentinel or with "work_queue.done()" or something like that. From attn.steven.kuo at gmail.com Thu Apr 12 20:25:10 2007 From: attn.steven.kuo at gmail.com (attn.steven.kuo at gmail.com) Date: 12 Apr 2007 17:25:10 -0700 Subject: "Cloning" file attributes and permissions In-Reply-To: <1176423552.199317.129400@n59g2000hsh.googlegroups.com> References: <1176394818.428367@jubilee.claranet.pt> <1176406707.711609.211110@q75g2000hsh.googlegroups.com> <1176419326.395692@jubilee.claranet.pt> <1176423552.199317.129400@n59g2000hsh.googlegroups.com> Message-ID: <1176423910.777066.45850@y80g2000hsf.googlegroups.com> On Apr 12, 5:19 pm, attn.steven.... at gmail.com wrote: > On Apr 12, 4:09 pm, Paulo da Silva wrote: > (snipped) > > > import subprocess > retcode = subprocess.call([ "/bin/cp", "-p", oldfile, newfile ]) > On my system, this preserves the access permissions and ownership. > > And if you modify the file after copying, you can alter > the access and modification times with posix.utime > to match that of the original. After poking around a bit I also discovered the shutil module. It looks like you can use shutil.copy2. More Pythonic, yes? -- Regards, Steven From cam.ac.uk at mh391.invalid Mon Apr 23 12:36:58 2007 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Mon, 23 Apr 2007 17:36:58 +0100 Subject: python style guide inconsistencies In-Reply-To: References: <5922mkF2i88dhU1@mid.individual.net> Message-ID: Darren Dale wrote: > Bjoern Schliessmann wrote: > >> Darren Dale wrote: >> >>> I was just searching for some guidance on how to name packages and >>> modules, and discovered some inconsistencies on the >>> www.python.org. http://www.python.org/doc/essays/styleguide.html >>> says "Module names can be either MixedCase or lowercase." That >>> page also refers to PEP 8 at >>> http://www.python.org/dev/peps/pep-0008/, which says "Modules >>> should have short, all-lowercase names. ... Python packages should >>> also have short, all-lowercase names ...". >>> >>> Which is most up to date? >> The priority is, IMHO, clear. The old style guide essay says, at the >> beginning: >> >> | This style guide has been converted to several PEPs (Python >> | Enhancement Proposals): PEP 8 for the main text, PEP 257 for >> | docstring conventions. See the PEP index. >> >> So PEP 8 is the most recent. > > Then perhaps http://www.python.org/doc/essays/styleguide.html should either > be updated to either agree with or simply link to PEPs 8 and 257. What is > the point of keeping old, out-of-date essays up on python.org? That > beginning comment does not indicate that the essay is any different from > the PEPs. http://wiki.python.org/moin/PythonWebsiteCreatingNewTickets -- Michael Hoffman From stefan.behnel-n05pAM at web.de Sat Apr 14 05:09:41 2007 From: stefan.behnel-n05pAM at web.de (Stefan Behnel) Date: Sat, 14 Apr 2007 11:09:41 +0200 Subject: Python and XML? In-Reply-To: References: Message-ID: <46209A55.9070102@web.de> Leonard J. Reder wrote: > What is the best way to process a Relax NG Schema and auto generate XML > Python parser/generator code? > Any suggestions? Not sure what you mean with "XML Python parser/generator code", but regarding RNG, you should definitely give lxml a try. It may already be what you were looking for anyway. http://codespeak.net/lxml Have fun, Stefan From KDawg44 at gmail.com Tue Apr 10 17:24:27 2007 From: KDawg44 at gmail.com (KDawg44) Date: 10 Apr 2007 14:24:27 -0700 Subject: Parsing log in SQL DB to change IPs to hostnames In-Reply-To: References: <1176219463.407804.315560@y80g2000hsf.googlegroups.com> <1176221494.813800.78580@y80g2000hsf.googlegroups.com> <1176231258.626137.228220@d57g2000hsg.googlegroups.com> Message-ID: <1176240266.979625.143520@n33g2000cwc.googlegroups.com> On Apr 10, 2:47 pm, Steve Holden wrote: > KDawg44 wrote: > > On Apr 10, 11:11 am, "Kushal Kumaran" > > wrote: > >> On Apr 10, 8:37 pm, "KDawg44" wrote: > > >>> Hi, > >>> I am brand new to Python. In learning anything, I find it useful to > >>> actually try to write a useful program to try to tackle an actual > >>> problem. > >>> I have a syslog server and I would like to parse the syslog messages > >>> and try to change any ips to resolved hostnames. Unfortunately, I am > >>> not getting any matches on my regular expression. > >>> A message will look something like this: > >>> Apr 10 2007 00:30:58 DEVICE : %DEVICEINFO: 1.1.1.1 Accessed URL > >>> 10.10.10.10:/folder/folder/page.html > >>> I would like to change the message to have the hostnames, or even > >>> better actually, have it appear as hostname-ip address. So a changed > >>> message would look like: > >>> Apr 10 2007 00:30:58 DEVICE : %DEVICEINFO: pcname-1.1.1.1 Accessed > >>> URLwww.asite.com-10.10.10.10:/folder/folder/page.html > >>> or some equivalent. > >>> Here is what i have so far. Please be kind as it is my first python > >>> program.... :) > >>> #! /usr/bin/python > >>> import socket > >>> import re > >>> import string > >>> import MySQLdb > >>> ipRegExC = r"\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}" > >>> ipRegEx = re.compile(ipRegExC) > >>> try: > >>> conn = MySQLdb.connect(host="REMOVED", user="REMOVED", > >>> passwd="REMOVED", db="REMOVED") > >>> except MySQLdb.Error, e: > >>> print "Error connecting to the database: %d - %s " % > >>> (e.args[0], e.args[1]) > >>> sys.exit(1) > >>> cursor = conn.cursor() > >>> cursor.execute("SELECT msg, seq FROM REMOVED WHERE seq = 507702") > >>> # one specific message so that it doesn't parse the whole DB during > >>> testing... > >>> while(1): > >>> row = cursor.fetchone() > >>> if row == None: > >>> break > >>> if ipRegEx.match(row[0]): > >>> .... > >>> > >> See the documentation of the re module for the difference between > >> matching and searching. > > >> -- > >> Kushal > > > Thank you very much. I think I have it figured out, except for an > > error on the SQL statement: > > > [----- BEGIN ERROR ---] > > Traceback (most recent call last): > > File "changeLogs.py", line 47, in ? > > cursor.execute("""UPDATE logs SET msg = %s WHERE seq = %i""", > > (newMsg,seqNum)) > > File "/usr/lib/python2.4/site-packages/MySQLdb/cursors.py", line > > 148, in execute > > query = query % db.literal(args) > > TypeError: int argument required > > [----- END ERROR ---] > > > Here is my code > > > [----- BEGIN CODE ---] > > #! /usr/bin/python > > > import socket > > import sys > > import re > > import string > > import MySQLdb > > > def resolveHost(ipAdds): > > ipDict = {} > > for ips in ipAdds: > > try: > > ipDict[ips] = socket.gethostbyaddr(ips)[0] > > except: > > ipDict[ips] = "Cannot resolve" > > return ipDict > > > ipRegExC = r"\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}" > > ipRegEx = re.compile(ipRegExC) > > > try: > > conn = MySQLdb.connect(host="REMOVED", user="REMOVED", > > passwd="REMOVED", db="REMOVED") > > > except MySQLdb.Error, e: > > print "Error connecting to the database: %d - %s " % > > (e.args[0], e.args[1]) > > sys.exit(1) > > > cursor = conn.cursor() > > cursor.execute("SELECT msg, seq FROM `logs` WHERE seq = 507702") > > while(1): > > row = cursor.fetchone() > > ipAddresses = [] > > resolvedDict = {} > > if row == None: > > break > > if ipRegEx.search(row[0]): > > seqNum = row[1] > > ipAddresses = ipRegEx.findall(row[0]) > > resolvedDict = resolveHost(ipAddresses) > > newMsg = row[0] > > for ip in resolvedDict.keys(): > > newMsg = newMsg.replace(ip,ip + "-" + > > resolvedDict[ip]) > > cursor.execute("""UPDATE REMOVED SET msg = %s WHERE > > seq = %i""", (newMsg,seqNum)) > > > [----- END CODE ---] > > > Thanks again! > > Since the source line that the traceback complains about doesn't appear > in the quoted code it's difficult to know what's going wrong. I'd hazard > a guess that you have a string in seqNum instead of an integer message > number (in which case try using int(seqNum) instead). > > Otherwise show us the real code, not the one after you modified it to > try and make it work, amd we might be able to help more ;-) > > 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 hmmm... I tried seqNum = int(seqNum[i]) to make seqNum an integer. That is the real code with the connection to the DB hidden and the name of the table which I didnt remove on the first query anyway so it was pointless. This is the whole code. THanks. From s_broscious at comcast.net Fri Apr 6 12:45:42 2007 From: s_broscious at comcast.net (Scott) Date: Fri, 6 Apr 2007 12:45:42 -0400 Subject: Newbie Question about sequence multiplication References: <6cOdnVFCLMXxuYnbnZ2dnUVZ_rCsnZ2d@comcast.com> <1175726885.373889.23850@y80g2000hsf.googlegroups.com> <1175739226.176472.96280@p77g2000hsh.googlegroups.com> Message-ID: Thanks to everyone that responded....I would never have figured that out. 7stud, Your suggestion is being considered lol, as there are a lot more bits of code in that book that I can't get running correctly. Any other books you'd, or anyone for that matter, would recommend as required reading? Free would be very very (read very) good, as you've already said the one I have isn't very viable and it cost me $50. Basically, what I'm saying is that if I go and spend another $50+ my wife is going to make it very hard to learn Python; after all, how much can I learn with a size 5 down my throat? lol Now when suggesting books, keep in mind that, that while I'm new to Python (and programming in general) I'm able to grasp difficult concepts as long as I have enough detail as to why it is the way it is. For instance I'm, by experience and nature, a computer technician and communications specialist. I've studied, everything from childrens walkie talkie to deep space satalittes back to how computers talk (which is why I'm here now trying to learn the language of computers). And all that just because I have a unquenchable desire to know. SO, with that all said, the more details the better. If you have a book with 4 chapters on functions......I want to read it. Any help would be greatly appreciated. As I've said, this is something that I feel I have to know. "7stud" wrote in message news:1175739226.176472.96280 at p77g2000hsh.googlegroups.com... > On Apr 4, 4:48 pm, "John Machin" > I suggest you get another book. I am currently reading that book, and > unless you are an experienced programmer that can detect all the > mistakes, and you have another book like "Python in a Nutshell" to > fill in all the gaps, I don't think you can learn python from that > book. > > I recently looked at Learning Python in the bookstore, and it seems a > lot better. Unfortunately, it doesn't reflect the major changes in > python over the last couple of years, but I would still recommend it > over Beginning Python: From Novice to Professional. > > > From kyosohma at gmail.com Fri Apr 27 16:23:57 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: 27 Apr 2007 13:23:57 -0700 Subject: wxPython (Flex)GridSizer Failing In-Reply-To: <1177699515.090165.232310@n35g2000prd.googlegroups.com> References: <1177699515.090165.232310@n35g2000prd.googlegroups.com> Message-ID: <1177705437.776630.159280@t39g2000prd.googlegroups.com> On Apr 27, 1:45 pm, "bcwh... at pobox.com" wrote: > Python v2.5 > wxPython v2.8.3.0 > > I've got an app that has a wx.Panel managed by a FlexGridSizer. There > are 5 columns and 6 rows, all with StaticText widgets and all of > similar size. Everything works fine until I Clear and re-fill the > sizer a few times, then it puts all of the text in the upper-left > corner. I can clear/refill the grid to my hearts contents but it > doesn't fix itself. However, if I resize the main window the next > clear/refill will display correctly and _sometimes_ the current fill > will change and display correctly. > > I have an identical panel directly below it (vertical box-sizer) with > the same number of columns but only 1 row and it never has a problem. > Both panels are identical because it's the same custom derived class > creating them and both are added to the box-sizer in an identical way. > > I tried changing to an (un-flexible) GridSizer and got a different > display but the same problem. If anything, it occurs sooner. > > Any ideas on what is happening? > > -- Brian It sounds kind of like your app isn't redrawing correctly or your not calling the sizer's Fit() method after re-filling it. You might try that. Also, I highly recommend posting wxPython questions to their users group. They are usually quite helpful and knowledgeable: http://www.wxpython.org/maillist.php Mike From larry.bates at websafe.com Thu Apr 19 12:39:50 2007 From: larry.bates at websafe.com (Larry Bates) Date: Thu, 19 Apr 2007 11:39:50 -0500 Subject: Python COM iterator In-Reply-To: References: Message-ID: <46279B56.4020901@websafe.com> Carsten Haese wrote: >> [...] >>> On Tue, 2007-04-17 at 16:54 -0500, Larry Bates wrote: >>>> Does anyone know if there is a way to make a Python COM object >>>> act like a proper iterator in VB/Delphi? >> [...] > > After more googling, staring at win32com's code, and a fair bit of trial > and error, I've come up with the following working example: > > # server.py > import pythoncom > > class HelloWorld: > _reg_clsid_ = "{CAB8BED1-9174-4AAD-ABC5-F377951CB71B}" > _reg_desc_ = "Python Test COM Server" > _reg_progid_ = "Python.TestServer" > _public_methods_ = ['Next'] > _com_interfaces_ = [pythoncom.IID_IEnumVARIANT] > > def __init__(self): > self.numbers=[1,2,3,4,5,6,7,8] > > def Next(self, count): > assert count==1 > try: > return (self.numbers.pop(0),) > except IndexError: > return () > > def _NewEnum(self): > import win32com.server.util > return win32com.server.util.wrap(self) > > if __name__=='__main__': > import win32com.server.register > win32com.server.register.UseCommandLine(HelloWorld) > > # client.py > import win32com.client > comobj = win32com.client.Dispatch("Python.TestServer") > for x in comobj: > print x > > This works for me on Python 2.5 and pywin32 Build 210, but I don't know > whether clients in VB or Delphi are able to use this iterator. > > -Carsten > > I tested in VB and by golly it works! What is odd is that this looks NOTHING like what we got from the docs earlier. No GetEnumerator method, no MoveNext method. I'm glad it works, but I'm a little puzzled as to why it works. Thanks loads. -Larry From paddy3118 at googlemail.com Mon Apr 2 02:33:33 2007 From: paddy3118 at googlemail.com (Paddy) Date: 1 Apr 2007 23:33:33 -0700 Subject: reverse engineering Excel spreadsheet In-Reply-To: <460fd6d0.0@entanet> References: <460fd6d0.0@entanet> Message-ID: <1175495613.264422.171930@y80g2000hsf.googlegroups.com> On Apr 1, 4:59 pm, Duncan Smith wrote: > Hello, > I am currently implementing (mainly in Python) 'models' that come > to me as Excel spreadsheets, with little additional information. I am > expected to use these models in a web application. Some contain many > worksheets and various macros. > > What I'd like to do is extract the data and business logic so that I can > figure out exactly what these models actually do and code it up. An > obvious (I think) idea is to generate an acyclic graph of the cell > dependencies so that I can identify which cells contain only data (no > parents) and those that depend on other cells. If I could also extract > the relationships (functions), then I could feasibly produce something > in pure Python that would mirror the functionality of the original > spreadsheet (using e.g. Matplotlib for plots and more reliable RNGs / > statistical functions). > > The final application will be running on a Linux server, but I can use a > Windows box (i.e. win32all) for processing the spreadsheets (hopefully > not manually). Any advice on the feasibility of this, and how I might > achieve it would be appreciated. > > I assume there are plenty of people who have a better knowledge of e.g. > COM than I do. I suppose an alternative would be to convert to Open > Office and use PyUNO, but I have no experience with PyUNO and am not > sure how much more reliable the statistical functions of Open Office > are. At the end of the day, the business logic will not generally be > complex, it's extracting it from the spreadsheet that's awkward. Any > advice appreciated. TIA. Cheers. > > Duncan Hi Duncan, OOffice can save sheets in Sylk format which gives you a simple textual format for cells, including the equations. Can't think of any easier way with the macros other than hard slog! P.S. It is well to remember that the UK Tax department have a very low opinion of the quality of spreadsheets so if you find oddities remember to query them. - Paddy. From tjreedy at udel.edu Sun Apr 22 17:14:17 2007 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 22 Apr 2007 17:14:17 -0400 Subject: function minimization References: <1177250114.342886.160520@o5g2000hsb.googlegroups.com> Message-ID: wrote in message news:1177250114.342886.160520 at o5g2000hsb.googlegroups.com... | Is anyone aware of python library that does function minimization a la | Minuit (http://wwwasdoc.web.cern.ch/wwwasdoc/minuit/) used by CERN? Have you checked the minimization function in scipy? From TimeHorse at gmail.com Thu Apr 5 15:51:20 2007 From: TimeHorse at gmail.com (TimeHorse at gmail.com) Date: 5 Apr 2007 12:51:20 -0700 Subject: RFC: Assignment as expression (pre-PEP) Message-ID: <1175802680.021987.39220@p77g2000hsh.googlegroups.com> I would like to gauge interest in the following proposal: Problem: Assignment statements cannot be used as expressions. Performing a list of mutually exclusive checks that require data processing can cause excessive tabification. For example, consider the following python snipet... temp = my_re1.match(exp) if temp: # do something with temp else: temp = my_re2.match(exp) if temp: # do something with temp else: temp = my_re3.match(exp) if temp: # do something with temp else: temp = my_re4.match(exp) # etc. Even with 2-space tabification, after about 20 matches, the indentation will take up half an 80-column terminal screen. Details: Python distinguishes between an assignment statement and an equality expression. This is to force disambiguation of assignment and comparison so that a statement like: if x = 3: Will raise an expression rather than allowing the programmer to accidentally overwrite x. Likewise, x == 3 Will either return True, False or raise a NameError exception, which can alert the author of any potential coding mistakes since if x = 3 (assignment) was meant, assignment being a statement returns nothing (though it may raise an exception depending on the underlying assignment function called). Because this forced disambiguation is a guiding virtue of the python language, it would NOT be wise to change these semantics of the language. Proposal: Add a new assignment-expression operator to disambiguate it completely from existing operators. Although any number of glyph could be used for such a new operator, I here propose using pascal/gnu make-like assignment. Specifically, let: x = 3 Be a statement that returns nothing; let: x == 3 Be an expression that, when x is a valid, in-scope name, returns True or False; let: x := 3 Be an expression that first assigned the value (3) to x, then returns x. Thus... if x = 3: # Rais exception pass if x == 3: # Execute IFF x has a value equivalent to 3 pass if x := 3: # Executes based on value of x after assignment; # since x will be 3 and non-zero and thus represents true, always executed pass Additional: Since python allows in-place operator assignment, (e.g. +=, *=, etc.), allow for these forms again by prefixing each diglyph with a colon (:), forming a triglyph. E.g. if x :+= 3: # Executes IFF, after adding 3 to x, x represents a non-zero number. pass Also note, that although the colon operator is used to denote the beginning of a programme block, it should be easily distinguished from the usage of : to denote a diglyph or triglyph assignment expression as well as the trinary conditional expression. This is because firstly, the statement(s) following a colon (:) in existing python should never begin with an assignment operator. I.e., if x: = y is currently not valid python. Any attempt at interpreting the meaning of such an expression in the current implementation of python is likely to fail. Secondly, the diglyph and triglyph expressions do not contain spaces, further disambiguating them from existing python. Alternative proposals for dyglyph and triglyph representations for assignment expressions are welcome. Implementation details: When the python interpreter parser encounters a diglyph or triglyph beginning with a colon (:) and ending with an equals sign (=), perform the assignment specified by glyph[1:] and then return the value of the variable(s) on the left-hand side of the expression. The assignment function called would be based on standard python lookup rules for the corresponding glyph[1:] operation (the glyph without the leading colon). Opposition: Adding any new operator to python could be considered code bloat. Using a colon in this way could still be ambiguous. Adding the ability to read triglyph operators in the python interpreter parser would require too big a code revision. Usage is too obscure. Using an assignment expression would lead to multiple conceptual instructions for a single python statement (e.g. first an assignment, then an if based on the assignment would mean two operations for a single if statement.) Comments: [Please comment] Jeffrey. From steve at holdenweb.com Fri Apr 13 08:55:36 2007 From: steve at holdenweb.com (Steve Holden) Date: Fri, 13 Apr 2007 08:55:36 -0400 Subject: VB6 To Python In-Reply-To: References: <2FAA57395C1F914DB27CAA4C376058F202434C96@S0-OTT-X2.nrn.nrcan.gc.ca> Message-ID: Michael Bentley wrote: > > On Apr 12, 2007, at 1:11 PM, Sampson, David wrote: > >> Any experience or insight would be great. > > It has been my experience that when migrating to a dissimilar system, > avoiding the rewrite is a mistake. And futile. > This is good advice. Since your original project had such a clean separation between GUI code and the rest of the logic, however, you might want to investigate the methods discussed in Robinson and Hammond's "Programming Win32 in Python", where they explain how Python logic can make use of COM interfaces to interact with VB (or other COM) GUIs. 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 p.edelman at gmail.com Thu Apr 26 12:10:01 2007 From: p.edelman at gmail.com (Pieter Edelman) Date: 26 Apr 2007 09:10:01 -0700 Subject: Access to raw command line? In-Reply-To: References: <1177571070.229968.155710@t39g2000prd.googlegroups.com> Message-ID: <1177603801.337600.5150@r30g2000prh.googlegroups.com> All your posts pretty much confirmed my own thoughts on this subject. Every option requires a specific action from the user, and as Bjoern points out, it would differ from what everybody is used to. I think there's no trivial and reliable way to do this, so I can better leave it the way it is (at least for now). Everybody thanks for your insights, Pieter From aboudouvas at panafonet.gr Wed Apr 11 17:17:51 2007 From: aboudouvas at panafonet.gr (king kikapu) Date: 11 Apr 2007 14:17:51 -0700 Subject: About Trolltech QT OpenSource license. In-Reply-To: References: <1176233376.712861.67160@o5g2000hsb.googlegroups.com> <1176237050.409742.8760@30g2000cwc.googlegroups.com> <1176285062.178372.15090@d57g2000hsg.googlegroups.com> Message-ID: <1176326271.183571.286710@l77g2000hsb.googlegroups.com> ?/? Robert Kern ??????: > It's a bit more complicated than that. There are good resources for > understanding the implications of the GPL on the FSF's site which other people > have pointed out. >From what i can understand, you can sell your product and you have to give the source. Also you must state clearly somewhere in the software that this is under GPL. Are there other complications that comes to the party ? (i really like Qt but if i have chances to mess with laywers, i show stick to wxPython and PythonCard...) From kyosohma at gmail.com Thu Apr 5 10:06:48 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: 5 Apr 2007 07:06:48 -0700 Subject: Newbie - Boa Constructor, wxPython problem running Boa In-Reply-To: <1175779931.504252.75840@b75g2000hsg.googlegroups.com> References: <1175779931.504252.75840@b75g2000hsg.googlegroups.com> Message-ID: <1175782008.538269.169490@b75g2000hsg.googlegroups.com> On Apr 5, 8:32 am, "Anbeyon" wrote: > Hi all > > I am a Newbie to the world of Python, wxPython and Boa. Please > forgive me if there is a really obvious answer to this one. > > I am trying to get Python, wxPython and Boa all to install on my > Windows XP machine. > > I have both Python and wxPython running. However, when I launch Boa I > get an error message; > > An 'Error On Startup' dialog/message box is displayed that says; > 'module' object has no attribute 'NotebookSizer' > (Output on the console window is at the end of this message incase > that helps.....) > > I click OK and everything closes. > > I have the following setup; > > Python2.5 > --------------- > installed using python-2.5.msi fromhttp://www.python.org/download/releases/2.5/ > > wxPython for Python2.5 > ------------------------------------ > installed usinghttp://prdownloads.sourceforge.net/wxpython/wxPython2.8-win32-unicode... > > Boa Constructor > ------------------------ > installed using boa-constructor-0.4.4.win32.exe > > Does anyone have any ideas, thoughts as to what the problem might be ? > > The only thing I'm wondering is that instead of installing on my c: > drive in installed on my d: drive ???? > > Thanks in advance > > Anbeyon > > >>>>>>> BELOW IS THE OUTPUT IN THE CONSOLE WINDOW WHEN I LAUNCH BOA <<<<<<<<<< > > Starting Boa Constructor v0.4.4 > importing wxPython > reading user preferences > running main... > importing Models.Controllers > importing Models.EditorModels > importing Views > importing Views.SourceViews > D:\Python25\Lib\site-packages\boa-constructor\Views\STCStyleEditor.py: > 59: Deprec > ationWarning: The wxPython compatibility package is no longer > automatically gene > rated or actively maintained. Please switch to the wx package as soon > as possib > le. > import wxPython.stc # needed names from 2.4 for config files > importing Explorers.ExplorerNodes > importing Companions > importing PropertyEditors > importing Companions.FrameCompanions > importing Companions.WizardCompanions > importing Companions.ContainerCompanions > importing Companions.SizerCompanions I haven't had much luck with Boa Constructor either. Here's a forum post on the same issue that might help you though: http://www.nabble.com/HOW-TO-START-BOAConstructor--t2545395.html You may want to try wxGlade, VisualWx, PythonCard, Dabo or Stani's Python Editor (SPE). Stani's, wxGlade, PythonCard and Dabo are mentioned often on the wxPython user's group. Mike From thorsten at thorstenkampe.de Mon Apr 2 14:06:49 2007 From: thorsten at thorstenkampe.de (Thorsten Kampe) Date: Mon, 2 Apr 2007 19:06:49 +0100 Subject: I18n issue with optik References: Message-ID: * Thorsten Kampe (Mon, 2 Apr 2007 16:05:25 +0100) > * Steven Bethard (Sun, 01 Apr 2007 10:21:40 -0600) > > Thorsten Kampe wrote: > > I'm not very experienced with internationalization, but if you change:: > > > > gettext.install('test') > > > > to:: > > > > gettext.install('test', unicode=True) > > > > what happens? > > Actually, this is the solution. > > But there's one more problem: the solution only works when the > Terminal encoding is not US-ASCII. Unfortunately (almost) all > terminals I tried are set to US-ASCII (rxvt under Cygwin, Console[1] > running bash, Poderosa[2] running bash). Only the Windows Console is > CP852 and this works. > > I got the tip to set a different encoding by > sys.stdout = codecs.EncodedFile(sys.stdout, 'utf-8') > > but unfortunately this does not change the encoding of any Terminal. > So my question is: how can I set a different encoding to sys.stdout > (or why can I set it without any error but nothing changes?) I solved it (finally after two days with the help of a lot of people): You have to set this... sys.stdout = codecs.EncodedFile(sys.stdout, 'iso-8859-15') sys.stdout.encoding = 'iso-8859-15' ...both of these and exactly in this order and not vice versa. It doesn't have to be 'iso-8859-15', Windows-1252 is fine, too (but UTF-8 doesn't work). Now we have a new problem: the native Windows consoles don't print the right characters. So you wrap this in a query: if sys.platform in ['cygwin', 'linux2']: sys.stdout = codecs.EncodedFile(sys.stdout, 'iso-8859-15') sys.stdout.encoding = 'iso-8859-15' This would be a problem if there's more than one translation (for instance one with polish characters that aren't contained in iso-8859- 15). One could work around this with if sys.platform in ['cygwin', 'linux2']: sys.stdout = codecs.EncodedFile(sys.stdout, locale.getpreferredencoding()) sys.stdout.encoding = locale.getpreferredencoding() Funny (more or less): two days work to print "U" and "A" with double points above. Thanks to all who have helped to clear my confusion and to bring me into the right direction for the solution. Thorsten From steve at holdenweb.com Mon Apr 23 20:55:33 2007 From: steve at holdenweb.com (Steve Holden) Date: Mon, 23 Apr 2007 20:55:33 -0400 Subject: Beginner: Formatting text output (PyQt4) Solved In-Reply-To: <7mcXh.4365$ns5.1139@newssvr17.news.prodigy.net> References: <7mcXh.4365$ns5.1139@newssvr17.news.prodigy.net> Message-ID: Glen wrote: > Sorry I've been away a while, figuring stuff out. It absolutely wasn't a > monospaced font that I was using. I'm still getting used to Qt Designer > and didn't see the expandable item under 'font' where I could easily > select another font. I felt pretty stupid when I saw it. My program > output the contents of my data file perfectly once I selected a fixed > pitch font. > > Thanks a lot for the replies. I didn't know how long to wait, since I'm > new around here, and I kind of gave up. I got some good info from you > guys anyway. Thanks. You'll probably be hearing from me pretty > regularly, since I'm in the process of learning Python and PyQt > simultaneously. > Welcome to c.l.py! regards Steve -- Steve Holden +1 571 484 6266 +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 mmanns at gmx.net Sun Apr 15 14:43:05 2007 From: mmanns at gmx.net (Martin Manns) Date: Sun, 15 Apr 2007 14:43:05 -0400 Subject: Method calls and stack consumption References: Message-ID: On Sun, 15 Apr 2007 07:27:25 +0200 Peter Otten <__peter__ at web.de> wrote: > Martin Manns wrote: > > > Calling methods of other object instances seems quite expensive on > > the stack (see example below). Is there a better way of traversing > > through methods of instances that are connected in a cyclic graph? > > (The real program's graph contains multiple successors in lists.) > a = a.a > while True: > a = a() > > That's how you can do it if your real program is similar enough to the > example... Thanks for pointing out the oversimplified nature of the original example.I hope that the following one clarifies the problem. (I do not know, what has to be stored on the stack, but it should not be that much, because all recursion calls originate from inside the return statement.) from random import randint,seed import sys seed() sys.setrecursionlimit(1000000) class Node(object): def __init__(self): self.state = abs(randint(1,1000)) def GetDepState(self): return self.state + max(s.GetDepState() for s in S[self]) class ConditionalBreakNode(Node): def GetDepState(self): if randint(1,5) > 1: return Node.GetDepState(self) else: return self.state S = {} nodes = [Node()] def AppendNode(curr_node, depth=1): global nodes r = randint(1,30) if r >= depth: for i in xrange(randint(1,3)): newnode = Node() nodes += [newnode] try: S[curr_node] += [newnode] except: S[curr_node] = [newnode] AppendNode(newnode, depth+1) else: newnode = ConditionalBreakNode() nodes += [newnode] try: S[curr_node] += [newnode] except: S[curr_node] = [newnode] S[newnode] = [nodes[0]] AppendNode(nodes[0]) print len(nodes) print nodes[0].GetDepState() From bhochstetler at gmail.com Tue Apr 3 16:22:31 2007 From: bhochstetler at gmail.com (bhochstetler at gmail.com) Date: 3 Apr 2007 13:22:31 -0700 Subject: troubles building python 2.5 on Windows XP x64 Windows Server 2003 sp1 Platform SDK In-Reply-To: References: <1175622506.730227.37060@p77g2000hsh.googlegroups.com> <1175624672.570370.248710@y80g2000hsf.googlegroups.com> Message-ID: <1175631751.721474.236190@n59g2000hsh.googlegroups.com> On Apr 3, 4:16 pm, Steven Bethard wrote: > bhochstet... at gmail.com wrote: > > On Apr 3, 2:04 pm, Steven Bethard wrote: > >> bhochstet... at gmail.com wrote: > >>> I am needing to build python 2.5 on Windows XP x64 Windows Server 2003 > >>> sp1 Platform SDK and am not finding anything documented on the process > >>> to use. Has anyone had any success with this? If so has anyone > >>> documented it? The documentation that resides in pcbuild/readme.txt is > >>> not helpful at all. > > >> What have you tried already? From the readme: > > >> All you need to do is open the workspace "pcbuild.sln" in MSVC++, > >> select the Debug or Release setting (using "Solution Configuration" > >> from the "Standard" toolbar"), and build the projects. > > > There is no IDE available with the 64 bit compiler on Windows Server > > 2003 Platform SDK, so that is not an option. > > Ahh, I see. Did you try this:: > > Building for Itanium > -------------------- > > The project files support a ReleaseItanium configuration which > creates Win64/Itanium binaries. For this to work, you need to > install the Platform SDK, in particular the 64-bit support. This > includes an Itanium compiler (future releases of the SDK likely > include an AMD64 compiler as well). > In addition, you need the Visual Studio plugin for external C > compilers, fromhttp://sf.net/projects/vsextcomp. The plugin will > wrap cl.exe, to locate the proper target compiler, and convert > compiler options accordingly. The project files require atleast > version 0.9. > > I can't tell whether vsextcomp handles your compiler or not though... > > STeVe This doc has not been updated since the 64 bit compilers came out officially. It doesn't make a whole lot of sense of what steps you should follow to build python. I saw a link on the comp.lang.python that had the steps, but that link doesn't go anywhere now. I had to jump through some hoops to get it to build on VC 2005 64 bit, but that at least had an IDE to use. From paddy3118 at googlemail.com Sun Apr 15 16:27:53 2007 From: paddy3118 at googlemail.com (Paddy) Date: 15 Apr 2007 13:27:53 -0700 Subject: Python Feature Request: Allow changing base of member indices to 1 In-Reply-To: References: <1176546465.632410.52630@w1g2000hsg.googlegroups.com> <1176579205.948684.171640@q75g2000hsh.googlegroups.com> Message-ID: <1176668873.556584.237410@p77g2000hsh.googlegroups.com> On Apr 15, 6:42 pm, "Javier Bezos" wrote: > > Here is a document giving good reasons for indexing to start at > > zero, as in Python. > >http://www.cs.utexas.edu/users/EWD/transcriptions/EWD08xx/EWD831.html > > The author has done a bit: > >http://en.wikipedia.org/wiki/Dijkstra > > Dijkstra's argument is obsolete, as it is based on > how array length was computed many years ago -- if > we have an array a = b..e, then the lenght of a > is e-b (half open range). Good at low level > programming. > > But a quarter of a century after we know concepts > are much better than low level programming and > explicit computations -- if we have an array > a = b..e, then the length of a should be a.length() > (or a.length(b,e)), and it is independent of > arbitrary ranges, index bases, or even steps > (eg, {-4, -2, 0, 2, 4}). > > Of course, the index base should be always the > same _by default_ (individual lists could require > another index base, and that's fine). Otherwise > it would a mess, as you said. > > Javier > -----------------------------http://www.texytipografia.com Hi Javier, You seem to have missed out array *indexing* in your argument, or is array indexing obsolete? - Paddy. From phil at riverbankcomputing.co.uk Mon Apr 16 05:52:21 2007 From: phil at riverbankcomputing.co.uk (Phil Thompson) Date: Mon, 16 Apr 2007 10:52:21 +0100 Subject: ANN: PyQt v4.2 (Python Bindings for Qt) Message-ID: <200704161052.22028.phil@riverbankcomputing.co.uk> Riverbank Computing is pleased to announce the release of PyQt v4.2 available from http://www.riverbankcomputing.co.uk/pyqt/. The highlights of this release include: - The ability to write widget plugins for Qt Designer in Python. - Integration of the Python command shell and the Qt event loop. This allows developers to call Qt functions dynamically on a running application. - Integration of the Qt event loop with the standard Python DBus bindings available from www.freedesktop.org. PyQt is a comprehensive set of Qt bindings for the Python programming language and supports the same platforms as Qt (Windows, Linux and MacOS/X). Like Qt, PyQt is available under the GPL and a commercial license. See http://www.riverbankcomputing.com/Docs/PyQt4/html/classes.html for the class documentation. PyQt v4 supports Qt v4 (http://www.trolltech.com/products/qt/index.html). PyQt v3 is still available to support earlier versions of Qt. PyQt v4 is implemented as a set of 10 extension modules containing approximately 400 classes and 6,000 functions and methods. QtCore The non-GUI infrastructure including event loops, threads, i18n, Unicode, signals and slots, user and application settings. QtGui A rich collection of GUI widgets. QtNetwork A set of classes to support TCP and UDP socket programming and higher level protocols (eg. HTTP). QtOpenGL A set of classes that allows PyOpenGL to render onto Qt widgets. QtSql A set of classes that implement SQL data models and interfaces to industry standard databases. Includes an implementation of SQLite. QtSvg A set of classes to render SVG files onto Qt widgets. QtTest A set of classes to automate unit testing of PyQt applications and GUIs. QtXML A set of classes that implement DOM and SAX parsers. QtAssistant A set of classes that enables the Qt Assistant online help browser to be integrated with an application. QAxContainer A set of classes for Windows that allows the integration of ActiveX controls and COM objects. A Windows installer is provided for the GPL version of PyQt to be used with the GPL version of Qt v4 (http://www.trolltech.com/download/qt/windows.html). It enabes a complete PyQt environment to be installed on Windows without the need for a C++ compiler. PyQt includes the pyuic utility which generates Python code to implement user interfaces created with Qt Designer in the same way that the uic utility generates C++ code. It is also able to load Designer XML files dynamically. From bj_666 at gmx.net Fri Apr 27 02:50:18 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Fri, 27 Apr 2007 08:50:18 +0200 Subject: My python annoyances so far References: <1177541453.471959.120830@c18g2000prb.googlegroups.com> <59bf34F2k27v5U1@mid.individual.net> <1177603623.774892.230390@t38g2000prd.googlegroups.com> Message-ID: In , Steven Howe wrote: > And before someone get's all technical, I know everything in Python is > an 'object' even None, which implies class, or is it the other way around? Objects don't imply classes. There are object oriented languages without classes like the Io language. Everything there is an object and the base object has a `clone()` method to make a copy. So you make copies of objects and modify them to tweak them into the way you want them. Ciao, Marc 'BlackJack' Rintsch From cfbolz at googlemail.com Thu Apr 26 19:59:04 2007 From: cfbolz at googlemail.com (cfbolz at googlemail.com) Date: 26 Apr 2007 16:59:04 -0700 Subject: Python un-plugging the Interpreter In-Reply-To: References: <1hwu415.1yyvbo61efn1uqN%aleax@mac.com> <1hx2dgy.zizz7ir95hlgN%aleax@mac.com> Message-ID: <1177631944.708205.285490@o40g2000prh.googlegroups.com> On 25 Apr., 16:09, Steve Holden wrote: > > Python as a language is in good shape. But the CPython > > implementation is holding back progress. What we need are better > > and faster implementations of the language we've got. > > Hear, hear! > > > PyPy, ShedSkin, and Jython all were steps in the right > > direction, but none had enough momentum to make it. > > Jython hasn't had a release since 2002, ShedSkin is basically > > one guy, and the EU pulled the plug onPyPy. > > Hey there, loose talk costs lives, you know. That is a complete > mischaracterization of the true position. Indeed! > Progress on Jython may not have been stellar, but it has occurred and is > ongoing. Yes, Shedskin is "one guy", but so was Psyco and that was (and > remains) a useful tool. > > As far as I am aware the PyPy project has come to the end of its initial > EU funding, and they chose to focus on producing deliverables close to > the end of the project phase rather that divert effort into securing > ongoing funding. So nobody has "pulled the plug", and I believe there is > every possibility of a further round of funded research and development > in the future. Certainly the results to date would justify that action > on the part of the EU. I don't know if and when the request for further > funding will be submitted. Indeed here too. "pulling the plug" sounds like an extremely unfair description. There never was the plan to get funding longer than what we got so far (at least not with additional action from our side). And yes, there is the possibility of getting additional funding in the future, although we are not concretely thinking about it yet. Apart from that, work on PyPy is definitely continuing, at least after the much needed break most PyPy-developers are currently taking to recover from the stress of the EU project (yes, funding has its downsides too). Cheers, Carl Friedrich From dborne at gmail.com Mon Apr 30 09:39:58 2007 From: dborne at gmail.com (Dave Borne) Date: Mon, 30 Apr 2007 08:39:58 -0500 Subject: Reading From an Excel Sheet In-Reply-To: <1177921521.652523.35850@e65g2000hsc.googlegroups.com> References: <1177921521.652523.35850@e65g2000hsc.googlegroups.com> Message-ID: <6e42ec490704300639w203a4a9do5838139e3fd16d77@mail.gmail.com> > I want to write a python script which reads in data from the > excel sheet .Can any one help out in this ...any help will be > appreciated. Try here: http://cheeseshop.python.org/pypi/xlrd/0.5.2 From uriel.katz at gmail.com Fri Apr 27 21:09:03 2007 From: uriel.katz at gmail.com (urielka) Date: 27 Apr 2007 18:09:03 -0700 Subject: Interop between C# and Python Message-ID: <1177722543.098518.192840@h2g2000hsg.googlegroups.com> i need a easy way to write a Python Service(be it SOAP or JSONRPC or whatever) but i need to easily access it from C#,i created a web service in ZSI(which is really easy) like this: from ZSI import dispatch def hello(): return "hello" dispatch.AsServer(port=8080) simple and easy but how i access it from C#,where is the wsdl for the service? is there any easier way to get this kind of interop?(not using a custom protocol over sockets) thx, Uriel Katz From mailmaverick666 at gmail.com Thu Apr 12 04:12:02 2007 From: mailmaverick666 at gmail.com (rishi pathak) Date: Thu, 12 Apr 2007 13:42:02 +0530 Subject: Newbie help with array handling In-Reply-To: <1176364734.439383.252930@o5g2000hsb.googlegroups.com> References: <1176364734.439383.252930@o5g2000hsb.googlegroups.com> Message-ID: <180b672e0704120112v136b85e1t88be039ef742c15b@mail.gmail.com> do something like this {keyvalue1:[ value1, value2, value3],keyvalue2:[value1,value2, value3],keyvalue3,:[value1,value2,value3]} On 12 Apr 2007 00:58:54 -0700, loial wrote: > > I am new to python and am converting an awk script to python > > I need to store some data in an array/table of some form > > keyvalue1, value1, value2, value3 > keyvalue2, value1,value2, value3 > keyvalue3, value1,value2,value3 > etc > > I will later need to sort in keyvalue order and also need to be able > to check if a key already exists > > It is not clear how to do this in python. All the examples I see have > just a key and a single value > > -- > 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 galathaea at gmail.com Wed Apr 4 15:23:37 2007 From: galathaea at gmail.com (galathaea) Date: 4 Apr 2007 12:23:37 -0700 Subject: Requirements For A Visualization Software System For 2010 In-Reply-To: <1175628186.459945.290750@d57g2000hsg.googlegroups.com> References: <1175628186.459945.290750@d57g2000hsg.googlegroups.com> Message-ID: <1175714617.095757.162510@y80g2000hsf.googlegroups.com> On Apr 3, 12:23 pm, "Xah Lee" wrote: [top posting for clarity] i have been writing a simulations engine in OCaml in my spare time over the past few years it uses openGL as its visualisation engine it is intended to transform specifications written in a domain-specific language based on category theory where the objects are specified by the transformations they undergo into "simulations" i have used the visualisation engine to explore functions and even posted some of the results http://tinyurl.com/3262ep i have also done visualisation in relativistic spacetimes in the past this included finite speed of light travel doppler shift of frequencies / color and some very basic work in generalised metrics this was done in POVRay but i ported most of that over last summer to my own engine lately i have been working on code generation of the simulations ( to c++ - which i've also posted some about ) so that i can publish my simulations while keeping my core technology proprietary but i was going to add more complete construction capabilities of complexes basic surgery operations ... to make its handling of nnoneuclidean geometry more robust and easier to manipulate through the gui much of what you posted is either already in my engine or slated to be added over the next year so... if you'd like i'd love for you to be an evangelist of my technology and maybe help get my dreams of starting my own company off the ground or if you are looking to develop something similar and become my competitor just be warned i have been studying " the art of war " ;) ( also note that many of your requirements are already handled by professional programs like maya and it's MEL scripting interface ) > REQUIREMENTS FOR A VISUALIZATION SOFTWARE SYSTEM FOR 2010 > > Xah Lee, 2007-03-16 > > In this essay, i give a list of requirements that i think is necessary > for a software system for creating scientific visualization for the > next decade (2007-2017). > > (for a HTML version with images, please seehttp://xahlee.org/3d/viz.html) > > For the past 10 years, i have been strongly interested in mathematical > visualization. I'm not a professor, and am not doing it for the > educational purposes per se. Geometry has just been beautiful for me, > and i'm also a professional programer. Programing computers to > visualize geometric theorems or geometric objects, has been a immense > personal pleasure. A particular aspect of visualization, is to design > it so that when viewed, it forces a immediate and crystal clear > understanding of the object or theorem, to its viewers. > > I have for the past couple years sought for a software platform/system > where i can build 3D objects, with abilities to do interactive > manipulation (such as moving a slider to change a parametric surface's > parameter), dynamic rotation (viewing from different angles > instantaneously), animations (such as morphing that shows geometric > processes), and most of all, walk-thru in it as if it is a building > (e.g. the perception of actually walking on a moebius strip? or Klein > bottle? is vastly different than just viewing it.). > > -------- > Requirement: Real-Time 3D Rotation > > For math visualization, it is absolutely necessary to be able to > rotate the object in real-time. For example, when viewing a complex > surface, a molecule structure, or the design of a complex device. This > requirement is so basic it warrants no further explanation. > > above: The Chen Gackstatter minimal surface as shown by the software > 3D-XplorMath ?. This surface has several 3-fold symmetries, but a > static image does not show this. (Live Rotation with Java Applet) > > -------- > Requirement: Real-time Interactivity > > The programer should be able to build buttons and sliders that change > parameters and have the object reflect these changes visually right > away. > > This real-time interactivity is frequently needed. For example, most > math visualizations involve a function, a process, or a geometric > object, that varies by parameters, and the key to the visualization is > showing how the parameter effect the graph or object. Some Examples > follows. > Example: Moebius Transformation > > above: A software that plots a complex function (the Moebius > transformation?), by showing the pre-image and post-image of the > function. The function is keyed by various parameters that can be > represented as points in the plane. Dragging these points will change > the image interactively. Source: MoeApplet by Paul Murray ? > Example: Regular Polytopes > > above: a Java applet showing a slice of 4-dimensional symmetric > polytopes? , with sliders that change the polytope's parameters. > Dragging the polytope will rotate it in real-time. Hyperstar Java > Applet by Mark Newbold ?. > Example: Plane Geometry > > above: A interactive plane geometry software showing a Equiangular > Spiral and its inverse curve , with respect to a point O. Equiangular > spiral is a family of curves varying by a parameter ?, from 0 to ?/2. > This parameter can be changed by dragging the point E of the angle > DAE, and the corresponding curve will be shown (blue). Its inverse > curve with respect to the point O is shown in pink. Dragging the point > O will change the position of O, and corresponding inverse curve will > be shown in real-time. > > above: A plane geometry software demonstrating Bezier curve. User can > drag the poins to very the input, and see the polynomial change shape > in real-time. Java Applet version. > Example: Conic Sections > > Computing power today are some 50 times faster than a decade ago. > However, math visualizations, have hardly advanced. For example, let's > consider the simple task of plotting of polynomial equations. As we > know, 2nd degree polynomials of 2 variables are conic sections. It > would nice, that the program can show the general form A x^2 + B x y + > C y^2 + D x + E y + F == 0 and let users change the constants by > sliders, and have the graph change on the fly. Such a application > would give immense feedback that reinforces learning, which is what > visualization is about. Similiarly, this can be done for 3rd degree > polynomials, and the visualization of polynomials of 3 variables. > > There are tens, if not hundreds, elementary equation and function > graphing software. However, it is almost impossible to find one that > shows the power of interactivity described above. Apple Computer Inc, > bundled with OS X as current as of March 2007, a plotting software > (called Grapher?) that has zero interactivity features. And > Mathematica's abilities for plotting polynomial equations in as late > as 2005, is basically the same as 1996. Its ability for visual > experiment and learning of polynomials of 3 variables is practically > zero. > > I have personally played with perhaps over 20 major plotting software > over the past 15 years, and i only know one that has this feature. > (see Nucalc?) > > -------- > Requirement: easy-to-create, real-time animation > > The software system must have the capabilities for programers to build > animations, and view the animation interactively in real-time (as > opposed to generating the animation once and save it as a movie). > > For example, once a programer has coded the animation, she should > easily play it forward and backward in the program, as well as > changing parameters and re-run the new animation without going thru > some compilation or export process. For example, if the animation > involves a 3D object, the system should also allow the user to rotate > it while the animation is on-going, all in real-time. > > For example, this system should allow programer to easily create a > animation that morphs a sphere into a cube, or a bunch of spheres > flying in space as a swarm of flies or in some artificial formation > like a 3D-kaleidoscope. > Example: Cycloidal Curves > > above: A movie generated by a math software, showing how the cycloid > curve is generated by rolling a circle. (cycloidGen.mov). > > In this example, you can see the trace by a point on the boundary of > the circle. What happens if the tracing point is nearer to the center > of the circle? This is a example where a interactive slider will help. > As a user adjust the slider, the animation should show its effects in > real-time. > Example: Cellular Automaton > > above: A software that computes the cellular automaton?known as Game > Of Life, showing it as a animation as it evolves. At any point in > time, a user can add more cells to it by clicking in the window, and > continue the animation to see its effects. > Example: Helicoid-catenoid Surface Family > > above: A frame of a software generated animation, showing the isometry > property of the surface family helicoid-catenoid. (helicoid- > catenoid.mov) > > This is a example where it shows the importance of being able to > rotate the object in real-time in a on-going animation. > Example: Sphere-eversion > > above: The classic Sphere-eversion visualization problem, visually > demonstrating how a sphere can be turned inside-out without creating > any crease. (Source: John Sullivan et al. ?. image source ?, accessed > on 2007-03-18.) (For detail about this problem, see: Smale's paradox?) > > Examples of system that do NOT satisfy this requirement would be: > Mathematica (up to version 5), 3D-XplorMath, most CAD systems. Most of > these systems allow animations, but usually for a generate-once and > save-as-static-movie-file, not designed for interactive view. > Example: Stereographic Projection > > above: A illustration showing stereographic projection. (source) > > To create visualization for stereographic projection, ideally, the > user should be able to rotate the whole plane, or move it up and down > in relation to the sphere, as to see the effect on the mapping. Also, > the user should be able to rotate the sphere and see the mapping > change on the plane. The user should also be able to move a single > projection line to see mappings of arbitrary points. Lastly, it is > ideal in this visualization to let users change the pattern on plane > or on the sphere to arbitrary images. For example, the plane should > have a default set containing rectangular grids and polar grids. > (showing the important property of circles mapping to circles/lines) > The sphere should have standard projection of platonic solids. > (showing the important concept of platonic solids as networks) And, > the user should be able to put the graph of arbitrary complex function > on the plane or a Riemann sphere? on the sphere. > > Today, it is non-trivial to create a visualization such as this. For > example, the above image is created in Mathematica. One has to write a > function that plots riemann sphere in the first place, to create the > image of the sphere. The system also needs to have animation and > interactive slider abilities, as to be able to make the sphere and > plane rotate or reposition independently in real-time, and the moving > of the projection line. > > Examples of visualization systems that do satisfy the animation > requirement to various degrees discussed in this section would be: > Macromedia Flash, VPython, 3D Game Engines. > > -------- > Requirement: Walk-thru > > The software system should have the capability of walk-thru or fly- > thru. That is, allow the programer precise control of the camera > position and orientation in real-time. > > The most obvious application of this requirement is in CAD systems > that are specialized for architecture. > > For example, if i build a fancy 3D-maze or elaborate cathedral, i > should be able to say, walk inside it, so as to view the object from > inside and as well as getting the real experience of perceiving such a > building. > > The ability to do walk-thrus has significant applications in math > visualization too, however, it is seldom realized. Here are some > examples of its application. > Example: Walking on Surfaces > > above: A hyperbolic-paraboloid, with a human character standing on top > of it. (from the computer graphics virtual world Second Life. Credit: > Henry Segerman?, aka Seifert Surface.) > > Compare the above image with the following abstract rendering that is > commonly found in math visualization software. > > above: a abstract rendering of the hyperbolic-paraboloid. Java Applet > > Perhaps due to the evolution of our perception system, the experience > of actually walking on or inside a math object, is vastly different > than just seeing it as zero-thickness abstract lines and sheets > rotating around its center. > > Although, the virtual world created by computer graphics only fake the > experience of actually being there, still, such a virtual world > experience throws a impact on understanding. Imagine, demonstrating > the one-sidedness property of surfaces such as the moebius strip? or > Klein bottle? thru a live rotation and explanation, compared to having > the student inadvertently taking a walk inside such a object and > suddenly felt the single-sided oddity. A person experiencing such a > situation will probably remember it as part of his life's memory. > Example: 3D-Lattices > > The ability to do walk-thrus also fits well in visualizations > involving 3-dimensional lattices, such as Crystallographic group?, 3D- > tilings (sphere packing), or visualizing periodic minimal surfaces. > > For example, the following images of periodic minimal surfaces are > shown in the way they are traditionally presented, as a few > representative patchs of the periodic surface, and users can rotate > the surfaces in real-time: > > above: Periodic minimal surfaces?. Source: Richard Palais, Karcher > Hermann. ?) > > As they are shown, their periodic structure is not visually clear, > especially those non-rectangular ones. (e.g. the last 3) It also takes > some effort to imagine how they actually fill the space. > > Now, imagine these shown in a walk-thru system, where a portion of > space is filled with its repetitions, and the user effectively becomes > a bee, flying about in it, able to observe detail in a close-up on any > point of the surface from any angle, or getting a bird's eye's > overview of the surface's lattice symmetry. > Example: 3-Manifolds > > above: Screenshot of Jeff Week's Curved Space ? software. This program > lets users fly-thru various 3-manifolds? . There is basically no other > way of visualizing 3-manifolds other than the techniques of walk-thru. > > There is effectively no visualization system that lets programers > easily code interactive walk-thrus. The possible exception is 3D Game > Engines?, however, it requires a specialized programer with years of > dedicated experience to create any thing in it, and the work is rather > tedious. Some such game engines have higher level (scripting) > languages that let the user (players) create objects or scenes in- > world. (A example is the Linden Scripting Language? of Second Life?. ) > > -------- > Requirement: Easy To Use For Average Programers > > The system must be easy to use for average programers or scientists. > For example, a person who had just a year of programing experience, > should be able to code a variety of visualization projects with the > system. > > Often, these high-level languages are called scripting languages. > Mathematica?, Lisps (Logo?, Scheme?, Tcl/tk? ), Visual Basic?, > VPython?, Macromedia Flash?, CAD systems (AutoLISP? ), Linden > Scripting Language? are examples of high-level systems. > > On the other hand, low-level language such as Java?, C sharp?, or, > systems such as OpenGL? and Game Engines?, or application programing > systems such as Cocoa (API)? and X Window System?, all require > professional programers with years of experience to create a non- > trivial application. These are not useful to most scientists or > engineers. > > -------- > Requirement: A Set of Basic Geometric Shapes > > The system must have a set of basic primitives or shapes that serve as > building blocks. For example, spheres, torus, cubes, as well as meshes > of triangles. > > Of course, the system should also have the following common elements: > various coordinates systems, projection systems, lighting and camera > control, build-in manifold by parametric surfaces and algebraic > equations, and a whole set of 2D and 3D transformation functions > (which can also work on n-dimensional coordinates). > > For a system aimed for math visualization, it would also be necessary > to have access to a full range of math functions, such as integration, > derivative, higher-order functions. > > [Continues on page 2] > > ----- > This post is archived at > > I'm still working on the second part. Your opinions and comments on > existing systems are welcome. Thanks. -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- galathaea: prankster, fablist, magician, liar From b83503104 at yahoo.com Tue Apr 3 15:13:13 2007 From: b83503104 at yahoo.com (bahoo) Date: 3 Apr 2007 12:13:13 -0700 Subject: how to remove multiple occurrences of a string within a list? In-Reply-To: <1175625098.269660.184790@o5g2000hsb.googlegroups.com> References: <1175624433.206953.214290@n59g2000hsh.googlegroups.com> <1175625098.269660.184790@o5g2000hsb.googlegroups.com> Message-ID: <1175627593.307674.11280@w1g2000hsg.googlegroups.com> On Apr 3, 2:31 pm, "Matimus" wrote: > It depends on your application, but a 'set' might really be what you > want, as opposed to a list. > > >>> s = set(["0024","haha","0024"]) > >>> s > > set(["0024","haha"])>>> s.remove("0024") > >>> s > > set(["haha"]) This sounds cool. But is there a command I can convert the "set" back to a "list"? From bbxx789_05ss at yahoo.com Sun Apr 15 02:20:39 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: 14 Apr 2007 23:20:39 -0700 Subject: Reading the first line of a file (in a zipfile) In-Reply-To: <1176318822.811661.115730@q75g2000hsh.googlegroups.com> References: <1176318822.811661.115730@q75g2000hsh.googlegroups.com> Message-ID: <1176618038.965801.228960@b75g2000hsg.googlegroups.com> On Apr 11, 1:13 pm, mike.aldr... at gmail.com wrote: > Hi folks, > > The first line in the file I am examining will be a number followed by > more whitespace. Looks like I cannot split by whitespace? > but I get 'cannot open > file' when i try to read from an archive.. ...and that led you to conclude that you cannot split by whitespace? From pekka.jarvinen at gmail.com Fri Apr 20 14:30:04 2007 From: pekka.jarvinen at gmail.com (=?iso-8859-1?q?Pekka_J=E4rvinen?=) Date: 20 Apr 2007 11:30:04 -0700 Subject: Calculating CIDR blocks In-Reply-To: References: <1177032744.375099.248380@q75g2000hsh.googlegroups.com> <1177074967.900881.256280@n76g2000hsh.googlegroups.com> Message-ID: <1177093804.545387.24680@b75g2000hsg.googlegroups.com> On 20 huhti, 18:30, e... at holyrood.ed.ac.uk (Eddie Corns) wrote: > =?iso-8859-1?q?Pekka_J=E4rvinen?= writes: > >On 20 huhti, 14:34, e... at holyrood.ed.ac.uk (Eddie Corns) wrote: > >> Look at:http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/466298 > >> it handles most of the logic of combining IP ranges. > > >> Eddie > >I'm getting error: > >Traceback (most recent call last): > > File "ipr.py", line 5, in > > x = ipv4.IP4Range(ips) > > File "IP4Range.py", line 119, in __init__ > > raise TypeError("Invalid argument.") > >TypeError: Invalid argument. > > I haven't used this module for some time but if I recall your requirements > properly you need something like: > > >>> R=IP4.IP4Range() > >>> for i in ips: > > ... R=R|IP4.IP4Range(i) > ...>>> for m in R.itermasks(): > > ... print m > ... > 192.168.0.0/26 > 192.168.0.64/27 > 192.168.0.96/29 > 192.168.0.104/30 > 192.168.0.108/31 > 192.168.0.110/32 > 192.168.0.128/25 > 192.168.0.112/28 > > > > There may be an easier way my memory is hazy. > > Eddie It does exactly what I'm after! Thanks a lot! :) From steve at REMOVE.THIS.cybersource.com.au Sat Apr 28 13:53:47 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Sun, 29 Apr 2007 03:53:47 +1000 Subject: Numbers and truth values References: Message-ID: On Sat, 28 Apr 2007 15:36:19 +0200, Szabolcs wrote: >>>>> True = 2 # DON'T DO THIS!!! >>>>> 2 == True >> True >> > > But shouldn't Python forbid this? Is it possible to get a warning when > unintentionally redefining built-in thing? Python forbids very few things in comparison to other languages. The attitude is "We're all adults here". Because Python is such a dynamic language, it is often hard for the compiler to tell the difference between something you are doing deliberately and a mistake. If you're worried about that, google for PyChecker. -- Steven. From sjmachin at lexicon.net Thu Apr 5 16:55:04 2007 From: sjmachin at lexicon.net (John Machin) Date: 5 Apr 2007 13:55:04 -0700 Subject: UNICODE mode for regular expressions - time to change the default? In-Reply-To: References: Message-ID: <1175806504.059999.43050@e65g2000hsc.googlegroups.com> On Apr 6, 5:50 am, John Nagle wrote: > Regular expressions are compiled in ASCII mode > unless > Unicode mode is specified to "rc.compile". The difference is that regular > expressions in ASCII mode don't recognize things like > Unicode whitespace, even when applied to Unicode strings. AFAICT, the default is that \s, \d, etc are interpreted according to the current locale's properties. Specifying re.U changes that to use the unicodedata properties instead. There is no such thing as "ASCII mode". > For example, Unicode character 0x00A0 is a "NO-BREAK SPACE", which is > a form of whitespace. It's the Unicode equivalent of HTML's " ". > This can create some strange bugs. > > Is the current default good? Or is it time to compile all regular > expressions in Unicode mode by default? It shouldn't hurt processing of > ASCII strings to do that. Believe it or not: there are folk out there who have data which is encoded in 8-bit encodings which are not ASCII and for which "\xA0".decode('whatever') does not produce u"\xA0" ... it could for example be a box-drawing character or a letter: >>> import unicodedata as ucd >>> "\xA0".decode('koi8-r') u'\u2550' >>> ucd.name(_) 'BOX DRAWINGS DOUBLE HORIZONTAL' >>> "\xA0".decode('cp850') u'\xe1' >>> ucd.name(_) 'LATIN SMALL LETTER A WITH ACUTE' >>> Problem number 2: It's probable that users in locale X wouldn't want a match to succeed on a character that is regarded as a digit (say) in distant locale Y, but if found in a data file in locale X is probably more indicative of having read binary data instead of Unicode text: >>> ucd.name(u"\u0f20") 'TIBETAN DIGIT ZERO' >>> re.match(ur"\d", u"\u0f20") >>> re.match(ur"\d", u"\u0f20", re.U) <_sre.SRE_Match object at 0x00EFC9C0> > The current setup is really a legacy of when > most things in Python didn't work in Unicode mode, and you didn't want to > introduce Unicode unnecessarily. It's another one of those obscure > Unicode "gotchas" that really should go away. It's the ASCII-centric mindset that creates gotchas and really should go away :-) HTH, John From stj911 at rock.com Thu Apr 26 01:02:03 2007 From: stj911 at rock.com (stj911 at rock.com) Date: 25 Apr 2007 22:02:03 -0700 Subject: Video: Professor of Physics, Phd at Cal Tech says: 911 Inside Job Message-ID: <1177563723.864674.162300@s33g2000prh.googlegroups.com> Video: Professor of Physics, Phd at Cal Tech says: 911 Inside Job Cal Tech is the ELITE of ELITE in physics. If Feynman were alive, he would point his finger straight at the 911 criminal operators, the yank bastards themselves ....... http://www.911blogger.com/node/8101 No self-respecting scientist should keep his mouth shut. Its a fundamental challenge to the method of science, a detective work most demanding of INTELLECTUAL HONESTY. From steve at REMOVE.THIS.cybersource.com.au Thu Apr 19 19:12:42 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Fri, 20 Apr 2007 09:12:42 +1000 Subject: Significance of "start" parameter to string method "endswith" References: <1177016236.700474.16170@n59g2000hsh.googlegroups.com> Message-ID: On Thu, 19 Apr 2007 13:57:16 -0700, Boris Dusek wrote: >> > what is the use-case of parameter "start" in string's "endswith" >> > method? > >> def foo(function,instance,param): >> if function(instance,param,2,4): >> return True >> else: return False >> >> The function must work whether you pass it >> foo(str.endswith,"blaahh","ahh"), or >> foo(str.startswith,"blaahh","aah"). This is a really bad example, but >> it gets the point across that similar functions must have similar >> parameters in order to be Pythonic. > > Thanks for explanation, this point makes sense. And I agree that I can > hardly imagine any use of both parameters :-). No, sorry, it doesn't make sense because not all string methods take the same arguments! See, for instance, ''.translate() and ''.lower(). The best reason for giving string methods and functions start and end parameters is to avoid copying potentially large lumps of text. Here's a silly example. Instead of doing this: while text: p = text.find('parrot') buffer = text[:p] text = text[p:] do_something_with(buffer) You can do this: p = 0 while text: p = text.find('parrot', p) do_something_with(buffer, p) which avoids copying text unnecessarily. Now, obviously there are better ways to re-write that code (e.g. by splitting the text into chunks with split) but it should illustrate the concept. -- Steven. From cjw at sympatico.ca Sat Apr 14 12:04:52 2007 From: cjw at sympatico.ca (Colin J. Williams) Date: Sat, 14 Apr 2007 12:04:52 -0400 Subject: vocab question In-Reply-To: References: Message-ID: James Stroud wrote: > Alan G Isaac wrote: >> Pardon the vocab question; >> I'm not a computer science type. >> According to the Reference Manual, >> a class defintion has the structure:: >> >> classdef ::= "class" classname [inheritance] ":" suite >> >> What is the entire part before the suite called? >> (Just pointing to a reference is fine & helpful, >> as long as its not an entire course on BNF.) >> >> Thanks, >> Alan Isaac +1 > > Signature? From cam.ac.uk at mh391.invalid Sun Apr 1 18:56:49 2007 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Sun, 01 Apr 2007 23:56:49 +0100 Subject: Launch script on Linux using Putty In-Reply-To: <1175467029.572354.138930@y66g2000hsf.googlegroups.com> References: <1175467029.572354.138930@y66g2000hsf.googlegroups.com> Message-ID: Ulysse wrote: > Hello, > > I have a python script which runs all the time (using of library > threading). I would like this scipt to run on a remote linux Os using > Putty. The problem is, when I close Putty command line window running > on my Win PC, the python script stops to run too. > > I tried to use cron tables instead. By setting the time and restart > cron process, but it's not practical. > > Do you know the right way to do this ? There are a few ways to do this, in order of easiest to most involved: 1. The easiest is to run nohup on your script in the background: $ nohup myscript.py > output.txt 2> error.txt & Then you can disconnect but your script will keep running. Try man nohup for more information. 2. Use GNU screen on your remote terminal, and detach the screen instead of logging off. 3. Set up your script to fork as a daemon. Google for ["python cookbook" fork daemon] to find a few recipes for this. -- Michael Hoffman From hlubenow2 at gmx.net Thu Apr 5 17:31:53 2007 From: hlubenow2 at gmx.net (hlubenow) Date: Thu, 05 Apr 2007 23:31:53 +0200 Subject: Looping issues References: <1175796069.501575.157410@w1g2000hsg.googlegroups.com> <1175797130.561115.147450@p77g2000hsh.googlegroups.com> <1175797514.270221.190610@n59g2000hsh.googlegroups.com> Message-ID: <9f6ge4-d67.ln1@athlon.my> brochu121 at gmail.com wrote: > On Apr 5, 2:18 pm, "anglozaxxon" wrote: >> On Apr 5, 2:01 pm, brochu... at gmail.com wrote: >> >> >> >> > What I am trying to do is compare two files to each other. >> >> > If the 2nd file contains the same line the first file contains, I want >> > to print it. I wrote up the following code: >> >> > correct_settings = open("C:\Python25\Scripts\Output >> > \correct_settings.txt","r") >> > current_settings = open("C:\Python25\Scripts\Output\output.txt","r") >> >> > for line in correct_settings: >> > for val in current_settings: >> > if val == line: >> > print line + " found." >> >> > correct_settings.close() >> > current_settings.close() >> >> > For some reason this only looks at the first line of the >> > correct_settings.txt file. Any ideas as to how i can loop through each >> > line of the correct_settings file instead of just looking at the first? >> >> Instead of "for line in correct_settings", try "for line in >> correct_settings.readlines()". > > That Still didnt fix it. Same output Try this: correct_settings = file("C:\Python25\Scripts\Output\correct_settings.txt", "r") current_settings = file("C:\Python25\Scripts\Output\output.txt", "r") a = correct_settings.readlines() b = current_settings.readlines() correct_settings.close() current_settings.close() for line in a: for val in b: if val == line: print line + " found." From rocky.bernstein at gmail.com Fri Apr 6 22:49:08 2007 From: rocky.bernstein at gmail.com (rocky.bernstein at gmail.com) Date: 6 Apr 2007 19:49:08 -0700 Subject: Getting Stack Trace on segfault In-Reply-To: References: Message-ID: <1175914148.105951.164250@b75g2000hsg.googlegroups.com> On Apr 6, 8:13 am, James Stroud wrote: > Hello All, > > The built-in mac osx vecLib is segfaulting in some cases--A very fun > fact to find out the hard way over two nights of work. I also spent an > embarrassing amount of time figuring out just where. Although I'm in > quite a self-congratulatory mood right now, in the future, I feel like I > could save a lot of time by coercing the interpreter to spew forth > method calls to stderr. Is this possible? > > I would hope to produce something hauntingly reminiscent of > > [] my_function > [my_function] another_function > [my_function -> another_function] yet_a_deeper_function > > Presentation, of course, is irrelevant. > > I read the docs onpdb, but it did not seem to do what I want--unless, > of course, I missed something. > > James pydb (http://bashdb.sf.net0 has the ability to do noninteractive line tracing. See http://bashdb.sourceforge.net/pydb/pydb/lib/subsubsection-set.html or the showmedo demo. It would be kind of neat to extend this to allow for method/fn tracing. Alas the simple hack I tried, didn't work because of code obscurities. (The code could stand to use a rewrite.) From moin at blackhole.labs.rootshell.ws Thu Apr 19 12:56:25 2007 From: moin at blackhole.labs.rootshell.ws (S.Mohideen) Date: Thu, 19 Apr 2007 10:56:25 -0600 Subject: Python un-plugging the Interpreter Message-ID: <005f01c782a3$ae84d710$fa936540@cisco.com> Hi All, I was thinking about the feasbility of adjusting Python as a compiled language. Being said that I feel these are the following advantages of doing so -- 1) Using the powerful easy-to -use feature of Python programming language constructs. 2) Making the program to run at par with the compiled version of C/C++ program- this is the main benefit which can be derived out of this. 3) Highly re-use existing Python code for High performance application. 4) Acheive true parallelism and performance by getting rid of the middle-man Interpreter and GIL. I know this must be appearing like a foolish idea. But I would like to know the opinion of people who might have thought about it. Thanks Moin From kyosohma at gmail.com Tue Apr 3 15:03:06 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: 3 Apr 2007 12:03:06 -0700 Subject: os.popen--which one to use? In-Reply-To: References: Message-ID: <1175626986.551626.8610@n59g2000hsh.googlegroups.com> On Apr 3, 1:53 pm, Kevin Walzer wrote: > I'm confused by the number of variations on "popen" that Python offers. > > I'm using os.popen in my programs without difficulty. Is this wrong? > Should I be using popen 2, popen3, etc.? I'm not clear on what the > advantages of popen2, 3 etc. are: they seem a lot more complicated. > > -- > Kevin Walzer > Code by Kevinhttp://www.codebykevin.com There's nothing wrong with using os.popen. Some of them are Unix specific though. And that module's functionality along with os.system, os.spawn and commands have all be integrated into the subprocess module, which I think is much less confusing. The only places I've seen a fairly coherent run-down of the os.popen modules is the "Python in a Nutshell" book and maybe (I can't remember for sure) "Core Python Programming". See http://pydoc.org/2.4.1/subprocess.html for more info on the subprocess module. Mike From nick at craig-wood.com Thu Apr 19 14:30:12 2007 From: nick at craig-wood.com (Nick Craig-Wood) Date: Thu, 19 Apr 2007 13:30:12 -0500 Subject: Binary file output using python References: Message-ID: Peter Otten <__peter__ at web.de> wrote: > Chi Yin Cheung wrote: > > > Is there a way in python to output binary files? I need to python to > > write out a stream of 5 million floating point numbers, separated by > > some separator, but it seems that all python supports natively is string > > information output, which is extremely space inefficient. > > > > I'd tried using the pickle module, but it crashed whenever I tried using > > it due to the large amount of data involved. > > A minimalistic alternative is array.tofile()/fromfile(), but pickle should > handle a list, say, of 5 million floating point numbers just fine. What > exactly are you doing to provoke a crash, and what does it look like? > Please give minimal code and the traceback. cPickle worked fine when I tried it... >>> L=map(float, range(5000000)) >>> import cPickle >>> out=file("z", "wb") >>> cPickle.dump(L, out, -1) >>> out.close() >>> inp=file("z", "rb") >>> K=cPickle.load(inp) >>> inp.close() >>> import os >>> os.system("ls -l z") -rw-r--r-- 1 ncw ncw 45010006 Apr 19 18:43 z 0 >>> Indicating each float took 9 bytes to store, which is 1 byte more than a 64 bit float would normally take. The pickle dump / load each took about 2 seconds. -- Nick Craig-Wood -- http://www.craig-wood.com/nick From http Sun Apr 1 15:21:56 2007 From: http (Paul Rubin) Date: 01 Apr 2007 12:21:56 -0700 Subject: Shed Skin Python-to-C++ Compiler 0.0.21, Help needed 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> <7x8xdcrc13.fsf@ruckus.brouhaha.com> <1175452252.278238.277220@p15g2000hsd.googlegroups.com> Message-ID: <7x3b3juch7.fsf@ruckus.brouhaha.com> mark.dufour at gmail.com writes: > > I don't see how that can be--we're talking about a GCC-based compiler, > > right? > > no, Shed Skin is a completely separate entity, I was referring to GNAT. From mensanator at aol.com Tue Apr 10 16:13:27 2007 From: mensanator at aol.com (mensanator at aol.com) Date: 10 Apr 2007 13:13:27 -0700 Subject: NLTK, Random Sentence Generators? In-Reply-To: <1176231570.124706@jubilee.claranet.pt> References: <87slb8d3uj.fsf@localhost.localdomain> <1176224912.373928.326030@e65g2000hsc.googlegroups.com> <1176231570.124706@jubilee.claranet.pt> Message-ID: <1176236007.393520.152760@h3g2000cwc.googlegroups.com> On Apr 10, 1:59 pm, Paulo da Silva wrote: > gene tani escreveu: > > > On Apr 10, 1:36 am, Passer By wrote: > >> Has any created or not of examples of random sentence generators using > >> n-gram models (or other models might be interesting). > > >> I know of one example from a course at MIT, but besides that nothing. > > >> Any help would be great. > > > Markov chains e.g. > >http://rubyquiz.com/quiz74.html > > Seems interesting ... Is there anybody who masters both python and ruby > to "translate" the code into python? Wouldn't it be easier to translate Python: From grante at visi.com Wed Apr 4 13:48:58 2007 From: grante at visi.com (Grant Edwards) Date: Wed, 04 Apr 2007 17:48:58 -0000 Subject: Write to a binary file References: Message-ID: <1317p8ab5216aae@corp.supernews.com> On 2007-04-04, Thomi Aurel RUAG A wrote: > I'm using Python 2.4.2 on an ARM (PXA-270) platform (linux-2.6.17). > My Goal is to write a list of bytes down to a file (opened in binary > mode) in one cycle. The crux is that a '0x0a' (line feed) will break the > cycle of one writing into several pieces. Says who? I've never experienced this... > Writing to a "simple" file, this wouldn't cause any problem. > > Assuming - without questioning ;-) - that a device file (/dev/*) has to > be written in one cycle because one write call will be interpreted as > one "transaction". I've never seen a write() on a file descriptor broken up by Python. What makes you think this is an issue? > The write behaviour on line feed's isn't really usefull What write behavior? > because such "transactions" would be broken up into serveral > pieces and therefore for the device into several > "transactions". > > Is there a possibility to write a list of bytes "en bloc" to a > binary file? (without the interpreting of the line feed's) > Opening a file i binary mode (i.e "wb") seems not to be > enough. It sounds like you're using open() and Python file objects. You probably ought to use os.open() an os.write(). -- Grant Edwards grante Yow! I want DUSTIN at HOFFMAN!! ... I want visi.com LIBRACE!! YOW!! From bbxx789_05ss at yahoo.com Mon Apr 16 04:11:55 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: 16 Apr 2007 01:11:55 -0700 Subject: pyparsing Catch-22 In-Reply-To: <1176710795.136757.26570@b75g2000hsg.googlegroups.com> References: <1176686782.270354.164630@l77g2000hsb.googlegroups.com> <1176696704.924584.75720@e65g2000hsc.googlegroups.com> <1176710795.136757.26570@b75g2000hsg.googlegroups.com> Message-ID: <1176711115.104185.35810@b75g2000hsg.googlegroups.com> On Apr 16, 2:06 am, "7stud" wrote: > Hmmm. My post got cut off. Here's the rest of it: I'm pretty facile with regex's, and after looking at some pyparsing threads over the last week or so, I was interested in trying it. However, all of the beginning examples use a Word() in the parse expression, but I couldn't find an adequate explanation of what the arguments to Word() are and what they mean. I finally found the information buried in one of the many documents--the one called "Using the Pyparsing Module". If that seems like an obvious place to look, I did start there, but I didn't find it at first. I also scoured the the wiki, and I looked in the file pycon06- IntroToPyparsing-notes.pdf, which has this: ------------ Basic Pyparsing Words and Literals From steve at REMOVEME.cybersource.com.au Tue Apr 3 01:07:18 2007 From: steve at REMOVEME.cybersource.com.au (Steven D'Aprano) Date: Tue, 03 Apr 2007 15:07:18 +1000 Subject: getattr/setattr q. References: <1175573213.682671@jubilee.claranet.pt> Message-ID: On Tue, 03 Apr 2007 05:08:42 +0100, Paulo da Silva wrote: > Hi! > > In a class C, I may do setattr(C,'x',10). > > Is it possible to use getattr/setattr for variables not inside > classes or something equivalent? I mean with the same result as > exec("x=10"). Yes, but you shouldn't unless you really need to. You're better off rethinking your algorithm. If you think you really need to, you probably don't. If you *really* think you really need to, you might. >>> x Traceback (most recent call last): File "", line 1, in ? NameError: name 'x' is not defined >>> globals()['x'] = 5 >>> x 5 Note that there is also a function locals(), but it doesn't work as you might expect: >>> def f(): ... locals()['x'] = 99 ... print x ... >>> f() 5 -- Steven D'Aprano From dotancohen at gmail.com Sat Apr 14 13:16:42 2007 From: dotancohen at gmail.com (Dotan Cohen) Date: Sat, 14 Apr 2007 20:16:42 +0300 Subject: Python editor/IDE on Linux? In-Reply-To: References: Message-ID: <880dece00704141016m709d59edo15c1feb41af9a638@mail.gmail.com> On 14/04/07, Kevin Walzer wrote: > Jack wrote: > > I wonder what everybody uses for Python editor/IDE on Linux? > > I use PyScripter on Windows, which is very good. Not sure if > > there's something handy like that on Linux. I need to do some > > development work on Linux and the distro I am using is Xubuntu. > > > > > > Why not IDLE? Because idle means no progress. Better use VI[M]. Dotan Cohen http://technology-sleuth.com/technical_answer/what_is_a_cellphone.html http://lyricslist.com/lyrics/artist_albums/345/metallica.html From tjreedy at udel.edu Sat Apr 14 18:48:06 2007 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 14 Apr 2007 18:48:06 -0400 Subject: Python Feature Request: Add the "using" keyword which works like"with" in Visual Basic References: <1176547372.584539.89170@q75g2000hsh.googlegroups.com> Message-ID: wrote in message news:1176547372.584539.89170 at q75g2000hsh.googlegroups.com... | self.setFixedSize(200, 120) | self.quit = QtGui.QPushButton("Quit", self) | self.quit.setGeometry(62, 40, 75, 30) | self.quit.setFont(QtGui.QFont("Times", 18, QtGui.QFont.Bold)) | self.connect(self.quit, QtCore.SIGNAL("clicked()"), QtGui.qApp, | QtCore.SLOT("quit()")) | | to be rewritten as: | | using self: | __setFixedSize(200,120) | __quit = QtGui.QPushButton("Quit", self) | __using quit: | ____setGeometry(62, 40, 75, 30) | ____setFont(QtGui.QFont("Times", 18, QtGui.QFont.Bold)) | __connect(self.quit, QtCore.SIGNAL("clicked()"), QtGui.qApp, | QtCore.SLOT("quit()")) If you want to save typing, you are free to use 's' instead of 'self' as the parameter name. No need to make a fairly major language change. I do things like 'import math as m' to save repetition. tjr From bj_666 at gmx.net Sat Apr 28 03:06:55 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Sat, 28 Apr 2007 09:06:55 +0200 Subject: Which are your favorite UML tools? References: <463265f0$0$19018$426a34cc@news.free.fr> Message-ID: In , Russell E. Owen wrote: > Some problems are intrinsic to UML (for instance it has no concept of > linking use case information to other elements). And I don't know of any > way to model functions (only classes). Just model modules as classes and functions as static methods of the module's class. Modules are objects too and can be seen as singletons. Ciao, Marc 'BlackJack' Rintsch From steve at holdenweb.com Thu Apr 26 08:13:20 2007 From: steve at holdenweb.com (Steve Holden) Date: Thu, 26 Apr 2007 08:13:20 -0400 Subject: My python annoyances so far In-Reply-To: <1177541453.471959.120830@c18g2000prb.googlegroups.com> References: <1177541453.471959.120830@c18g2000prb.googlegroups.com> Message-ID: flifus at gmail.com wrote: > Hi all. I'm learning python these days. I'm going to use this thread > to post, from time to time, my annoyances with python. I hope someone > will clarify things to me where I have misunderstood them. > > Annoyances: > > 1. Underscores! What's the deal with that? Especially those double > underscores. The best answer I read on this is that the double > underscores denotes special methods that the interpreter may > automatically use. For example, 4+4 get expanded by the interpreter to > 4.__add__(4). > > 2. There are modules, there are functions, and there are classes- > methods! Wouldn't it have been easier had everything either been a > function or a class method? > Actually, it's really simple. When you get right down to it, *everything* in *every* current implementation of Python is either a one or a zero. Would you like us to make it all zeros? Perhaps you should meditate on the idea to the concept of "sufficient and necessary complexity" ... If you're a beginning programmer then it might be that Python contains features you haven't yet needed. If you come from other languages (and there's a certain Java-ish feel to the second comment) then perhaps you aren't yet sufficiently familiar with Python to stop trying to write other languages in it. I know I gave up Java because, among other reasons, I found it tedious that I had to build a class method (and reference it) when what I really wanted was a function. Finally, I think as a learner you *can* do the language a service by explaining what you find unnatural, inconvenient or incomprehensible. Do please realise though that many times things will be as they are for specific reasons, and sometimes even when the reasons aren't that good some people will argue for retaining the status quo. Your posting actually reads quite like a letter to Viz - see http://www.viz.co.uk/ and follow the "Letterbocks" link - so it gave me a smile before I realised it was (probably) serious. regards Steve -- Steve Holden +1 571 484 6266 +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 Mon Apr 30 06:06:43 2007 From: steve at REMOVEME.cybersource.com.au (Steven D'Aprano) Date: Mon, 30 Apr 2007 20:06:43 +1000 Subject: How do I parse a string to a tuple?? References: <1177926452.830059.269230@n59g2000hsh.googlegroups.com> Message-ID: On Mon, 30 Apr 2007 02:47:32 -0700, Soren wrote: > Hi! > > I have a string that contains some text and newline characters. I want > to parse the string so that the string just before a newline character > goes in as an element in the tuple. > > ex: > > "text1 \n text2 \n text3 \n text4" --> (text1, text2, text3, text4) > > Is there an easy way to do this? the_string = "text1 \n text2 \n text3 \n text4" tuple(the_string.split('\n')) If you don't need a tuple, and a list will do: the_string.split('\n') If you want to get rid of the white space after each chunk of text: [s.strip() for s in the_string.split('\n')] -- Steven D'Aprano From nagle at animats.com Sat Apr 14 17:31:12 2007 From: nagle at animats.com (John Nagle) Date: Sat, 14 Apr 2007 21:31:12 GMT Subject: "HTTP error -1" from urllib2 In-Reply-To: <873b33cm4f.fsf@pobox.com> References: <873b33cm4f.fsf@pobox.com> Message-ID: John J. Lee wrote: > John Nagle writes: > Can you create an example (preferably small) that fails? Feel free to > email it to me if it includes something you don't want to post. It's not a Python problem, as it turns out. It's a problem in, surprisingly, Coyote Point load balancers. This fails: ==== telnet www.coyotepoint.com 80 GET / HTTP/1.0 Host: www.fourmilab.ch User-agent: am ==== This works: ==== telnet www.coyotepoint.com 80 GET / HTTP/1.0 Host: www.fourmilab.ch User-agent: an ===== Note the difference in the "User-agent" field; "m" vs. "n". There's some problem in Coyote Point Equalizer load balancers in USER-AGENT parsing. If it sees a USER-AGENT string ending in "m" but with no earlier "m" in the string, and the USER-AGENT field is the last field in the HTTP header, it drops the packet. One can make this happen talking to the HTTP server with a Telnet client. If you paste the sections between "===" lines above into a Windows command line window, you can demonstrate this too. (Remember to copy the blank line that ends the header.) We found this because we were using a user agent string of "SiteTruth.com rating system", which ends in "m" but doesn't contain any other "m" characters. A site run by people we know wouldn't respond, and we've been working to figure out why. They own a Coyote Point Equalizer, and after much digging through log files, it became clear that the load balancer was dropping these packets, even though it wasn't configured to do so. So we tried Coyote Point's own site, and it has exactly the same problem. It's thus probably a generic problem with Coyote Point load balancers. It's not a configuration problem; we've checked the load balancer's configuration file. That load balancer uses regular expressions to parse HTTP headers. My guess is that we're going to find a "\m" somewhere that a "\n" was intended. I'll be on the phone to Coyote Point on Monday. John Nagle From deets at nospam.web.de Fri Apr 20 06:49:38 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Fri, 20 Apr 2007 12:49:38 +0200 Subject: setDaemon problem. In-Reply-To: <1177057029.688992.160020@o5g2000hsb.googlegroups.com> References: <1177057029.688992.160020@o5g2000hsb.googlegroups.com> Message-ID: <58rk68F2hof6mU1@mid.uni-berlin.de> Ramashish Baranwal schrieb: > Hi, > > I am facing an issue in daemonizing a thread using setDaemon method. > Here is my code- > > import time > from threading import Thread > > class MThread(Thread): > def run(self): > f = open('/tmp/t.log', 'w') > for i in range(10): > f.write('Iteration %d\n' % i) > time.sleep(1) > f.close() > > if __name__ == "__main__": > t = MThread() > t.setDaemon(True) > print 'Starting thread' > t.start() > > The scripts runs all fine, but nothing gets logged to "/tmp/t.log". > However when I run the same script without setting thread as daemon > (no call to t.setDaemon), everything works fine. > > Am I missing anything? Yes. You miss the documentation of setDaemon. It is _not_ a PROCESS-daemonization recipe - which you can get here: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66012 Instead, it means that the thread started is considered not to be worth waiting for when the main thread exits. Which it does immediately in your code, resulting in nothing written in the logfile. I think the name setDaemon is somewhat unfortunate. Diez From steve at holdenweb.com Fri Apr 13 08:52:40 2007 From: steve at holdenweb.com (Steve Holden) Date: Fri, 13 Apr 2007 08:52:40 -0400 Subject: Need help with the get() method of a Text entry In-Reply-To: <1176414612.620268.200780@e65g2000hsc.googlegroups.com> References: <1176409717.585710.184960@y80g2000hsf.googlegroups.com> <1176414612.620268.200780@e65g2000hsc.googlegroups.com> Message-ID: <461F7D18.5070403@holdenweb.com> Chad wrote: > On Apr 12, 5:03 pm, James Stroud wrote: >> James Stroud wrote: >>> Chad wrote: >>>> I have a simple little program that brings up asks the user to enter a >>>> note, then is supposed to place that note into a text file when the >>>> user hits the submit button. However, when the user hits the submit >>>> button, absolutely nothing happens. IDLE doesn't give an error >>>> message and the note is not entered into the text file. For >>>> troubleshooting puposes, I wanted to see if IDLE would at least print >>>> the user's input; it doesn't do that either. Can someone please help >>>> me? [...] [James second-guesses himself twice] > > Thank you, that worked very well. > I thought it was particularly helpful of James to do the debugging for you without waiting for you to point out the errors in his first and second submissions. You just don't *get* help like that most places nowadays. 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 robert.kern at gmail.com Fri Apr 27 16:09:29 2007 From: robert.kern at gmail.com (Robert Kern) Date: Fri, 27 Apr 2007 15:09:29 -0500 Subject: Import Problems In-Reply-To: References: Message-ID: Bill Jackson wrote: > Once again, I am having issues with imports... > > Until now, I thought the general guidelines were to rarely use 'from x > import y' syntax, except when you really want to copy names over. No, the guideline is to not use "from x import *" except at the interactive prompt and occasionally in __init__.py's to "copy names over" as you put it. > However, I have run into issues by following this guideline. So... > > 1) What is going wrong in the example below? > 2) What is a good way to handle imports for packages w/subdirectories? > > Here is a sample directory structure: > > importtest/ > __init__.py > test2/ > __init__.py > someclass.py > mytest.py > > > Here are the definitions of the files: > > # importtest/__init__.py > from test2 import * > > # importtest/test2/__init__.py > from someclass import * > from test2 import * > > # importtest/test2/someclass.py > class SomeClass: > pass > > # importtest/test2/mytest.py > import importtest > print importtest.SomeClass > > > On import I get the following: > > >>> import importtest > Traceback (most recent call last): > File "", line 1, in ? > File "/home/user/lib/python/importtest/__init__.py", line 1, in ? > from test2 import * > File "/home/user/lib/python/importtest/test2/__init__.py", line 2, in ? > from mytest import * > File "/home/user/lib/python/importtest/test2/mytest.py", line 3, in ? > print importtest.SomeClass > AttributeError: 'module' object has no attribute 'SomeClass' > >>> > > > The problem seems to be an 'order' issue. importtest/test2/__init__.py > has loaded someclass.py, but it doesn't seem to have copied its contents > into importtest/__init__.py....perhaps it is because it hasn't finished > all of its imports. Is this correct? You are right that it is an order issue. The line "from test2 import *" hasn't finished executing by the time "print importtest.SomeClass" is executed because the former is trying to execute the latter. > So what is a good way to deal with this? In files which contain > implementations, I thought it was best not to use 'from x import y', but > this seems to be the only way to get this to work: My recommendation is that inside packages, be as specific as is feasible with your imports, even if you expose the symbols at a higher level for external callers. If you have a module whose contents are being exposed in your __init__.py, never rely on the contents of that __init__.py in that code. Instead, go straight to the real modules that implement the symbols that you need. So mytest.py should read: from importtest.test2.someclass import SomeClass print SomeClass or from importtest.test2 import someclass print someclass.SomeClass -- 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 lorenzo at diespammerhethurmans.com Sat Apr 7 17:29:18 2007 From: lorenzo at diespammerhethurmans.com (Lorenzo Thurman) Date: Sat, 07 Apr 2007 16:29:18 -0500 Subject: Mail not setting timestamp In-Reply-To: <1175973291.952880.78970@y80g2000hsf.googlegroups.com> References: <1175923152.762487.273780@n76g2000hsh.googlegroups.com> <1175973291.952880.78970@y80g2000hsf.googlegroups.com> Message-ID: <32fle4-mio.ln1@Hedley.internal.thethurmans.com> Gabriel Genellina wrote: > Lorenzo Thurman wrote: >> Gabriel Genellina wrote: >>> Lorenzo Thurman wrote: >>> >>>> I'm using the Mimewriter and mimetools modules to create html messages. >>>> They work OK, except that when the messages are received, they always >>>> have the timestamp of 12/31/1969. I've looked through both packages and >>>> >>> The date goes into the message headers, like From, To, Subject... >>> message.add_header("Date", "Thu, 22 Jun 2006 23:18:15 -0300") >>> >> Thanks for the reply. When I try this though, I get an error: >> AttributeError: 'datetime.datetime' object has no attribute 'split' >> I'm trying to use a variable for the date, since of course, it should >> always be 'now'. > > You have to convert the date into a string, using the right format. > The docs for the time module have a recipe: > http://www.python.org/doc/current/lib/module-time.html > (look for RFC 2822) > > -- > Gabriel Genellina > Got it! thx From marco.minerva at gmail.com Thu Apr 5 05:42:34 2007 From: marco.minerva at gmail.com (marco.minerva at gmail.com) Date: 5 Apr 2007 02:42:34 -0700 Subject: String manipulation In-Reply-To: References: <1175699768.427986.210310@l77g2000hsb.googlegroups.com> <1175702569.161940.113040@y66g2000hsf.googlegroups.com> Message-ID: <1175766154.893699.300250@l77g2000hsb.googlegroups.com> On 4 Apr, 21:47, Alexander Schmolck wrote: > marco.mine... at gmail.com writes: > > Thank you very much, your code works perfectly! > > One thing I forgot: you might want to make the whitespace handling a bit more > robust/general e.g. by using something along the lines of > > set_phrase.replace(' ', r'\w+') > > 'as Hi! Thanks again... But where must I insert this instruction? -- Marco Minerva, marco.minerva at gmail.com http://blogs.ugidotnet.org/marcom From duncan.booth at invalid.invalid Mon Apr 9 07:30:41 2007 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 9 Apr 2007 11:30:41 GMT Subject: Is there a simple function to generate a list like ['a', 'b', 'c', ... 'z']? References: <1176107364.000517.68580@q75g2000hsh.googlegroups.com> Message-ID: Michael Bentley wrote: > > On Apr 9, 2007, at 3:29 AM, ??????????????????????????????????????? > ?????? wrote: > >> Is there a simple function to generate a list like ['a', 'b', 'c', ... >> 'z']? The range() just can generate the numeric list. > > > import string > list(string.lowercase) > Be careful here. If you change locale that will return all lowercase letters not just 'a' to 'z'. For example: >>> import locale, string >>> locale.setlocale(locale.LC_ALL, '') 'English_United Kingdom.1252' >>> print string.lowercase abcdefghijklmnopqrstuvwxyz??????????????????????????????????????? >>> From mansonmuni at alexandria.cc Mon Apr 23 20:54:43 2007 From: mansonmuni at alexandria.cc (Glen) Date: Mon, 23 Apr 2007 19:54:43 -0500 Subject: Beginner: Simple Output to a Dialog PyQt4 References: <1e3a4$46296596$54d1d767$7184@news.chello.no> Message-ID: On Sat, 21 Apr 2007 03:15:00 +0200, David Boddie wrote: > On Tuesday 17 April 2007 07:42, Glen wrote: > # Just to avoid any misunderstanding: the form is actually stored as XML. # You can create C++ code with uic or Python code with pyuic4. Right. I do remember noticing that when I opened one of the .ui files. Thanks for the instructions. I'm tackling signals and slots next. I'll be reading your post a few times, I'm sure. For the time being, just to get myself off the ground and see some output, I imported my functions from cnt.py into my main with 'from cnt import cnt'. Then I passed my QTextEdit object into my python code and output the contents of my file with: f = file("filename", 'r') for line in f: QTxtObj.insertPlainText(line) Maybe you could point out some problems with doing it this way, but I'm at the point now where I have to learn how to handle signals and slots. I'm setting up an input dialog with several options, such as download a URL, choose an existing file. Your information will come in handy. Glen > >> [quoted text muted] > > OK. Ideally, your window will contain a button (or some other control) > that the user can click to execute the functions. > >> [quoted text muted] > > If, for example, you included a push button (QPushButton) in the form > you created with Qt Designer, and called it executeButton, you could > connect its clicked() signal to a function in cnt by including the > following line after setting up the user interface: > > window.connect(ui.executeButton, SIGNAL("clicked()"), cnt.myFunction) > > This assumes that your function is called myFunction(), of course. > However, you wouldn't be able to get the output from this function back > to the dialog just by using a signal-slot connection like this. > > One way to solve this would be to wrap the function using another > function or instance that is able to modify the contents of the dialog. > Another cleaner approach would be to subclass the user interface class > (Ui_Dialog) and implement a custom slot that can both call the function > and modify the dialog. > > For example: > > class Dialog(QDialog, Ui_Dialog) > > def __init__(self, parent = None): > > QDialog.__init__(self, parent) > self.setupUi(self) > > self.connect(self.executeButton, SIGNAL("clicked()"), > self.callFunction) > > def callFunction(self): > > data = cnt.myFunction() > # Do something with the data. > > Hope this gets you started, > > David From bdesth.quelquechose at free.quelquepart.fr Wed Apr 11 16:57:05 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Wed, 11 Apr 2007 22:57:05 +0200 Subject: Nested dictionaries trouble In-Reply-To: <1176317876.917874.58040@n59g2000hsh.googlegroups.com> References: <1176317876.917874.58040@n59g2000hsh.googlegroups.com> Message-ID: <461d427e$0$18058$426a74cc@news.free.fr> IamIan a ?crit : > Hello, > > I'm writing a simple FTP log parser that sums file sizes as it runs. I > have a yearTotals dictionary with year keys and the monthTotals > dictionary as its values. The monthTotals dictionary has month keys > and file size values. The script works except the results are written > for all years, rather than just one year. I'm thinking there's an > error in the way I set my dictionaries up or reference them... > > import glob, traceback > > years = ["2005", "2006", "2007"] > months = ["01","02","03","04","05","06","07","08","09","10","11","12"] > # Create months dictionary to convert log values > logMonths = > {"Jan":"01","Feb":"02","Mar":"03","Apr":"04","May":"05","Jun":"06","Jul":"07","Aug":"08","Sep":"09","Oct":"10","Nov":"11","Dec":"12"} DRY violation alert ! logMonths = { "Jan":"01", "Feb":"02", "Mar":"03", "Apr":"04", "May":"05", #etc } months = sorted(logMonths.values()) > # Create monthTotals dictionary with default 0 value > monthTotals = dict.fromkeys(months, 0) > # Nest monthTotals dictionary in yearTotals dictionary > yearTotals = {} > for year in years: > yearTotals.setdefault(year, monthTotals) A complicated way to write: yearTotals = dict((year, monthTotals) for year in years) And without even reading further, I can tell you have a problem here: all 'year' entry in yearTotals points to *the same* monthTotal dict instance. So when updating yearTotals['2007'], you see the change reflected for all years. The cure is simple: forget the monthTotals object, and define your yearTotals dict this way: yearTotals = dict((year, dict.fromkeys(months, 0)) for year in years) NB : for Python versions < 2.4.x, you need a list comp instead of a generator expression, ie: yearTotals = dict([(year, dict.fromkeys(months, 0)) for year in years]) HTH From hlubenow2 at gmx.net Tue Apr 10 11:50:11 2007 From: hlubenow2 at gmx.net (hlubenow) Date: Tue, 10 Apr 2007 17:50:11 +0200 Subject: Check for keypress on Linux xterm ? References: <131m56dsgr7or38@corp.supernews.com> Message-ID: Grant Edwards wrote: > On 2007-04-09, hlubenow wrote: > >> My problem is, I don't want my program to wait for the keypress. >> I just want to check, if a key is currently pressed and if not, I'd like >> to continue with my program (like "INKEY$" in some BASIC-dialects). > > The answer to this frequently asked question is actually in the FAQ: > > http://www.python.org/doc/faq/library.html#how-do-i-get-a-single-keypress-at-a-time > > Google finds us further examples: > > http://mail.python.org/pipermail/pythonmac-sig/2004-February/010140.html > http://mail.python.org/pipermail/python-list/2000-June/041251.html > I see now, you're right. Sorry. From facundo at taniquetil.com.ar Wed Apr 4 20:09:52 2007 From: facundo at taniquetil.com.ar (Facundo Batista) Date: Thu, 5 Apr 2007 00:09:52 +0000 (UTC) Subject: string templates References: <1235142.VYMsP3if9A@teancum> Message-ID: David Bear wrote: > I was justing wondering how safe python string templates are to use with > unicode. I was just scanning pep 292 and it seems to say that they are -- > or can by with inheritance... but I don't quite understand. What do you mean with "safe"? I use string.Template a lot, don't worrying about unicode (it just works) and never got hurt... Regards, -- . Facundo . Blog: http://www.taniquetil.com.ar/plog/ PyAr: http://www.python.org/ar/ From rehceb at no.spam.plz Sat Apr 7 14:09:30 2007 From: rehceb at no.spam.plz (Rehceb Rotkiv) Date: Sat, 07 Apr 2007 13:09:30 -0500 Subject: Unicode problem Message-ID: Please have a look at this little script: #!/usr/bin/python import sys import codecs fileHandle = codecs.open(sys.argv[1], 'r', 'utf-8') fileString = fileHandle.read() print fileString if I call it from a Bash shell like this $ ./test.py testfile.utf8.txt it works just fine, but when I try to pipe the output to another process ("|") or into a file (">"), e.g. like this $ ./test.py testfile.utf8.txt | cat I get an error: Traceback (most recent call last): File "./test.py", line 6, in ? print fileString UnicodeEncodeError: 'ascii' codec can't encode character u'\xe4' in position 538: ordinal not in range(128) I absolutely don't know what's the problem here, can you help? Thanks, Rehceb From howachen at gmail.com Wed Apr 18 22:39:52 2007 From: howachen at gmail.com (howa) Date: 18 Apr 2007 19:39:52 -0700 Subject: Compiling python from soruce vs RPM ? In-Reply-To: <1176934250.650536.239040@p77g2000hsh.googlegroups.com> References: <1176911689.026633.230390@l77g2000hsb.googlegroups.com> <1176934250.650536.239040@p77g2000hsh.googlegroups.com> Message-ID: <1176950392.192425.90980@b58g2000hsg.googlegroups.com> On Apr 19, 6:10 am, Paul Boddie wrote: > > Since /usr/bin/python isn't found, it doesn't look like there's an > existing version of Python that you might overwrite, but it's > important to verify such things when installing software. That's where > your distribution's packages have an advantage, and it's arguably a > better idea to install such packages instead, possibly building them > from source if no binary packages exist yet for Python 2.5. (If no > source packages exist, you have a bit more work to do.) > > Paul Thanks. One more question: How to uninstall using the source package? the source package doesn't come with `make uninstall`? From nogradi at gmail.com Thu Apr 12 19:16:28 2007 From: nogradi at gmail.com (Daniel Nogradi) Date: Fri, 13 Apr 2007 01:16:28 +0200 Subject: Binary To File In-Reply-To: <695408014765593209@unknownmsgid> References: <695408014765593209@unknownmsgid> Message-ID: <5f56302b0704121616n1d3e05dfv2e5fbb4fe4d3fc6e@mail.gmail.com> > Is there an easy way to take binary data and build it into a file? Generally > this will be BLOB data drawn from a database, the data will be for jpg > images, I want to take the blob data and build it into a physical .jpg file. > > > > Is there a simple function for doing this in python? Like binary2file() or > something along those lines? myblob = ......... # let's say you got it from your database somehow myjpeg = open( 'image.jpg', 'w' ) myjpeg.write( myblob ) myjpeg.close( ) Daniel From aboudouvas at panafonet.gr Thu Apr 19 06:30:17 2007 From: aboudouvas at panafonet.gr (king kikapu) Date: 19 Apr 2007 03:30:17 -0700 Subject: About installing new Python version. In-Reply-To: <1176977440.265263.186450@n76g2000hsh.googlegroups.com> References: <1176973387.967130.27370@y80g2000hsf.googlegroups.com> <1176975545.693682.51870@q75g2000hsh.googlegroups.com> <1176976568.438207.253120@d57g2000hsg.googlegroups.com> <1176977440.265263.186450@n76g2000hsh.googlegroups.com> Message-ID: <1176978617.299033.37250@n59g2000hsh.googlegroups.com> On Apr 19, 12:10 pm, Ant wrote: > > checked and everything seems to working fine. But this is an update > > release to 2.5, i do not know what is happening when, for example, a > > totally new Python version come out, like 2.6 or 2.7 or... > > Again just install it - it will by default install alongside Python > 2.5 in a different directory, and set itself as the default python > version. You'll then need to update all your third party extensions to > ones compiled against the new version - so if you have a lot of these, > it makes sense to wait a while before upgrading. > > -- > Ant. Hmm...ok, i was sure that i wouldn't avoid that...The nice thing is that 2.5.1 installed in default directory so no problem for now. Thanks! From cousinstanley at hotmail.com Thu Apr 12 03:53:58 2007 From: cousinstanley at hotmail.com (Cousin Stanley) Date: Thu, 12 Apr 2007 02:53:58 -0500 Subject: Connection problems with irclib References: Message-ID: <1176364438_1265@sp12lax.superfeed.net> > Hi. I've written a bot in python, > using the irclib by Joel Rosdahl. > > Works fine from my linux box at home, > but when I upload it to my shell > at veritynet.net, can't seem to get it > to connect to an irc server. > > It doesn't report any errors. > > Anyone have any idea how I might go about > at least diagnosing the problem? > > Any suggestions might help. Dropkick P .... For a bit of inspiration you might take a look at Supybot which is a Python-based irc bot .... http://supybot.com It's designed to run from your local machine and connect to a remote irc server .... I ran it from home 24/7 with virtually no problems at all for several months from a very modest and old Compaq box running Debian Gnu/Linux Sarge which connected via aDSL .... A brief description from the Debian package manager .... robust and user friendly Python IRC bot Supybot is a robust (it doesn't crash), user friendly (it's easy to configure) and programmer friendly (plugins are *extremely* easy to write) Python IRC bot. It aims to be an adequate replacement for most existing IRC bots. It includes a very flexible and powerful ACL system for controlling access to commands, as well as more than 50 builtin plugins providing around 400 actual commands. -- 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 kyosohma at gmail.com Tue Apr 24 10:41:38 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: 24 Apr 2007 07:41:38 -0700 Subject: getting scancodes In-Reply-To: References: Message-ID: <1177425698.117905.250460@t39g2000prd.googlegroups.com> On Apr 23, 7:39 pm, andma... at gmail.com wrote: > Anyone knows if its possible to get scan codes ??? > I tried with getch () but with no success, just keycodes. > May be using the something in the sys.stdin module ?? > > Pleasee, any help would be very appreciated. > > -- > Andr?s M. > --------------------------------------------- > .--. > |o_o | > |:_/ | > // \ \ > (| | ) > /'\_ _/`\ > \___)=(___/ > --------------------------------------------- Looks like there's a thread from 2003 on this subject. Check it out here: http://www.thescripts.com/forum/thread20311.html Mike From ceball at gmail.com Wed Apr 18 03:33:24 2007 From: ceball at gmail.com (Chris) Date: 18 Apr 2007 00:33:24 -0700 Subject: Strange terminal behavior after quitting Tkinter application Message-ID: <1176881604.574369.77230@b58g2000hsg.googlegroups.com> Hi, I'm puzzled by some strange behavior when my Python/Tkinter application quits (on linux): the terminal from which I started Python is messed up. If start up python, then import the code below, then start the program with Application(), then click the Quit button, my terminal never prints anything again (such as commands I type). import Tkinter import sys class Application(Tkinter.Tk): def __init__(self,**config): Tkinter.Tk.__init__(self,**config) Tkinter.Button(self,text="Quit",command=self.quit_application).pack() def quit_application(self): sys.exit() Can anyone tell me what I'm doing wrong? Thanks for your help. Chris From carsten at uniqsys.com Fri Apr 13 09:09:03 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Fri, 13 Apr 2007 09:09:03 -0400 Subject: Arrays, Got Me Confused In-Reply-To: <001c01c77dca$67232210$35696630$@rawlins@thinkbluemedia.co.uk> References: <000101c77dc3$d4152a00$7c3f7e00$@rawlins@thinkbluemedia.co.uk> <461F7712.2040201@timgolden.me.uk> <001c01c77dca$67232210$35696630$@rawlins@thinkbluemedia.co.uk> Message-ID: <1176469743.3428.9.camel@dot.uniqsys.com> On Fri, 2007-04-13 at 13:50 +0100, Robert Rawlins - Think Blue wrote: > Hello Guys, > > Wider fragments of code don't really exists at this moment in time :-D this > is just a bit of a 'tester' class for me to get used to the methods. > Basically I'm trying to create a class that contains an array of MAC > address, these look something like this 'FD:E4:55:00:FG:A9. I want the class > to have the following methods for easy manipulation of the array. > > addDevice(Address) - Pass in the MAC address and have it add it to the > array. > > removeDevice(Address) - Finds a device with that address in the array and > removes it. > > isFirewalled(Address) - looks for that address in the array and returns > true/false dependant on whether it finds it. > > Clear() - empty the array of all its contents. Unless your class is going to grow more hair than what you specify above, such as the ability to specify ranges of addresses, I think you'll want to use a set. See http://docs.python.org/lib/types-set.html HTH, Carsten. From laurent.pointal at limsi.fr Fri Apr 27 07:32:21 2007 From: laurent.pointal at limsi.fr (Laurent Pointal) Date: Fri, 27 Apr 2007 13:32:21 +0200 Subject: How to find complementary colour for pixel In-Reply-To: References: <1177578583.205643.65200@r35g2000prh.googlegroups.com> Message-ID: Steven D'Aprano a ?crit : > I shouldn't think so... I always forget if black is all ones or all > zeroes, so I checked here: http://www.pitt.edu/~nisg/cis/web/cgi/rgb.html For this I use the mnemotechnics idea of "chromatic coil" [*], when there are *all* colors turning it appear to be *white*. And *no* color is then *black*. [*] Babelfish translation for french "roue chromatique" From kyosohma at gmail.com Mon Apr 30 10:17:11 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: 30 Apr 2007 07:17:11 -0700 Subject: tkinter undo In-Reply-To: References: Message-ID: <1177942631.590817.110330@n76g2000hsh.googlegroups.com> On Apr 28, 8:50 am, Gigs_ wrote: > Hi > > I dont have idea how to write tkinter undo/redo function form my text editor and > my paint program. > Could someone help? I'm not asking for code, just for some guidelines to get me > in the right way. > > thanks >From what I've read, the Tkinter Text widget has an unlimited undo/ redo function built into it. If you use it for text editing, you shouldn't need to worry about it. If you want to do it yourself, I would recommend reading the code behind that widget or reading the code behind IDLE itself. Mike From paddy3118 at googlemail.com Wed Apr 11 17:54:16 2007 From: paddy3118 at googlemail.com (Paddy) Date: 11 Apr 2007 14:54:16 -0700 Subject: text file vs. cPickle vs sqlite a design question In-Reply-To: References: Message-ID: <1176328456.026570.43220@y80g2000hsf.googlegroups.com> On Apr 11, 5:40 pm, Dag wrote: > I have an application which works with lists of tuples of the form > (id_nr,'text','more text',1 or 0). I'll have maybe 20-50 or so of these > lists containing anywhere from 3 to over 30000 tuples. The actions I > need to do is either append a new tuple to the end of the list, display > all the tuples or display all the tuples where the last element is a 1 > > Basically what I'm wondering is the best way to store these data stuctures > to disc. As the subject mentioned I've basically got three approaches. > Store each list as a text file, pickle each list to file or shove the > whole thing into a bunch of database tables. I can see pros and cons > with each approach. Does anybody have any advice as to whether any of > these approaches is obviously better than any other? On one hand I like > the text file approach since it lets me append without loading > everything into memory, on the other hand the sqlite approach makes it > easy to select stuff with SELECT * FROM foo WHERE... which could be > handy if ever need to add more advanced filtering. > > Dag If you have enough resources to keep all the lists comfortably in memory, and you have enough disk space then I would save your data as python text. Something like: print "# " print "all_lists = []" for i,l in enumerate(all_lists): print "all_lists.append( [ #", i for tpl in l: print " ", tpl, "," print " ]) #", i You would then have your data saved in a format that could easily be re-used by other programs at a later date, and that can be examined in any text editor. - Paddy. From bbxx789_05ss at yahoo.com Sat Apr 14 15:06:14 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: 14 Apr 2007 12:06:14 -0700 Subject: reading from sys.stdin In-Reply-To: References: <1176366058.261031.111870@p77g2000hsh.googlegroups.com> <1176387908.406115.270630@w1g2000hsg.googlegroups.com> <1176438754.995753.50190@d57g2000hsg.googlegroups.com> <1176454871.538968.176620@n76g2000hsh.googlegroups.com> <1176457007.589050.285400@d57g2000hsg.googlegroups.com> <1176538930.891355.230880@n59g2000hsh.googlegroups.com> Message-ID: <1176577574.338733.325790@n59g2000hsh.googlegroups.com> On Apr 14, 7:43 am, Steve Holden wrote: > 7stud wrote: > > On Apr 13, 6:20 am, Michael Hoffman wrote: > [...] > > > But if you hit return on a blank line, there is no error. In other > > words, will stop on a blank line and not return EOFError. > > > Anyway, it seems everyone is saying that when you iterate over a file, > > the whole file is first read into memory. Therefore iterating over > > sys.stdin is consistent: you have to type Ctrl+D to signal EOF before > > the iteration can start. Is that about right? > > No. The file content is usually buffered, but the buffering doesn't > necessarily include the whole content of the file. > > If you are iterating over the file the correct way to access the next > line is to call the file's .next() method, as I indicated before. > > If you are reading lines the appropriate way is to use readline(). > > And, as you have already seen an error message telling you, mixing the > two types is unlikely to give you usable results. > > 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 Does iterating over stdin work the same way? If one were to type in enough lines to fill the buffer would iteration begin before entering EOF with Ctrl+D? From sjmachin at lexicon.net Sun Apr 15 08:36:48 2007 From: sjmachin at lexicon.net (John Machin) Date: 15 Apr 2007 05:36:48 -0700 Subject: OverflowError: mktime argument out of range ??? In-Reply-To: References: <11e49df10704150341p1a9056e7hfba36a523517fad3@mail.gmail.com> Message-ID: <1176640607.972087.153470@o5g2000hsb.googlegroups.com> On Apr 15, 8:48 pm, Michael Bentley wrote: > On Apr 15, 2007, at 5:41 AM, Jorgen Bodde wrote: > > > This is what I try: > > >>>> time.mktime((1928, 12,28, 0, 0, 0, 0, 0, 0)) > > Traceback (most recent call last): > > File "", line 1, in > > OverflowError: mktime argument out of range > > Probably depends on your system. Maybe it does. It sure would be nice to get a definite answer. Pity nobody documented the time module. Oh yeah, and the secret closed-shop source code -- damnation! Anyone got a bootleg pirate copy of timemodule.c lying around anywhere? > It doesn't break for me: Please consider the possibility that it didn't break for the OP either. > > >>> import time > >>> time.mktime((1928, 12,28, 0, 0, 0, 0, 0, 0)) > -1294164000.0 > > --- > Simplicity is the ultimate sophistication. > -Leonardo da Vinci From jmcbray-usenet at carcosa.net Sat Apr 7 08:55:04 2007 From: jmcbray-usenet at carcosa.net (Jason F. McBrayer) Date: Sat, 07 Apr 2007 08:55:04 -0400 Subject: Hide the python-script from user References: <8ktie4-0i9.ln1@athlon.my> <1175898877.869321.112310@w1g2000hsg.googlegroups.com> <7ovie4-nfa.ln1@athlon.my> Message-ID: hlubenow writes: > Ok, but now I can offer a real secure solution: Nope. [snip] > Then you have to program a start-script, that reads in your script and the > decryption-key. The decryption-key must be encrypted too. Such a encrypted > key can be generated by the modules if you don't pass a password to my > function "doEncrypt(). The decryption-key must then be hidden somewhere > within the encrypted program-script. That's because, if the user knows > where to find the key, he can decrypt the program-script. > > If your start-script is written, everything should work automatically, one > shouldn't nearly notice the decryption-process. That is to say, for the user to be able to run your program, they must have the key. They don't have to know they have the key, but they have to have it. This isn't really secure, it's just obscure. It depends on the user not finding the key, and on no one telling them where it is. A determined and technically savvy user will surely find the key (not least by debugging the start-script). Basically, this doesn't work for the same reason that DRM doesn't work. -- +-----------------------------------------------------------+ | Jason F. McBrayer jmcbray at carcosa.net | | If someone conquers a thousand times a thousand others in | | battle, and someone else conquers himself, the latter one | | is the greatest of all conquerors. --- The Dhammapada | From richardjones at optushome.com.au Wed Apr 25 21:16:54 2007 From: richardjones at optushome.com.au (Richard Jones) Date: Thu, 26 Apr 2007 11:16:54 +1000 Subject: Another Python Game Programming Challenge concludes References: <462F7688.2020300@vpcit.ru> Message-ID: <462ffd86$0$5748$afc38c87@news.optusnet.com.au> Terry Reedy wrote: > "???? ???" wrote in message > news:462F7688.2020300 at vpcit.ru... > | The fourth Python Game Programming Challenge (PyWeek) has now concluded > | with > | judges (PyWeek being peer-judged) declaring the winners: > | > | Individual: Which way is up? by Hectigo > | http://www.pyweek.org/e/Hectic/ > | > | Team: Bubble Kong by The Olde Battleaxe > | http://www.pyweek.org/e/toba4/ > > 404 Not found > > Ditto for links on rating page. Yeah, sorry, terribly bad timing means the site is being migrated to a new host right at the moment. I hope to have it back up and running ASAP. Richard From python-url at phaseit.net Wed Apr 11 00:15:48 2007 From: python-url at phaseit.net (Cameron Laird) Date: Wed, 11 Apr 2007 04:15:48 +0000 (UTC) Subject: Python-URL! - weekly Python news and links (Apr 11) Message-ID: QOTW: "Dictionaries are one of the most useful things in Python. Make sure you know how to take adavantage of them..." - Jeremy Sanders "Python has consistently failed to disappoint me." - Tal Einat "super() only works on new-style classes ..." and "has its own set of gotchas": http://groups.google.com/group/comp.lang.python/msg/f44c8c09e1593dcf Yes, there certainly *are* times that connection to a terminal makes a difference. There also are ways to control that difference: http://groups.google.com/group/comp.lang.python/browse_thread/thread/b5975d27da432e92/ Michael Bentley reports satisfaction with Wing IDE's ability to debug multithreading Python: http://groups.google.com/group/comp.lang.python/msg/f44c8c09e1593dcf Does Python know about such matters as '>' ('>')? Sure: just "import htmlentitydefs": http://groups.google.com/group/comp.lang.python/browse_thread/thread/7f96723282376f8c/ http://groups.google.com/group/comp.lang.python/browse_thread/thread/d09417aedc1b807b/ ======================================================================== 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 should get through. To receive a new issue of this posting in e-mail each Monday morning (approximately), ask 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 mangabasi at gmail.com Wed Apr 4 19:28:58 2007 From: mangabasi at gmail.com (Mangabasi) Date: 4 Apr 2007 16:28:58 -0700 Subject: Calling Fortran from Python In-Reply-To: References: <1175640339.648190.207530@y66g2000hsf.googlegroups.com> <1175685841.847487.173440@w1g2000hsg.googlegroups.com> <1175718204.410453.29510@q75g2000hsh.googlegroups.com> <1175726427.114890.7990@y80g2000hsf.googlegroups.com> Message-ID: <1175729338.287712.305870@e65g2000hsc.googlegroups.com> On Apr 4, 5:48 pm, Robert Kern wrote: > Mangabasi wrote: > > Would Python 2.5 work with Visual Studio 6.6? > > No. > > -- > 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 I will try the GCC then. It is a shame that I could not get calldll to work. It was very simple to use. I think I am making a mistake with the argument types but not sure. Thanks for your help, it is greatly appreciated. From wangday at gmail.com Sun Apr 8 06:36:03 2007 From: wangday at gmail.com (lancered) Date: 8 Apr 2007 03:36:03 -0700 Subject: Newbie Question about sequence multiplication In-Reply-To: <6cOdnVFCLMXxuYnbnZ2dnUVZ_rCsnZ2d@comcast.com> References: <6cOdnVFCLMXxuYnbnZ2dnUVZ_rCsnZ2d@comcast.com> Message-ID: <1176028563.566089.237110@b75g2000hsg.googlegroups.com> On Apr 5, 12:19 am, "Scott" wrote: > Alright, so I've been trying to teach myself Python which, when compared to > my attempt to learn C++, is going pretty well. > But I've come across an issue that I can't figure out, so I figured I'd ask > the pro's. > > Now it looks pretty weird in this format but it was copied exactly from IDLE > > *****code follows******* > > #What this program is suppose to do is print a sentence centered in a box > > sentence = raw_input('Sentence: ') > > screen_width = 80 > text_width = len(sentence) > box_width = text_width + 6 > left_margin = (screen_width - box_width) // 2 > > print > print ' ' * left_margin + '+' + '-' * (box_width-2) + '+' > print ' ' * left_margin + '| ' + ' ' * text_width + ' |' > print ' ' * left_margin + '| ' + ' ' sentence + ' |' > print ' ' * left_margin + '| ' + ' ' * text_width + ' |' > print ' ' * left_margin + '+' + '-' * (box_width-2) + ' |' > print > > ****end code**** > > Now that, even though copied straight from "Beginning Python: From Novice to > Professional", returns : > There's an error in your program: invalid syntax > > with the word sentence highlighted (not the sentence when I'm defining the > name, the one in......uhm....the body of the code) > > Now if i put * before sentence as it is with the rest of the variables, it > actually gets to the point where it asks me for the sentence, but after > inputting my sentence I receive: > Traceback (most recent call last): > File "D:/Programming/Python/sequence string multiplication example", line > 16, in > print ' ' * left_margin + '| ' + ' ' * sentence + ' |' > TypeError: can't multiply sequence by non-int of type 'str' > > Why can't I get it to do what it's supposed to do? What am I > missing/misunderstanding? > Very simply all its supposed to do is something like this (now bear with me > formating might distort this a bit lol) > +------------------------------------+ > | | > | Like This | > | | > +------------------------------------+ > > Any help would be greatly appreciated > > -Scott I modified the codes a little bit to get it running, and give the correct alignment. Just as a reference for you. Here is it: ********************************************* sentence = raw_input('Sentence: ') screen_width = 80 text_width = len(sentence) box_width = text_width + 6 left_margin = (screen_width - box_width) /2 print print ' ' * left_margin + '+' + '-' * (box_width-2) + '+' print ' ' * left_margin + '|' + ' ' * (box_width-2) + '|' print ' ' * left_margin + '|' + ' '*2+sentence +' '*2+ '|' print ' ' * left_margin + '|' + ' ' * (box_width-2) + '|' print ' ' * left_margin + '+' + '-' * (box_width-2) + '+' print **************************************************** From henriklied at gmail.com Thu Apr 5 17:36:28 2007 From: henriklied at gmail.com (Henrik Lied) Date: 5 Apr 2007 14:36:28 -0700 Subject: Problems with os.spawnv In-Reply-To: <1175808803.379481.62290@l77g2000hsb.googlegroups.com> References: <1175807996.524018.146070@n76g2000hsh.googlegroups.com> <1175808803.379481.62290@l77g2000hsb.googlegroups.com> Message-ID: <1175808988.605801.185630@n76g2000hsh.googlegroups.com> On Apr 5, 11:33 pm, kyoso... at gmail.com wrote: > On Apr 5, 4:19 pm, "Henrik Lied" wrote: > > > > > Hi there! > > > I'm trying to convert a video in a background process. > > The scenario I'm after: > > 1. The user uploads a video > > 2. The video is saved in my media directory, and the database is > > populated with the references > > 3. The video gets converted to FLV - but the user shouldn't have to > > wait around for this to happen > > > So, I thought to myself that spawnv would be a good fit for this. The > > problem is that it doesn't fire of the command. > > > Here's my test script:http://dpaste.com/hold/7981/ > > > Why won't this work? The while-loop is printed, but the os command > > isn't executed. I've also tried to specify the whole path to mencoder > > (/opt/local/bin/mencoder), but to no use. > > I don't know what the deal is. Maybe you should try the subprocess > module since it replaces the os.spawn* modules and do a > subprocess.Popen instead? Or don't assign the result to a variable > since you told it not to wait. You may need to do a combination of the > subprocess module and one of the Threading modules. > > Mike Thanks for the quick reply, Mike! I've taken a look at the Subprocess module, but it's all a bit new to me, if you know what I mean. You wouldn't be able to supply me with an example, would you? Thanks! From aleax at mac.com Mon Apr 2 11:02:51 2007 From: aleax at mac.com (Alex Martelli) Date: Mon, 2 Apr 2007 08:02:51 -0700 Subject: Sorting a multidimensional array by multiple keys References: <1hvww1d.1k8ozo312a7yazN%aleax@mac.com> <4vydnSCXtPBrkIzbnZ2dnUVZ_szinZ2d@comcast.com> Message-ID: <1hvxnjh.1ie4bhk1yrx0aqN%aleax@mac.com> Steven Bethard wrote: > Thomas Kr?ger wrote: > > Alex Martelli schrieb: > >> Thomas Kr?ger wrote: > >>> def sorter(a, b): > >>> return cmp(a.id, b.id) > >>> > >>> obj_lst.sort(sorter) > >> A MUCH better way to obtain exactly the same semantics would be: > >> > >> def getid(a): > >> return a.id > >> > >> obj_list.sort(key=getid) > > > > Frankly speaking the purpose of the example was to show how to pass a > > function as argument for the sort method. > > Your code may be more efficient but it explains something different. > > Yes, but there's almost never a reason to use the cmp= argument to > sort() anymore. It's almost always better to use the key= argument. Exactly. Passing a "comparison function" rather than a key-extraction function is rarely a good idea -- except for some extremely complicated cases involving e.g. certain string (or more complicated) fields needing to be sorted in the reverse direction from others. In practice, the existence of that argument and its prominent position as the first positional argument is due entirely to backwards compatibility issues. Alex From robert.rawlins at thinkbluemedia.co.uk Fri Apr 13 08:04:02 2007 From: robert.rawlins at thinkbluemedia.co.uk (Robert Rawlins - Think Blue) Date: Fri, 13 Apr 2007 13:04:02 +0100 Subject: Arrays, Got Me Confused Message-ID: <000101c77dc3$d4152a00$7c3f7e00$@rawlins@thinkbluemedia.co.uk> Hello Guys, I'm struggling to get my head into arrays in python, I've used them plenty in other languages but I'm struggling to find any decent documentation for them in python. I'm looking to build a list of network MAC address's into an array, which will probably be used for logging and firewalling and things. I've build the basic class, the idea is that the class represents the firewall, and I have functions for the firewall like addDevice() and isFirewalled() where I pass in the address and it returns a value or updates the array. However I'm getting an error when trying to create an empty array on the init. #!/usr/bin/python # Filename: Firewall.py class Firewall: def __init__(self): Self.FireArray = array(c) p = Firewall() print p Throws: Traceback (most recent call last): File "./firewall.py", line 9, in ? p = Firewall() File "./firewall.py", line 7, in __init__ Self.FireArray = array(c) NameError: global name 'array' is not defined How can I solve this problem? From what I've seen writing I can't see anything wrong with my syntax, perhaps you can shed some light on the situation. Whilst I'm writing there is also another question I would like to pose briefly. How do a create an object from an external file? Obviously in my one above all I need do is call Firewall() and it creates an instance, but I'm used to creating my class's as separate files, how do I create them as an object in my main application? Thanks, Rob -------------- next part -------------- An HTML attachment was scrubbed... URL: From anton.vredegoor at gmail.com Fri Apr 20 13:23:29 2007 From: anton.vredegoor at gmail.com (Anton Vredegoor) Date: Fri, 20 Apr 2007 19:23:29 +0200 Subject: multirember&co In-Reply-To: References: <1176768854.720234.23320@w1g2000hsg.googlegroups.com> <1176790588.024371.119360@n76g2000hsh.googlegroups.com> <1176850352.999231.79260@n59g2000hsh.googlegroups.com> <1176921030.330467.76860@o5g2000hsb.googlegroups.com> <1176925857.535835.130010@b58g2000hsg.googlegroups.com> <1177010211.252779.83620@y5g2000hsa.googlegroups.com> <1177025176.943890.252910@b75g2000hsg.googlegroups.com> Message-ID: Anton Vredegoor wrote: > def xsplitter(seq, pred): > Q = deque(),deque() > it = iter(seq) > def gen(p): > for x in it: > Q[pred(x) == p].append(x) > while Q[p]: yield Q[p].popleft() > while Q[p]: yield Q[p].popleft() > return gen(1),gen(0) This should be: def xsplitter(seq, pred): Q = deque(),deque() it = iter(seq) def gen(p): for x in it: Q[pred(x)].append(x) while Q[p]: yield Q[p].popleft() while Q[p]: yield Q[p].popleft() return gen(1),gen(0) But I'm still not sure if this is the desired function. Is it normal for people to start replying to their own messages when they're studying coroutines? A From howe.steven at gmail.com Wed Apr 4 20:19:35 2007 From: howe.steven at gmail.com (Steven Howe) Date: Wed, 04 Apr 2007 17:19:35 -0700 Subject: how can I clear a dictionary in python In-Reply-To: References: <1175121525.261424.72350@n76g2000hsh.googlegroups.com> Message-ID: <46144097.3060108@gmail.com> Tempest in a teapot guys. Aahz wrote: > In article , > Antoon Pardon wrote: > >> On 2007-04-03, Aahz wrote: >> >>> In article , >>> Larry Bates wrote: >>> >>>> 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. >>>> >>> Then you should explain why you didn't answer the question that was >>> asked. Answering a different question without explanation makes your >>> answer irrelevant at best, wrong at worst. >>> >> This is not true. If this different question was in fact the intended >> question instead of the one actually asked. Anwering this different >> question can be more usefull than answering the one actually asked. >> > > Note carefully that I did not say, "Don't answer the question you think > should have been asked." What I said was, "If you answer a different > question, EXPLAIN WHY." Is that so difficult to understand? > From bbxx789_05ss at yahoo.com Sun Apr 15 22:53:51 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: 15 Apr 2007 19:53:51 -0700 Subject: pyparsing Catch-22 In-Reply-To: References: <1176686782.270354.164630@l77g2000hsb.googlegroups.com> Message-ID: <1176692031.142326.134710@y80g2000hsf.googlegroups.com> On Apr 15, 7:41 pm, Steven Bethard wrote: > 7stud wrote: > > For as hard as you push pyparsing on this forum, I would think you > > would make it easier to download and install your module. In my > > opinion, the wiki should provide detailed installation instructions > > for all supported os's, and the sourceforge downloading process is too > > complicated. > > FWIW, here's what works for me:: > > * Go tohttp://pyparsing.wikispaces.com/ > * Click the link at the top that says "Download from SourceForge" > * Click the big green "Download Python parsing module" button > * Click the big green "Download" button next to "pyparsing-1.4.6" > * Click pyparsing-1.4.6.tar.gz > * Extract the dowloaded .tar.gz > * Use the standard python installation idiom "python setup.py install" > > If you're not familiar with the standard Python installation idiom, take > a few minutes to read: > > "Installing Python Modules"http://docs.python.org/inst/inst.html > > In particular it starts with "The new standard: Distutils", which tells > you to try:: > > python setup.py install > > HTH, > > STeVe Thanks! I thought I would write down what I did in case someone else looks this up: 1) Even though the download at sourceforge said the file name was: pyparsing-1.4.6.tar.gz it was downloaded to my Desktop as: pyparsing-1.4.6.tar Did os x 10.4.7 automatically unzip it for me? .gz means the file was compressed with gzip, but I didn't have to do any unzipping. 2) Apparently, a .tar file is not a compressed file--it just organizes a bunch of files into one big file or "archive". You still need to do something to extract all the files from the archive. Here is the command: $ tar -xvf /Users/me/Desktop/pyparsing-1.4.6.tar That command extracts the contents into the current directory(i.e. the directory the prompt is pointing to), which can overwrite files with the same names. So I created a directory called tar_temp: /Users/me/tar_temp and used the cd command to change the prompt to that directory. (Note: the ~ prompt is shorthand for /Users/YourHomeDirName) 3) To run: python setup.py install, you need to get to the top level directory of the download. So, I cd'ed to the directory: ~/tar_temp/pyparsing-1.4.6 and then ran the setup command: ~/tar_temp/pyparsing-1.4.6$ python setup.py install I tested the setup by running the hello world program described in the document: ~/tar_temp/pyparsing-1.4.6/HowToUsePyparsing.html and it worked. From jowr.pi at gmail.com Sat Apr 28 12:56:48 2007 From: jowr.pi at gmail.com (Eric Gisse) Date: 28 Apr 2007 09:56:48 -0700 Subject: Video: Professor of Physics Phd at Cal Tech says: 911 Inside Job In-Reply-To: <1177778685.506101.201540@h2g2000hsg.googlegroups.com> References: <1177467203.719625.93920@u32g2000prd.googlegroups.com> <1177778685.506101.201540@h2g2000hsg.googlegroups.com> Message-ID: <1177779408.398296.230580@p77g2000hsh.googlegroups.com> On Apr 28, 8:44 am, War Office <911falsef... at gmail.com> wrote: > On 25 abr, 21:33, "Bill Habr" wrote: > > > > > wrote in message > > >news:1177467203.719625.93920 at u32g2000prd.googlegroups.com... > > > > Cal Tech is the ELITE of ELITE in physics. > > > > If Feynman were alive, he would point his finger straight at the 911 > > > criminal operators, the yank bastards themselves ....... > > > >http://www.911blogger.com/node/8101 > > > > No self-respecting scientist should keep his mouth shut. Its a > > > fundamental challenge to the method of science, a detective work most > > > demanding of INTELLECTUAL HONESTY. > > > Isn't this the guy who has more conspiracy theories than Carter has pills? > > > Whitewater, Vince Foster, moon landing hoax one week - we found a UFO on the moon the > > next, Oklahoma City bombing, a new conspiracy every day ad nauseum? > > Why can't any of you just discuss the fact that free-fall collapse of > this building contradicts the laws of physics? > > Why do you all have to avoid the topic and rather go on a character > assassination which is totally abhorent to scientific method? ...because that's all that is left. From ginstrom at tree.odn.ne.jp Wed Apr 4 04:20:37 2007 From: ginstrom at tree.odn.ne.jp (ginstrom) Date: 4 Apr 2007 01:20:37 -0700 Subject: zip list with different length In-Reply-To: <1175673207.231212.28310@n76g2000hsh.googlegroups.com> References: <1175673207.231212.28310@n76g2000hsh.googlegroups.com> Message-ID: <1175674837.104900.161000@y80g2000hsf.googlegroups.com> On Apr 4, 4:53 pm, s99999999s2... at yahoo.com wrote: > elements, say len(a) = 5, len(b) = 3 > >>> a = range(5) > >>> b = range(3) ... > I want the results to be > [(0, 0), (1, 1), (2, 2) , (3) , (4) ] > can it be done? A bit cumbersome, but at least shows it's possible: >>> def superZip( a, b ): common = min( len(a), len(b) ) results = zip( a[:common], b[:common] ) if len( a ) < len( b ): a = b return results + [ (x,) for x in a[common:] ] >>> superZip( range( 5 ), range( 3 ) ) [(0, 0), (1, 1), (2, 2), (3,), (4,)] >>> superZip( range( 3 ), range( 5 ) ) [(0, 0), (1, 1), (2, 2), (3,), (4,)] >>> superZip( range( 0 ), range( 5 ) ) [(0,), (1,), (2,), (3,), (4,)] >>> superZip( range( 3 ), range( 3 ) ) [(0, 0), (1, 1), (2, 2)] Regards, Ryan Ginstrom From mail at microcorp.co.za Fri Apr 20 02:51:01 2007 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Fri, 20 Apr 2007 08:51:01 +0200 Subject: List of Objects References: <1177037915.042476.153190@n76g2000hsh.googlegroups.com> Message-ID: <00ef01c78318$6956d2e0$03000080@hendrik> "Steve Holden" wrote: > Steven D'Aprano wrote: > [...] > > > > Forth method: create identical gazelles, then modify them: > > > > list_of_beasties = [Gazelle(defaults) for i in xrange(1000)] > > for i, beastie in enumerate(xrange(1000)): > > list_of_beasties[i] = modify(beastie) > > > Nope, 'sorry, that's Python a's well. Forth u'se's rever'se Poli'sh > notation. > No it wa's a biblical incantation - "go forth and multiply..." - Hendrik From tennessee at tennessee.id.au Wed Apr 25 02:40:09 2007 From: tennessee at tennessee.id.au (Tennessee Leeuwenburg) Date: Wed, 25 Apr 2007 16:40:09 +1000 Subject: [python-advocacy] Would You Write Python Articles or Screencasts for Money? In-Reply-To: References: <462DCCE6.9060908@taupro.com> <462E0D93.3090705@holdenweb.com> Message-ID: <43c8685c0704242340v45352f95m73c6808dbf1afb1f@mail.gmail.com> Firstly, let me put up my hand and say that I would be happy to write Python articles for cash. Now, on to business. I am already doing something similar with /The Python Papers/. As part of putting together each edition (especially the upcoming, bumper edition due out soon), I seek out authors, solicit contributions, review available literature and generally promote good content. I don't think it's too much to suggest that anyone seeking to assist in creating a good image for Python could very usefully contribute to this effort. In the last edition we offered a prize for the best article, and also undertook some review of published papers and articles, reprinting 'best of' papers from the recent OSDC conference. We are also seeking recommendations from other conference organisers so that we can, on an ongoing basis, select and republish 'the best' and present them in one globally accessible place. The Python Papers has a growing profile, but it is still very early days. We need help at the editorial level very much, and also in building a new website. Additionally, I can see the value in getting more column inches in journals and magazines with already large readerships. As editor, I already have a relationship with many authors of Python material. If I knew of opportunities for publishing in other journals, I would be more than happy to try to organise a contribution. I have been waiting until after the publication of our next edition to propose anything of the kind, but in light of this discussion perhaps I should bring it up now -- perhaps there is the possibility of The Python Papers becoming more officially related to python.org. This might give the PSF a tool by which they can officially recognise members of the Python community. Unfortunately, we are limited at the moment by a lack of manpower. Each edition is the result of a lot of effort on my part, and also by contributors and other members of the editorial board. Being able to have more committed individuals involved in its production would, I feel, rapidly improve the reach and quality of the publication. I'm not looking for a handout, as I'm happy with what I'm doing already, but I thought I'd point out that The Python Papers could be an instrument for achieving many of the goals outlined in this discussion. All the best, -Tennessee On 4/25/07, Facundo Batista wrote: > 2007/4/24, Steve Holden : > > > and I was more looking for a way to reward authors of excellence, as > > judged by some subset of the Python community - this might have to be > > the PSF membership given the impracticality of running a meaningful poll > > with a larger set of voters. > > Why? Because of spammers and/or false voters? > > When I first read about this, I thought about a web page where anybody > could "propose" articles for voting, and anybody could vote them. > Monthly, an award goes for the top 1, and that article goes out from > the poll. > > Why can't that be done? > > Other point: what happens with all the non-english articles? Other categories? > > > > There are many other possibilities too. What about an award for "most > > helpful responses on c.l.py" over some period? I think one of the > > How do you evaluate such thing? I think this is too complicated... > > Regards, > > -- > . Facundo > > Blog: http://www.taniquetil.com.ar/plog/ > PyAr: http://www.python.org/ar/ > _______________________________________________ > Advocacy mailing list > Advocacy at python.org > http://mail.python.org/mailman/listinfo/advocacy > From kw at codebykevin.com Fri Apr 13 12:27:01 2007 From: kw at codebykevin.com (Kevin Walzer) Date: Fri, 13 Apr 2007 12:27:01 -0400 Subject: mac IDLE problems In-Reply-To: <1176441305.802719.105520@q75g2000hsh.googlegroups.com> References: <1176441305.802719.105520@q75g2000hsh.googlegroups.com> Message-ID: <461FAF55.9090109@codebykevin.com> 7stud wrote: > Hi, > > In the IDLE, I can't get most shortcut keys that are listed next to > the menu items to work. For instance, under the Format menu item only > the shortcuts for "indent region" and "undent region" work. If I > highlight some text and use Shift+3 to comment out the region I > highlighted, the code is erased and I get the # symbol. When I use > the option(alt key) and type a character, I get things like this: > > ??,??,??,?? > > I looked under Options/Configure IDLE/Keys and tried the various built > in key sets, and none seem to work. > > I also can't use my mouse to copy(or cut) and paste. When I highlight > something and right click(in an attempt to bring up the context menu > that has copy, cut, paste, etc.), the text that is highlighted is > doubled when I right click, e.g.: > > some text > > becomes: > > some textsome text > > And, sometimes when I try to highlight a line, the line 7 lines below > the cursor gets highlighted. > > intel mac, os 10.4.7, python 2.4.4 > IDLE under 2.5 has been much improved on the Mac; all the standard Mac keyboard shortcuts are supported, and in general it's more stable. With 2.5, IDLE replaces the old PythonIDE that used to ship with MacPython. Can you update to 2.5? -- Kevin Walzer Code by Kevin http://www.codebykevin.com From steve at holdenweb.com Sat Apr 14 11:32:49 2007 From: steve at holdenweb.com (Steve Holden) Date: Sat, 14 Apr 2007 11:32:49 -0400 Subject: Python Feature Request: Allow changing base of member indices to 1 In-Reply-To: <1176559643.450533.296850@n59g2000hsh.googlegroups.com> References: <1176546465.632410.52630@w1g2000hsg.googlegroups.com> <4620b47b$0$14410$9b622d9e@news.freenet.de> <1176557999.665663.299740@y80g2000hsf.googlegroups.com> <1176559643.450533.296850@n59g2000hsh.googlegroups.com> Message-ID: jamadagni wrote: >> Modules are parsed when they are imported. And some modules are already >> imported before your module is imported because they are built-in or >> loaded to be able to import your module in the first place. And what >> about modules that are written in C? > > OK fine. It is clear that this feature must be implemented if at all > only on a per-module basis. So can we have votes for per-module > implementation of this feature? > Like votes would make a difference. Please just accept that this is not a sensible suggestion and leave it at that. 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 andmarti at gmail.com Tue Apr 24 05:18:34 2007 From: andmarti at gmail.com (andmarti at gmail.com) Date: Tue, 24 Apr 2007 09:18:34 +0000 Subject: getting scancodes In-Reply-To: <132r2hb2gltbf4d@corp.supernews.com> References: <132r2hb2gltbf4d@corp.supernews.com> Message-ID: <20070424091834.GA27732@lacordilleraandina.com.ar> On Tue, Apr 24, 2007 at 04:40:11AM -0000, Grant Edwards wrote: > On 2007-04-24, andmarti at gmail.com wrote: > > > Anyone knows if its possible to get scan codes ??? > > What hardware? What OS? Debian Sarge/Etch, i386.. :P Molte grazie. Andres M. > > > I tried with getch () but with no success, just keycodes. > > May be using the something in the sys.stdin module ?? > > > > Please, any help would be very appreciated. > > You're going to have to be a little more specific... > From clajo04 at mac.com Thu Apr 5 16:55:38 2007 From: clajo04 at mac.com (John Clark) Date: Thu, 5 Apr 2007 16:55:38 -0400 Subject: grandparent method with super In-Reply-To: <20070405163845.2ffa8d32@localhost> References: <20070405161939.694d51a1@localhost> <20070405163845.2ffa8d32@localhost> Message-ID: <01c001c777c4$c61c0950$fefea8c0@haengma> >> Pretty sure you can do this: >> >> class A(object): >> def m(self): >> class B(A): >> def m(self): >> class C(A): >> def m(self): >> class D(B,C): >> def m(self): >> A.m(self) >> >> I don't think you want to try to use super() in this case. > >That works, but when I replace A with something else, I do not get the grandparent anymore >without changing all the method calls. Basically, I would like to call the method m in the first >grandparent of D. > >Martin I think the problem you may run into is with the term "first grandparent" - when you look at the method resolution order of the class D, you will find that the MRO goes "D, C, B, A"... I think it's going to be difficult to figure out where the "first grandparent" is in the MRO. For example: class A(object): def m(self): pass class B(A): def m(self): pass class C(B): def m(self): pass class D(A): def m(self): pass class E(C,D): def m(self): firstgrandparent(E,self).m() #Should call B.m class F(D,C): def m(self): firstgrandparent(F,self).m() # Should call F.m The mro for class E is going to be "E,C,B,D,A" where as the mro for class F is going to be "F,D,C,B,A". However, the first grandparent for E should be B, where as the first grandparent for F should be A. Because the MRO isn't just a depth first traversal, the term "first grandparent" gets tricky to define... -jdc -- http://mail.python.org/mailman/listinfo/python-list From bbxx789_05ss at yahoo.com Sat Apr 14 06:22:55 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: 14 Apr 2007 03:22:55 -0700 Subject: list comparison help? In-Reply-To: References: Message-ID: <1176546175.099596.44140@w1g2000hsg.googlegroups.com> On Apr 14, 3:36 am, "Dropkick Punt" wrote: > Hi. I have a list of common prefixes: > > >>> prefixes = [ "the", "this", "that", "da", "d", "is", "are", "r", "you", "u"] > > And I have a string, that I split() into a list. > > >>> sentence = "what the blazes is this" > >>> sentence = sentence.split() > > Now I want to strip the sentence of all words in the prefix list. > > I tried this method: > > >>> for x in prefixes: > > ... if sentence.index(x): > ... del sentence[sentence.index(x)] > > This raises, the error: > > Traceback (most recent call last): > File "", line 3, in ? > ValueError: list.index(x): x not in list > > This puzzles me, because if x isn't in the list, the subroutine shouldn't attempt to delete it > from the list, so I'm not sure why it's complaining. > > Can anybody explain this to me, &/or show me a better way to do it? Add some print statements to help you figure out what is going on: for x in prefixes: print x a = sentence.index(x) print "index: " + str(a) if a: del sentence[sentence.index(x)] The problem is: to evaluate the if statement, python executes sentence.index(x) and the return value of that is examined to see if it is True or False. However sentence.index(x) throws an exception when the word x is not found in sentence, and therefore your program terminates before the if statement ever completes its evaluation. So you need to use something in your if condition that won't throw an exeception, i.e. something that returns only true or false, like: for prefix in prefixes: while prefix in sentence: #remove only removes the first occurrence sentence.remove(prefix) Here is a better way: prefixes = [ "the", "this", "that", "da", "d", "is", "are", "r", "you", "u"] sentence = "what the blazes is the da this da this the" sentence = sentence.split() result = [word for word in sentence if word not in prefixes] print result From gregcorradini at gmail.com Wed Apr 11 12:51:52 2007 From: gregcorradini at gmail.com (Greg Corradini) Date: Wed, 11 Apr 2007 09:51:52 -0700 (PDT) Subject: Creating Unique Dictionary Variables from List Message-ID: <9943317.post@talk.nabble.com> Hello All, I'm attempting to create multiple dictionaries at once, each with unique variable names. The number of dictionaries i need to create depends on the length of a list, which was returned from a previous function. The pseudo code for this problem would be: returnedlist = [x,y,z] count = 0 for i in returnedlist: if count < len(returnedlist): # then create a dictionary (beginning with variable dic) for each i with a unique name such that # my unique name would be dic + count Any ideas about this? Greg -- View this message in context: http://www.nabble.com/Creating-Unique-Dictionary-Variables-from-List-tf3560469.html#a9943317 Sent from the Python - python-list mailing list archive at Nabble.com. From Emile.Boudreau at cognos.com Tue Apr 3 11:00:59 2007 From: Emile.Boudreau at cognos.com (Boudreau, Emile) Date: Tue, 3 Apr 2007 11:00:59 -0400 Subject: Problem with filter() In-Reply-To: <09042D621CD4AA479C678463F3A646D0F73D1A@sottemail1.ent.ad.cognos.com> References: <09042D621CD4AA479C678463F3A646D0F73D1A@sottemail1.ent.ad.cognos.com> Message-ID: <09042D621CD4AA479C678463F3A646D0F73D24@sottemail1.ent.ad.cognos.com> Sorry folks my mistake def is_dev should be: def is_Dev(stringy): stringx = stringy.split('-') if stringx[0] == '': if stringx[1] == r'win32': if stringx[2] == r'app': if stringx[4] == r'dev.tar.gz': return 1 But now the results of the filter is an empty list and i know it shouldn't be. Emile Boudreau ________________________________ 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, April 03, 2007 10:52 AM To: python-list at python.org Subject: Problem with filter() Hey all, So I'm trying to filter a list with the built-in function filter(). My list looks something like this: ['logs', 'rqp-8.2.104.0.dep', 'rqp-8.2.93.0.dep', 'rqp-win32-app-8.2.96.0-inst.tar.gz', 'rqp-win32-app-8.2.96.0-inst.tar.gz'] Calling filter like this: compFiles = filter(is_Dev, compFiles) compFiles is my list and is_dev is the following def is_Dev(stringy): print stringy stringx = stringy.split('-') if stringx[1] == r'win32': if stringx[2] == r'app': if stringx[4] == r'dev.tar.gz': return 1 For some reason I only get 'logs' printed when is_Dev is called. (ie. It's only going through is_dev once) Does anyone see something wrong that I'm not seeing?? Thanks, 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 usenet-mail-0306.20.chr0n0ss at spamgourmet.com Thu Apr 12 09:37:00 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Thu, 12 Apr 2007 15:37:00 +0200 Subject: wxPython, mac, wx.HSCROLL not working References: <1176364597.741079.25840@n59g2000hsh.googlegroups.com> Message-ID: <586qvsF2fbq3rU1@mid.individual.net> 7stud wrote: > I'm trying to allow for a horizontal scrollbar on a textarea, but > the scrollbar won't appear when I enter a long string of text(by > leaning on one character on my keyboard): Works for me (Linux, self-built Python 2.5 and wxPython 2.8.3.0). Regards, Bj?rn -- BOFH excuse #285: Telecommunications is upgrading. From ask at me Thu Apr 12 22:17:54 2007 From: ask at me (alf) Date: Thu, 12 Apr 2007 21:17:54 -0500 Subject: compiling modules with VS 2008 for python 2.4 prepared with Visual Studio 2003 In-Reply-To: <1hw2ak4.1cxnvt81nzd971N%aleax@mac.com> References: <1hw2ak4.1cxnvt81nzd971N%aleax@mac.com> Message-ID: Alex Martelli wrote: > I would think this error message is as clear as it can be, and then > some! It even gives very practical advice on how to work around the > problem. Either install VS2003, if you own it or can purchase it, or > else install mingw32 (which is free and can be downloaded) and use the > option which the error message tells you to. > well, instructions were clear enough for me. What is hard to get why it could not use free M$ compiler which is presumably produces compatible objects and libraries. In fact I played with msvccompiler.py a little bit, get around registry paths and was able to produce .pyo file. Then I hit some runtime lib issues. In meantime I found precompiled probstat lib so gave up on making msvccompiler.py compatible with VS 2008. Bottomline - it would be nice to have such support. -- alf From mehmetsyildirim at gmail.com Thu Apr 5 11:47:30 2007 From: mehmetsyildirim at gmail.com (msy) Date: 5 Apr 2007 08:47:30 -0700 Subject: embedded python project Message-ID: <1175788050.718363.307460@e65g2000hsc.googlegroups.com> selamlar; T?rkiyeden selamlar. Grubunuza yeni kat?ld?m. Pythonu ?ok merak ediyorum.Y?ksek lisans projemi python ile yapmak istiyorum. G?m?l? sistemler ?zerine bir konu tasarlamay? d???n?yorum. Basit olursa sevinirim. ?nerilerinizi bekliyorum. ?imdiden te?ekk?rler. Hi from Turkey. I am new in your grub. I wonder The Python. I want to do master project with python.I am thinking about to design an embedded system. ii will be happy if it be a simple. I wait your recommends. thanks for now. Mehmet S. YILDIRIM Bucak/Burdur Teacher of Computer || Bilgisayar ??retmeni Isparta S?leyman Demirel University || S?leyman Demirel ?niversitesi Institute of Sciences || Fen Bilimleri Enstit?s? Departman of Electronic and Computer || Elektronik ve Bilgisayar B?l?m? Master Student || Y?ksek Lisans ??rencisi T?rkiye From gjcarneiro at gmail.com Sun Apr 1 08:41:56 2007 From: gjcarneiro at gmail.com (Gustavo Carneiro) Date: Sun, 1 Apr 2007 13:41:56 +0100 Subject: [Python-Dev] Python 3000 PEP: Postfix type declarations In-Reply-To: References: Message-ID: On 4/1/07, Georg Brandl wrote: [...] > Example > ======= > > This is the standard ``os.path.normpath`` function, converted to type > declaration > syntax:: > > def normpath?(path?)?: > """Normalize path, eliminating double slashes, etc.""" > if path? == '': > return '.' > initial_slashes? = path?.startswith?('/')? > # POSIX allows one or two initial slashes, but treats three or > more > # as single slash. > if (initial_slashes? and > path?.startswith?('//')? and not path?.startswith?('///')?)?: > initial_slashes? = 2 > comps? = path?.split?('/')? > new_comps? = []? > for comp? in comps?: > if comp? in ('', '.')?: > continue > if (comp? != '..' or (not initial_slashes? and not > new_comps?)? or > (new_comps? and new_comps?[-1]? == '..')?)?: > new_comps?.append?(comp?) > elif new_comps?: > new_comps?.pop?()? > comps? = new_comps? > path? = '/'.join(comps?)? > if initial_slashes?: > path? = '/'*initial_slashes? + path? > return path? or '.' > > As you can clearly see, the type declarations add expressiveness, while at > the > same time they make the code look much more professional. Is this supposed to be a joke? Please tell me this isn't a real PEP. While I'm all for allowing unicode identifiers in Python, postfix type annotations make Python look like Perl. And how can you claim this code is more readable? It certainly is _less_ readable, not more. I agree that Python should support type annotations, but they should be optional and only present at the function interfaces, i.e. specify the type in the function parameter lists, like in plain old C. +1 from me for allowing unicode identifiers. -MAXVOTE for type annotations in identifiers. -- Gustavo J. A. M. Carneiro "The universe is always one step beyond logic." -------------- next part -------------- An HTML attachment was scrubbed... URL: From whamil1 at entergy.com Mon Apr 23 10:30:47 2007 From: whamil1 at entergy.com (Hamilton, William ) Date: Mon, 23 Apr 2007 09:30:47 -0500 Subject: Tutorial creates confusion about slices In-Reply-To: Message-ID: <588D53831C701746A2DF46E365C018CE01D2CA76@LITEXETSP001.etrsouth.corp.entergy.com> > -----Original Message----- > From: python-list-bounces+whamil1=entergy.com at python.org [mailto:python- > list-bounces+whamil1=entergy.com at python.org] On Behalf Of Antoon Pardon > Sent: Monday, April 23, 2007 7:38 AM > To: python-list at python.org > Subject: Tutorial creates confusion about slices > > The following is part of the explanation on slices in the > tutorial: > > The best way to remember how slices work is to think of the indices as > pointing between characters, with the left edge of the first character > numbered 0. Then the right edge of the last character of a string of n > characters has index n, for example: > > +---+---+---+---+---+ > | H | e | l | p | A | > +---+---+---+---+---+ > 0 1 2 3 4 5 > -5 -4 -3 -2 -1 > > This is all very well with a simple slice like: > > "HelpA"[2:4] => "lp" > > > But it give the wrong idea when using the following extended slice: > > "HelpA"[4:2:-1] => "Ap" > > So this doesn't result in the reverse of the previous expression while > the explanation above suggest it does. It makes sense if you recognize that the negative step value also flips which "side" the index is on. +---+---+---+---+---+ | H | e | l | p | A | +---+---+---+---+---+ 0 1 2 3 4 -6 -5 -4 -3 -2 -1 --- -Bill Hamilton From jzgoda at o2.usun.pl Tue Apr 10 16:55:36 2007 From: jzgoda at o2.usun.pl (Jarek Zgoda) Date: Tue, 10 Apr 2007 22:55:36 +0200 Subject: About Trolltech QT OpenSource license. In-Reply-To: <1176237050.409742.8760@30g2000cwc.googlegroups.com> References: <1176233376.712861.67160@o5g2000hsb.googlegroups.com> <1176237050.409742.8760@30g2000cwc.googlegroups.com> Message-ID: king kikapu napisa?(a): >> This is a bullsh*t. Qt is free (as in "free speech") on GPL. Nothing >> stops you from using it in any commercial project if only it fits the >> licensing terms (i.o.w. it's free software). This specially applies to >> inhouse development, as in such case there's no "distribution". > > Hmmm...how a commercial software (that means i get paid for give it) > it will be consider "free software" ? > I ask because i surely do not understand correctly the GPL lisence and > all that stuff. The GPL is about distribution of software. If you provide your program with sources and allow redistribution under provisions of GPL, it will be free (as you provide some "freedoms" listed in the license statement), even if you earn cash for it. It's "free as in freedom" (or free speech), not as in "free beer". Please, contact your local FSF, CreativeCommons or ISOC lawyer to get an advice if you feel you need a lawyer's assistance. For the brief explanation of the problem, see http://www.gnu.org/philosophy/selling.html. This document should cover most cases. ;) >> Plus, this (sales)person forgot to state clearly, that GPL covers only >> distribution, not the cost of software. If you manage to get some hot >> cash for selling sources of your GPL-ed program, the license would not >> try to stop you from doing that. ;) > > As i said, i do not fully understand all this license stuff. All i > want to ask is, i can make GPL software and gain money from this ? And > if that so, then why they "force" you to buy the commercial lisence in > such case ? They cann't and the don't. If you obey GPL rules, you're right. The (sales)person you had a conversation with is, well, just a salesperson. Trolltech makes money from selling commercial licenses, so these persons will always try to persuade you to buying a license or two, "just in case". ;) -- Jarek Zgoda http://jpa.berlios.de/ From aleax at mac.com Sat Apr 28 17:09:44 2007 From: aleax at mac.com (Alex Martelli) Date: Sat, 28 Apr 2007 14:09:44 -0700 Subject: relative import broken? References: Message-ID: <1hxa9x3.c0unyd1jw7vu9N%aleax@mac.com> Alan Isaac wrote: > Are relative imports broken in 2.5? > Directory ``temp`` contains:: > > __init__.py > test1.py > test2.py > > File contents: > __init__.py and test2.py are empty > test1.py contains a single line:: > > from . import test2 > > Python 2.5.1 under Win2000, cmd line execution, > produces as output:: > > Traceback (most recent call last): > File "F:\temp\test1.py", line 1, in > from . import test2 > ValueError: Attempted relative import in non-package > > Why? If you're running test1.py as your main module, then it's not part of a package, so the relative import should indeed fail as you mention. OTOH, something like: $ python -c'from temp import test1' from the parent directory of temp should work fine. Since you don't give us the exact command line you're trying to execute, it's impossible to guess exactly what you're doing. Alex From surekap at gmail.com Mon Apr 23 05:24:45 2007 From: surekap at gmail.com (Prateek) Date: 23 Apr 2007 02:24:45 -0700 Subject: Support for new items in set type In-Reply-To: References: <1177211624.069474.3960@y5g2000hsa.googlegroups.com> <1hwxx1e.1un7urc1de872aN%aleax@mac.com> <1177305469.398817.80600@y80g2000hsf.googlegroups.com> Message-ID: <1177320285.068937.31860@n59g2000hsh.googlegroups.com> > I don't see where your SeaSet class is used. > Actually that is the point. According to the hotshot profile, the problem code doesn't use the SeaSet implementation. Yet that same code was running much faster earlier. I tried multiple time (2-3 times). >From what I can fathom, nothing else changed - just the set implementation. It seems obvious that the read() call in the __readTableHeader method is blocking for longer periods although it isn't exactly obvious why that might be. I was hoping someone with an idea of Python-C interaction could shed some light on this. I'm on a different computer right now, I'll log back in later and post more code if that helps. Again, thanks to anyone who can help. Prateek From tjreedy at udel.edu Tue Apr 10 20:48:21 2007 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 10 Apr 2007 20:48:21 -0400 Subject: tuples, index method, Python's design References: <1175953520.316208.241490@o5g2000hsb.googlegroups.com><7xzm5igbrb.fsf@ruckus.brouhaha.com><1176200361.260546.280510@n76g2000hsh.googlegroups.com> <740c3aec0704100824m132c45fbi5c4c3ec0c0fa3a67@mail.gmail.com> Message-ID: "BJ?rn Lindqvist" wrote in message news:740c3aec0704100824m132c45fbi5c4c3ec0c0fa3a67 at mail.gmail.com... On 4/10/07, Steve Holden wrote: > One might perversely allow extension to lists and tuples to allow > > [3, 4] in [1, 2, 3, 4, 5, 6] > > to succeed, but that's forcing the use case beyond normal limits. I'd love to have that! There are at least one million use cases for finding a sequence in a sequence and implementing it yourself is non-trivial. Plus then both list and tuple's index methods would work *exactly* like string's. It would be easier to document and more useful. A big win. ======================= It would be ambiguous: [3,4] in [[1,2], [3,4], [5,6]] is True now. Strings are special in that s[i] can only be a (sub)string of length 1. 'b' in 'abc' is True. This makes looking for longer substrings easy. However, [2] in [1,2,3] is False. IE, list[i] is not normally a list. So looking for sublists is different from looking for items. Terry Jan Reedy From gagsl-py2 at yahoo.com.ar Mon Apr 9 02:46:10 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: 8 Apr 2007 23:46:10 -0700 Subject: Exec Statement Question In-Reply-To: <1176099427.158621.45580@o5g2000hsb.googlegroups.com> References: <1176099427.158621.45580@o5g2000hsb.googlegroups.com> Message-ID: <1176101170.066391.134010@y66g2000hsf.googlegroups.com> 7stud wrote: > On Apr 8, 11:31 pm, "Gregory Pi?ero" wrote: > > Is there a way to call exec such that it won't have access to any more > > objects than I explicitly give it? > > I think the way it works is that when the def is parsed, a function > object is created and assigned to the name func1. When the function > object is created, d is "bound" to the global value 3, while a,b,c lie > in wait for arguments to land in their gullets like venus fly traps. > Your dictionary has a key whose value is a reference to the function > object, which already has the value 3 bound to d. Not exactly. As Georg Brandl said, the function has a reference to the *globals* currently in use when it was defined, not directly to the name "d". To the OP: If you want a function with almost "empty" globals, compile it the same way you used to execute it: >>> text = """def func1(a): ... print a ... print b ... ... func1(3) ... print func1.func_globals.keys() ... """ >>> >>> exec text in {} 3 Traceback (most recent call last): File "", line 1, in ? File "", line 5, in ? File "", line 3, in func1 NameError: global name 'b' is not defined >>> exec text in {"b": 123} 3 123 ['__builtins__', 'func1', 'b'] >>> I said *almost* empty because Python may insert other keys into the globals, like __builtins__ above (see http://docs.python.org/ref/exec.html) -- Gabriel Genellina From spradml at gmail.com Fri Apr 27 01:59:27 2007 From: spradml at gmail.com (Pradnyesh Sawant) Date: Fri, 27 Apr 2007 11:29:27 +0530 Subject: pyqt4 signal/slot using PyObject* and shortcut Message-ID: <80628d680704262259o46d06926n6d5f7b9e375c08b2@mail.gmail.com> Hello, i have the following code: ################################################################# import time import sys from PyQt4 import QtGui, QtCore class Counter(QtCore.QThread): def __init__(self): QtCore.QThread.__init__(self) def run(self): cntr = 0 while cntr < 10: cntr += 1 self.emit(QtCore.SIGNAL("showCntr1(PyObject*)"), (cntr, "a")) # line 1 self.emit(QtCore.SIGNAL("showCntr2"), (cntr, "a")) # line 2 time.sleep(0.2) class Gui(QtGui.QDialog): def __init__(self, parent = None): QtGui.QDialog.__init__(self, parent) frameStyle = QtGui.QFrame.Sunken | QtGui.QFrame.Panel self.lCntr = QtGui.QLabel() self.lCntr.setFrameStyle(frameStyle) loGrd = QtGui.QGridLayout() loGrd.addWidget(self.lCntr, 0, 0) self.setLayout(loGrd) self.setWindowTitle(self.tr("Counter")) def showCntr1(self, val): print val, str(val) self.lCntr.setText(str(val)) def showCntr2(self, val): print val, str(val) self.lCntr.setText(str(val)) if __name__ == "__main__": app = QtGui.QApplication(sys.argv) dialog = Gui() cntr = Counter() cntr.start() QtCore.QObject.connect(cntr, QtCore.SIGNAL("showCntr1(PyObject*)"), dialog.showCntr1, QtCore.Qt.QueuedConnection) QtCore.QObject.connect(cntr, QtCore.SIGNAL("showCntr2"), dialog.showCntr1, QtCore.Qt.QueuedConnection) sys.exit(dialog.exec_()) ################################################################# If i comment out "line 1", then i get the following output: 0.2 0.2 0.2 0.2 0.2 0.2 0.2 0.2 0.2 0.2 0.2 0.2 0.2 0.2 0.2 0.2 0.2 0.2 0.2 0.2 Notice that 0.2 is the time value of the sleep instruction. Why is this happening? On the other hand, if i comment out "line 2", then i get the following output: (, 'a') (, ) (, 'a') (, ) (, 'a') (, ) (, 'a') (, ) (, 'a') (, ) (, 'a') (, ) (, 'a') (, ) (, 'a') (, ) (, 'a') (, ) (, 'a') (, ) What i get from the above is that a reference to "cntr" is being passed, but by the time the gui thread is actually run, both the values (cntr and "a") have been destroyed, hence the NULL values. ***How do i circumvent this problem?*** Lastly, if i don't comment out any of line 1 or 2, then i get the foll output: (<__main__.Gui object at 0xb6a8f12c>, (<__main__.Gui object at 0xb6a8f12c>, (<__main__.Gui object at 0xb6a8f12c>, (<__main__.Gui object at 0xb6a8f12c>, (<__main__.Gui object at 0xb6a8f12c>, (<__main__.Gui object at 0xb6a8f12c>, (<__main__.Gui object at 0xb6a8f12c>, (<__main__.Gui object at 0xb6a8f12c>, (<__main__.Gui object at 0xb6a8f12c>, (<__main__.Gui object at 0xb6a8f12c>, (<__main__.Gui object at 0xb6a8f12c>, (<__main__.Gui object at 0xb6a8f12c>, (<__main__.Gui object at 0xb6a8f12c>, (<__main__.Gui object at 0xb6a8f12c>, (<__main__.Gui object at 0xb6a8f12c>, (<__main__.Gui object at 0xb6a8f12c>, (<__main__.Gui object at 0xb6a8f12c>, (<__main__.Gui object at 0xb6a8f12c>, .......... i don't know what this means??? Can anyone kindly explain what's happening... I'm using: python: 2.4.4~c1-0ubuntu1 qt4-dev-tools: not installed python-qt4: 4.0.1-1ubuntu1 sip4: (4.4.5-2ubuntu1 os: ubuntu edgy -- warm regards, Pradnyesh Sawant -- Be yourself, everyone else is taken. --Anon From gagsl-py2 at yahoo.com.ar Mon Apr 30 21:41:15 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 30 Apr 2007 22:41:15 -0300 Subject: logging SMTPHandler and Authentication References: <1177978114.284934.27140@l77g2000hsb.googlegroups.com> Message-ID: En Mon, 30 Apr 2007 21:08:34 -0300, escribi?: > I'm new to Python, but I've been thrown into coding a pretty > complicated regression testing script. I need to email the log of the > daily test to the code owners. I thought I could use SMTPHandler for > this, but our email system requires authentication. I have not been > able to figure out how to log in using SMTPHandler. I found the > following post on comp.lang.python: > > http://groups.google.com/group/comp.lang.python/browse_frm/thread/ef873c79157b8624/cdb67687e507c974?lnk=gst&q=SMTPHandler+authentication&rnum=1#cdb67687e507c974 > > However, I haven't been able to translate this to anything I can use. > I've also looked at the source code for the SMTPHandler, but I don't > want to edit that. Unfortunately -and despite what's said on that post- SMTPHandler does *not* provide any hook to customize the way it sends the message. The SMTP instance used internally is not available so you can't call its login() method from the outside. If you don't want to edit the sources, you could inherit from SMTPHandler, copy the emit() implementation and add the missing login() call: --- begin code --- import logging, logging.handlers, string class SMTPHandlerWithAuth(logging.handlers.SMTPHandler): def emit(self, record): """ Emit a record. Format the record and send it to the specified addressees. """ try: import smtplib try: from email.Utils import formatdate except: formatdate = self.date_time port = self.mailport if not port: port = smtplib.SMTP_PORT smtp = smtplib.SMTP(self.mailhost, port) msg = self.format(record) msg = "From: %s\r\nTo: %s\r\nSubject: %s\r\nDate: %s\r\n\r\n%s" % ( self.fromaddr, string.join(self.toaddrs, ","), self.getSubject(record), formatdate(), msg) # ADD THE FOLLOWING LINE: smtp.login(username, password) smtp.sendmail(self.fromaddr, self.toaddrs, msg) smtp.quit() except (KeyboardInterrupt, SystemExit): raise except: self.handleError(record) rootLogger = logging.getLogger('') smtpHandler = SMTPHandlerWithAuth(('localhost',587), 'from_address at xxx.com', 'to_address at xxx.com', "Error subject") rootLogger.addHandler(smtpHandler) logging.error('This is an error message that should be sent by mail.') --- end code --- -- Gabriel Genellina From hlubenow2 at gmx.net Tue Apr 10 20:12:02 2007 From: hlubenow2 at gmx.net (hlubenow) Date: Wed, 11 Apr 2007 02:12:02 +0200 Subject: Check for keypress on Linux xterm ? References: Message-ID: I wrote: > Hello, > > I'd like to check, if a single key is pressed on a Linux xterm. > My problem is, I don't want my program to wait for the keypress. > I just want to check, if a key is currently pressed and if not, I'd like > to continue with my program (like "INKEY$" in some BASIC-dialects). Ok, here's the code I use now. Thanks to Grant Edwards for pointing me into the right direction: ---------------------------------------------------------- #!/usr/bin/env python import os import sys import tty import termios import fcntl import time fd = sys.stdin.fileno() oldterm = termios.tcgetattr(fd) oldflags = fcntl.fcntl(fd, fcntl.F_GETFL) tty.setcbreak(sys.stdin.fileno()) newattr = termios.tcgetattr(fd) newattr[3] = newattr[3] & ~termios.ICANON & ~termios.ECHO def oldTerminalSettings(): termios.tcsetattr(fd, termios.TCSAFLUSH, oldterm) fcntl.fcntl(fd, fcntl.F_SETFL, oldflags) def newTerminalSettings(): termios.tcsetattr(fd, termios.TCSANOW, newattr) fcntl.fcntl(fd, fcntl.F_SETFL, oldflags | os.O_NONBLOCK) def checkKey(): try: c = sys.stdin.read(1) return ord(c) except IOError: return 0 print print "Ok, in 3 seconds, I'll check 100 times, which key you press." print # Initializing: Things like "raw_input()" won't work after that: newTerminalSettings() time.sleep(3) for i in range(100): a = "Key pressed: " key = checkKey() if key: a += chr(key) a += "." else: a += "Nothing pressed." print a # Somehow it doesn't work, if this loop runs too fast, so: time.sleep(0.05) oldTerminalSettings() print print "Terminal-settings restored." print raw_input("raw_input() works again. So please press Return: ") print ---------------------------------------------------------- Thanks again H. From bj_666 at gmx.net Wed Apr 25 06:18:40 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Wed, 25 Apr 2007 12:18:40 +0200 Subject: Coding conventions for class names References: <1177492705.232244.312520@c18g2000prb.googlegroups.com> Message-ID: In <1177492705.232244.312520 at c18g2000prb.googlegroups.com>, Kay Schluehr wrote: > set, int, float, list, object,... > > Don't see any of the basic types following the capitalized word > convention for classes covered by PEP 08. This does not hold only for > __builtins__ in the strict sense but also for types defined in builtin > modules like datetime. Most built-ins are easy to explain: They were functions long before it was possible to use them as base classes and stayed lowercase for backwards compatibility. Don't know about `set` and `object`. I guess it's foolish consistency!? > My question is: does anyone actually follow guidelines here and if yes > which ones and are they resonable ( e.g. stable with regard to > refactoring etc. )? I follow PEP?8 in my (mostly unpublished) code if that does matter to you. :-) Ciao, Marc 'BlackJack' Rintsch From robert.rawlins at thinkbluemedia.co.uk Tue Apr 24 06:17:23 2007 From: robert.rawlins at thinkbluemedia.co.uk (Robert Rawlins - Think Blue) Date: Tue, 24 Apr 2007 11:17:23 +0100 Subject: Minidom Help Message-ID: <004601c78659$c0882e30$41988a90$@rawlins@thinkbluemedia.co.uk> Hello guys, Not got much experience with working with minidom, but I'm looking to parse this XML and retrieve the 'name' value from the xml. Think Blue 0x1002 1 I've got as far as parsing the XML using self.doc = xml.dom.minidom.parse(self.filepath) but that's as far as I've managed to get. I've spent a little time googling around but it's all double Dutch to me. Any ideas? Thanks, Rob -------------- next part -------------- An HTML attachment was scrubbed... URL: From deets at nospam.web.de Thu Apr 26 10:41:14 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 26 Apr 2007 16:41:14 +0200 Subject: passing tuple with pyqt4 signal/slot mechanism In-Reply-To: References: Message-ID: <59bs0gF2iutnsU1@mid.uni-berlin.de> Pradnyesh Sawant schrieb: > Hello, > I have a pyqt4 code in which i'm trying the signal/slot mechanism. The > (stripped) code is as follows: > > class D(QtCore.QThread): > def __init__(self): > QtCore.QThread.__init__(self) > tpl = ("Primary", "priSec") > print "tpl:", tpl > self.emit(QtCore.SIGNAL("setLabel"), tpl) > class Gui(QtGui.QDialog): > def __init__(self, parent = None): > QtGui.QDialog.__init__(self, parent) > def setLabel(self, tpl): > print "####tpl:", tpl > print "**********tpl:", str(tpl) > return > if __name__ == "__main__": > app = QtGui.QApplication(sys.argv) > dialog = Gui() > d = D() > QtCore.QObject.connect(d, QtCore.SIGNAL("setLabel"), > dialog.setLabel, QtCore.Qt.QueuedConnection) > sys.exit(dialog.exec_()) > > The output i'm getting is as follows: > > tpl: ('Primary', 'priSec') > ####tpl: (,) > **********tpl: ((((((((,),),),),),),),) > > Can anyone kindly tell me what's happening here? Why is the tuple > ("Primary", "priSec") getting converted to this thingy? And > what is this thingy anyways (It looks to be a deeply nested tuple, but > am not sure). It's just wild guessing back from my Qt3-days - but isn't PYSIGNAL instead of SIGNAL necessary here? Diez From gherron at islandtraining.com Wed Apr 18 18:46:41 2007 From: gherron at islandtraining.com (Gary Herron) Date: Wed, 18 Apr 2007 15:46:41 -0700 Subject: comparison with None In-Reply-To: <3IqdnfRnCNWPC7vbnZ2dnUVZ_jqdnZ2d@rcn.net> References: <3IqdnfRnCNWPC7vbnZ2dnUVZ_jqdnZ2d@rcn.net> Message-ID: <46269FD1.8030200@islandtraining.com> Alan G Isaac wrote: > >>> None >= 0 > False > >>> None <= 0 > True > > Explanation appreciated. > > Thanks, > Alan Isaac > So that we can sort lists of objects, even when the objects of are different types, Python guarantees to supply a unique and consistent ordering of any two objects. The definition of Python does not specify what that ordering is -- that's implementation dependent -- but any two objects of any two types *do* have an ordering and that ordering will always be the same. So in your implementation None is less than 0 (and probably less than any integer). Given that, your two observations above are consistent. Gary Herron From nagle at animats.com Sat Apr 28 14:35:36 2007 From: nagle at animats.com (John Nagle) Date: Sat, 28 Apr 2007 11:35:36 -0700 Subject: Numbers and truth values In-Reply-To: References: Message-ID: Steven D'Aprano wrote: > On Sat, 28 Apr 2007 15:36:19 +0200, Szabolcs wrote: > > >>>>>>True = 2 # DON'T DO THIS!!! >>>>>>2 == True >>> >>>True >>> >> >>But shouldn't Python forbid this? Is it possible to get a warning when >>unintentionally redefining built-in thing? > > > Python forbids very few things in comparison to other languages. The > attitude is "We're all adults here". Because Python is such a dynamic > language, it is often hard for the compiler to tell the difference between > something you are doing deliberately and a mistake. I'd have to consider that a bug. Some very early FORTRAN compilers allowed you to redefine integer constants: CALL SET(25,99) WRITE (6,100) 25 100 FORMAT(I6) SUBROUTINE SET(IVAR, INEWVAL) IVAR = INEWVAL would print 99 It was generally agreed by 1970 or so that this was a bad idea, and was taken out of the language. C originally didn't have a Boolean type, and it took years to get that in and uniformly defined. But in the end, "true" and "false" were reserved words. "True", "False", and "None" should be reserved words in Python. "None" already is. John Nagle From kumar.mcmillan at gmail.com Thu Apr 19 18:31:10 2007 From: kumar.mcmillan at gmail.com (Kumar McMillan) Date: Thu, 19 Apr 2007 17:31:10 -0500 Subject: Python Feature Request: Explicit variable declarations In-Reply-To: References: <1176546078.934340.253810@y5g2000hsa.googlegroups.com> Message-ID: On 4/14/07, James Stroud wrote: > samjnaa at gmail.com wrote: > But, if you have masochistic tendencies and want a lot of overhead in > your programming, you can always bind yourself mercilessly to classes: > > > class C(object): > declared = ['bob', 'carol', 'ted', 'alice'] > def __setattr__(self, anattr, aval): > if anattr not in C.declared: > raise TypeError, "Just can't hook you up, bro." > else: > self.__dict__[anattr] = aval > You could also do this with __slots__, like: >>> class C(object): ... __slots__ = ['bob','carol','ted','alice'] ... >>> c = C() >>> c.bob = 42 >>> c.bob 42 >>> c.x = 69 Traceback (most recent call last): File "", line 1, in ? AttributeError: 'C' object has no attribute 'x' although, I personally have never found the need nor desire to use __slots__ > > E.g.: > > py> class C(object): > ... declared = ['bob', 'carol', 'ted', 'alice'] > ... def __setattr__(self, anattr, aval): > ... if anattr not in C.declared: > ... raise TypeError, "Just can't hook you up, bro." > ... else: > ... self.__dict__[anattr] = aval > ... > py> c = C() > py> c.bob = 42 > py> c.bob > 42 > py> c.x = 69 > Traceback (most recent call last): > File "", line 1, in > File "", line 5, in __setattr__ > TypeError: Just can't hook you up, bro. > > > Extending this ugliness to type-checking is left as an exercise for the > reader. Using metaclasses for such nonsense is left as an exercise for > metaclass maniacs. > > James > -- > http://mail.python.org/mailman/listinfo/python-list > From aboudouvas at panafonet.gr Thu Apr 19 05:03:08 2007 From: aboudouvas at panafonet.gr (king kikapu) Date: 19 Apr 2007 02:03:08 -0700 Subject: About installing new Python version. Message-ID: <1176973387.967130.27370@y80g2000hsf.googlegroups.com> Hi to all, i started with Python at v2.5 and now i see that a new version is released. As i already have a lot of stuff for Python installed in the site- packages directory, which is the correct way to install a new Python version without do any damage ? Remove Python and ALL Python related software and install them all over again (painful)? Remove Python and do not touch anything else and install new version on top of them at the same directory ? Any other choice available ? Thanks a lot for any help! From antroy at gmail.com Wed Apr 25 03:44:20 2007 From: antroy at gmail.com (Ant) Date: 25 Apr 2007 00:44:20 -0700 Subject: Tutorial creates confusion about slices In-Reply-To: References: Message-ID: <1177487060.580155.84150@r3g2000prh.googlegroups.com> Hi Antoon, > The best way to remember how slices work is to think of the indices as ... > +---+---+---+---+---+ > | H | e | l | p | A | > +---+---+---+---+---+ > 0 1 2 3 4 5 > -5 -4 -3 -2 -1 > > This is all very well with a simple slice like: > > "HelpA"[2:4] => "lp" But that is the whole point of a language tutorial, to introduce the language and provide a way to get started. Note that the tutorial doesn't even go into any details on extended slicing - as far as the beginner is concerned at this point, there *is* no extended slice notation. Even if the tutorial *did* go into more detail about slicing, mentioning negative steps would be folly - the tutorial should be an easy way into the language, and in such a context the above tool for remembering how they work is just fine. The exact (mathematical) definition for string slices is given in the Library reference (http://docs.python.org/lib/typesseq.html), which is where it should be. If you are at the point where understanding what the deal is with extended slice notation for strings, then you are ready to look at the real manual. If the tutorial was fully comprehensive it would be massive and daunting. You'd probably have to split it up as well, into, say, a Language reference and a Library reference. From spamtrap at dot-app.org Sun Apr 29 22:10:00 2007 From: spamtrap at dot-app.org (Sherm Pendley) Date: Sun, 29 Apr 2007 22:10:00 -0400 Subject: SEO - Search Engine Optimization - Seo Consulting References: <1177808356.681710.42980@n76g2000hsh.googlegroups.com> Message-ID: "Juan T. Llibre" writes: > Top or bottom posting is a user choice. Yes, one can choose to be polite and follow established usenet conventions, or one can choose to be rude and self-centered. Those who choose rudeness over courtesy can expect to be called down for it - which is arguably rude in itself, but on usenet one reaps what one sows. Someone who can't deal with that, shouldn't be on usenet. sherm-- -- Web Hosting by West Virginians, for West Virginians: http://wv-www.net Cocoa programming in Perl: http://camelbones.sourceforge.net From aahz at pythoncraft.com Tue Apr 3 15:58:32 2007 From: aahz at pythoncraft.com (Aahz) Date: 3 Apr 2007 12:58:32 -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 , Larry Bates wrote: >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. Then you should explain why you didn't answer the question that was asked. Answering a different question without explanation makes your answer irrelevant at best, wrong at worst. >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. Because Christian already answered the question! Granted, he chose a pseudo-Socratic approach, but with the OP already using the word "clear" in the Subject: line, I think that was entirely reasonable. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Need a book? Use your library! From apardon at forel.vub.ac.be Sat Apr 14 15:43:41 2007 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 14 Apr 2007 19:43:41 GMT Subject: tuples, index method, Python's design References: <1175953520.316208.241490@o5g2000hsb.googlegroups.com> <7xzm5igbrb.fsf@ruckus.brouhaha.com> <1176200361.260546.280510@n76g2000hsh.googlegroups.com> <740c3aec0704100824m132c45fbi5c4c3ec0c0fa3a67@mail.gmail.com> Message-ID: On 2007-04-13, Steve Holden wrote: > Antoon Pardon wrote: >> On 2007-04-13, Steve Holden wrote: >>> Antoon Pardon wrote: >>>> On 2007-04-12, Carsten Haese wrote: >>>>> On Thu, 2007-04-12 at 14:10 +0000, Antoon Pardon wrote: >>>>>> People are always defending duck-typing in this news group and now python >>>>>> has chosen to choose the option that makes duck-typing more difficult. >>>>> Au contraire! The "inconsistent" behavior of "in" is precisely what >>>>> duck-typing is all about: Making the operator behave in a way that makes >>>>> sense in its context. >>>> No it isn't. Ducktyping is about similar objects using a similar >>>> interface to invoke similar behaviour and getting similar result. >>>> >>>> So that if you write a function you don't concern yourself with >>>> the type of the arguments but depend on the similar behaviour. >>>> >>> Please note that "similar" does not mean "exact". >> >> That is because I don't want to get down in an argument about >> whether tp[:3] and ls[:3] is similar behaviour or exact the >> same behaviour when tp is a tuple and ls is a list. >> >>> The behavior of str.__contains__ and list.__contains__ is similar. >> >> That would depend on how much you find things may differ and >> still call them similar. IMO they are not similar enough >> since "12" in "123" doesn't behave like [1,2] in [1,2,3] >> > And it never will, because of the property of strings I mentioned > previously. Unless you want to introduce a character type into Python > there is no way that you are ever going to be be satisfied. The properties of strings didn't force the developers to make those two behave differently. They could have made the choice that "12" in "123" returned False and could have introduced a method that would return True or False depending on whether the argument was a substring or not. The same method could then eventually be used in other sequences to test whether the argument was a subsequence or not. Either by the python-developers themselves if they ever thought that usefull or by any programmer who could add this functionality to a subclass. Yes the properties of strings allowed for the solution the python developers have chosen, a solution not extendable to other sequence types. So yes [1,2] in [1,2,3] will never behave like "12" in "123" currently does and the properties of strings allowed it to evolve this way but in the end it was a design choice that could have been made differently and could have been made in a way to allow more duck typing and more access to polymorphism. >> And consider that each small inconsistency in itself >> may be not important enough to remove. But if you >> have enough of them remembering all these special >> cases can become tedious. >> > But not as tedious as this eternal discussion of already-decided issues. A number of those "decided" issue have been changed. Besides nobody is forcing you to participate. If you think these kind of issues is too tedious for your taste, feel free to no longer participate. >> Strings have some properties that are different and some >> properties that are similar with other sequences. My argument >> is that if you want to facilitate duck typing and natural access to >> polymorphism in peoples functions that work with sequences in general >> you'd better take care that the sequence api of strings resembles >> the sequence api of other sequences as good as possible. >> > This is just a bald restatement of the same argument you feel makes it > desirable to add an index() method to tuples. No it is not a bald statement. If tuple would have methods like index and count, more functions could be written that are indifferent to the argument being a tuple or a list or at least it would make writing such a function easier, so it would allow for more duck typing and give more access to polymorphism. You may think this kind of duck typing and polymorphism insignificant but that doesn't change the truth about the above statement. > If taken to its logical > (and ridiculous) extreme there should only be one sequence type in Python. No it doesn't. There is a big difference between having sequences with different properties because there is a need for those different properties and making things more different than needed and using the need for different properties to introduce differences that are unnecessary. >> You on the other hand seem to argue that since strings have >> properties where they differ from other sequences it no longer >> is so important that the sequence api of strings resembles those >> of other sequences. >> > Well, of course. Programming languages are for human users, and they > should do what human users find most natural. Since humans can disagree > the developers (amongst who I do not count myself, although I *am* > concerned about the development of Python) have to try and go by > consensus, which by and large they do reasonably successfully. But the defence of not having tuple.index has never been about what was natural to the user or not, but has always been about what tuples were supposedly intended for. > So what I suppose I *am* saying is that your opinions would seem to > differ from the consensus. While you are not in a minority of one you > are in a minority, and it would be nice if we could proceed without > having to continually revisit each small design decision on a continuous > basis. I am not so sure I'm in a minority. This kind of thing is not decided by consensus at least not among the python users. It is the sole decision of the BDFL. Besides, this is usenet, all kind of things get revisted here on a continuous basis. Why should design decisions be an exception? -- Antoon Pardon From howe.steven at gmail.com Thu Apr 19 12:03:10 2007 From: howe.steven at gmail.com (Steven Howe) Date: Thu, 19 Apr 2007 09:03:10 -0700 Subject: comparison with None In-Reply-To: References: <_JAVh.1700$jR5.897@trnddc08> <462709FB.9020607@gmail.com> Message-ID: <462792BE.906@gmail.com> Steven D'Aprano wrote: > On Thu, 19 Apr 2007 08:18:30 -0400, Steve Holden wrote: > > >>> Which is why I suggested using the explicit type(x) == types.NoneType as >>> opposed to >>> x is None >>> >>> >>> >> This seems to go entirely against the spirit of the language. It's about >> as sensible as writing >> >> (3 > 4) == True >> > > > Please! For extra certainty, you should write that as: > > ((int(3) > int(4)) == True) == True > > Explicit is better than sensible, yes? > > *wink* > > > > Your example, even with the *wink*, is stupid. The language requires 3 to be an integer, 4 to be an integer. The point I was show is with respect to a returned variable (like from a function or method? *wink* *wink*). For example, if you expect an open file handle, but get a NoneType because you didn't really open a file (having given a bad name or maybe didn't have permission to open a file), then it would be best to test the type of return object before using it. Then you program could handle the error gracefully (*wink* *wink* *wink*). As much as I love Python, it's ability to morph an object type can be a pain. Testing before using can prevent a program from Error-ing out. Steven Howe -------------- next part -------------- An HTML attachment was scrubbed... URL: From thorsten at thorstenkampe.de Sun Apr 1 15:48:11 2007 From: thorsten at thorstenkampe.de (Thorsten Kampe) Date: Sun, 1 Apr 2007 20:48:11 +0100 Subject: I18n issue with optik References: Message-ID: * Thorsten Kampe (Sun, 1 Apr 2007 20:22:51 +0100) > * Thorsten Kampe (Sun, 1 Apr 2007 20:08:39 +0100) > > * Thorsten Kampe (Sun, 1 Apr 2007 19:45:59 +0100) > > > Yes, I could do that but I'd rather know first if my code is wrong or > > > the optparse code. > > > > It might be the bug mentioned in > > http://mail.python.org/pipermail/python-dev/2006-May/065458.html > > > > The patch although doesn't work. From my unicode-charset-codepage- > > codeset-challenged point of view the encoding of sys.stdout doesn't > > matter. The charset is defined in the .po/.mo file (but of course > > optparse can't know if the message has been translated by gettext > > ("_"). > > If I "patch" line 1648 (the one mentioned in the traceback) of > optparse.py from > > file.write(self.format_help().encode(encoding, "replace")) > to > file.write(self.format_help()) > > ...then everything works and is displayed fine [...] ...but only in Cygwin rxvt, the standard Windows console doesn't show the right colors. I give up and revert back to ASCII. This whole charset mess is not meant to solved by mere mortals. Thorsten From quiettechblue at yahoo.com Sun Apr 22 22:22:18 2007 From: quiettechblue at yahoo.com (joseph2k) Date: Sun, 22 Apr 2007 19:22:18 -0700 Subject: *** Dr G Polya BRILLIANTLY analyses the Virgina Shooting Incident *** References: <1177266754.126153.202760@b58g2000hsg.googlegroups.com> Message-ID: thermate at india.com wrote: > Dr Gideon Polya published some 130 works in a 4 decade scientific > career, most recently a huge pharmacological reference text > "Biochemical Targets of Plant Bioactive Compounds" (Taylor & Francis, > New York & London, 2003), and is currently editing a completed book on > global avoidable mortality (numerous articles on this matter can be > found by a simple Google search for "Gideon Polya" and on his > websites: > > Here is the BRILLIANT AND INCISIVE ANALYSIS: > > http://countercurrents.org/polya230407.htm <------ > > Dr Polya, we are incredibly proud of you. God Bless you for your > courage. That certainly does not qualify as analysis, and clearly falls short of brilliant or incisive let alone both together. -- JosephKK Gegen dummheit kampfen die Gotter Selbst, vergebens.?? --Schiller From carsten at uniqsys.com Tue Apr 10 07:47:46 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Tue, 10 Apr 2007 07:47:46 -0400 Subject: tuples, index method, Python's design In-Reply-To: References: <1175867771.114540.61810@n76g2000hsh.googlegroups.com> <1175884427.779950.267220@y80g2000hsf.googlegroups.com> <1175953520.316208.241490@o5g2000hsb.googlegroups.com> <7xzm5igbrb.fsf@ruckus.brouhaha.com> Message-ID: <20070410114243.M53276@uniqsys.com> On 10 Apr 2007 09:48:41 GMT, Antoon Pardon wrote > If someone states: "Show me your use case for using tuple.index and I > will show you how to avoid it." or words to that effect I think there > is little use trying. Or maybe you just can't think of any good use cases, and that's annoying you because it proves my point. Please, prove me wrong by showing use cases for tuple.index that can't be rewritten. -Carsten From durumdara at gmail.com Wed Apr 25 07:09:19 2007 From: durumdara at gmail.com (Durumdara) Date: Wed, 25 Apr 2007 13:09:19 +0200 Subject: PIL font formatting... Message-ID: <9e384ef60704250409q410f0e32wd08ca3af7e0e853c@mail.gmail.com> Hi! I wrote a web visitor counter with modpy and pil. It is must working on half-static page, so I must write this counter with jpeg image output. Everything is working good, but I need to change this counter a little, it's style isn't same as it's webpage's style. I want to make bold and italic text into image. How to I do it? font = ImageFont.truetype('arial.ttf', 15, ????) .text('aaaaa', font = font, ????) Please help me!!! dd -------------- next part -------------- An HTML attachment was scrubbed... URL: From deets at nospam.web.de Tue Apr 17 04:17:54 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 17 Apr 2007 10:17:54 +0200 Subject: Compare regular expressions In-Reply-To: <1176753723.382697.268430@y80g2000hsf.googlegroups.com> References: <1176753723.382697.268430@y80g2000hsf.googlegroups.com> Message-ID: <58je5lF2hg4r3U2@mid.uni-berlin.de> Paddy schrieb: > On Apr 16, 10:50 am, Thomas Dybdahl Ahle wrote: >> Hi, I'm writing a program with a large data stream to which modules can >> connect using regular expressions. >> >> Now I'd like to not have to test all expressions every time I get a line, >> as most of the time, one of them having a match means none of the others >> can have so. >> >> But ofcource there are also cases where a regular expression can >> "contain" another expression, like in: >> "^strange line (\w+) and (\w+)$" and "^strange line (\w+) (?:.*?)$" in >> which case I'd like to first test the seccond and only if it mathces test >> the seccond. >> >> Do anybody know if such a test is possible? >> if exp0.contains(exp1): ... > > you could OR all the individual RE's test them all at once then find > out which matched. > > big_re = "|".join( r"(?P<__match_%i__>%s)" % (i, r) > for i,r in enumerate(regexps) ) > > now if one of the regexps matches then the corresponding named > group should have a non-empty string value. This doesn't answer the question if two of the sub-expressions matched. Diez From steve at REMOVE.THIS.cybersource.com.au Thu Apr 12 00:23:08 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Thu, 12 Apr 2007 14:23:08 +1000 Subject: Strange Behavior with Old-Style classes and implicit __contains__ References: <1176334655.677943.70030@q75g2000hsh.googlegroups.com> Message-ID: On Thu, 12 Apr 2007 00:32:32 -0300, Gabriel Genellina wrote: > First I want to say that __getitem__ should raise IndexError, not > KeyError, to indicate "not found" How do you know the Original Poster's class was meant to be a sequence rather than a mapping? -- Steven. From frank at niessink.com Wed Apr 11 12:07:46 2007 From: frank at niessink.com (Frank Niessink) Date: Wed, 11 Apr 2007 18:07:46 +0200 Subject: Seeking list of Python applications on OS X In-Reply-To: References: Message-ID: <67dd1f930704110907k6a2b2yf790206f5698f857@mail.gmail.com> Hi Kevin, 2007/4/11, Kevin Walzer : > Hello, > > I am seeking to update this wiki page, which lists Mac OS X applications > using Python in a significant way: Task Coach is developed with python and wxPython and is distributed as dmg. See http://www.taskcoach.org Cheers, Frank From aleax at mac.com Sun Apr 29 20:36:46 2007 From: aleax at mac.com (Alex Martelli) Date: Sun, 29 Apr 2007 17:36:46 -0700 Subject: relative import broken? References: <1hxa9x3.c0unyd1jw7vu9N%aleax@mac.com> Message-ID: <1hxcdkq.47p2r6beuctcN%aleax@mac.com> Alan Isaac wrote: > "Alex Martelli" wrote in message > news:1hxa9x3.c0unyd1jw7vu9N%aleax at mac.com... > > If you're running test1.py as your main module, then it's not part of a > > package, so the relative import should indeed fail as you mention. > > So if I understand you, > in a package, any module that I wish > to make available for execution as a script > (in the usual way, with a main function) > cannot have any relative imports. > Is this right? What is the reason for > this restriction? (And where is it > documented?) The most up-to-date documentation for import and from statements is at but it's still somewhat incomplete -- it gives the grammar for relative imports, but does not explain its semantics, nor, for that matter, any of the semantics of pakages. The discussions about relative imports in particular are recorded as PEP 328, while an old essay about the semantics of packages is recorded at a link give on the docs page I mentioned. Very simply, PEP 328 explains: """ Relative Imports and __name__ Relative imports use a module's __name__ attribute to determine that module's position in the package hierarchy. If the module's name does not contain any package information (e.g. it is set to '__main__') then relative imports are resolved as if the module were a top level module, regardless of where the module is actually located on the file system. """ and points to four discussion threads on python-dev which, after much give and take, led to Guido picking these semantics. To me, it makes sense: if a module is top-level, and thus not part of a package (and __main__ in particular is always in that state), then saying "import from the current package" has no well defined meaning, because there IS no "current package". Using __name__ rather than __file__, in turn, makes a lot of sense, because a package's _logical_ structure is defined by its __path__, and need not coincide with any _physical_ arrangement of directories. If you have a better and sharper idea about how relative imports should work in toplevel modules (those whose __name__ indicates they have NOT been imported as part of a package, including __main__), feel free to make a case for it on python-dev (python-list is fine for preliminary discussions and brainstorming, but nothing will happen about any idea until and unless it's taken to python-dev, survives the scathing barrage of objections that strongly characterizes that mailing list, and finally manages to convince Guido:-). Alex From attn.steven.kuo at gmail.com Wed Apr 4 15:33:09 2007 From: attn.steven.kuo at gmail.com (attn.steven.kuo at gmail.com) Date: 4 Apr 2007 12:33:09 -0700 Subject: calling super() In-Reply-To: <1175714555.413502.77390@o5g2000hsb.googlegroups.com> References: <1175714555.413502.77390@o5g2000hsb.googlegroups.com> Message-ID: <1175715189.655580.187160@y80g2000hsf.googlegroups.com> On Apr 4, 12:22 pm, Finger.Octo... at gmail.com wrote: > Hello, I have been trying to call the super constructor from my > derived class but its not working as expected. See the code: > > class HTMLMain: > def __init__(self): > self.text = ""; > print(self.text); > def __del__(self): > self.text = ""; > print(self.text); > > class NewPage(HTMLMain): > def __init__(self): > print 'derive2 init' > super(NewPage, self).__init__(); > > N = NewPage(); > del N > > And here's the error message I get: The error message is trying to tell you that 'super' should be used with new style classes. So, class HTMLMain: should be class HTMLMain(object): -- Hope this helps, Steven From samjnaa at gmail.com Sat Apr 14 10:07:23 2007 From: samjnaa at gmail.com (jamadagni) Date: 14 Apr 2007 07:07:23 -0700 Subject: Python Feature Request: Allow changing base of member indices to 1 In-Reply-To: References: <1176546465.632410.52630@w1g2000hsg.googlegroups.com> <4620b47b$0$14410$9b622d9e@news.freenet.de> <1176557999.665663.299740@y80g2000hsf.googlegroups.com> Message-ID: <1176559643.450533.296850@n59g2000hsh.googlegroups.com> > Modules are parsed when they are imported. And some modules are already > imported before your module is imported because they are built-in or > loaded to be able to import your module in the first place. And what > about modules that are written in C? OK fine. It is clear that this feature must be implemented if at all only on a per-module basis. So can we have votes for per-module implementation of this feature? From adrian_p_smith at yahoo.com Sun Apr 22 02:08:04 2007 From: adrian_p_smith at yahoo.com (Adrian Smith) Date: 21 Apr 2007 23:08:04 -0700 Subject: python cgi problem with textarea Message-ID: <1177222084.696307.128620@n59g2000hsh.googlegroups.com> This may be more a cgi thing than a Python one, but I'm trying to get this page: http://adrian10.phpwebhosting.com/trial.html consisting basically of this:

...to print out the contents of the textarea with this cgi script: #!/usr/bin/python import cgi print "Content-type: text/html\n" form = cgi.FieldStorage() print form["essay"].value ...and I get an internal server error if I have any spaces in the textarea, which is really going to limit its usefulness to me. Oddly, it seems to work for a friend in the UK who's looked at it, but it doesn't work for me here in Japan. From grgstch at googlemail.com Wed Apr 25 07:37:31 2007 From: grgstch at googlemail.com (Gregor Stich) Date: 25 Apr 2007 04:37:31 -0700 Subject: jython: user-defined modules Message-ID: <1177501051.043114.261420@r30g2000prh.googlegroups.com> Dear all, I hope my question is here in the right place... What I want to achieve is a communication between Java and Python. We have a pretty strong framework of existing python scripts and modules. Now I want to use jython in order to faciliate the communication between another Java framework. But I`m currently stuck with jython: Trying to import the user-defined python modules, these cannot be found. I read a lot about the jython registry and I setup a $HOME/.jython file where I created a python.path=... resource, however, when I start the jython command line and type print python.path then this property is not found. Passing it with the -D option does not work as well, or maybe I`m too confused to make it work anyway? Any help would be great! Best regards Greg From alisonken1 at gmail.com Fri Apr 27 17:59:42 2007 From: alisonken1 at gmail.com (alisonken1) Date: 27 Apr 2007 14:59:42 -0700 Subject: if __name__ == 'main': & passing an arg to a class object In-Reply-To: <1177708104.277756.245360@t38g2000prd.googlegroups.com> References: <1177708104.277756.245360@t38g2000prd.googlegroups.com> Message-ID: <1177711182.787219.272900@s33g2000prh.googlegroups.com> On Apr 27, 2:08 pm, gtb wrote: > The lines > > if __name__ == 'main': > someClass().fn() > > appear at the end of many examples I see. Is this to cause a .class > file to be generated? > These are samples to give the programmer an idea of how the code is supposed to work. If you cut/paste these examples in your working code, you have to change the source to something that actually works. BTW - Python does not use separate *.class files - *.py scripts (text files) are byte compiled to *.pyc files for the python interpreter. Would you perchance be referring to Java programming (which is a different newsgroup)? > The last line of the sample below has a string parameter. When I > mimicked this I got an error stating that the class constructor did > not take an arg, which seems correct. > > Thanks, > > gtb > > # Generated by MaxQ [com.bitmechanic.maxq.generator.CompactGenerator] > from CompactTest import CompactTest > > class MaxQTest(CompactTest): > # Recorded test actions. > def runTest(self): > self.msg('Test started') > > # ^^^ Insert new recordings here. (Do not remove this line.) > > # Code to load and run the test > if __name__ == 'main': > MaxQTest('MaxQTest').Run() In this case, the routine was called from a python command line, so the __name__ variable is set to "__main__". This is a standard Python trick to see if you are running the file as a stand alone script, or if it was imported as a module (typically used with code that was written that can be either standalone or used as part of a different package - good for unit testing). The example above { MaxQTest("MaxQTest").Run() } tells me either you're trying to run a threaded application, or you're used to Java programming. Again, would you be wanting to talk to a Java newsgroup rather than a Python newsgroup? From maric at aristote.info Thu Apr 19 12:28:16 2007 From: maric at aristote.info (Maric Michaud) Date: Thu, 19 Apr 2007 18:28:16 +0200 Subject: Iterate through a dictionary of lists one "line" at a time In-Reply-To: <1176921542.567121.248820@b58g2000hsg.googlegroups.com> References: <1176921542.567121.248820@b58g2000hsg.googlegroups.com> Message-ID: <462798A0.4040902@aristote.info> wswilson a ?crit : > Here is my code: > > listing = {'id': ['a', 'b', 'c'], 'name': ['Joe', 'Jane', 'Bob']} > > I need to output: > > id name > a Joe > b Jane > c Bob > > I could do: > > print 'id', 'name' > for id, name in zip(listing['id'], listing['name']): print id, name > > but that only works if there are two entries in the dictionary, id and > name, and I know what they are. My problem is I don't know how many of > these entries there will be. Thanks for any help you can give! > The most simple and generic I see, it could be even more simple if you don't care of memory usage : Let's fill a random dict : In [118]: d=dict(zip((str(e) for e in xrange(10)), ([i**e for e in xrange(5)] for i in xrange(10)))) In [119]: d Out[119]: {'0': [1, 0, 0, 0, 0], '1': [1, 1, 1, 1, 1], '2': [1, 2, 4, 8, 16], '3': [1, 3, 9, 27, 81], '4': [1, 4, 16, 64, 256], '5': [1, 5, 25, 125, 625], '6': [1, 6, 36, 216, 1296], '7': [1, 7, 49, 343, 2401], '8': [1, 8, 64, 512, 4096], '9': [1, 9, 81, 729, 6561]} go on : In [146]: sorted_keys = tuple(sorted(d.keys())) In [147]: from itertools import izip, chain In [148]: sorted_keys = tuple(sorted(d.keys())) In [149]: sorted_values = ( d[k] for k in sorted_keys ) In [150]: for vals in chain([sorted_keys], izip(*sorted_values)) : .....: print '%5s'*len(d) % vals .....: .....: 0 1 2 3 4 5 6 7 8 9 1 1 1 1 1 1 1 1 1 1 0 1 2 3 4 5 6 7 8 9 0 1 4 9 16 25 36 49 64 81 0 1 8 27 64 125 216 343 512 729 0 1 16 81 256 625 1296 2401 4096 6561 -- _____________ Maric Michaud _____________ Aristote - www.aristote.info 3 place des tapis 69004 Lyon Tel: +33 4 26 88 00 97 Mobile: +33 6 32 77 00 21 From aisaac at american.edu Fri Apr 27 23:18:55 2007 From: aisaac at american.edu (Alan Isaac) Date: Sat, 28 Apr 2007 03:18:55 GMT Subject: relative import problem Message-ID: I'm new to relative imports and having a problem. (ValueError: Attempted relative import in non-package) I noticed this: http://www.thescripts.com/forum/thread549516.html Is this behavior intentional? I'm seeing it in Python 2.5.1. Thanks, Alan Isaac From spohle at gmail.com Mon Apr 30 10:56:52 2007 From: spohle at gmail.com (spohle) Date: 30 Apr 2007 07:56:52 -0700 Subject: import structures Message-ID: <1177945012.753497.117630@o5g2000hsb.googlegroups.com> hi, i have written a small project for myself all in seperate classes and each of the classes lives in a seperate file. now i am looking for an import structure something like import wx, and then have access to all my classes just like wx.Button or wx.BoxSizer etc. as of now i have a __init__.py file in the directory with: from pkgutil import extend_path __path__ = extend_path(__path__, __name__) but i still have to import each class by it's own. im really looking for something like import wx and then get all my access right away under this new namespace. thank you in advance From aboudouvas at panafonet.gr Wed Apr 11 16:41:41 2007 From: aboudouvas at panafonet.gr (king kikapu) Date: 11 Apr 2007 13:41:41 -0700 Subject: About Trolltech QT OpenSource license. In-Reply-To: References: <1176233376.712861.67160@o5g2000hsb.googlegroups.com> <1176237050.409742.8760@30g2000cwc.googlegroups.com> <1176285062.178372.15090@d57g2000hsg.googlegroups.com> Message-ID: <1176324101.685399.263330@w1g2000hsg.googlegroups.com> > > Ok, i see...So i can use Qt OS edition and earn money from this as > > long as i explicitly say (is a reference to a GPL in a readme text > > file enough for this ?) that this software is under the GPL lisence > > and i have the obligation to give the source code with it. > > It's a bit more complicated than that. Why ? From the whole discussion here, i understand that ok, i will give my source code with my program and i can sell this at the same time and earn money. If i mess with Qt, i will write software for myself, internaly at the company i work for and maybe produce software and sell it by myself. If you think that i am missing something, please let me know. (Maybe i should stick with wxPython and PythonCard...) From tjreedy at udel.edu Mon Apr 23 14:15:18 2007 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 23 Apr 2007 14:15:18 -0400 Subject: python style guide inconsistencies References: <5922mkF2i88dhU1@mid.individual.net> Message-ID: "Darren Dale" wrote in message news:f0ih8j$9o4$1 at ruby.cit.cornell.edu... | Then perhaps http://www.python.org/doc/essays/styleguide.html should either | be updated to either agree with or simply link to PEPs 8 and 257. What is | the point of keeping old, out-of-date essays up on python.org? Now that Guido has agreed with you (on pydev), wait a couple of days, if there is no response from one of webmasters, go to this page, click update suggestion link at bottom, and cut and paste his posting. No need for further discussion here. Thanks for following this thru. Persistence is how docs get improved. tjr From danb_83 at yahoo.com Sat Apr 14 11:29:43 2007 From: danb_83 at yahoo.com (Dan Bishop) Date: 14 Apr 2007 08:29:43 -0700 Subject: Simple integer comparison problem In-Reply-To: References: Message-ID: <1176564583.077072.325970@w1g2000hsg.googlegroups.com> On Apr 14, 10:19 am, t... at finland.com wrote: > Hi! > I ran in problem with simple exercise. I'm trying to get program to > return grade when given points but no matter what, I always get F. > > def grader(): > print "Insert points: " > points = raw_input('> ') > int(points) > > if points > 89 and points <= 100: > return "A" > elif points > 89 and points <= 89: > return "B" > elif points > 69 and points <= 79: > return "C" > elif points > 59 and points <= 69: > return "D" > else: > return "F" > > grade = grader() > print grade You have a typo in the first "elif": "points > 89 and points <= 89" is never true, so you'll get an "F" instead of a "B". BTW, Python lets you write things like "80 <= points < 90". From nospam at invalid.com Wed Apr 25 19:06:50 2007 From: nospam at invalid.com (Jack) Date: Wed, 25 Apr 2007 16:06:50 -0700 Subject: MS SQL Server Extension? References: Message-ID: <-ImdnURzH42aQrLbnZ2dnUVZ_tunnZ2d@comcast.com> Thanks Tim for the reply. Good info. I just set up pymssql. Setting it up was fairly straightforward. What kind of problems does it have with unicode? "Tim Golden" wrote in message news:mailman.6928.1177487066.32031.python-list at python.org... > Jack wrote: >> Hi all, in my next project, my Python code needs to talk to an MS SQL >> 2000 Server. Internet search gives me http://pymssql.sourceforge.net/ >> I wonder what module(s) people are using. My code runs on a Linux >> box so the module has to build on Linux. Any hints/pointers are welcome. > > There are several modules around which will cover this. > One of these days I'll take the post I'm about to write > and stick it on a Wiki or something because I seem to > write it about once every six months :) > > In no particular order: > > adodbapi - recently resurrected from moribundity (if > that's a word); search the list archives because I > can't remember who's working on it. > > + Win32 only (afaik) > + Covers all sorts of things as well as MSSQL > + Allows for passthrough authentication > > - Used to have some slight flakiness in it. Bloke > who's taken over maintenance says he's patched and > simplified things. Haven't tried it since. > > pymssql - http://pymssql.sf.net > > + Win32 & Linux (via FreeTDS) > > - Doesn't allow passthrough authentication > - Has some issues with Unicode > > pyodbc - http://pyodbc.sf.net > (a recent runner) > > + Win32 & Linux (via whatever *nix ODBC package) > + Apparently more actively maintained than pymssql > + (Is currently the favoured front-runner among the sqlalchemy devs) > > - Lacks .nextset (in case that's important to you) > > Other contenders: > > mxODBC - Commercial License but a very strong > and long-standing candidate. Lacks .nextset > support. Works on *nix via iODBC etc. > > Object Craft MSSQL - Worked well for me for years > but they seemed to have abandoned it of late. > Still there. Still works. But no binaries beyond > Python 2.3. (I did try to recompile using MingW > but couldn't get it to work). Works on *nix via > FreeTDS. > > TJG From jeba.ride at gmail.com Thu Apr 19 14:32:42 2007 From: jeba.ride at gmail.com (Clement) Date: 19 Apr 2007 11:32:42 -0700 Subject: NFS Help Message-ID: <1177007562.103413.310390@o5g2000hsb.googlegroups.com> how to get the file from NFS share in python...... From attn.steven.kuo at gmail.com Sun Apr 1 18:21:24 2007 From: attn.steven.kuo at gmail.com (attn.steven.kuo at gmail.com) Date: 1 Apr 2007 15:21:24 -0700 Subject: Overlapping matches In-Reply-To: References: Message-ID: <1175466084.892930.248310@n76g2000hsh.googlegroups.com> On Apr 1, 1:38 pm, Rehceb Rotkiv wrote: > In the re documentation, it says that the matching functions return "non- > overlapping" matches only, but I also need overlapping ones. Does anyone > know how this can be done? Perhaps lookahead assertions are what you're looking for? import re import string non_overlap = re.compile(r'[0-9a-fA-F]{2}') pairs = [ match.group(0) for match in non_overlap.finditer(string.hexdigits) ] print pairs overlap = re.compile(r'[0-9a-fA-F](?=([0-9a-fA-F]))') pairs = [ match.group(0) + match.group(1) for match in overlap.finditer(string.hexdigits) ] print pairs -- Hope this helps, Steven From flyzone at technologist.com Thu Apr 26 02:30:59 2007 From: flyzone at technologist.com (Flyzone) Date: 25 Apr 2007 23:30:59 -0700 Subject: freeze and problem with static libraries In-Reply-To: <1177428217.892613.125750@u32g2000prd.googlegroups.com> References: <1177428217.892613.125750@u32g2000prd.googlegroups.com> Message-ID: <1177569059.184898.108880@b40g2000prd.googlegroups.com> On 24 Apr, 17:23, Flyzone wrote: > I get this warning on freezing my source: I use the command: ./Python-2.3.6/Tools/freeze/freeze.py /path/to/my/file.py From paddy3118 at googlemail.com Thu Apr 5 15:08:43 2007 From: paddy3118 at googlemail.com (Paddy) Date: 5 Apr 2007 12:08:43 -0700 Subject: Why NOT only one class per file? In-Reply-To: <2O9Rh.24647$uo3.24013@newssvr14.news.prodigy.net> References: <1175721799.714907.52770@o5g2000hsb.googlegroups.com> <46142acc$0$7532$426a34cc@news.free.fr> <4614b40e$0$26843$426a74cc@news.free.fr> <1175778276.603838.86500@l77g2000hsb.googlegroups.com> <2O9Rh.24647$uo3.24013@newssvr14.news.prodigy.net> Message-ID: <1175800123.904669.172490@n76g2000hsh.googlegroups.com> On Apr 5, 5:51 pm, John Nagle wrote: > Nate Finch wrote: > > I think you're all going about this the wrong way. There's no reason > > to *always* have one class per file. However, there's also no reason > > to have 1600 lines of code and 50 classes in one file either. > > It's really an operating system thing. We think of programs as > living in text files, manipulated by programs which are basically text > editors. Python has that implicit assumption. There have been > systems that didn't work that way, in which the program source was > manipulated within the language environment, in a more structured > fashion. Smalltalk, LISP, and (wierdly) Forth environments have been > built that way. But it never really caught on. > > The assumption that programs are text files is deeply embedded in > programming culture, so deeply that it's seldom questioned. Programs > are the last refuge of non-rich media. You can't even embed an image > in your program; it has to be in some completely separate file. > > Interestingly, PHP breaks this model; PHP programs are web pages. > They may be on to something. > > John Nagle Some languages (Specman e, and I think Perl), have the concept of begin and end end markers. The interpreted/compiled code is what is seen between those markers allowing the source to be embedded in other text. From robert.kern at gmail.com Wed Apr 11 03:56:51 2007 From: robert.kern at gmail.com (Robert Kern) Date: Wed, 11 Apr 2007 02:56:51 -0500 Subject: About Trolltech QT OpenSource license. In-Reply-To: <1176237050.409742.8760@30g2000cwc.googlegroups.com> References: <1176233376.712861.67160@o5g2000hsb.googlegroups.com> <1176237050.409742.8760@30g2000cwc.googlegroups.com> Message-ID: king kikapu wrote: > As i said, i do not fully understand all this license stuff. All i > want to ask is, i can make GPL software and gain money from this ? And > if that so, then why they "force" you to buy the commercial lisence in > such case ? Others have given good answers. I would only like to clarify what I think is the source of confusion here. While the FSF and many open source advocates make a distinction between the words "commercial" (meaning that someone derives money from distributing the software, whether it is GPLed or not) and "proprietary" (meaning that the software is not being distributed under an open source license but one that restricts user's rights), Trolltech abuses the term "commercial" to mean "proprietary" in this case. If you obey the terms of the GPL and still manage to derive money from it, you don't need Trolltech's "commercial" license. Just be sure that you do obey the terms of the GPL; it's not entirely trivial to build a business model around it. Such a business will be somewhat different from one that uses proprietary licenses. -- 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 apardon at forel.vub.ac.be Wed Apr 25 03:13:20 2007 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 25 Apr 2007 07:13:20 GMT Subject: Tutorial creates confusion about slices References: <1177457741.037238.315050@r35g2000prh.googlegroups.com> Message-ID: On 2007-04-24, sjdevnull at yahoo.com wrote: > > Antoon Pardon wrote: >> On 2007-04-24, Michael Bentley wrote: >> > >> > On Apr 24, 2007, at 6:35 AM, Antoon Pardon wrote: >> > >> >> People don't read tutorials in a strictly linear fashion. They can >> >> continue to later subjects and then come back here to see how things >> >> tie together. So the fact that it is only confusing to those who >> >> know more than is already presented doesn't seem a very good reason >> >> to leave it in. >> > >> > Yet they understand that earlier in the document, there is likely to >> > be a less complete coverage of a given topic. There is in fact, a >> > link on that page that includes a more complete coverage of that >> > topic (which I mentioned to you in an earlier message IIRC). >> >> That there is more complete coverage elsewhere is no good reason >> to come with an explanation that suggests things working in >> a way that will be contradicted by that more complete coverage. > > I happen to agree with you, but that's not a completely non- > controversial position. Many tutorials/manuals will prevent a > simplified (and incorrect for the general case) description of how > something works early on, and then clarify it later for the general > case. Personally I'd usually rather have the complete description > earlier rather than an incorrect simplification, or at least have a > footnote to the effect of "this is a simple introduction, the full > behavior will be described later". > > But there's a good argument to be made for omitting confounding > details early on in a tutorial if there's a pedogogical reason for > doing so--indeed, there's such a widespread belief that early > oversimplification is actually helpful that I'd guess the majority of > language tutorials engage in it to some degree. Thank you for bringing this up so explicitly. I must confess this point hadn't entered my mind but it is worth thinking about. I'll see if I can come up with a new proposal bearing this in mind. Thank you. -- Antoon Pardon From horpner at yahoo.com Wed Apr 25 10:17:50 2007 From: horpner at yahoo.com (Neil Cerutti) Date: 25 Apr 2007 16:17:50 +0200 Subject: Tutorial creates confusion about slices References: Message-ID: On 2007-04-25, Hamilton, William wrote: > That's how everything I've ever learned has been taught. Start > with a simple explanation that may not be completely accurate > but is functional, then fill in the details later when there is > a context to put them in. The tutorial could start out by > explaining everything at the implementation level; it doesn't > because it is a _tutorial_, intended to give new users the > context they need to understand the more complicated nuances of > the language. > > If it covered every fiddly little detail, it wouldn't be a > tutorial. It would be a language reference document instead. Presenting a simplified model is a good technique, but when a simplified model is presented it should be clearly stated wether or not that model will eventually prove inadequate. Is the divider-between-elements model presented in the tutorial really the "best way" to understand half-open range notation? I vote we change the word "best" to "possible" in the excerpt. -- Neil Cerutti From bbxx789_05ss at yahoo.com Mon Apr 9 00:25:55 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: 8 Apr 2007 21:25:55 -0700 Subject: python, wxpython and Mac OS X In-Reply-To: References: <1176086130.330795.268590@n76g2000hsh.googlegroups.com> Message-ID: <1176092755.914088.5040@p77g2000hsh.googlegroups.com> On Apr 8, 8:46 pm, Robert Kern wrote: > 7stud wrote: > > Why 2.4.4 instead of the official 2.5 binary fromwww.python.org? > > http://www.python.org/download/ > 1) On some download page that listed both python 2.5 and 2.4, it said that python 2.4 had more packages/modules available for Macs than 2.5. 2) The wxPython website says that to use wxPython on a Mac, you need a special "framework" build of python--like the one that comes preinstalled. It says framework builds are available for python 2.4. Should I remove 2.4.4 and install 2.5 instead? > > > Also, what wxPython download should I install? > > For 2.4:http://prdownloads.sourceforge.net/wxpython/wxPython2.8-osx-unicode-2... > > For 2.5:http://prdownloads.sourceforge.net/wxpython/wxPython2.8-osx-unicode-2... > Thanks. From bj_666 at gmx.net Thu Apr 26 08:53:10 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Thu, 26 Apr 2007 14:53:10 +0200 Subject: File not read to end References: <1177522730.327454.121120@s33g2000prh.googlegroups.com> <-LWdnRS04OCCCLLbnZ2dnUVZ_uSgnZ2d@comcast.com> <1177589949.885985.164380@c18g2000prb.googlegroups.com> Message-ID: In <1177589949.885985.164380 at c18g2000prb.googlegroups.com>, andrew.jefferies wrote: > On Apr 25, 2:51 pm, Larry Bates wrote: >> andrew.jeffer... at gmail.com wrote: >> > Hi, >> >> > I'm trying to write a simple log parsing program. I noticed that it >> > isn't reading my log file to the end. >> >> > My log is around 200,000 lines but it is stopping at line 26,428. I >> > checked that line and there aren't any special characters. >> >> > This is the file reading code segment that I'm using: >> > sysFile=open(sysFilename,'r') >> > lineCount = 0 >> > for line in sysFile: >> > lineCount +=1 >> > print str(lineCount) + " -- " + line >> >> > I also stuck this same code bit into a test script and it was able to >> > parse the entire log without problem. Very quirky. > > [?] > > I've attached the whole script. Thanks again for your help. There are ``break`` statements in the loop body!? Do you really want to leave the loop at those places? And I've seen at least two times ``somefile.close`` which does just reference the `close()` method but does not *call* it. Parenthesis are the "call operator" in Python and they are not optional! Ciao, Marc 'BlackJack' Rintsch From nagle at animats.com Mon Apr 23 13:21:12 2007 From: nagle at animats.com (John Nagle) Date: Mon, 23 Apr 2007 10:21:12 -0700 Subject: Socket exceptions aren't in the standard exception hierarchy In-Reply-To: References: Message-ID: Dennis Lee Bieber wrote: > On Sun, 22 Apr 2007 23:20:25 -0700, John Nagle > declaimed the following in comp.lang.python: > > >>2. File "D:\Python24\lib\socket.py", line 295, in read >>data = self._sock.recv(recv_size) >>error: (10054, 'Connection reset by peer') >> > > That looks like M$ Windows version of UNIX/Linux error number 54 > (pretty much all Windows socket errors are UNIX number+10000) > > Errors coming from Windows may not be mapped to specific Python > exceptions, but rather to some general error conditions. {hypothesis} As > such, the Windows errors may not match what UNIX/Linux report. Actually, that's not what's happening. The socket module is explicitly raising "socket.error" in C code. It's not an OSError or a WindowsError, although the text makes it look like one. The problem is not that socket errors aren't entirely portable. It's that they're not even in the Python exception hierarchy. See "http://docs.python.org/lib/module-exceptions.html". They have their own hierarchy, which starts at "socket.error". All built-in exceptions were supposed to be converted to the standard exception hierarchy back before Python 2.0, but these weren't. Either they should be under IOError, or there should be "NetworkError" under EnvironmentError, and they should be under that. "NetworkError", alongside IOError in the hierarchy, would be useful. All the things that go wrong in networking belong under there. Socket-level errors, SSL/TLS-level errors, and HTTP/FTP/etc. level errors all belong under NetworkError. This has to be fixed before PEP 352, when the exception hierarchy is enforced, or the socket exceptions won't even work right. John Nagle From buzzard at urubu.freeserve.co.uk Sun Apr 1 11:59:21 2007 From: buzzard at urubu.freeserve.co.uk (Duncan Smith) Date: Sun, 01 Apr 2007 16:59:21 +0100 Subject: reverse engineering Excel spreadsheet Message-ID: <460fd6d0.0@entanet> Hello, I am currently implementing (mainly in Python) 'models' that come to me as Excel spreadsheets, with little additional information. I am expected to use these models in a web application. Some contain many worksheets and various macros. What I'd like to do is extract the data and business logic so that I can figure out exactly what these models actually do and code it up. An obvious (I think) idea is to generate an acyclic graph of the cell dependencies so that I can identify which cells contain only data (no parents) and those that depend on other cells. If I could also extract the relationships (functions), then I could feasibly produce something in pure Python that would mirror the functionality of the original spreadsheet (using e.g. Matplotlib for plots and more reliable RNGs / statistical functions). The final application will be running on a Linux server, but I can use a Windows box (i.e. win32all) for processing the spreadsheets (hopefully not manually). Any advice on the feasibility of this, and how I might achieve it would be appreciated. I assume there are plenty of people who have a better knowledge of e.g. COM than I do. I suppose an alternative would be to convert to Open Office and use PyUNO, but I have no experience with PyUNO and am not sure how much more reliable the statistical functions of Open Office are. At the end of the day, the business logic will not generally be complex, it's extracting it from the spreadsheet that's awkward. Any advice appreciated. TIA. Cheers. Duncan From nyamatongwe+thunder at gmail.com Sat Apr 21 20:03:03 2007 From: nyamatongwe+thunder at gmail.com (Neil Hodgson) Date: Sun, 22 Apr 2007 00:03:03 GMT Subject: No speedup on multi-processor machine? In-Reply-To: <1177197495.821701.140390@b58g2000hsg.googlegroups.com> References: <1177189332.916296.205280@d57g2000hsg.googlegroups.com> <1177197495.821701.140390@b58g2000hsg.googlegroups.com> Message-ID: Fuzzyman: > IronPython is *definitely* not restricted by the GIL. IronPython is currently mostly slower than CPython although the particular problem should be tested to see if IronPython helps. Some recent benchmarks between IronPython and CPython: http://sparcs.kaist.ac.kr/~tinuviel/pybench/ Neil From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Sun Apr 29 07:26:36 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Sun, 29 Apr 2007 13:26:36 +0200 Subject: Beginner Ping program References: <1177739647.737759.32610@u30g2000hsc.googlegroups.com> <1177755579.454423.35590@n59g2000hsh.googlegroups.com> Message-ID: <59jdncF2jhibgU1@mid.individual.net> Linus Cohen wrote: > Actually the class ping bit is a placeholder. But why is it one? "ping" is something you do -- and not a "thing" of which you could have several copies. > I'm actually developing a module with python implementations of > most standard network/internet tools such as telnet, tracert, > whois etc. It will be called inettools, and the ping function is > what I'm working on first. It should be a simple enough job to > code in the features the Unix and DOS ping programs have(never > stop, change size, change timeout). IIRC, MS ping has no "never stop", you can only say "repeat 99999 times". Regards, Bj?rn -- BOFH excuse #148: Insert coin for new game From kyosohma at gmail.com Wed Apr 18 15:08:32 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: 18 Apr 2007 12:08:32 -0700 Subject: Help Understanding mx.ODBC Error In-Reply-To: References: Message-ID: <1176923312.859650.6430@q75g2000hsh.googlegroups.com> On Apr 18, 1:36 pm, Greg Corradini wrote: > Hello All, > A few weeks ago, I wrote two scripts using mx.ODBC on an Access DB. Among > other things, both scripts create new tables, perform a query and then > populate the tables with data in a dictionary that I've uploaded from > elsewhere. These scripts have run hundreds of times in the last few weeks > with no problems. > > But recently they continue to bail on the mycursor.execute('An SQL > Statement') after the table has been created. I get the following error > message: > Traceback (most recent call last): > File "C:\Documents and Settings\marv1shi\Desktop\Workspace\Existence > Script\DBF Checker\Access_SQL.py", line 35, in ? > curse.execute(sql) > ProgrammingError: ('07001', -3010, '[Microsoft][ODBC Microsoft Access > Driver] Too few parameters. Expected 4.', 4612) > > The real stinker, however, is that after it bails I can manually call > mycursor.execute('An SQL Statement'), then call my insert statement in the > Python Shell and it works fine. > > I just can't figure out how to reconcile this problem. Has anybody run into > this before? > > Thanks > Greg Corradini > -- > View this message in context:http://www.nabble.com/Help-Understanding-mx.ODBC-Error-tf3602497.html... > Sent from the Python - python-list mailing list archive at Nabble.com. Normally too few parameters refers to the SQL statement not inserting the proper number of items. An example would be to list 4 values and only insert 3. See below for a pseudo-SQL statement: INSERT into someDB (id, name, address, state) VALUES (value1, value2, value3) That should give the same error, I would think. You may need to check if your SQL statement or the way your db is created has changed in some way. Mike From parimala.kalavala at gmail.com Tue Apr 17 02:22:02 2007 From: parimala.kalavala at gmail.com (PARIMALA KALAVALA) Date: Tue, 17 Apr 2007 11:52:02 +0530 Subject: how to copy the contents of pygtk into a file Message-ID: <67eb1c790704162322v40fbb9e9m85c54e7dad206b47@mail.gmail.com> hi, I want to know how to copy the contents of a pygtk application into a file and include that in other applications. Pls reply to this . bye. -------------- next part -------------- An HTML attachment was scrubbed... URL: From bjourne at gmail.com Tue Apr 10 11:10:07 2007 From: bjourne at gmail.com (=?ISO-8859-1?Q?BJ=F6rn_Lindqvist?=) Date: Tue, 10 Apr 2007 17:10:07 +0200 Subject: tuples, index method, Python's design In-Reply-To: <1176210960.3430.20.camel@dot.uniqsys.com> References: <1175867771.114540.61810@n76g2000hsh.googlegroups.com> <1175884427.779950.267220@y80g2000hsf.googlegroups.com> <1176210960.3430.20.camel@dot.uniqsys.com> Message-ID: <740c3aec0704100810g5f962e8eu614fbaedecf3608e@mail.gmail.com> On 4/10/07, Carsten Haese wrote: > i = p.index(current_player) > opponents = p[:i-1] + p[i+1:] > > An alternative is this: > > opponents = tuple(x for x in p if x is not current_player) > > You may disagree, but in my opinion, the alternative is better because > it is a more natural translation of the concept that the opponents of > the current player are all players that are not the current player. Your alternative is wrong because it wont raise ValueError if current_player is not present in the tuple. Please revise your "solution." -- mvh Bj?rn From sjmachin at lexicon.net Tue Apr 24 23:50:53 2007 From: sjmachin at lexicon.net (John Machin) Date: Wed, 25 Apr 2007 13:50:53 +1000 Subject: Where's the source code for __builtin__? In-Reply-To: <-NadnSatQtP9VbPbnZ2dnUVZ_rTinZ2d@comcast.com> References: <1177457545.075398.204990@r3g2000prh.googlegroups.com> <462EA63C.6080805@lexicon.net> <87lkghgp72.fsf@benfinney.id.au> <-NadnSatQtP9VbPbnZ2dnUVZ_rTinZ2d@comcast.com> Message-ID: <462ed021$1@news.eftel.com.au> On 25/04/2007 1:17 PM, Steven Bethard wrote: > Ben Finney wrote: >> John Machin writes: >>> On 25/04/2007 9:32 AM, Dustan wrote: >>>> I've been paging through the source code for various C modules in >>>> python, and wanted to find the source of some of the builtin >>>> functions. >>> What's the 2nd file (in alphabetical order) in the Python folder? >> >> What is "the Python folder"? >> >> Assuming you mean "the folder for the Python standard library >> modules": > > Actually, he meant the folder named 'Python' in the checkout from the > repository: > > C:\...\python\2.X>dir Python > > Directory of C:\...\python\2.X\Python > > 03/21/2007 12:13 PM . > 03/21/2007 12:13 PM .. > 02/17/2007 03:11 PM 697 asdl.c > 03/19/2007 04:31 PM 103,444 ast.c > 02/17/2007 03:11 PM 865 atof.c > 03/19/2007 04:31 PM 66,286 bltinmodule.c > > Probably 'bltinmodule.c' is a good place to start. > It *was* the 2nd file in the 2.4.3 source I happened to have lying around on my hard drive :-) From aleax at mac.com Sat Apr 28 17:05:44 2007 From: aleax at mac.com (Alex Martelli) Date: Sat, 28 Apr 2007 14:05:44 -0700 Subject: My Python annoyances References: <1177790269.523160.276060@l77g2000hsb.googlegroups.com> Message-ID: <1hxa91l.1m4j5111n9vqrcN%aleax@mac.com> James Stroud wrote: > Andr? wrote: [snipping total repost of Andr?'s post] > > I'm really annoyed at Python - and not for the reasons already > > mentioned on this list. > > > > Everyone know that programming is supposed to be a dark art, nearly > > impossible to learn. Computer code is supposed to be something > > impossible to read to the common person and yet reveal their secrets > > to the initiated - just remember the code displayed in the Matrix... > > > > Python takes all of that away. It is just too readable. Even > > beginners can quickly learn to read code written by experts. > > > > To make it even friendlier to beginners, Python uses ugly double > > underscores both as prefix and suffix on "magic methods" to be invoked > > only by more advanced programmers. What's the fun in hiding the > > complexity so that beginners can stay away from potential problems. > > > > And why, oh why, does raw_input() have to go? Here was at least one > > good example of something that gave a hint (what does "raw" mean?) at > > the underlying complexity. Combined with the evil of the hidden eval > > in the more obvious input(), there was at least a chance to trip > > beginners into doing something "dangerous". Alas, that will no longer > > be the case... > > > > Python does not even make good use of weird symbols like $ and @ and % > > to define variable types like Perl does. Now, that's a language to > > learn if you want to be respected. I think that Georg Brandl had it > > right in his recent proposal: > > http://mail.python.org/pipermail/python-dev/2007-April/072419.html > > > > If not Perl, perhaps Python should be inspired by a language like C++, > > full of arcane stuff and, thankfully, requiring typing declaration. > > This dynamic typing thing makes it just too easy to write working > > programs quickly, especially combined with the ease of use of the > > interpreter. And this other thing called "duck typing" is just too > > flexible to use. > > > > No, Python should be more difficult. It should take a full two > > minutes to compile a "Hello World" program on a modern computer. > > > > Also, this "docstring" business has to go. Any programmer should, as > > a rite of passage, have to spend countless hours reading obscure > > documentation to learn other people's code before finding out what > > methods can be used and how they should be used. Having to use things > > like "dir" and "help" just makes it too easy. > > > > And don't get me started about the absence of curly braces to define > > blocks of code. What's the fun in making it so darn visually easy to > > define such blocks of code, removing the possibility of creating > > subtle bugs due to the misplacement of a curly bracket. No sir, with > > Python, the structure has to be obvious at a glance - newbies can see > > it just as well as experts, thereby decreasing the aura surrounding > > the latter. This is not fair for people that have spent dozens of > > hours in learning to program using Python! > > > > And don't talk to me about functions, classes and methods, not to > > mention modules. Python makes it too easy to write code in many > > different styles, trying to please people who like to write only > > object-oriented code as well as those that follow the more traditional > > procedural approach. Even "functional" type people find their way to > > write code in their preferred method using Python. This is not right. > > > > Fortunately, Python has incorporated some newbie-unfriendly features, > > like metaclasses and, to a lesser extent, decorators which, at last, > > make use of a special character. There should be more of these, to > > make Python something more challenging to learn. > > > > Programming should be more difficult than this - otherwise, how can > > programmers be respected by the common folks? > > --- > > Andr? > > > > I want to complain about the fact that I wrote 200 lines the other day > and it worked first time. Problem was, I spent 20 minutes before I > realized that the lack of errors was a result of the lack of bugs. From timr at probo.com Mon Apr 30 01:35:37 2007 From: timr at probo.com (Tim Roberts) Date: Mon, 30 Apr 2007 05:35:37 GMT Subject: I have a chance to do somting diffrent way not Python ?! References: <1177777623.038902.108590@y5g2000hsa.googlegroups.com> Message-ID: <300b33t1stl3l5hhfm1kktq899esfnjadt@4ax.com> anders wrote: > >On my work we have a lot off diffrent server to make software for >diffrent os from Windows, OS/X to Linux Solaris > >Everyting is scripted with shell, but Windows has batchfiles witch is >very limited, compared to cshell etc. There are several very good Unix-derived shells available for Windows. UnxUtils includes a bash and a zsh. -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From ratchetgrid at googlemail.com Mon Apr 30 07:53:24 2007 From: ratchetgrid at googlemail.com (Nathan Harmston) Date: Mon, 30 Apr 2007 12:53:24 +0100 Subject: Restricting the alphabet of a string Message-ID: <676224240704300453n343c90bcs878b2d981deb3351@mail.gmail.com> Hi, I ve being thinking about playing around with bit strings but use in some encoding problems I m considering and was trying to decide how to implement a bit string class. Is there a library out there for doing basic things with bit strings already is my first question? I know that I can extend string to bit string, but is there anyway I can force the alphabet to be restricted to 1's and 0's (or even 1, 0 and -1, as an extension to from trinary strings). class Binary_String(String): pass Many Thanks Nathan From martin at v.loewis.de Wed Apr 4 16:58:38 2007 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Wed, 04 Apr 2007 22:58:38 +0200 Subject: Problem installing Python 2.5 In-Reply-To: References: Message-ID: <4614117e$0$3498$9b622d9e@news.freenet.de> > After a lot of output, got this: You will need to check this output line-for-line to see why it fails. Regards, Martin From gagsl-py2 at yahoo.com.ar Sun Apr 1 03:58:43 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sun, 01 Apr 2007 04:58:43 -0300 Subject: re.findall() hangs in python References: <1175397176.567214.194810@n59g2000hsh.googlegroups.com> Message-ID: En Sun, 01 Apr 2007 03:58:51 -0300, Peter Otten <__peter__ at web.de> escribi?: > silverburgh.meryl at gmail.com wrote: > >> 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("(.*)> re.S) > > Could it be that it is just slow? If not, post a small example of data > that > provokes findall() to hang. I bet it is very slooooooow! To the OP: do you actually need all those groups? Specially the first and last (.*), they match all the surrounding text. -- Gabriel Genellina From bcwhite at pobox.com Wed Apr 18 15:10:49 2007 From: bcwhite at pobox.com (bcwhite at pobox.com) Date: 18 Apr 2007 12:10:49 -0700 Subject: Future Python Gui? In-Reply-To: References: <1176859699.906386.326720@b75g2000hsg.googlegroups.com> Message-ID: <1176923448.998078.170760@e65g2000hsc.googlegroups.com> > Tile is available right now in Tk as an extension package, and a Tkinter > wrapper for it can be found here: > > http://tkinter.unpythonic.net/wiki/TileWrapper That site seems to be down (500 Internal Server Error). > Tile will be integrated into Tk's core when 8.5 is released. It's > supposed to enter beta testing Real Soon Now. However, I imagine that > Python/Tkinter will depend on Tk 8.4 for the foreseeable > future--certainly 8.5 won't be supported officially before a full, > stable release is made. Perhaps in Python 2.6? That is okay with me. It'll be a long time before I get to a point where I'll need easy release. But knowing that it will be part of a future release will also mean I don't have to worry about refactoring everything if the toolkit I'm using goes out of style and is replaced by something else. Out of curiosity... Did that page have install instructions for Tile? Other pages I've seen talk about it but don't say how to integrate it in to a python installation (under Windows or Linux). -- Brian From cam.ac.uk at mh391.invalid Tue Apr 24 08:52:07 2007 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Tue, 24 Apr 2007 13:52:07 +0100 Subject: Tutorial creates confusion about slices In-Reply-To: References: Message-ID: Antoon Pardon wrote: >> Submit a patch if you want it changed. I'm sure your valuable >> insights will greatly improve the quality of the python documentation. > > Fat chance, if they reason like you. I don't think that Michael Bentley is the documents maintainer. Are you trying to pick a fight with him or improve the docs? Personally, I do not think of slices in the way this tutorial suggests, but I think taking it out without replacement would not help. If you want to add a more accurate replacement, I think that would be better received than just saying that the section should be removed. Even more so if you provide it in the form of a patch. -- Michael Hoffman From isaac.rodriguez at comcast.net Wed Apr 18 09:36:37 2007 From: isaac.rodriguez at comcast.net (Isaac Rodriguez) Date: 18 Apr 2007 06:36:37 -0700 Subject: What makes an iterator an iterator? In-Reply-To: References: Message-ID: <1176903397.501965.258990@d57g2000hsg.googlegroups.com> Sorry, my previous post was incomplete. I didn't realized that you implemented _next() as a generator funcition. Besides changing __init__() from self.next = self._next() to self.next = self._next you need to implement __iter__() as: return self.next() > class Parrot(object): > def __iter__(self): > return self > def __init__(self): > self.next = self._next() > def _next(self): > for word in "Norwegian Blue's have beautiful plumage!".split(): > yield word > From ceball at gmail.com Wed Apr 18 03:36:44 2007 From: ceball at gmail.com (Chris) Date: 18 Apr 2007 00:36:44 -0700 Subject: Strange terminal behavior after quitting Tkinter application In-Reply-To: <1176881604.574369.77230@b58g2000hsg.googlegroups.com> References: <1176881604.574369.77230@b58g2000hsg.googlegroups.com> Message-ID: <1176881804.567931.85770@b58g2000hsg.googlegroups.com> (I'm not sure what happened to the formatting in my post: the "Tkinter.Button" line should be at the same level of indentation as the "Tkinter.Tk.__init__" line.) From hipertracker at gmail.com Tue Apr 3 11:22:53 2007 From: hipertracker at gmail.com (Jaroslaw Zabiello) Date: Tue, 3 Apr 2007 16:22:53 +0100 Subject: Problem installing Python 2.5 References: Message-ID: Dnia Tue, 3 Apr 2007 11:52:55 -0300, Sebastian Bassi napisa?(a): > I was trying to install Python 2.5 compiling from sources. I used: > ./compile > It run OK. > Then: > make altintall > After a lot of output, got this: > Listing /usr/local/lib/python2.5/xml/sax ... > Compiling /usr/local/lib/python2.5/xml/sax/__init__.py ... > Compiling /usr/local/lib/python2.5/xml/sax/_exceptions.py ... > Compiling /usr/local/lib/python2.5/xml/sax/expatreader.py ... > Compiling /usr/local/lib/python2.5/xml/sax/handler.py ... > Compiling /usr/local/lib/python2.5/xml/sax/saxutils.py ... > Compiling /usr/local/lib/python2.5/xml/sax/xmlreader.py ... > Compiling /usr/local/lib/python2.5/xmllib.py ... > Compiling /usr/local/lib/python2.5/xmlrpclib.py ... > Compiling /usr/local/lib/python2.5/zipfile.py ... > make: *** [libinstall] Error 1 > > It seems I am not the only one with this error: > http://www.thescripts.com/forum/thread613458.html > http://www.megasolutions.net/python/Python-installation-problem-(sorry-if-this-is-a-dup)-22624.aspx > http://ubuntuforums.org/showthread.php?p=1912370 > > System: Freespire 1.0.13 (based on Debian). After executing ./configure you have to edito Modules/Setup file and uncomment the following line: #zlib zlibmodule.c -I$(prefix)/include -L$(exec_prefix)/lib -lz Then continue with normal make; make install. -- Jaroslaw Zabiello http://blog.zabiello.com From grahn+nntp at snipabacken.dyndns.org Thu Apr 19 16:38:38 2007 From: grahn+nntp at snipabacken.dyndns.org (Jorgen Grahn) Date: 19 Apr 2007 20:38:38 GMT Subject: Making a tree out of a 2 column list References: Message-ID: On Sat, 14 Apr 2007 11:37:11 -0300, Sebastian Bassi wrote: > I have a two column list like: > > 2,131 > 6,335 > 7,6 > 8,9 > 10,131 > 131,99 > 5,10 > > And I want to store it in a tree-like structure. CS side note: your "columns" describe a graph; http://en.wikipedia.org/wiki/Graph_(mathematics) > So if I request 131, it should return all the child of 131, like 2, 10 > and 5 (since 5 is child of 10). OK, so it is a directed graph. You might want to think about whether it is also a DAG. If not, you could be asked for the children of 1 in 2, 1 1, 2 As I interpret your specification, the correct answer is [1, 2] -- the set of children for 1. /Jorgen -- // Jorgen Grahn R'lyeh wgah'nagl fhtagn! From wswilson at gmail.com Mon Apr 2 12:51:54 2007 From: wswilson at gmail.com (wswilson) Date: 2 Apr 2007 09:51:54 -0700 Subject: can a method access/set another's variables? In-Reply-To: References: <1175477764.549115.159410@n59g2000hsh.googlegroups.com> Message-ID: <1175532714.927724.303000@n59g2000hsh.googlegroups.com> On Apr 2, 11:01 am, Dennis Lee Bieber wrote: > On 1 Apr 2007 18:36:04 -0700, "asdf1234234" > declaimed the following in comp.lang.python: > > > My code is: > > -a.py- > > import b > > > class A: > > def __init__(self): > > pass > > Delete this empty __init__() [and, consider converting the class to > new-style] > > > def my_method(self): > > var = 1 > > var is a local to method only name, it goes away when the method > ends. > > > self.var = 2 > > b.set_var(self) > > print var > > print self.var > > > my_a = A() > > my_a.my_method() > > > -b.py- > > def set_var(self): > > var = 2 > > Again, var is local to just set_var(). > > > self.var = 2 > > > I want both var and self.var to be 2 at the end. Is there anything I > > can pass to set_var() that will give it access to the variables in > > my_method() like I can use self for the variables in the class A? > > The common scheme, unless you expect to have multiple instances of > this class with /separate/ local "var", would be to put var in a > "common" module > > -=-=-=-=- common.py > > var = None > > -=-=-=-=- > > Then have both a.py and b.py "import common", followed by changing > all "var =" to "common.var =" > -- > 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/ Thanks! I like the sound of that...it should work for what I need it to do. From erichapkido at gmail.com Sat Apr 14 20:46:51 2007 From: erichapkido at gmail.com (Eric) Date: 14 Apr 2007 17:46:51 -0700 Subject: Getting started with python Message-ID: <1176598011.463543.96990@q75g2000hsh.googlegroups.com> Hello, after reading some of the book Programming Python it seems that python is something I would like to delve deeper into. The only thing is, I have no idea what I should try and write. So I was hoping that someone here could help point me to a group/project that would be a good starting place for a person with limited python knowledge, but that is willing to learn whatever is necessary. I'm hoping that with a goal I can start to learn python instead of just playing around with it. Thanks. From ayaz at dev.slash.null Sun Apr 8 04:30:59 2007 From: ayaz at dev.slash.null (Ayaz Ahmed Khan) Date: Sun, 08 Apr 2007 13:30:59 +0500 Subject: Console UI References: <1175994720.819372.232380@o5g2000hsb.googlegroups.com> Message-ID: "Clement" typed: > My project is based on console Application. Is there any console UI > except urwid. If so, can i come to know. There is ``curses''. -- Ayaz Ahmed Khan Do what comes naturally now. Seethe and fume and throw a tantrum. From andmarti at gmail.com Tue Apr 24 08:45:57 2007 From: andmarti at gmail.com (andmarti at gmail.com) Date: Tue, 24 Apr 2007 12:45:57 +0000 Subject: getting scancodes In-Reply-To: <1177425698.117905.250460@t39g2000prd.googlegroups.com> References: <1177425698.117905.250460@t39g2000prd.googlegroups.com> Message-ID: <20070424124557.GA30797@lacordilleraandina.com.ar> On Tue, Apr 24, 2007 at 07:41:38AM -0700, kyosohma at gmail.com wrote: > On Apr 23, 7:39 pm, andma... at gmail.com wrote: > > Anyone knows if its possible to get scan codes ??? > > I tried with getch () but with no success, just keycodes. > > May be using the something in the sys.stdin module ?? > > > > Pleasee, any help would be very appreciated. > > > > -- > > Andr?s M. > > --------------------------------------------- > > .--. > > |o_o | > > |:_/ | > > // \ \ > > (| | ) > > /'\_ _/`\ > > \___)=(___/ > > --------------------------------------------- > > Looks like there's a thread from 2003 on this subject. Check it out > here: http://www.thescripts.com/forum/thread20311.html Yes, I saw it; but didnt help at all. :( You have to be root to use the first one. And the second its for Windows. I use debian, and other linux distros. Ciao. Andr?s M. From gagsl-py2 at yahoo.com.ar Mon Apr 23 03:55:11 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 23 Apr 2007 04:55:11 -0300 Subject: Dictionaries and dot notation References: <23087554.X5dcTmlj7P@beaureve.gmx.net> <462B6227.5070405@web.de> <5296241.Dh78hTc8ZZ@beaureve.gmx.net> <1hwzndv.1licthzy6aocnN%aleax@mac.com> <1724551.h8mdBJEZWL@beaureve.gmx.net> Message-ID: En Mon, 23 Apr 2007 03:14:32 -0300, Martin Drautzburg escribi?: > I did not notice that I can use a single class (or a module) for > all my datastructures, because I can "plug in" new attributes into the > instance without the class knowing about them. > > I was mistaken to believe that I had to know about attributes at the > time of class creation. But your expample does not require that. Should > have read this more carefully. Welcome to Python and its dynamic nature! -- Gabriel Genellina From deets at nospam.web.de Tue Apr 24 15:48:19 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 24 Apr 2007 21:48:19 +0200 Subject: PIL and font colours. In-Reply-To: <1177442941.190119.157230@u32g2000prd.googlegroups.com> References: <1177442941.190119.157230@u32g2000prd.googlegroups.com> Message-ID: <597588F2jn0l3U1@mid.uni-berlin.de> Johny schrieb: > I use PIL to write some text to a picture.The text must be seen wery > clearly. > I write the text to different pictures but to the same position. As > pictures maybe different, colour, in the position where I write the > text, is also different. > Is there a way how to set the font colour so that it will be seen very > clearly in the picture? > For example, if the picture is bright ( for example yellow), the font > colour should be dark( e.g. black) and vice versa. > Can anyone help? Please don't post the same message three times. Once is enough. For your problem are different solutions - you could compute an average over the occupied background, convert the result to HSV and select a H at the opposite, and also modify S and V. Diez From martin at v.loewis.de Mon Apr 16 17:44:57 2007 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Mon, 16 Apr 2007 23:44:57 +0200 Subject: C++ extension problem In-Reply-To: <1176741526.541997.52100@e65g2000hsc.googlegroups.com> References: <1176741526.541997.52100@e65g2000hsc.googlegroups.com> Message-ID: <4623EE59.7020800@v.loewis.de> > Now this is what confuses me: Why does it say that I have the wrong > type when it's the same type as it suggests? When referring to the type, you must *always* form the address of the type structure, including, but not limited to, the line > if (!PyArg_ParseTuple(args, "O!", SillyStringType, &o)) HTH, Martin From kyosohma at gmail.com Tue Apr 10 11:51:12 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: 10 Apr 2007 08:51:12 -0700 Subject: install wxPython In-Reply-To: References: Message-ID: <1176220272.244599.9160@b75g2000hsg.googlegroups.com> On Apr 9, 3:20 pm, Marco wrote: > Hi, > > I have a problem to install wxPython on my MacBook (Pythonversion 2.5). > If would install the wxPython (python setup.py install), then I got > this error: > > Traceback (most recent call last): > File "/Users/marco/Desktop/flexo1/wxpython/wxPython-src-2.8.3.0/ > wxPython/setup.py", line 49, in > copy_file('config.py', 'wx/build', update=1, verbose=1) > File "/Users/marco/python//lib/python2.5/distutils/file_util.py", > line 119, in copy_file > "can't copy '%s': doesn't exist or not a regular file" % src > distutils.errors.DistutilsFileError: can't copy 'config.py': doesn't > exist or not a regular file > > Where is the problem and how could i fix it? > > Thx for your answers. > marco You need to post this problem to the wxPython user's group at: http://wxpython.org/maillist.php There are a number of Mac users there that should be able to help you. Mike From steve at holdenweb.com Fri Apr 13 09:12:43 2007 From: steve at holdenweb.com (Steve Holden) Date: Fri, 13 Apr 2007 09:12:43 -0400 Subject: where to report bug/get help for wxpython In-Reply-To: References: Message-ID: alf wrote: > Hi, > > I have another problem with wxpython - that is the best place to report > bug - evident memory leak on Linux and win32. > Google for wxpython mailing list and see if you still need help after that. Bug reports on c.l.py will almost certainly go unregarded. 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 bobjohnson11 at gmail.com Sat Apr 7 14:00:29 2007 From: bobjohnson11 at gmail.com (RobJ) Date: 7 Apr 2007 11:00:29 -0700 Subject: Is http://cheeseshop.python.org/pypi/ having issues In-Reply-To: <44f1b$4617da15$54d1d767$21800@news.chello.no> References: <1175967418.642658.46930@l77g2000hsb.googlegroups.com> <44f1b$4617da15$54d1d767$21800@news.chello.no> Message-ID: <1175968829.702359.246700@y66g2000hsf.googlegroups.com> On Apr 7, 1:51 pm, David Boddie wrote: > On Saturday 07 April 2007 19:36, RobJ wrote: > > > Has any one noticed any issues withhttp://cheeseshop.python.org/pypi/ > > ? I have been trying for hours to install packages (using > > easy_install) but the connection keeps timing out. > > Don't worry, you're not the first person to notice: > > http://mail.python.org/pipermail/catalog-sig/2007-April/001050.html > > Maybe someone can suggest a workaround for easy_install while the server > is unavailable. > > David Thanks David I thought I was going nuts. Rob J From irstas at gmail.com Sat Apr 7 08:40:01 2007 From: irstas at gmail.com (irstas at gmail.com) Date: 7 Apr 2007 05:40:01 -0700 Subject: block scope? In-Reply-To: References: Message-ID: <1175949601.672150.187790@b75g2000hsg.googlegroups.com> On Apr 7, 6:48 am, James Stroud wrote: > Neal Becker wrote: > > One thing I sometimes miss, which is common in some other languages (c++), > > is idea of block scope. It would be useful to have variables that did not > > outlive their block, primarily to avoid name clashes. This also leads to > > more readable code. I wonder if this has been discussed? > > Probably, with good code, block scope would be overkill, except that I > would welcome list comprehensions to have a new scope: Generator expressions have a new scope, and in Python 3.0 list comprehensions will have one as well (according to http://www.python.org/dev/peps/pep-0289/ ). It's a fix that might break existing code so it couldn't be introduced in "minor" versions like 2.4 and 2.5. From oliphant.travis at ieee.org Wed Apr 4 14:08:18 2007 From: oliphant.travis at ieee.org (Travis Oliphant) Date: Wed, 04 Apr 2007 12:08:18 -0600 Subject: An error of matrix inversion using NumPy In-Reply-To: <1175692530.364381.77110@n59g2000hsh.googlegroups.com> References: <1175692530.364381.77110@n59g2000hsh.googlegroups.com> Message-ID: lancered wrote: > > > So, can you tell me what goes wrong? Is this a bug in > Numpy.linalg? How to deal with this situation? If you need, I can > post the matrix I used below, but it is so long,so not at the moment. > As you discovered, it is very likely your problem is a very high condition number. The easiest thing to do is to use numpy.linalg.pinv to perform a pseudo-inverse which will only use the singular-values that are well-conditioned to compute the inverse. This will still not give you an exact identity, but at least you will know you aren't amplifiying low-valued singular vectors. -Travis From apardon at forel.vub.ac.be Fri Apr 20 08:32:19 2007 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 20 Apr 2007 12:32:19 GMT Subject: Do other Python GUI toolkits require this? References: <462697A6.6010007@codebykevin.com> <465B30B4-5BA0-459A-BE6F-1038874FA74B@jedimindworks.com> <1177064687.963629.94100@y80g2000hsf.googlegroups.com> Message-ID: On 2007-04-20, Paul Boddie wrote: > On 20 Apr, 09:21, Antoon Pardon wrote: >> >> Indeed I have no wish to bow before common usage. > > Then nobody will understand you properly if you start referring to a > "steep learning curve" when in their terminology you actually mean a > "shallow learning curve". Certainly, this discussion has alerted me to > a level of ambiguity with the term that would dissuade me from using > it, but then it's a hand-waving kind of term, anyway, which would be > better replaced with a proper description of whatever effect is > supposed to be observable. Well that I made some people aware was all I intended. Personaly I don't use the term either unless I have an actual curve to show which I can use to explain how to interpret it. -- Antoon Pardon From sjmachin at lexicon.net Fri Apr 27 18:54:59 2007 From: sjmachin at lexicon.net (John Machin) Date: Sat, 28 Apr 2007 08:54:59 +1000 Subject: getting rid of EOL character ? In-Reply-To: References: <268cc$4631f634$83aef404$27224@news1.tudelft.nl> Message-ID: <46327f48$1@news.eftel.com.au> On 27/04/2007 11:19 PM, Michael Hoffman wrote: > stef wrote: >> hello, >> >> In the previous language I used, >> when reading a line by readline, the EOL character was removed. Very interesting; how did you distinguish between EOF and an empty line? Did you need to call an isEOF() method before each read? >> >> Now I'm reading a text-file with CR+LF at the end of each line, >> Datafile = open(filename,'r') line = Datafile.readline() >> >> now this gives an extra empty line >> print line >> >> and what I expect that should be correct, remove CR+LF, >> gives me one character too much removed >> print line[,-2] Stef, that would give you a syntax error. I presume that you meant to type line[:-2] >> >> while this gives what I need ??? >> print line[,-1] >> >> Is it correct that the 2 characters CR+LF are converted to 1 character ? In text mode (the default), whatever is the line ending on your platform is converted to a single "newline" '\n' which is the same as LF. Using line[:-1] is NOT recommended, as the last line in your file may not be terminated, and in that case you would lose the last data character. >> Is there a more automatic way to remove the EOL from the string ? > > line = line.rstrip("\r\n") should take care of it. If you leave out the > parameter, it will strip out all whitespace at the end of the line, > which is what I do in most cases. If you want *exactly* what is in the line, use line.rstrip('\n') -- this will remove only the trailing newline (if it exists). If you want to strip all trailing whitespace, use line.rstrip() as Michael suggested. Michael, note carefully that line.rstrip('\r\n') removes instances of '\r' OR '\n' -- the arg is a set of characters to be removed, not a suffix to be removed. In Stef's situation, it "works" only by accident. Using that would not always give you the correct answer -- e.g. if your (Windows) file had a line ending in CR CR LF [I've seen stranger]. HTH, John From howe.steven at gmail.com Mon Apr 2 16:48:30 2007 From: howe.steven at gmail.com (Steven Howe) Date: Mon, 02 Apr 2007 13:48:30 -0700 Subject: How can i compare a string which is non null and empty Message-ID: <46116C1E.2030009@gmail.com> how about just testing it's length? >>> from types import StringType def stringTest(x): ... if type(x) == StringType: ... if len(x) == 0: ... print 'Empty String' ... else: ... print 'Not Empty String' ... else: ... print 'value not String Type' ... lst = ['a','',5,(5,6),{'a':5}] for item in lst: ... stringTest(item) ... Not Empty String Empty String value not String Type value not String Type value not String Type From zhonghua.m.yang at gmail.com Wed Apr 4 17:47:29 2007 From: zhonghua.m.yang at gmail.com (ZMY) Date: 4 Apr 2007 14:47:29 -0700 Subject: Numeric compiling problem under QNX 4.25 In-Reply-To: References: <1175578324.426293.21970@y80g2000hsf.googlegroups.com> <1175622049.939184.28670@d57g2000hsg.googlegroups.com> <1175632439.676454.21830@q75g2000hsh.googlegroups.com> Message-ID: <1175723249.400296.169290@w1g2000hsg.googlegroups.com> On Apr 3, 2:52 pm, Robert Kern wrote: > ZMY wrote: > > On Apr 3, 10:51 am, Robert Kern wrote: > >> ZMY wrote: > >>> Is "ld" part of make command? I am not familiar with compiling with > >>> make in general. > >> No, it's the linker. I takes the object files (.o) which are generated by the > >> compiler (cc, I imagine) and links them together into the shared library (.so). > >> make is a program that can automate builds given instructions, but Numeric > >> doesn't use it, nor do most other Python packages. > > >>> Most other extensions (including math, os, struct, cPickle) from > >>> Python 2.2 works when I install python on QNX. > >> No, I was wondering if you could build any other third-party extension modules. > >> Did you install Python from source? When building extension modules, Python uses > >> whatever linker was used to build itself. > > >> -- > >> 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 E > > > Dear Robert, > > > Looks like you are right. Here is what I got when I compile the > > Python2.2 from source (or I believe so): > > > $ sudo make SHELL=/usr/local/bin/bash > > Password: > > case $MAKEFLAGS in \ > > *-s*) CC='cc' LDSHARED='ld' OPT='-DNDEBUG -O' ./python -E //6/openqnx/ > > Python-2.2/setup.py -q build;; \ > > *) CC='cc' LDSHARED='ld' OPT='-DNDEBUG -O' ./python -E //6/openqnx/ > > Python-2.2/setup.py build;; \ > > esac > > running build > > running build_ext > > building 'regex' extension > > skipping //6/openqnx/Python-2.2/Modules/regexmodule.c (build/temp.qnx- > > O-PCI-2.2/regexmodule.o up-to-date) > > skipping //6/openqnx/Python-2.2/Modules/regexpr.c (build/temp.qnx-O- > > PCI-2.2/regexpr.o up-to-date) > > ld build/temp.qnx-O-PCI-2.2/regexmodule.o build/temp.qnx-O-PCI-2.2/ > > regexpr.o -L/usr/local/lib -o build/lib.qnx-O-PCI-2.2/regex.so > > unable to execute ld: No such file or directory > > .... > > > If there is no 'ld' linker, what should be used instead?? > > I don't know. I've never used QNX. It looks like the Python binaries were built > with a linker that you don't have on your system. Usually, you have to use the > same compiler/linker combination to build extension modules that you used to > build Python itself. > > -- > 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 Dear All, I finally figured out how to install Numeric Python on QNX4. To my understanding of a QNX programmer's lecture, the problem of QNX4 is that it doesn't support dynamic linking, so the linker can't link the new compiled object files with existing python binary. The new module must be built together with python itself. What I did was: 1) copy every file in /Lib, /Src, /Include from Numeric/ into the corresponding directories in /openqnx/Python2.2/ (I put *object files in /Object) 2) change Modules/Setup to include following (ranlib and arraytypes don't work, but I got modules I need) _numpy _numpymodule.c arrayobject.c ufuncobject.c #ranlib ranlibmodule.c ranlib.c umath umathmodule.c multiarray multiarraymodule.c # arraytypes arraytypes.c arrayfns arrayfnsmodule.c 3) install from source by make Thanks a lot for all your help again! From kyosohma at gmail.com Fri Apr 6 14:26:28 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: 6 Apr 2007 11:26:28 -0700 Subject: Picture resolution and PIL In-Reply-To: <1175883388.743729.111850@o5g2000hsb.googlegroups.com> References: <1175883388.743729.111850@o5g2000hsb.googlegroups.com> Message-ID: <1175883988.638746.232470@d57g2000hsg.googlegroups.com> On Apr 6, 1:16 pm, "Johny" wrote: > Is it possible to find out a picture resolution by using PIL package? > Thanks for help > L. Dunno. But I found some ways to read metadata that should give you the info in most cases: http://snippets.dzone.com/posts/show/768 http://hachoir.org/wiki/hachoir-metadata Hope that helps, Mike From carsten at uniqsys.com Mon Apr 30 11:36:55 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Mon, 30 Apr 2007 11:36:55 -0400 Subject: regexp match string with word1 and not word2 In-Reply-To: <1177946577.080567.73400@u30g2000hsc.googlegroups.com> References: <1177920984.247487.54620@c35g2000hsg.googlegroups.com> <9rGdnQGHaNy1mqvbnZ2dnUVZ_v_inZ2d@comcast.com> <1177946577.080567.73400@u30g2000hsc.googlegroups.com> Message-ID: <1177947415.4090.18.camel@dot.uniqsys.com> On Mon, 2007-04-30 at 08:22 -0700, Flyzone wrote: > On 30 Apr, 17:11, Steven Bethard wrote: > > > You don't need a regexp:; > > I need a regexp.....i'm parsing a file with a rule-file that contains > also regexp and strings too.... That was not at all evident from your original description. The quality of the advice you receive is directly influenced by the quality of your description of the problem you're trying to solve. -Carsten From paddy3118 at googlemail.com Sat Apr 14 15:33:26 2007 From: paddy3118 at googlemail.com (Paddy) Date: 14 Apr 2007 12:33:26 -0700 Subject: Python Feature Request: Allow changing base of member indices to 1 In-Reply-To: <1176546465.632410.52630@w1g2000hsg.googlegroups.com> References: <1176546465.632410.52630@w1g2000hsg.googlegroups.com> Message-ID: <1176579205.948684.171640@q75g2000hsh.googlegroups.com> On Apr 14, 11:27 am, samj... at gmail.com wrote: > This is like the previous one. Please check for sanity and approve for > posting at python-dev. > > I would like to have something like "option base" in Visual Basic. > IIRC it used to allow me to choose whether 0 or 1 should be used as > the base of member indices of arrays. In Python, the same can be used > with strings, lists, tuples etc. > > This would mean: > foo = "foo" > => foo[1] == 'f' > > foo = ['foo', 'bar', 'spam' ] > => foo[1] == 'foo' > > foo = ('spam', 'eggs') > => foo[1] == 'spam' > > For convenience it should also affect the range function so that: > > range(3) = [1, 2, 3] > > because this is often used where arrays would be used in VB. > > Finally, when the programmer does not specify his choice of base at > the beginning of the program, the current behaviour of using 0 as base > should continue so that there is no problem with backward > compatibility. Here is a document giving good reasons for indexing to start at zero, as in Python. http://www.cs.utexas.edu/users/EWD/transcriptions/EWD08xx/EWD831.html The author has done a bit: http://en.wikipedia.org/wiki/Dijkstra Having more than one index start point would be a maintenance nightmare best avoided. (It can be done in Perl). - Paddy. From irstas at gmail.com Tue Apr 3 11:05:54 2007 From: irstas at gmail.com (irstas at gmail.com) Date: 3 Apr 2007 08:05:54 -0700 Subject: numpy performance and list comprehension In-Reply-To: <1175611372.971235.191280@d57g2000hsg.googlegroups.com> References: <1175611372.971235.191280@d57g2000hsg.googlegroups.com> Message-ID: <1175612754.684921.307940@n76g2000hsh.googlegroups.com> On Apr 3, 5:42 pm, "TG" wrote: > Hi there. > > Reading the page on python performance (http://scipy.org/PerformancePython > ) made me realize that I can achieve tremendous code acceleration with > numpy just by using "u[:,:]" kind of syntax the clever way. > > Here is a little problem (Oja's rule of synaptic plasticity) > > * W is a matrix containing the weights of connections between elements > i > and j > * V is an array containing the values of elements > > I want to make W evolve with this rule : > > dW[i,j] / dt = alpha * (V[i] * V[j] - W[i,j] * V[i]^2) > > (don't pay attention to the derivate and stuff) > > So, how would you write it in this nifty clever way ? > > As a begining I wrote this : > > W += V.flatten().reshape((V.size,1)) * > V.flatten().reshape((1,V.size)) > > But it is not complete and, I guess, not efficient. alpha * (V[i] * V[j] - W[i,j] * V[i]^2) = alpha * V[i] * (V[j] - W[i,j] * V[i]) Assuming that V is a column vector, you could do it like this: V = array([[5],[3],[7]]) W = array([[1,5,3],[2,2,7],[3,9,8]]) W += alpha * V * (transpose(V) - W * V) From aleax at mac.com Thu Apr 26 22:24:56 2007 From: aleax at mac.com (Alex Martelli) Date: Thu, 26 Apr 2007 19:24:56 -0700 Subject: If Dict Contains a particular key References: <000001c78695$ed321540$c7963fc0$@rawlins@thinkbluemedia.co.uk> <1177436682.3441.15.camel@dot.uniqsys.com> <1177565430.992904.149450@n35g2000prd.googlegroups.com> <1hx5dto.hwi9shy3mg47N%aleax@mac.com> <1177630049.320928.63280@r30g2000prh.googlegroups.com> Message-ID: <1hx6yvu.ttiyxukgn9uxN%aleax@mac.com> mensanator at aol.com wrote: ... > > > > if 'a' in thedict: ... > > > if thedict.has_key('a'): ... > > Why consume twice as much time with no advantages whatever?! > > Did I wander into comp.lang.perl by mistake? Of course not -- note that the faster, modern idiom is also simpler, more concise, _and_ more readable, _and_ also more general/polymorphic than the tired old way that's still kept around only for backwards compatibility. Simplicity, terseness, readability, generality, _and_ speed, all at the same time, as long as you use the "new" way (meaning, in this case, the one that's been around for "only" about seven years...!!!) -- now that's a combination of factors that's reasonably typical of Python, but not quite so frequent in other languages!-) Alex From aleax at mac.com Sat Apr 7 20:34:34 2007 From: aleax at mac.com (Alex Martelli) Date: Sat, 7 Apr 2007 17:34:34 -0700 Subject: block scope? References: <7xr6qwal50.fsf@ruckus.brouhaha.com> <7xtzvseqzo.fsf@ruckus.brouhaha.com> <1hw72cg.115yokgarr9enN%aleax@mac.com> <1hw7kzo.1hepj3c1who5zhN%aleax@mac.com> Message-ID: <1hw7lxn.18itayl1fua6w0N%aleax@mac.com> Aahz wrote: > In article <1hw7kzo.1hepj3c1who5zhN%aleax at mac.com>, > Alex Martelli wrote: > >Steve Holden wrote: > >> > >> What do you think the chances are of this being accepted for Python 3.0? > >> It is indeed about the most rational approach, though of course it does > >> cause problems with dynamic namespaces. > > > >What problems do you have in mind? The compiler already determines the > >set of names that are local variables for a function; all it needs to do > >is diagnose an error or warning if the set of names for a nested > >function overlaps with that of an outer one. > > exec? option 1: that just runs the compiler a bit later -- thus transforming ClashingVariableError into a runtime issue, exactly like it already does for SyntaxError. option 2: since a function containing any exec statement does not benefit from the normal optimization of local variables, let it also forgo the normal diagnosis of shadowed/clashing names. option 3: extend the already-existing prohibition of mixing exec with nested functions: >>> def outer(): ... def inner(): return x ... exec('x=23') ... return inner() ... File "", line 3 SyntaxError: unqualified exec is not allowed in function 'outer' it contains a nested function with free variables to prohibit any mixing of exec and nested functions (not just those cases where the nested function has free variables). My personal favorite is option 3. Alex From jan.m.danielsson at gmail.com Sun Apr 15 08:08:28 2007 From: jan.m.danielsson at gmail.com (Jan Danielsson) Date: Sun, 15 Apr 2007 14:08:28 +0200 Subject: Standardizing XML In-Reply-To: <1176625793.392269.24060@n59g2000hsh.googlegroups.com> References: <1176625793.392269.24060@n59g2000hsh.googlegroups.com> Message-ID: <462215bc$1@griseus.its.uu.se> ZeeGeek wrote: > Is there a module for python to standardize XML? Since MSN Live Space > doesn't use standard XML in the posts, I want to standardize them so > that I can use them elsewhere. Hmm... XML _is_ standardized. If it doesn't follow the specs, then it's not XML. If you want to make XML out of something which isn't XML, you'll probably have to be a little more specific about how this other format works. -- Kind regards, Jan Danielsson From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Sun Apr 29 07:55:25 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Sun, 29 Apr 2007 13:55:25 +0200 Subject: My newbie annoyances so far References: <1177688082.758043.133920@r30g2000prh.googlegroups.com> <59f5btF2k70baU2@mid.individual.net> <59gglhF2l1u43U2@mid.individual.net> Message-ID: <59jfddF2ljlg7U1@mid.individual.net> Steven D'Aprano wrote: > There are bad programmers in every language, but RPL conditional > blocks aren't the cause of them. Once you learn how RPL works, if > statements work consistently and obviously (although maybe not to > programmers who don't get RP notation). ACK. What made me anwswer wasn't RPL (after all I use an RPN calculator ;) ), but the statement that it were "more logic" than Python's "classic" infix logic. > In RPL, there are no expressions. RPL programs are constructed > from data and commands, not expressions. So you shouldn't think of > > if [else ] > > as an expression. Think of it as a block, equivalent to the > Python: > > if garbage_can_full: > fetch > out > garbage > else: > don't > > except that you can write it as a single line. Newlines in RPL are > just another sort of whitespace, with no special significance. > > If the else clause is missing, then nothing is executed and > processing simply continues past the end of the block. That made it clear, thanks. Regards, Bj?rn -- BOFH excuse #439: Hot Java has gone cold From nulla.epistola at web.de Mon Apr 23 09:41:16 2007 From: nulla.epistola at web.de (Hertha Steck) Date: Mon, 23 Apr 2007 15:41:16 +0200 Subject: TK-grid problem, please help In-Reply-To: References: <3CgWh.23821$PL.17381@newsread4.news.pas.earthlink.net> Message-ID: Hello, Ray schrieb: > Hi, Thanks for the help. > > > I was trying to find a book "Python TK" something on last Friday. > but didn't find it :-) > There is only one printed book, all the details here: http://wiki.python.org/moin/GuiBooks HTH Hertha From bearophileHUGS at lycos.com Thu Apr 12 13:36:58 2007 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 12 Apr 2007 10:36:58 -0700 Subject: tuples, index method, Python's design In-Reply-To: References: <1175953520.316208.241490@o5g2000hsb.googlegroups.com> <7xzm5igbrb.fsf@ruckus.brouhaha.com> <1176200361.260546.280510@n76g2000hsh.googlegroups.com> <740c3aec0704100824m132c45fbi5c4c3ec0c0fa3a67@mail.gmail.com> Message-ID: <1176399418.268235.65820@b75g2000hsg.googlegroups.com> Carsten Haese: > Nobody seems to be complaining about "+" behaving > "inconsistently" depending on whether you're adding numbers or > sequences. We can learn a bit from the D language too, it uses ~ for array/string concatenation, look for the "Array Concatenation" here: http://www.digitalmars.com/d/arrays.html Bye, bearophile From robert.rawlins at thinkbluemedia.co.uk Fri Apr 13 08:50:43 2007 From: robert.rawlins at thinkbluemedia.co.uk (Robert Rawlins - Think Blue) Date: Fri, 13 Apr 2007 13:50:43 +0100 Subject: Arrays, Got Me Confused In-Reply-To: <461F7712.2040201@timgolden.me.uk> References: <000101c77dc3$d4152a00$7c3f7e00$@rawlins@thinkbluemedia.co.uk> <461F7712.2040201@timgolden.me.uk> Message-ID: <001c01c77dca$67232210$35696630$@rawlins@thinkbluemedia.co.uk> Hello Guys, Wider fragments of code don't really exists at this moment in time :-D this is just a bit of a 'tester' class for me to get used to the methods. Basically I'm trying to create a class that contains an array of MAC address, these look something like this 'FD:E4:55:00:FG:A9. I want the class to have the following methods for easy manipulation of the array. addDevice(Address) - Pass in the MAC address and have it add it to the array. removeDevice(Address) - Finds a device with that address in the array and removes it. isFirewalled(Address) - looks for that address in the array and returns true/false dependant on whether it finds it. Clear() - empty the array of all its contents. Sorry for the sloppy code so far, I'm really new to Python so it's a steep learning curve for me, I'm by no means a programming numpty and allot of the principles are the same, but the languages I'm used to are more robust and vague so I don't have to define what type of data i'm storing the array and things. Thanks guys, Rob -----Original Message----- From: python-list-bounces+robert.rawlins=thinkbluemedia.co.uk at python.org [mailto:python-list-bounces+robert.rawlins=thinkbluemedia.co.uk at python.org] On Behalf Of Tim Golden Sent: 13 April 2007 13:27 Cc: python-list at python.org Subject: Re: Arrays, Got Me Confused Michael Bentley wrote: > > On Apr 13, 2007, at 7:04 AM, Robert Rawlins - Think Blue wrote: >> #!/usr/bin/python >> >> # Filename: Firewall.py >> class Firewall: >> def __init__(self): >> >> Self.FireArray = array(c) >> >> p = Firewall() >> >> print p >> Throws: >> >> >> >> Traceback (most recent call last): >> >> File "./firewall.py", line 9, in ? >> >> p = Firewall() >> >> File "./firewall.py", line 7, in __init__ >> >> Self.FireArray = array(c) >> >> NameError: global name 'array' is not defined >> >> >> >> How can I solve this problem? > from array import array Well, also the line referencing "Self.FireArray" is not going to work, unless there's some global "Self" knocking around. Python is case-sensitive. More importantly, I suspect, is that the OP's almost certainly looking for a Python *list*, not an array in this case. It's hard to tell, since we've no idea what's in the "c" which is being passed to the array. Robert - can you explain what you're trying to do and/or post a wider fragment of code? TJG -- http://mail.python.org/mailman/listinfo/python-list From jstroud at mbi.ucla.edu Fri Apr 27 00:24:52 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Thu, 26 Apr 2007 21:24:52 -0700 Subject: Problem with Matplotlib and the Tk-Backend In-Reply-To: <1177587594.078411.18720@u32g2000prd.googlegroups.com> References: <1177587594.078411.18720@u32g2000prd.googlegroups.com> Message-ID: thorstenkranz wrote: > Hi everyone, > > I'm new here and I have a question ( I guess as everybody who is new > here ;-) ), > > I'm having some strange problem with Matplotlib, using it in a Tkinter > application. > > I create a Canvas, a figure, subplot and then a toolbar. It works > fine, but only without the toolbar! When I want to add the toolbar, I > get an error > > File "./tkViewer.py", line 102, in setupGUI > self.toolbar = NavigationToolbar2TkAgg( self.canvas, master ) > File "/usr/lib/python2.4/site-packages/matplotlib/backends/ > backend_tkagg.py", line 537, in __init__ > NavigationToolbar2.__init__(self, canvas) > File "/usr/lib/python2.4/site-packages/matplotlib/backend_bases.py", > line 1107, in __init__ > self._init_toolbar() > File "/usr/lib/python2.4/site-packages/matplotlib/backends/ > backend_tkagg.py", line 577, in _init_toolbar > borderwidth=2) > File "/usr/lib/python2.4/lib-tk/Tkinter.py", line 2378, in __init__ > Widget.__init__(self, master, 'frame', cnf, {}, extra) > File "/usr/lib/python2.4/lib-tk/Tkinter.py", line 1865, in __init__ > self.tk.call( > _tkinter.TclError: bad screen distance "500.0" > > Here is the part my code: > > self.canvFrame = Frame(master) > self.canvFrame.pack(side=TOP, fill=BOTH, expand=1) > self.canvFrame2 = Frame(self.canvFrame) > self.canvFrame2.pack(side=LEFT, fill=BOTH, expand=1) > self.f = Figure(figsize=(5,4), dpi=100) > self.a = self.f.add_subplot(111) > self.subplAxis = self.f.get_axes() > self.canvas = FigureCanvasTkAgg(self.f, > master=self.canvFrame2) > self.canvas.show() > self.canvas.get_tk_widget().pack(side=TOP, fill=BOTH, > expand=1) > self.toolbar = NavigationToolbar2TkAgg( self.canvas, > self.canvFrame2 ) > self.toolbar.update() > self.canvas._tkcanvas.pack(side=TOP, fill=X, expand=1) > > > master is a parameter passed to my method, which actually is set to > Tk() > > What did I get wrong? What is the problem? Thanks in advance... > > Thorsten > Just prior to "self.toolbar = ...", try : master.winfo_toplevel().update_idletasks() James From half.italian at gmail.com Sun Apr 22 16:55:14 2007 From: half.italian at gmail.com (half.italian at gmail.com) Date: 22 Apr 2007 13:55:14 -0700 Subject: recursion depth problem In-Reply-To: <1177267774.416169.276780@e65g2000hsc.googlegroups.com> References: <1177267774.416169.276780@e65g2000hsc.googlegroups.com> Message-ID: <1177275314.846022.249000@e65g2000hsc.googlegroups.com> On Apr 22, 11:49 am, proctor <12cc... at gmail.com> wrote: > hello, > > i have a small function which mimics binary counting. it runs fine as > long as the input is not too long, but if i give it input longer than > 8 characters it gives > > RuntimeError: maximum recursion depth exceeded in cmp > > i'm not too sure what i am doing improperly. is there really a lot of > recursion in this code? > > ================== > > import sys > > def ch4(item, n=0): > if n < len(item): > if item[n] == '0': > item[n] = '1' > print ''.join(item) > ch4(item) > elif item[n] == '1': > item[n] = '0' > ch4(item, n+1) > > ch4(list(sys.argv[1])) > > ================== > > this function expects input in the form of a string of zeros, like > this: > > python test-bin.py 00000000 > > and is expected to output a list of permutations like this: > > $ python test-bin.py 0000 > 1000 > 0100 > 1100 > 0010 > 1010 > 0110 > 1110 > 0001 > 1001 > 0101 > 1101 > 0011 > 1011 > 0111 > 1111 > > thanks for all help! > > sincerely, > proctor If you just want to make it work as is....check sys.setrecursionlimit() ~Sean From yinglcs at gmail.com Wed Apr 4 15:58:52 2007 From: yinglcs at gmail.com (yinglcs at gmail.com) Date: 4 Apr 2007 12:58:52 -0700 Subject: How can I make sure my python exit Message-ID: <1175716731.915570.236820@w1g2000hsg.googlegroups.com> Hi, I have a python script: At the end of the script, I have: print "Build Done!" my question is does that mean my python script exits after it prints "Build done!" I have a java program which calls this python script. But i run into a problem in which the python script never returns to the java program after it performs a system call to execute that python script. From cginboston at hotmail.com Sun Apr 15 13:58:04 2007 From: cginboston at hotmail.com (Chaz Ginger) Date: Sun, 15 Apr 2007 17:58:04 GMT Subject: Authenticating clients and servers Message-ID: I am writing a distributed server system using Python. I need to support authentication and was wondering what approaches are available under Python and what are the best practices. Thanks in advance Chaz From bbxx789_05ss at yahoo.com Wed Apr 4 14:57:26 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: 4 Apr 2007 11:57:26 -0700 Subject: operator overloading In-Reply-To: <1175712109.655293.296720@o5g2000hsb.googlegroups.com> References: <1175679412.741899.45990@l77g2000hsb.googlegroups.com> <1175712109.655293.296720@o5g2000hsb.googlegroups.com> Message-ID: <1175713046.254505.10730@o5g2000hsb.googlegroups.com> On Apr 4, 12:41 pm, "7stud" wrote: > On Apr 4, 3:36 am, "looping" wrote: > > > > > Hi, > > for the fun I try operator overloading experiences and I didn't > > exactly understand how it works. > > > Here is my try:>>> class myint(int): > > > def __pow__(self, value): > > return self.__add__(value) > > > >>> a = myint(3) > > >>> a ** 3 > > > 6 > > > OK, it works. Now I try different way to achieve the same result but > > without much luck: > > > >>> class myint(int): > > pass > > >>> myint.__pow__ = myint.__add__ > > > or:>>> class myint(int): > > > __pow__ = int.__add__ > > > or: > > > >>> class myint(int): > > pass > > >>> a.__pow__ = a.__add__ > > > but for every try the result was the same:>>> a = myint(3) > > >>> a ** 3 > > > 27 > > > Why it doesn't works ? > > Look at the output of the following code: > > class myint(int): > pass > > print myint.__pow__ > print myint.__add__ > > -----output:----- > > > > That shows that the names '__pow__' and '__add__' are __slots__. > According to Python in a Nutshell(p.102), a name that is a slot can > only be "bound"(i.e. assigned to) inside the class body. Any later > attempt to assign something to a name that is a slot has no effect. > In your case, I think that means that the only place you can assign > something to an int slot is inside the int class. > > As an alternative, you could override __pow__(). Something like this: > > class myint(int): > def __pow__(self, num): > return super(myint, self).__add__(num) > > n = myint(3) > print n**3 > > ---output:--- > 6 > > That doesn't attempt to reassign something to the slot int.__pow__; > rather it creates a new __pow__ name that hides int.__pow__. Hmmm...after reading Ziga's post and doing some more testing, I don't think __slots__ has anything to do with it. From pavlovevidence at gmail.com Mon Apr 9 19:16:11 2007 From: pavlovevidence at gmail.com (Carl Banks) Date: 9 Apr 2007 16:16:11 -0700 Subject: Classes with initialization In-Reply-To: <1176103583.032209.304710@p77g2000hsh.googlegroups.com> References: <1176103583.032209.304710@p77g2000hsh.googlegroups.com> Message-ID: <1176160571.174848.57920@e65g2000hsc.googlegroups.com> On Apr 9, 3:26 am, mariano.suarezalva... at gmail.com wrote: > Hi all, > > I'm currently using code similar to this: > > class ClassWithInitialization(type): > def __init__(cls, name, bases, dict): > type.__init__(name, bases, dict) > dict['__class_init__'](cls) > > class A: > __metaclass__ = ClassWithInitialization > > def __class_init__(cls): > cls.some_attribute = ... > ... > > in order to get class attributes initialized (since the values of > these attributes > need non trivial work to be computed, putting the code that does that > computation in the class scope ends up with the class having extra > attributes---the `local' variables used in the computation of the > values of class attribute; so I'm using __class_init__'s scope to > contain those variables) > > I was wondering: is there a simpler approach to this? You could put the computations right in the class, and del the extra variables when done. Carl Banks From g.brandl at gmx.net Sun Apr 1 06:19:13 2007 From: g.brandl at gmx.net (Georg Brandl) Date: Sun, 01 Apr 2007 12:19:13 +0200 Subject: Unicode list In-Reply-To: References: Message-ID: Rehceb Rotkiv schrieb: > 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 As Paul said, your terminal is likely set to iso-8859 encoding, which is why it doesn't display UTF-8 correctly. The above program produces correct UTF-8 output. What you could do is: 1. read the file in as unicode 2. print the unicode to the terminal (will use the terminal encoding) or convert the unicode to strings with an explicit encoding before printing codecs.open() is very helpful for step 1, BTW. Georg From malaclypse2 at gmail.com Wed Apr 11 12:55:09 2007 From: malaclypse2 at gmail.com (Jerry Hill) Date: Wed, 11 Apr 2007 12:55:09 -0400 Subject: pop() clarification In-Reply-To: References: Message-ID: <16651e80704110955r50cda3ccp39158afb549b8257@mail.gmail.com> On 4/11/07, Scott wrote: > I see says, "When removing a specific element from a list using pop() it > must be in this format: list.pop([i]). The tutorial (http://docs.python.org/tut/node7.html) says the following: pop( [i] ) Remove the item at the given position in the list, and return it. If no index is specified, a.pop() removes and returns the last item in the list. (The square brackets around the i in the method signature denote that the parameter is optional, not that you should type square brackets at that position. You will see this notation frequently in the Python Library Reference.) Does that answer your question? -- Jerry From bruno.42.desthuilliers at wtf.websiteburo.oops.com Wed Apr 4 06:46:19 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Wed, 04 Apr 2007 12:46:19 +0200 Subject: bool value 'False' no memory address? In-Reply-To: <1175682972.507206.29000@n76g2000hsh.googlegroups.com> References: <1175682972.507206.29000@n76g2000hsh.googlegroups.com> Message-ID: <461381ef$0$15440$426a74cc@news.free.fr> autin a ?crit : > such as: >>>> b = False >>>> id(b) > Traceback (most recent call last): > File "", line 1, in ? > TypeError: 'bool' object is not callable > IMVHO, you shadowed the builtin id() function with a boolean somewhere else... 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. >>> b = False >>> id(b) 135506080 >>> >>> id = False >>> id(b) Traceback (most recent call last): File "", line 1, in ? TypeError: 'bool' object is not callable >>> My 2 cents... From aleax at mac.com Sat Apr 7 19:43:46 2007 From: aleax at mac.com (Alex Martelli) Date: Sat, 7 Apr 2007 16:43:46 -0700 Subject: block scope? References: <7xr6qwal50.fsf@ruckus.brouhaha.com> <7xtzvseqzo.fsf@ruckus.brouhaha.com> <1hw72cg.115yokgarr9enN%aleax@mac.com> <7xr6qvrha9.fsf@ruckus.brouhaha.com> Message-ID: <1hw7l3w.9hqnibhtvghgN%aleax@mac.com> Paul Rubin wrote: > aleax at mac.com (Alex Martelli) writes: > > Thus the following example does not compile: > > class Test { > > public static void main(String[] args) { > > int i; > > for (int i = 0; i < 10; i++) > > I'm ok with this; at the minimum, I think such nesting should produce > a warning message. Yes, a warning could surely be a reasonable compromise. Alex From s_broscious at comcast.net Wed Apr 11 12:52:35 2007 From: s_broscious at comcast.net (Scott) Date: Wed, 11 Apr 2007 12:52:35 -0400 Subject: Hellow World:) References: <765964.71169.qm@web63102.mail.re1.yahoo.com> Message-ID: <6NKdnTVMc_TCj4DbnZ2dnUVZ_hynnZ2d@comcast.com> The author of that book is qouted as saying: ''Note: My more recent book, Beginning Python is an expanded and revised version of this book.'' That qoute can be found at http://hetland.org/writing/practical-python/ However, from my personal experience some of the codes in beginning python have some errors and without a decent foundation in programming can lead to very frustrated attempts at understanding a topic, but the source for all code examples can be found online at http://hetland.org/writing/beginning-python/ As someone thats new to programming myself visit http://diveintopython.org/ its a book thats written by the same guy (I believe), and so far its helped me tremendously in conjuction with beginning python and (now dont laugh) python for dummies. That book was suggested to me when I asked basically the same thing you are asking. "Gabriel Genellina" wrote in message news:mailman.6001.1175734121.32031.python-list at python.org... > En Thu, 29 Mar 2007 16:19:24 -0300, void pointer > escribi?: > >> Hi All ..I am looking for PDF version of " Practical Python" and a >> language to stick to .....Should I find that book ,I wil lconsder this >> Python :) From aleax at mac.com Thu Apr 19 23:39:56 2007 From: aleax at mac.com (Alex Martelli) Date: Thu, 19 Apr 2007 20:39:56 -0700 Subject: Python un-plugging the Interpreter References: Message-ID: <1hwu3xs.pimnimyfct2yN%aleax@mac.com> Michael Hoffman wrote: > S.Mohideen wrote: > > > I was thinking about the feasbility of adjusting Python as a > > compiled language. > > In addition to the Python compilers listed by Steve, there is also > Pyrex, which translates a Python-like language to C, and allows one to > interact with it from Python with very little difficulty. ...and Boo, which is kind of a Python dialect in the same sense as Pyrex is, but has type inference as well as declarations, and (there being only one current implementation) compiles into good dotNet code. Alex From bbxx789_05ss at yahoo.com Mon Apr 16 05:58:51 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: 16 Apr 2007 02:58:51 -0700 Subject: string methods of a str subclass In-Reply-To: References: Message-ID: <1176717531.063492.56880@e65g2000hsc.googlegroups.com> On Apr 16, 3:28 am, "Daniel Nogradi" wrote: > I am probably misunderstanding some basic issue here but this > behaviour is not what I would expect: > > Python 2.4 (#1, Mar 22 2005, 21:42:42) > [GCC 3.3.5 20050117 (prerelease) (SUSE Linux)] on linux2 > Type "help", "copyright", "credits" or "license" for more information.>>> class mystr( str ): > > ... pass > ... > > >>> x = mystr( 'x' ) > >>> isinstance( x, mystr ) > True > >>> isinstance( x.strip( ), mystr ) > False > > Why is the strip( ) method returning something that is not a mystr > instance? I would expect all methods operating on a string instance > and returning another string instance to correctly operate on a mystr > instance and return a mystr instance. How would I achieve something > like this without manually copying all string returning methods from > str and stuffing the result to mystr( ) before returning? class A(object): def __init__(self, s): self.s = s def strip(self): return 2 class mystr(A): pass x = mystr("x") print isinstance(x, mystr) print isinstance(x.strip(), mystr) From steve at holdenweb.com Wed Apr 4 14:46:15 2007 From: steve at holdenweb.com (Steve Holden) Date: Wed, 04 Apr 2007 14:46:15 -0400 Subject: try... except SyntaxError: unexpected EOF while parsing In-Reply-To: References: <1175708304.034078.139020@e65g2000hsc.googlegroups.com> Message-ID: Steve Holden wrote: > oscartheduck wrote: [...] >> > Yes. SyntaxError is raised when the interpreter is compiling the Python > into byetcodes ready for execution. This *can* happen at run time, but > usually it's when you are importing a module and so it gets > transmogrified into an ImportError, though you can trigger it with, for > example, eval: > Of course I omitted to notice that input() can also raise SyntaxError ... sorry about that. 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 rNOSPAMon at flownet.com Sun Apr 22 18:48:58 2007 From: rNOSPAMon at flownet.com (Ron Garret) Date: Sun, 22 Apr 2007 15:48:58 -0700 Subject: Bug in select (was: Re: Select weirdness) References: <3dRWh.4178$j63.322@newsread2.news.pas.earthlink.net> Message-ID: In article <3dRWh.4178$j63.322 at newsread2.news.pas.earthlink.net>, Dennis Lee Bieber wrote: > Well, on WinXP, Python 2.4, with I should have specified: I'm running 2.5 on unix. (I've reproduced the problem on both Linux and OS X.) rg From robert.rawlins at thinkbluemedia.co.uk Fri Apr 27 03:23:47 2007 From: robert.rawlins at thinkbluemedia.co.uk (Robert Rawlins - Think Blue) Date: Fri, 27 Apr 2007 08:23:47 +0100 Subject: : Re-ocurring Events Message-ID: <003101c7889c$ffabe6c0$ff03b440$@rawlins@thinkbluemedia.co.uk> Thank you guys for your suggestions. I've been having a look at that launchd stuff from apple but couldn?t really see how that applies to my requirements. I've been putting some serious thought into how this should work as its essentially the final part of the puzzle for my application, I'll have a fully working model for my application. I've been thinking about the possibility of using a combination of xpath to search the XML with some loops which change the date. As events won't ever be set to start before 01-01-2007 I can set that as the ceiling for my loop. So when I'm searching for weekly events, I 'simply' take today's date and time and loop from now until 01-01-2007 decrementing the date by a week each iteration of the loop and then search the XML for events in that date, make sense? I know that's a fairly intensive way of doing it, but if it works it works. Now, the loop is where I'm really struggling, I've not done any looping with dates, can anyone give me a hand with this? How can I loop back in time from now to beginning of 07 a week at a time? Do we have some form of dateAdd() I can use with a while loop? Perhaps. Date = (now) While date > 2007-01-01: Date = dateAdd(date, -1, w) Something to that effect? Then I can quickly xpath for every iteration of the loop. Thanks guys for any help. Rob -----Original Message----- From: python-list-bounces+robert.rawlins=thinkbluemedia.co.uk at python.org [mailto:python-list-bounces+robert.rawlins=thinkbluemedia.co.uk at python.org] On Behalf Of Laurent Pointal Sent: 26 April 2007 15:33 To: python-list at python.org Subject: Re: Re-ocurring Events Daniel Nogradi a ?crit : >> A bit more of a complex one this time, and I thought I'd get your >> opinions >> on the best way to achieve this. Basically I'm looking for a way to >> describe >> a re-occurring event, like a calendar event or appointment I guess. I'm >> likely to use an XML file for the definition of the events, but >> imagine I've >> got an event that looks something like this. >> >> > repeat="daily" >> /> May take a look at launchd (Apple) XML dialect, it may have at least the semantic for your need. For other parts... elementtree, yes. >> Now what I want to do is be able to build a class which has a function >> like >> 'getCurrentEvent()' which will return any events that should be >> occurring at >> that time. So if the current system time and date is 2007-01-03 13:00:00 >> then it will return THAT event to me, but if it was say 2007-01-03 >> 16:00:00 >> then it would not, as the event isn't 'due' to occur at that time. Make >> sense? >> >> What's the best way of handling this? I'm really a little lost as to >> how I >> might get started, checking a static date time isn't a problem, it's >> when it >> comes to these re-occurring events that I struggle a little. The idea is >> that I would have 5 core repetitions, none, daily, weekly, monthly and >> annually. > > This will not solve all your problems, but a very convenient way of > handling XML is the element tree module (that comes with python 2.5): > http://docs.python.org/lib/module-xml.etree.ElementTree.html > > HTH, > Daniel -- http://mail.python.org/mailman/listinfo/python-list From cfriedalek at gmail.com Thu Apr 19 19:47:55 2007 From: cfriedalek at gmail.com (cfriedalek at gmail.com) Date: 19 Apr 2007 16:47:55 -0700 Subject: class __getitem__ when item is not a sequence ??? Message-ID: <1177026475.610239.22720@q75g2000hsh.googlegroups.com> Sorry for the vague subject. Not sure what the right terminology is. How can I use an instance's data by reference to the instance name, not the instance attribute? OK the question is probably really poor but hopefully an example will make it clear. > x=1 > type(x) > x.__add__(1) 2 > print x 1 > 3*x 3 In this case x is an integer. My understanding is that x in an instance of an integer class. Since it refers to only a single value things like print x, 3*x etc operate on the instance name which seems to refer to the instance data, not the instance itself. I want to do the same for my own classes. For example: > class y: def __init__(self,val): self.val = val > y1 = y(10) > print y1 <__main__.y instance at 0x043C7B20> > 3*y1 : unsupported operand type(s) for *: 'int' and 'instance I have been able to do this by overriding __getitem__ when self.val is a sequence. But I can't find out what to do when self.val is a simple type like int, float etc. From elguavas at users.sourceforge.net Sat Apr 21 00:04:28 2007 From: elguavas at users.sourceforge.net (Stephen M. Gava) Date: Sat, 21 Apr 2007 04:04:28 -0000 Subject: using tkinter to display html References: <2e295$4628c3ed$4275d90a$24599@FUSE.NET> Message-ID: On Fri, 20 Apr 2007 09:45:16 -0400, Kevin Walzer wrote: > PySol has an HTML viewer. Here's a link to some discusison about it: > > http://mail.python.org/pipermail/tkinter-discuss/2006- January/000614.html > > PySol is GPL, so if your application is also GPL, then it might be an > option. thanks kevin, i already use a derivative of that code in another app :) , but i need table and other stuff this time. stephen. > From S.Mientki-nospam at mailbox.kun.nl Mon Apr 30 19:36:28 2007 From: S.Mientki-nospam at mailbox.kun.nl (Stef Mientki) Date: Tue, 01 May 2007 01:36:28 +0200 Subject: [ANN] Update to Python Quick Reference Card (for Python 2.4) (v0.67) In-Reply-To: References: Message-ID: <33ba3$46367ce6$d443bb3a$3128@news.speedlinq.nl> hi Laurent, this is really a work of Art, thank you very much !! Oh, wouldn't it be nice to have reference cards of all library packages ;-) cheers Stef Mientki Laurent Pointal wrote: > PQRC (Python Quick Reference Card) is a condensed documentation for > Python and its main libraries, targetting production of printed quick > reference cards. > Its available as OpenDocument .odt files and as A4 and USLetter > formatted PDF files ready to print. > Its distributed under a Creative Commons Attribution - NonCommercial - > ShareAlike - 2.5 License, with allowing in-house print for curses. > > Modifications since previous publication: > Switching to DejaVu font. > Rework styles. > Get around bad index page numbers generation bug. > Small corrections. > > > Its here: > http://www.limsi.fr/Individu/pointal/python/pqrc/ > > > Note: Next version will target Python 2.5. I'll keep version for Python > 2.4 but should only make minor updates. > > From arkanes at gmail.com Wed Apr 11 11:57:19 2007 From: arkanes at gmail.com (Chris Mellon) Date: Wed, 11 Apr 2007 10:57:19 -0500 Subject: tuples, index method, Python's design In-Reply-To: <1176305859.581010.199600@n76g2000hsh.googlegroups.com> References: <1176210960.3430.20.camel@dot.uniqsys.com> <740c3aec0704100810g5f962e8eu614fbaedecf3608e@mail.gmail.com> <1176219856.3430.76.camel@dot.uniqsys.com> <740c3aec0704101021i1fd79ef2l99eac4ced1e252d9@mail.gmail.com> <1176226682.3430.86.camel@dot.uniqsys.com> <4866bea60704101104r4600d281h135286b66378f4d4@mail.gmail.com> <740c3aec0704101534y3c65f5a7je382f97e1f6301b7@mail.gmail.com> <1176305859.581010.199600@n76g2000hsh.googlegroups.com> Message-ID: <4866bea60704110857sbacfe58sf661dc1a437705c9@mail.gmail.com> On 11 Apr 2007 08:37:39 -0700, Paul Boddie wrote: > On 11 Apr, 16:14, "Chris Mellon" wrote: > > > > If you want a language that just adds whatever methods anyone thinks > > of, along with whatever aliases for it any can think of, to every data > > type, you know where to find Ruby. > > Nobody is asking for Ruby, as far as I can see. I even submitted a > quick patch to provide tuple.index (a method that has already been > thought of), given the triviality of the solution, but you won't find > me asking for a bundle of different convenience methods with all their > aliases on every object, regardless of whether you can monkey-patch > them after the fact or not. For example: > Note that the mail I responded to was using being drunk, not knowing any better, and having fun as use cases for the method. That sounds like Ruby-style method proliferation to me ;) > Note that, in that document, index and count are methods of > MutableSequence. Quite why this should be from a conceptual > perspective is baffling, but don't underestimate the legacy influence > in such matters. > Well, I'm not Guido obviously, but here's why I don't find it baffling. There are 2 main reasons why you'd use an immutable sequence for something: 1) You want to make sure it's not modified by a callee. This is unPythonic and mostly unnecessary. Pass them a copy if you're that paranoid. 2) Because you are representing a known, structured data type. This can be either unordered, in which case index() is meaningless (as in frozenset), or it can be ordered, in which case the order is an implicit part of the structure. In such a case, index() is also meaningless, and should never be necessary. The primary use case for index on tuple is because people use them as immutable lists. That's fine as far as it goes, but I want to know what the justification is for using an immutable list, and if you have one why you need to use index() on it. There's only 2 use cases I've heard so far for that: certain types of binary parsing, which I don't think is common enough to justify modification to the language core, and third party libs returning silly things, which I *certainly* don't think justifies changes to the language core. I'm pretty against tuples growing index() ever. I think that if there is a real need (and just because I haven't seen one doesn't mean it's not there) for an immutable list, the introduction of fozenlist() to the collections module (or something) would be a better solution. On the other hand, if tuples grew list methods and we got a new immutable sequence that had order, unpacking, and *named fields* along the lines of Pascal records I'd be happy with that too. From claird at lairds.us Fri Apr 20 19:25:53 2007 From: claird at lairds.us (Cameron Laird) Date: Fri, 20 Apr 2007 23:25:53 +0000 Subject: Testing GUI's References: <46293e84$1_2@mk-nntp-2.news.uk.tiscali.com> Message-ID: <1punf4-0lq.ln1@lairds.us> In article <46293e84$1_2 at mk-nntp-2.news.uk.tiscali.com>, Stephen Lewitowski wrote: >Can any of you guy's out there point me to information on automating >GUI's that use Tkinter. > >I would like to find out more and possibly get involved if there are any > projects under development. . . . From erikwickstrom at gmail.com Mon Apr 2 15:50:59 2007 From: erikwickstrom at gmail.com (erikcw) Date: 2 Apr 2007 12:50:59 -0700 Subject: How do you escape % when formatting a string? Message-ID: <1175543459.131630.96650@y80g2000hsf.googlegroups.com> Hi, I'm trying to format a string like so: string = "You have a 75% chance of success with %s, don't use %s" %(a, b) This gives me: TypeError: not enough arguments for format string I've tried 75\%, but that doesn't seem to help. What am I missing? Thanks! Erik From wswilson at gmail.com Wed Apr 11 10:23:59 2007 From: wswilson at gmail.com (wswilson) Date: 11 Apr 2007 07:23:59 -0700 Subject: passing class by reference does not work?? Message-ID: <1176301439.769248.247720@y5g2000hsa.googlegroups.com> Here is my code: class A(): val = 0 def b(item, a): a.val = a.val + 1 return item + a.val def c(): d = [1, 2, 3] print [b(item, A()) for item in d] c() I expected this to output [2, 4, 6]. However, it outputs [2, 3, 4] which is not what I wanted. I thought that if I passed the A() instance in my list comprehension in c(), then the changes I made to a.val in b() would be reflected in the A() instance next time the list comprehension called b(). But, obviously that is not happening. I'm kinda new at python so I may be missing something obvious here. Any suggestions? From Emile.Boudreau at cognos.com Tue Apr 3 13:26:54 2007 From: Emile.Boudreau at cognos.com (Boudreau, Emile) Date: Tue, 3 Apr 2007 13:26:54 -0400 Subject: Extracting a file from a tarball Message-ID: <09042D621CD4AA479C678463F3A646D0F73DD5@sottemail1.ent.ad.cognos.com> I am trying to extract one file from a tarball, without success. This is the code I'm using to open the tarball and extract the file: tar = tarfile.open(component+'-win32-app-'+bestVersion+'-dev.tar.gz', 'r') extractedFile = tar.extractfile('symbols.xml') And this is my error: Traceback (most recent call last): File "C:\CognosInstalls\AutoTest\PollDir.py", line 121, in main() File "C:\CognosInstalls\AutoTest\PollDir.py", line 119, in main extract('c:\\', 'I:\\daily\\'+components[i], components[i]) File "C:\CognosInstalls\AutoTest\PollDir.py", line 27, in extract filelike = tar.extractfile('symbols.xml') File "C:\Python25\lib\tarfile.py", line 1488, in extract tarinfo = self.getmember(member) File "C:\Python25\lib\tarfile.py", line 1171, in getmember raise KeyError("filename %r not found" % name) KeyError: "filename 'symbols.xml' not found" I know that the tarball contants this file "symbols.xml" but I don't understand why it's not extracting it. Any help will be greatly appreciated. Thanks, 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 anton.hartl at gmail.com Wed Apr 18 13:39:36 2007 From: anton.hartl at gmail.com (Anton Hartl) Date: Wed, 18 Apr 2007 17:39:36 +0000 (UTC) Subject: 2.5 from source install problem with extensions References: <1176892612.378898.34580@e65g2000hsc.googlegroups.com> <1176898857.656696.221690@p77g2000hsh.googlegroups.com> Message-ID: Hi, On 2007-04-18, Florian Demmer wrote: > On Apr 18, 12:36 pm, Florian Demmer wrote: >> Hi! >> >> I am doing a from source installation of Python 2.5 on some old Debian >> machine. As the target directoy I want /opt/somename so i added it to >> the configure like so: >> >> ./configure --prefix=/opt/somedir >> >> The following make works fine as far as I can see. Then the make >> install also actually works and installs python in /opt/somedir with >> all its subdirectoris (bin, lib, man, include). >> The extensions (*.so) however get put in /usr/local/lib/... and there >> also in the wrong python directoy: 2.4 Basically I had the same problem(s). >> (How) can I change the install_dir for the extensions? >> Why does it use python2.4 anyway?! What env var or else is set here >> that I cannot find? I've patched setup.py as follows: --- setup.py.orig Thu Aug 10 01:42:18 2006 +++ setup.py Mon Dec 25 19:05:29 2006 @@ -147,6 +147,14 @@ if ext.name in sys.builtin_module_names: self.extensions.remove(ext) + # so -lpython2.5 works in the build + ext.library_dirs.append('.') + + # so shared libs requiring libpython2.5.so work + py_instdir = os.environ.get("INSTDIR_PYTHON", None) + if py_instdir: + ext.library_dirs.append(os.path.join(py_instdir, 'lib')) + if platform != 'mac': # Parse Modules/Setup and Modules/Setup.local to figure out which # modules are turned on in the file. Then you have to add INSTDIR_PYTHON to your shell environment, i.e. INSTDIR_PYTHON=/opt/somedir ; export INSTDIR_PYTHON or whatever your shell requires. This works for me. Hope it helps, Anton From paul at boddie.org.uk Wed Apr 18 18:10:50 2007 From: paul at boddie.org.uk (Paul Boddie) Date: 18 Apr 2007 15:10:50 -0700 Subject: Compiling python from soruce vs RPM ? In-Reply-To: <1176911689.026633.230390@l77g2000hsb.googlegroups.com> References: <1176911689.026633.230390@l77g2000hsb.googlegroups.com> Message-ID: <1176934250.650536.239040@p77g2000hsh.googlegroups.com> howa wrote: > I have compiled python 2.5 from source > > i.e. > > ./configure > make > make install By default, configure uses /usr/local as the "prefix", not /usr... > but when i try to install another package require python, seems it > can't regonize python... > > e.g.. > > > /usr/bin/python is needed by xyz Consequently, by default, Python will be found at /usr/local/bin/ python, not /usr/bin/python as you seem to require. Try building from source again: make clean # probably needed if rebuilding in the same place ./configure --prefix=/usr make make install Since /usr/bin/python isn't found, it doesn't look like there's an existing version of Python that you might overwrite, but it's important to verify such things when installing software. That's where your distribution's packages have an advantage, and it's arguably a better idea to install such packages instead, possibly building them from source if no binary packages exist yet for Python 2.5. (If no source packages exist, you have a bit more work to do.) Paul From notrealaddress at all.com Wed Apr 11 09:31:50 2007 From: notrealaddress at all.com (Dropkick Punt) Date: Wed, 11 Apr 2007 22:31:50 +0900 Subject: Connection problems with irclib Message-ID: Hi. I've written a bot in python, using the irclib by Joel Rosdahl. Works fine from my linux box at home, but when I upload it to my shell at veritynet.net, can't seem to get it to connect to an irc server. It doesn't report any errors. Anyone have any idea how I might go about at least diagnosing the problem? Any suggestions might help. Thanks in advance. From steve at REMOVEME.cybersource.com.au Mon Apr 2 05:41:05 2007 From: steve at REMOVEME.cybersource.com.au (Steven D'Aprano) Date: Mon, 02 Apr 2007 19:41:05 +1000 Subject: Question about text in Python References: <4610c366$0$15022$5a62ac22@per-qv1-newsreader-01.iinet.net.au> Message-ID: On Mon, 02 Apr 2007 18:48:00 +1000, Steve wrote: > Hi, > > I've created a Python program that a user enteres one line of text which > will then create an acronym from that text. > > What I want to add to the program is the abilty to rerun this process (where > the user enteres another line of text) until the user has had enough and > enters a blank line which would then end the program. > > Can anyone help with this? It isn't really a question about _text_. It's a question about programming techniques. Firstly, break the task into small pieces: * get input (a line of text) from the user; * make an acronym from the text; * decide if you're done; * if not, repeat from the beginning. Now write code to do each piece. Now all you need to do is create functions to do each sub-task: def get_input(): """Get input from the user.""" return raw_input("Please type a sentence. ") def make_acronym(text): """Return an acronym from the given text.""" # you have already done this .... do stuff ... return acronym def are_we_done(): """Return a boolean flag indicating whether we're done making acronyms. """ print "Would you like to make another acronym?" print "Type Y or y for yes, N or n for no." result = raw_input("Then press the Enter key. (y/n?) ") return result in 'yY' Now put them all together into a loop. done = False # we're not done yet while not done: # repeat until we're done text = get_input() acronym = make_acronym(text) print acronym done = are_we_done() There are lots of other ways of doing this. This one is (I think) the easiest to understand, but there are other ways that are more efficient but use more advanced concepts like exceptions. Have fun exploring the different ways of doing this task. -- Steven D'Aprano From quetzalcotl at consultant.com Tue Apr 17 04:12:38 2007 From: quetzalcotl at consultant.com (Ingo Menger) Date: 17 Apr 2007 01:12:38 -0700 Subject: is laziness a programer's virtue? In-Reply-To: <1176757271.282365.319740@n76g2000hsh.googlegroups.com> References: <1176757271.282365.319740@n76g2000hsh.googlegroups.com> Message-ID: <1176797558.403629.53140@b75g2000hsg.googlegroups.com> On 16 Apr., 23:01, "Xah Lee" wrote: > If your article is relevant to X, Y, and Z, > please cross post it. Yeah right, and if it is not, don't post it at all. Your articles are nothing but a bunch of unfounded allegations, moralism and your personal notion of what alledgedly "hurts society". As such, they have no relevance at all in technical news groups. From mik3l3374 at gmail.com Fri Apr 13 05:25:12 2007 From: mik3l3374 at gmail.com (mik3l3374 at gmail.com) Date: 13 Apr 2007 02:25:12 -0700 Subject: Try problem In-Reply-To: <1176455642.199343.136720@l77g2000hsb.googlegroups.com> References: <1176455642.199343.136720@l77g2000hsb.googlegroups.com> Message-ID: <1176456312.752519.198130@e65g2000hsc.googlegroups.com> On Apr 13, 5:14 pm, "SamG" wrote: > import sys > try: > s=1 > if s==1: > sys.exit(0) > else: > sys.exit(1) > except SystemExit,s: > if (s==0): > print s > else: > print "Hello" > > How come i always end up getting the "Hello" printed on the screen as > logically i should a '0' printed? if you put a debug print statement, eg ... except SystemExit,s: print "s in exception " , s, type(s) if (s==0): .... you will notice 's' is an "instance". so when it reaches the if (s==0), which you are comparing with a number, it will fail and then hello is printed. From gagsl-py2 at yahoo.com.ar Thu Apr 12 04:00:34 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 12 Apr 2007 05:00:34 -0300 Subject: redirecting stdout to a file as well as screen References: <1176362072.527678.201150@l77g2000hsb.googlegroups.com> Message-ID: En Thu, 12 Apr 2007 04:14:32 -0300, SamG escribi?: > How could i make, from inside the program, to have the stdout and > stderr to be printed both to a file as well the terminal(as usual). A very minimal example: import sys class Tee(file): others = () def write(self, data): file.write(self, data) for f in others: f.write(data) tee = Tee(r"c:\temp\output.log","wt") tee.others = [sys.stdout, sys.stderr] sys.stdout = sys.stderr = tee print dir(sys) sys.foo # error -- Gabriel Genellina From jorgen.maillist at gmail.com Tue Apr 17 05:39:19 2007 From: jorgen.maillist at gmail.com (Jorgen Bodde) Date: Tue, 17 Apr 2007 11:39:19 +0200 Subject: OverflowError: mktime argument out of range ??? In-Reply-To: <1176761366.967796.102110@y5g2000hsa.googlegroups.com> References: <11e49df10704150341p1a9056e7hfba36a523517fad3@mail.gmail.com> <1176640607.972087.153470@o5g2000hsb.googlegroups.com> <1176735739.422686.227960@d57g2000hsg.googlegroups.com> <1176761366.967796.102110@y5g2000hsa.googlegroups.com> Message-ID: <11e49df10704170239s34a3075bg4547639380d2bb51@mail.gmail.com> Thanks again, I will explain what happened. I am a python newbie. The time and datetime modules are confusing at the beginning, but after diving into them I started to understand the structure. So what I did was using the time module for date storage, but I came to understand that time is actually more used for file dates and times. That would explain the epoch and 1970 boundaries as there are not much files before the pre-PC era to keep timestamps for. Basically it would have been clearer if the time module would have been called 'filetime' as datetime kind of supercedes the time by removing all boundaries and still presenting all methods to the user. Onca again, it was confusing for someone starting with python, but I think I got it now. I cannot claim it was not documented, I was more surprised that there was a boundary and decided to ask before reading the python docs, sorry .... With regards, - Jorgen From bbxx789_05ss at yahoo.com Mon Apr 9 04:43:11 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: 9 Apr 2007 01:43:11 -0700 Subject: Is there a simple function to generate a list like ['a', 'b', 'c', ... 'z']? In-Reply-To: <1176107364.000517.68580@q75g2000hsh.googlegroups.com> References: <1176107364.000517.68580@q75g2000hsh.googlegroups.com> Message-ID: <1176108191.558918.196040@d57g2000hsg.googlegroups.com> On Apr 9, 2:29?am, "???????????????" wrote: > Is there a simple function to generate a list like ['a', 'b', 'c', ... > 'z']? ? The range() just can generate the numeric list. Not very simple, but how about a list comprehension: import string lst = [char for char in string.letters[:26] ] print lst From Arao44 at gmail.com Fri Apr 27 03:07:53 2007 From: Arao44 at gmail.com (AK444) Date: 27 Apr 2007 00:07:53 -0700 Subject: video lectures on C, C++, Java, Python and other programming and Computer science. Message-ID: <1177657673.091543.182440@b40g2000prd.googlegroups.com> Hi Friends, Check here http://freevideolectures.com/computerscience.html for video lectures on Programming languages like C, C++, Java, COBOL etc.., OS, Algorithms, Data Structures, RDBMS, Web designing, etc.......... It also has amazing collection of video lectures and animations on all Engineering and Medical Sciences. I am sure you will be surprised to see such great collection. Do you like it??? From http Sun Apr 8 20:23:03 2007 From: http (Paul Rubin) Date: 08 Apr 2007 17:23:03 -0700 Subject: tuples, index method, Python's design References: <1175867771.114540.61810@n76g2000hsh.googlegroups.com> <1175884427.779950.267220@y80g2000hsf.googlegroups.com> <1175953520.316208.241490@o5g2000hsb.googlegroups.com> <7xzm5igbrb.fsf@ruckus.brouhaha.com> <7x8xd2iq53.fsf@ruckus.brouhaha.com> Message-ID: <7xd52e8kgo.fsf@ruckus.brouhaha.com> Carsten Haese writes: > Will tuples also get a sort method? What about append and extend? pop? > __iadd__? __delslice__? They are immutable so they won't get .sort() etc. sorted(...) already works on them. > How many brain cells are actually freed up by not having to remember > that *one* method that you'd never use doesn't exist? I dunno but I do know that Ruby is attracting a lot of potential Python users because it apparently has fewer of these inconsistencies. A big web site I hang out on decided to do a software rewrite (currently using a huge perl script) and evaluated a bunch of possible approaches. In the final decision, Ruby/Rails won out over Python/Django. From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Mon Apr 2 16:48:27 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Mon, 02 Apr 2007 22:48:27 +0200 Subject: Problem with global variables References: <1311u48bqkehk24@corp.supernews.com> <57ciafF2cf6qdU1@mid.individual.net> <461161a8$0$27400$ba4acef3@news.orange.fr> Message-ID: <57d8glF2bjfpcU1@mid.individual.net> Laurent Pointal wrote: > Yes, and i replies: "which contains a foo assignment. As foo is > not defined "global", it is considered to be local. " > > Maybe my explanation was not clear enough with variable foo to be > considered local because there is an *assignment* to foo. Yep, thanks for the clarification. After four replies and despite weird conjugations, I've definitely got it now ... ;) Regards, Bj?rn -- BOFH excuse #113: Root nameservers are out of sync From tdelaney at avaya.com Tue Apr 10 01:36:56 2007 From: tdelaney at avaya.com (Delaney, Timothy (Tim)) Date: Tue, 10 Apr 2007 15:36:56 +1000 Subject: RFC: Assignment as expression (pre-PEP) Message-ID: <2773CAC687FD5F4689F526998C7E4E5FF1ED56@au3010avexu1.global.avaya.com> Alex Martelli wrote: >> As others have mentioned, your particular instance is probably >> evidence that you need to restructure your code a little bit, but I >> do agree that "x = y; if x: ..." is a common enough idiom that it >> warrants a shortcut. And reusing "as", I think, is nice and readable, >> and it's an advantage that it doesn't require adding any new keywords >> or symbols. > > Actually, I agree with you. Unfortunately, I doubt python-dev will, > but the chance is good enough that it's probably worth proposing there > (ideally together with a patch to implement it, just to avoid any > [otherwise likely] whines about this being difficult to implement:-). This was proposed on python-dev (or maybe it was python-ideas) - I think the discussion died out though without any resolution. You should check the archives to see if there was a resolution on it, and if not I'd suggest putting a PEP together, rather than just raising it again. Tim Delaney From junkdump2861 at hotmail.com Fri Apr 13 13:10:19 2007 From: junkdump2861 at hotmail.com (junkdump2861 at hotmail.com) Date: 13 Apr 2007 10:10:19 -0700 Subject: Inconsistent result from urllib.urlopen In-Reply-To: References: <1176402303.340868.165510@o5g2000hsb.googlegroups.com> Message-ID: <1176484219.914951.222110@b75g2000hsg.googlegroups.com> Laszlo Nagy wrote: > > Any ideas why I don't get the same result from the python script as I > > do from a web browser? This problem seems to be a recent > > development. The scripts I wrote like this worked fine for a while > > and then stopped working within the past couple of weeks. > > > Maybe it has to do something with your user agent string. The server > side can decide to return a different content when your user agent is > not 'mozilla', 'internet explorer' or 'opera' etc. > > Do you want to know how to change your user agent string? Google for > it.... :-) > > Laszlo Thanks. That is the fix I needed. I added urllib.URLopener.version = 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.4) Gecko/20030624 Netscape/7.1 (ax)' as the second line of code and now it is actually getting content, not just an error message. It's not the exact same format as you get from saving the page from the web browser, but all the links and image addresses are in place. From kevinliu23 at gmail.com Fri Apr 20 14:51:02 2007 From: kevinliu23 at gmail.com (kevinliu23) Date: 20 Apr 2007 11:51:02 -0700 Subject: Newbie question regarding string.split() Message-ID: <1177095062.826018.63590@n59g2000hsh.googlegroups.com> Hey guys, So I have a question regarding the split() function in the string module. Let's say I have an string... input = "2b 3 4bx 5b 2c 4a 5a 6" projectOptions = (input.replace(" ", "")).split('2') print projectOptions ['', 'b34bx5b', 'c4a5a6'] My question is, why is the first element of projectOptions an empty string? What can I do so that the first element is not an empty string? but the 'b34bx5b' string as I expected? Thanks so much guys. :) From tjreedy at udel.edu Wed Apr 25 17:39:54 2007 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 25 Apr 2007 17:39:54 -0400 Subject: Would You Write Python Articles or Screencasts for Money? References: <462DCCE6.9060908@taupro.com> <1hx2dvj.10ek1v51noh1otN%aleax@mac.com> Message-ID: "Anton Vredegoor" wrote in message news:f0o5dp$8nl$1 at news5.zwoll1.ov.home.nl... || I didn't realize this was about an PSF internal affair. [snip] Enough of the sour grapes, please. The question posted is whether non-members would be interested in prizes or contracts voted on by members (who would some or all be ineligible for the outlays). That question is quite appropriate here. For me: I can imagine that even smallish amounts might act as a tipping-point incentive to more than I might otherwise. I think working with The Python Papers as one avenue should be considered. tjr From martin.clausen at gmail.com Sun Apr 22 06:41:52 2007 From: martin.clausen at gmail.com (Martin) Date: 22 Apr 2007 03:41:52 -0700 Subject: Access to file dropped on .exe/.app icon Message-ID: <1177238512.066413.41660@n59g2000hsh.googlegroups.com> If i create an app using py2exe/py2app is there then a way on windows/ mac to get access to a file dragged and dropped on to the .exe/.app icon? Martin From pythoncurious at gmail.com Tue Apr 17 03:52:46 2007 From: pythoncurious at gmail.com (pythoncurious at gmail.com) Date: 17 Apr 2007 00:52:46 -0700 Subject: script for seconds in given month? In-Reply-To: <1176745773.092500.47600@w1g2000hsg.googlegroups.com> References: <1176740556.859125.221980@l77g2000hsb.googlegroups.com> <1176744505.863580.182390@e65g2000hsc.googlegroups.com> <1176745773.092500.47600@w1g2000hsg.googlegroups.com> Message-ID: <1176796366.836503.322830@e65g2000hsc.googlegroups.com> On Apr 16, 7:49 pm, "edfialk" wrote: > Jim: I need years too, basically from 1960-2000. Don't want to > hardcode all those days :) > > Matt: Thanks, I will try this out. > > Paul: I don't believe we need leapseconds. Leap days definitely. > > I'll let you know how Matt's code works. Any other suggestions feel > free to let me know. > > Thanks all! > -Ed There's one thing I forgot to mention: mktime (like most things using the standard C functions) will work reliably from 1970 to 2038 or so. Also, I think posix explicitly says that leap seconds are ignored, so those are not covered. /Matt From ptmcg at austin.rr.com Fri Apr 13 10:19:49 2007 From: ptmcg at austin.rr.com (Paul McGuire) Date: 13 Apr 2007 07:19:49 -0700 Subject: Problem with algorithm In-Reply-To: References: <1176434160.047703.214600@q75g2000hsh.googlegroups.com> <1176434937.258002.162220@p77g2000hsh.googlegroups.com> <1176448576.047996.12930@d57g2000hsg.googlegroups.com> Message-ID: <1176473989.420067.190970@l77g2000hsb.googlegroups.com> On Apr 13, 8:53 am, Steve Holden wrote: > Jia Lu wrote: > >> for m in test: > >> for n in test: > >> for o in test: > >> for p in test: > >> print m+n+o+p > > > Thanx for your anwser. > > But if I consider about a combination of over 26 letter's list just > > like: > > "abcdefssdzxcvzxcvzcv" > > "asllxcvxcbbedfgdfgdg" > > ..... > > > Need I write 26 for loops to do this? > > > Thanx > > > Jia LU > > Your new example uses 20-byte strings anyway, so to produce those using > the specified method you would need 20 nested for loops, not 26. > > I'm pretty sure you could give a separate name to each atom ont he known > universe with a scheme like this. Do you really need 20-byte strings? > > 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 - If you just expand the length to five million* or so, one of those strings will contain all the works of Shakespeare. -- Paul * ref: Project Gutenberg - http://www.gutenberg.org/etext/100 - unzipped plaintext is ~5.3Mb From skip at pobox.com Mon Apr 9 09:59:49 2007 From: skip at pobox.com (skip at pobox.com) Date: Mon, 9 Apr 2007 08:59:49 -0500 Subject: Is there a simple function to generate a list like ['a', 'b', 'c', ... 'z']? In-Reply-To: References: <1176107364.000517.68580@q75g2000hsh.googlegroups.com> Message-ID: <17946.18133.822637.523208@montanaro.dyndns.org> Thomas> [ chr(i) for i in range(97, 123) ] Or with fewer magic numbers: [chr(i) for i in range(ord('a'), ord('z')+1)] Skip From kyosohma at gmail.com Mon Apr 9 10:29:46 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: 9 Apr 2007 07:29:46 -0700 Subject: Why does not my wx.html.HtmlWindow work? In-Reply-To: <1176082305.001647.152860@n59g2000hsh.googlegroups.com> References: <1176003505.794328.62170@n76g2000hsh.googlegroups.com> <1176082305.001647.152860@n59g2000hsh.googlegroups.com> Message-ID: <1176128986.138864.63920@q75g2000hsh.googlegroups.com> On Apr 8, 8:31 pm, "liqfem... at gmail.com" wrote: > On Apr 9, 1:01 am, Rob Williscroft wrote: > > > > > liqfem... at gmail.com wrote innews:1176003505.794328.62170 at n76g2000hsh.googlegroups.comin > > comp.lang.python: > > > > Below are my source code: > > > > import wx > > > import wx.html > > > > class MyHtmlFrame(wx.Frame): > > > > def __init__(self, parent, title): > > > wx.Frame.__init__(self, parent, -1, title, size=(600,400)) > > > html = wx.html.HtmlWindow (self) > > > if "gtk2" in wx.PlatformInfo: > > > html.SetStandardFonts() > > > html.LoadPage(" > > > http://www.pythonthreads.com/articles/python/incorporating-into > > > -wxpython-part-1.html") > > > > app = wx.PySimpleApp() > > > frm = MyHtmlFrame(None, "Simple HTML Browser") > > > frm.Show() > > > app.MainLoop() > > > > It is just an example in the book "wxPython in action". But every time > > > when I try to get it run, my CPU is fully occupied, and there is no > > > frame that comes into existence. Why? > > > I think your problem is that you call LoadPage before app.MainLoop() is > > called, IOW you need to call LoadPage in an event handler: > > > import wx > > import wx.html > > > class MyHtmlFrame(wx.Frame): > > > HOME = "http://www.google.co.uk" > > > def __init__(self, parent, title): > > wx.Frame.__init__(self, parent, -1, title, size=(600,400)) > > self.html = wx.html.HtmlWindow (self) > > if "gtk2" in wx.PlatformInfo: > > self.html.SetStandardFonts() > > self.done_show = False > > wx.EVT_IDLE( self, self.OnShow ) > > self.html.SetPage( > > "Loading ..." % self.HOME > > ) > > > def OnShow( self, event ): > > if self.done_show: > > return > > self.done_show = True > > self.html.LoadPage( self.HOME ) > > > app = wx.PySimpleApp() > > frm = MyHtmlFrame(None, "Simple HTML Browser") > > frm.Show() > > app.MainLoop() > > > Note: the URL you loading takes ages to show, which is why I > > use:http://www.google.co.ukabove. > > > Rob. > > --http://www.victim-prime.dsl.pipex.com/ > > To Rob Williscroft, > > It works when I call LoadPage() in any event handler, though I don't > know the reason. I'll try to learn it. > Thank you. > And the example in the book "wxPython In Action" is wrong? I know some of the examples from the book are no longer current, but I cannot recall if the HtmlWindow one was one of them or not. You can ask at the wxPython users group. Robin Dunn (one of the authors of the book) is one of the moderators there. http://wxpython.org/maillist.php I recommend using the examples in the wxPython Demo as they are usually the most current. Mike From wangday at gmail.com Wed Apr 4 09:40:30 2007 From: wangday at gmail.com (Dayong Wang) Date: Wed, 4 Apr 2007 15:40:30 +0200 Subject: An error of matrix inversion using NumPy In-Reply-To: <740c3aec0704040637i50efaaa9u1fdd5d39bcd73aca@mail.gmail.com> References: <1175692518.282887.3040@y66g2000hsf.googlegroups.com> <740c3aec0704040637i50efaaa9u1fdd5d39bcd73aca@mail.gmail.com> Message-ID: Here below is the matrix KK I used: [[ 1939.33617572 -146.94170404 0. 0. 0. 0. 0. 0. 0. -1172.61032101 0. 0. -193.69962687 -426.08452381 0. 0. 0. 0. 1792.39447168] [ -146.94170404 5175.33392519 -442.430839 0. 0. 0. 0. 0. 0. 0. -3409.58801135 0. 0. 0. -767.46969697 -408.90367384 0. 0. 4585.96138215] [ 0. -442.430839 4373.33685159 0. 0. 0. 0. 0. 0. 0. 0. -2354.70959362 0. 0. 0. 0. -855.36922061 -720.82719836 3930.90601259] [ 0. 0. 0. 17064.73017917 -949.49987581 0. 0. 0. 0. 0. 0. 0. -16115.23030336 0. 0. 0. 0. 0. 16115.23030336] [ 0. 0. 0. -949.49987581 11005.53604312 -1358.01000599 0. 0. 0. 0. 0. 0. 0. -8698.02616132 0. 0. 0. 0. 8698.02616132] [ 0. 0. 0. 0. -1358.01000599 18322.57142994 -1495.29428718 0. 0. 0. 0. 0. 0. 0. -15469.26713677 0. 0. 0. 15469.26713677] [ 0. 0. 0. 0. 0. -1495.29428718 12497.65812936 -1858.81899672 0. 0. 0. 0. 0. 0. 0. -9143.54484546 0. 0. 9143.54484546] [ 0. 0. 0. 0. 0. 0. -1858.81899672 20170.17739075 -1249.5298217 0. 0. 0. 0. 0. 0. 0. -17061.82857234 0. 17061.82857234] [ 0. 0. 0. 0. 0. 0. 0. -1249.5298217 9476.04289846 0. 0. 0. 0. 0. 0. 0. 0. -8226.51307677 8226.51307677] [ -1172.61032101 0. 0. 0. 0. 0. 0. 0. 0. 1500.8055591 -328.1952381 0. 0. 0. 0. 0. 0. 0. -1172.61032101] [ 0. -3409.58801135 0. 0. 0. 0. 0. 0. 0. -328.1952381 4112.15248021 -374.36923077 0. 0. 0. 0. 0. 0. -3409.58801135] [ 0. 0. -2354.70959362 0. 0. 0. 0. 0. 0. 0. -374.36923077 2729.07882439 0. 0. 0. 0. 0. 0. -2354.70959362] [ -193.69962687 0. 0. -16115.23030336 0. 0. 0. 0. 0. 0. 0. 0. 17726.91399397 -1417.98406375 0. 0. 0. 0. -16308.92993023] [ -426.08452381 0. 0. 0. -8698.02616132 0. 0. 0. 0. 0. 0. 0. -1417.98406375 12320.46305747 -1778.36830859 0. 0. 0. -9124.11068513] [ 0. -767.46969697 0. 0. 0. -15469.26713677 0. 0. 0. 0. 0. 0. 0. -1778.36830859 19552.18019195 -1537.07504962 0. 0. -16236.73683374] [ 0. -408.90367384 0. 0. 0. 0. -9143.54484546 0. 0. 0. 0. 0. 0. 0. -1537.07504962 12983.70625768 -1894.18268877 0. -9552.44851929] [ 0. 0. -855.36922061 0. 0. 0. 0. -17061.82857234 0. 0. 0. 0. 0. 0. 0. -1894.18268877 21039.17951514 -1227.79903343 -17917.19779295] [ 0. 0. -720.82719836 0. 0. 0. 0. 0. -8226.51307677 0. 0. 0. 0. 0. 0. 0. -1227.79903343 10175.13930856 -8947.34027513] [ 1792.39447168 4585.96138215 3930.90601259 16115.23030336 8698.02616132 15469.26713677 9143.54484546 17061.82857234 8226.51307677 -1172.61032101 -3409.58801135 -2354.70959362 -16308.92993023 -9124.11068513 -16236.73683374 -9552.44851929 -17917.19779295 -8947.34027513 85023.67196244]] On 4/4/07, BJ?rn Lindqvist wrote: > On 4 Apr 2007 06:15:18 -0700, lancered wrote: > > During the calculation, I noticed an apparent error of > > inverion of a 19x19 matrix. Denote this matrix as KK, U=KK^ -1, I > > found the product of U and KK is not equivalent to unit matrix! This > > apparently violate the definition of inversion. The inversion is > > through the function linalg.inv(). > > Could it have something to do with floating point accuracy? > > >>> r = matrix([[random.random() * 9999 for x in range(19)] for y in range(19)]) > >>> allclose(linalg.inv(r) * r, identity(19)) > True > > > So, can you tell me what goes wrong? Is this a bug in > > Numpy.linalg? How to deal with this situation? If you need, I can > > post the matrix I used below, but it is so long,so not at the moment. > > Please post it. > > -- > mvh Bj?rn > From nagle at animats.com Thu Apr 26 23:21:38 2007 From: nagle at animats.com (John Nagle) Date: Fri, 27 Apr 2007 03:21:38 GMT Subject: My python annoyances so far In-Reply-To: <1hx6zi2.1oz684ndspxdgN%aleax@mac.com> References: <1177541453.471959.120830@c18g2000prb.googlegroups.com> <59bf34F2k27v5U1@mid.individual.net> <1177603623.774892.230390@t38g2000prd.googlegroups.com> <1hx6zi2.1oz684ndspxdgN%aleax@mac.com> Message-ID: <6%dYh.12648$YL5.4047@newssvr29.news.prodigy.net> Alex Martelli wrote: > Steven D'Aprano wrote: > ... > >>detail you shouldn't care about. Functions that cache the result of long >>time-consuming complications are _good_. > > > Not necessarily -- > > asserts the exactly opposite principle, "Don't save anything you can > recalculate"... of course, the best approach is generally a compromise, > but it's good to be aware of the potentially high costs of caching:-). > > > Alex Abelson and Sussman has a better discussion of this subject. Look under "memoization". John Nagle From samjnaa at gmail.com Sat Apr 14 09:39:59 2007 From: samjnaa at gmail.com (jamadagni) Date: 14 Apr 2007 06:39:59 -0700 Subject: Python Feature Request: Allow changing base of member indices to 1 In-Reply-To: <4620b47b$0$14410$9b622d9e@news.freenet.de> References: <1176546465.632410.52630@w1g2000hsg.googlegroups.com> <4620b47b$0$14410$9b622d9e@news.freenet.de> Message-ID: <1176557999.665663.299740@y80g2000hsf.googlegroups.com> On Apr 14, 4:01 pm, "Martin v. L?wis" wrote: > This one is not sane. It's not possible to change the indexing of > objects on a per-module basis, as objects may cross module boundaries. I do not request for this to be changed per-module. Once I say something like: from __future__ import indices_start_at_one afterwards I would expect *any* index from *any* module to start at 1. To my understanding, Python is going to parse the content of modules only as and when they are called. So Python is basically reading the content of those modules when the flag of indices_start_at_one is active, and hence I would expect it to start counting at 1. I can envisage, stemming from your comments, that this can lead to trouble when a module being accessed has hard-coded indices. It would not be fair of me to expect all module writers to declare the base option at the head of each file, though it would be good practice. So the solution is to allow the programmer to choose to limit this tag locally or activate it globally. option base 1 local option base 1 global From kw at codebykevin.com Wed Apr 18 11:35:40 2007 From: kw at codebykevin.com (Kevin Walzer) Date: Wed, 18 Apr 2007 11:35:40 -0400 Subject: Future Python Gui? In-Reply-To: <1176909848.455264.174730@e65g2000hsc.googlegroups.com> References: <1176859699.906386.326720@b75g2000hsg.googlegroups.com> <1176863948.526051.186210@n76g2000hsh.googlegroups.com> <1176909848.455264.174730@e65g2000hsc.googlegroups.com> Message-ID: <46263ACC.8080400@codebykevin.com> bcwhite at pobox.com wrote: >> I'd say that the best bet is to learn swig and similar >> bridging, expanding, and embedding mechanisms. >> Python GUI programming is likely to involve either >> python hooking into frameworks like Cocoa, Qt, or >> wxWidgets, python embedded in frameworks >> like Java or .NET, or flavors of python used >> as domain-specific languages in applications such as >> emacs, vim, and OpenOffice.org. > > If this were just a tool for me, it wouldn't matter. My concern is > distribution. If anybody who wants to run my software then they also > have to go through all the trouble to install these extensions, none > of which seem to have decent instructions. I'm an old-time hack and I > have trouble getting them to work. A simple user won't have a chance! > This is what deployment tools such as py2app or py2exe are for--to wrap all the bits up into a simple package that the end user just installs, without worrying about dependencies. -- Kevin Walzer Code by Kevin http://www.codebykevin.com From nagle at animats.com Mon Apr 30 20:32:20 2007 From: nagle at animats.com (John Nagle) Date: Tue, 01 May 2007 00:32:20 GMT Subject: re-importing modules In-Reply-To: <1177967919.968338.3300@l77g2000hsb.googlegroups.com> References: <8%pZh.18192$Kd3.76@newssvr27.news.prodigy.net> <1177962288.575008.48490@q75g2000hsh.googlegroups.com> <1177967919.968338.3300@l77g2000hsb.googlegroups.com> Message-ID: kyosohma at gmail.com wrote: >>In addition to the warning that reload() does not recursively reload >>modules that the reloaded module depends on, be warned that reloading a >>module does not magically affect any functions or objects from the old >>version that you may be holding on to. Maybe reloading modules should be deprecated. The semantics are awful, and it interferes with higher-performance implementations. John Nagle From maxerickson at gmail.com Fri Apr 20 10:10:27 2007 From: maxerickson at gmail.com (Max Erickson) Date: Fri, 20 Apr 2007 14:10:27 +0000 (UTC) Subject: Do other Python GUI toolkits require this? References: <462697A6.6010007@codebykevin.com> <1177014799.004875.262060@y80g2000hsf.googlegroups.com> Message-ID: Antoon Pardon wrote: >>> Just asserting how something can make a difference withouth >>> arguing how in the particular case it actucally makes a >>> difference is just a divertion tactic without real merrit. >>> >> In the face of a notion that all steep curves determining >> "progress made in something" must be good I stand with my mouth >> agape. I am aware that common usage does not concur with >> academic rigor, but in this particular instance I'm with the >> common herd. > > Well that notion is entirely yours. My notion was only that > progres in productivity, earnings and learning was good and thus > that curves that are to be prefered tend to be the same shape for > those three subjects. > If we are being pedantic about describing a curve that shows the progress of a person in learning a topic, there is no arguing with you, a steep curve describes fast uptake and is a good thing. If we are being pedantic about what a learning curve describes, it seems possible that it describes the rate of knowledge uptake required to master a given topic, and that such a learning curve could exclude people that were unable to take in knowledge at that rate(for whatever reason) from mastering that topic, making it reasonable to describe such a topic as both 'hard' and 'having a steep learning curve'. max From nagle at animats.com Tue Apr 24 19:32:43 2007 From: nagle at animats.com (John Nagle) Date: Tue, 24 Apr 2007 16:32:43 -0700 Subject: Socket exceptions aren't in the standard exception hierarchy In-Reply-To: References: Message-ID: Steve Holden wrote: > John Nagle wrote: > >> Steve Holden wrote: >> >>> John Nagle wrote: >>> [socket.error bug report] > All these notes should be included in the bug report, as I suspect the > module would benefit from additional clarity. Done. See [ 1706815 ] socket.error exceptions not subclass of StandardError Also see [ 805194 ] Inappropriate error received using socket timeout [ 1019808 ] wrong socket error returned [ 1571878 ] Improvements to socket module exceptions [ 708927 ] socket timeouts produce wrong errors in win32 for related but not identical problems in that area. John Nagle From kyosohma at gmail.com Thu Apr 26 17:12:22 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: 26 Apr 2007 14:12:22 -0700 Subject: urlopen In-Reply-To: References: Message-ID: <1177621942.250741.176460@r35g2000prh.googlegroups.com> On Apr 26, 12:39 pm, "Dave Dean" wrote: > Hi all, > I'm running into some trouble using urllib.urlopen to grab a page from our > corporate intranet. The name of the internal site is simplyhttp://web(no > www or com). I can use urlopen to grab a site likehttp://www.google.com > just fine. However, when I use urlopen to grab the internal site, I instead > get data fromhttp://www.web.com. This is the url returned by the geturl() > function. > There must be a way to stop Python, or whoever is doing it, from changing > my url. Maybe urllib is not the correct approach. Does anyone know a > solution to this? > Thanks, > Dave Dunno for sure, but maybe you should be using urllib2. Good info on the module can be found here: http://www.voidspace.org.uk/python/articles/urllib2.shtml#fetching-urls I suppose you could also edit your hosts file too. Mike From gneuner2/ at comcast.net Tue Apr 17 21:03:58 2007 From: gneuner2/ at comcast.net (George Neuner) Date: Tue, 17 Apr 2007 21:03:58 -0400 Subject: is laziness a programer's virtue? References: <1176757271.282365.319740@n76g2000hsh.googlegroups.com> <1176797558.403629.53140@b75g2000hsg.googlegroups.com> <1176823224.099381.4630@n59g2000hsh.googlegroups.com> Message-ID: On 17 Apr 2007 08:20:24 -0700, Ingo Menger wrote: >On 17 Apr., 12:33, Markus E Leypold > wrote: > >> What makes Xah a troll is neither off-topic posts nor being >> incoherent -- its the attitude. He's broadcasting his drivel to a >> number of groups not with the intention to discuss (he hardly ever >> answers to answers to his posts), but solely with the intention to >> inform the world at large about his own magnificient thoughts. > >This hits the nail on the head. >Perhaps one could understand this behaviour on cultural grounds. In >chinese culture it may be not uncommon to write something that merely >sounds like great wisdom and it is nevertheless appreciated because >it's a piece of calligraphic art. > >> Trying to correct Xah's behaviour is probably impossible. > >Perhaps somebody could ask the chinese government to put him in jail >for "hurting international society" :) That's going to be tough because, according to his web page, he's living in a Honda Civic somewhere in Illinois, USA. http://xahlee.org/PageTwo_dir/Personal_dir/xah.html George -- for email reply remove "/" from address From __peter__ at web.de Fri Apr 6 07:07:54 2007 From: __peter__ at web.de (Peter Otten) Date: Fri, 06 Apr 2007 13:07:54 +0200 Subject: [optparse] Problem with getting an option value References: Message-ID: Lucas Malor wrote: > Hello all. I'm trying to do a little script. Simply I want to make a list > of all options with them default values. If the option is not specified in > the command line, the script must try to read it in a config.ini file. If > it's not present also there, it must set the default value. > > The problem is I maked a simple list for this: > > optname = [ > [ "delete", False ], > [ "file", "file" ], > [ "dir", "" ], > > But I must check that the option was specified in command line: > > (options, args) = parser.parse_args() > for opt in optname : > if not options.opt[0] : > # read the options from config.ini > > The problem is options is an instance, so options."delete", for example, > is wrong; I should pass options.delete . How can I do? Use getattr(): for name, default_value in optname: if getattr(options, name) == default_value: value = ... # read value from config file setattr(options, name, value) Personally, I would always read the config file, use the values found there to set up the parser and avoid such post-processing. Peter From steve at REMOVE.THIS.cybersource.com.au Fri Apr 13 06:58:23 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Fri, 13 Apr 2007 20:58:23 +1000 Subject: tuples, index method, Python's design References: <1176210960.3430.20.camel@dot.uniqsys.com> <740c3aec0704100810g5f962e8eu614fbaedecf3608e@mail.gmail.com> <1176219856.3430.76.camel@dot.uniqsys.com> <740c3aec0704101021i1fd79ef2l99eac4ced1e252d9@mail.gmail.com> <1176226682.3430.86.camel@dot.uniqsys.com> <4866bea60704101104r4600d281h135286b66378f4d4@mail.gmail.com> <740c3aec0704101534y3c65f5a7je382f97e1f6301b7@mail.gmail.com> <1176305859.581010.199600@n76g2000hsh.googlegroups.com> Message-ID: On Fri, 13 Apr 2007 07:46:58 +0000, Antoon Pardon wrote: >> So much fuss over such a little thing... yes it would be nice if tuples >> grew an index method, but it isn't hard to work around the lack. > > Yes it is a little thing. But if it is such a little thing why do > the developers don't simply add it? Perhaps because they've got better things to do than spend all their time adding little things that are the work of thirty seconds for a developer like yourself to create when you need it. -- Steven. From b.r.willems at gmail.com Sun Apr 29 21:59:19 2007 From: b.r.willems at gmail.com (Bart Willems) Date: Sun, 29 Apr 2007 21:59:19 -0400 Subject: Chart drawing tool in python In-Reply-To: <1177897942.532255.317000@y80g2000hsf.googlegroups.com> References: <1177897942.532255.317000@y80g2000hsf.googlegroups.com> Message-ID: <_3cZh.224$Kc5.133@newsfe12.lga> yinglcs at gmail.com wrote: > Hi, > > In Perl, there is a GD module to draw custom chart. > http://www-128.ibm.com/developerworks/opensource/library/os-perlgdchart/?ca=dgr-lnxw01Perl-GD-Charts > Can you please tell me if there is an equivalent library in python? Did you take a look at reportlab? (http://www.reportlab.org) Besides PDF also output in bitmap format, and there is a lot of customization possible. From max at alcyone.com Sun Apr 22 18:24:41 2007 From: max at alcyone.com (Erik Max Francis) Date: Sun, 22 Apr 2007 15:24:41 -0700 Subject: Bug in select In-Reply-To: References: <1aGdndBf1ON7UrbbnZ2dnUVZ_hjinZ2d@speakeasy.net> Message-ID: Ron Garret wrote: > Geez you people are picky. Since I ran this several times I ran into > the TIM_WAIT problem. Here's the actual transcript: It's not about being picky, it's about making it clear what your problem is. You're now describing an entirely different problem, hence why it's important to be clear about _precisely_ what it is you're doing and _precisely_ what's happening that you think that's wrong. > Python 2.5 (r25:51908, Mar 1 2007, 10:09:05) > [GCC 4.0.1 (Apple Computer, Inc. build 5367)] on darwin > Type "help", "copyright", "credits" or "license" for more information. >>>> from socket import * >>>> from select import select >>>> s=socket(AF_INET, SOCK_STREAM) >>>> s.bind(('',8080)) > Traceback (most recent call last): > File "", line 1, in > File "", line 1, in bind > socket.error: (48, 'Address already in use') >>>> s.bind(('',8081)) >>>> s.listen(5) >>>> f = s.accept()[0].makefile() >>>> f.readline() > '123\r\n' >>>> select([f],[],[],1) > ([], [], []) >>>> f.readline() > '321\r\n' -- 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 There are no dull subjects. There are only dull writers. -- H.L. Mencken From gagsl-py2 at yahoo.com.ar Thu Apr 26 02:57:40 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 26 Apr 2007 03:57:40 -0300 Subject: random.py References: Message-ID: En Thu, 26 Apr 2007 02:08:42 -0300, Bill Jackson escribi?: > In random.py (Python 2.5.1), line 86 says: > > VERSION = 2 # used by getstate/setstate > > Then, in the definition of Random.setstate, we have: > > if version == 2: > > Why is it not: > > if version == self.VERSION: Just thinking: Possibly because that conditional tries to detect whether the following code block applies or not; the code knows how to handle "version 2" data, and that happens to be the current version, but that's just because there is not a "version 3" (yet). Let's say, in the future, there is a version 3; the code could become: if version == 3: # new code to handle version 3 data elif version == 2: # code to handle version 2 data # this is the current contents else: # error message, as right now. -- Gabriel Genellina From cam.ac.uk at mh391.invalid Wed Apr 25 17:00:01 2007 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Wed, 25 Apr 2007 22:00:01 +0100 Subject: bitwise shift? In-Reply-To: References: Message-ID: desktop wrote: > I have found a code example with this loop. > > for k in range(10, 25): > n = 1 << k; > > > I have never read Python before but is it correct that 1 get multiplied > with the numbers 10,11,12,12,...,25 No. > assuming that 1 << k means "1 shift left by k" Yes. > which is the same as multiplying with k. No. Try starting the Python interpreter and entering 1 << 10. -- Michael Hoffman From aleax at mac.com Sun Apr 8 18:02:52 2007 From: aleax at mac.com (Alex Martelli) Date: Sun, 8 Apr 2007 15:02:52 -0700 Subject: how to remove multiple occurrences of a string within a list? References: <1175624433.206953.214290@n59g2000hsh.googlegroups.com> <1175625098.269660.184790@o5g2000hsb.googlegroups.com> <1175626164.428718.267670@w1g2000hsg.googlegroups.com> <1175626674.836668.293850@b75g2000hsg.googlegroups.com> Message-ID: <1hw9abl.1x15aay1k88r30N%aleax@mac.com> Ayaz Ahmed Khan wrote: ... > I am getting varying results on my system on repeated runs. What about > itertools.ifilter()? Calling itertools.ifilter returns an iterator; if you never iterate on that iterator, that, of course, is going to be very fast (O(1), since it does not matter how long the list you _don't_ iterate on is), but why would you care how long it takes to do no useful work at all? > $ python -m timeit -s "L = ['0024', 'haha', '0024']; import itertools" "itertools.ifilter(lambda i: i != '1024', L)" > 100000 loops, best of 3: 5.37 usec per loop > > $ python -m timeit -s "L = ['0024', 'haha', '0024']" > "[i for i in L if i != '0024']" > 100000 loops, best of 3: 5.41 usec per loop Here are the numbers I see: brain:~ alex$ python -m timeit -s "L = ['0024', 'haha', '0024']; > import itertools" "itertools.ifilter(lambda i: i != '1024', L)" 1000000 loops, best of 3: 0.749 usec per loop This is the "we're not doing any work" timing. brain:~ alex$ python -m timeit -s "L = ['0024', 'haha', '0024']" "[i for i in L if i != '1024']" 1000000 loops, best of 3: 1.37 usec per loop This is "make a list in the obvious way, excluding an item that's never there" (like in your code's first case, I'm comparing with 1024, which ain't there, rather than with 0024, which is). brain:~ alex$ python -m timeit -s "L = ['0024', 'haha', '0024']; import itertools" "list(itertools.ifilter(lambda i: i != '1024', L))" 100000 loops, best of 3: 6.18 usec per loop This is the "make it the hard way" (excluding a non-present item). About 5/6 of the overhead comes from the list constructor. When we exclude the item that IS there twice: brain:~ alex$ python -m timeit -s "L = ['0024', 'haha', '0024']" "[i for i in L if i != '0024']" 1000000 loops, best of 3: 0.918 usec per loop this is the "obvious way to do it", brain:~ alex$ python -m timeit -s "L = ['0024', 'haha', '0024']; import itertools" "list(itertools.ifilter(lambda i: i != '0024', L))" 100000 loops, best of 3: 6.16 usec per loop and this is the "hard and contorted way". If you only want to loop, not to build a list, itertools.ifilter (or a genexp) may be convenient (if the original list is long); but for making lists, list comprehensions win hand-down. Here are a few cases of "just looping" on lists of middling size: brain:~ alex$ python -m timeit -s "L = 123*['0024', 'haha', '0024']" "for j in [i for i in L if i != '0024']: pass" 10000 loops, best of 3: 70 usec per loop brain:~ alex$ python -m timeit -s "L = 123*['0024', 'haha', '0024']" "for j in (i for i in L if i != '0024'): pass" 10000 loops, best of 3: 70.9 usec per loop brain:~ alex$ python -m timeit -s "L = 123*['0024', 'haha', '0024']; import itertools" "for j in itertools.ifilter(lambda i: i != '0024', L ): pass" 10000 loops, best of 3: 151 usec per loop Here, the overhead of itertools.ifilter is only about twice that of a genexp (or list comprehension; but the LC should cost relatively more as L's length keeps growing, due to memory-allocation issues). BTW, sometimes simplest is still best: brain:~ alex$ python -m timeit -s "L = 123*['0024', 'haha', '0024']" "for i in L: > if i != '0024': > pass" 10000 loops, best of 3: 52.5 usec per loop I.e., when you're just looping... just loop!-) Alex From lycka at carmen.se Fri Apr 20 12:59:57 2007 From: lycka at carmen.se (Magnus Lycka) Date: Fri, 20 Apr 2007 18:59:57 +0200 Subject: Fast and capable XML parser? In-Reply-To: <4628E6BE.60100@websafe.com> References: <4628E6BE.60100@websafe.com> Message-ID: Larry Bates wrote: > I don't know if it meets ALL of your requirements but this might > help: > > http://www.reportlab.org/pyrxp.html AFAIK, there is no XML Schema support in PyRXP. This is really bad enough. GPL is not an option for us, and a commercial licence is less good than e.g. MIT or LGPL. (Partly due to the cost, but also because it causes much more work for me.) Besides, I'm a bit suspicious concerning the lack of benchmarks for the Unicode version... It seems to me that lxml is better in all aspects. From gigs at hi.t-com.hr Thu Apr 19 13:09:49 2007 From: gigs at hi.t-com.hr (Gigs_) Date: Thu, 19 Apr 2007 19:09:49 +0200 Subject: tkinter canvas Message-ID: I want to when create text box with objid = self.canvas.create_text(x, y, width=event.x-x, text='') how can i bind KeyPress to objid? I want that text appear on canvas as i write it. dont know do I need to use self.canvas.create_window, and put in that window Tkinter Text widget. Or I can do it with canvas.create_text. thanks! sorry for bad english, hope you understand what i mean From __peter__ at web.de Wed Apr 25 02:56:24 2007 From: __peter__ at web.de (Peter Otten) Date: Wed, 25 Apr 2007 08:56:24 +0200 Subject: function object.func_default off the console References: Message-ID: Aaron Brady wrote: >>>> f.func_defaults[0] > [2, 3] >>>> f.func_defaults[0]+=[4] > Traceback (most recent call last): > File "", line 1, in > TypeError: 'tuple' object does not support item assignment >>>> f.func_defaults[0] > [2, 3, 4] > > V. interesting. Operation succeeds but with a throw. Er, raise. This is not specific to func_defaults: >>> t = ([1],) >>> t[0] += [2] Traceback (most recent call last): File "", line 1, in TypeError: 'tuple' object does not support item assignment >>> t ([1, 2],) t[0] += [2] is resolved to t.__setitem__(t[0].__iadd__([2])) where list.__iadd__() succeeds but __setitem__() fails (because tuples don't have that method). Peter From rhamph at gmail.com Fri Apr 20 22:34:34 2007 From: rhamph at gmail.com (Rhamphoryncus) Date: 20 Apr 2007 19:34:34 -0700 Subject: Python's handling of unicode surrogates In-Reply-To: <4629591a$0$13629$9b622d9e@news.freenet.de> References: <4628532B.5060104@v.loewis.de> <1177051493.468698.176740@b75g2000hsg.googlegroups.com> <4629591a$0$13629$9b622d9e@news.freenet.de> Message-ID: <1177122874.524447.85130@p77g2000hsh.googlegroups.com> On Apr 20, 6:21 pm, "Martin v. L?wis" wrote: > > I don't believe this specific variant has been discussed. > > Now that you clarify it: no, it hasn't been discussed. I find that > not surprising - this proposal is so strange and unnatural that > probably nobody dared to suggest it. Difficult problems sometimes need unexpected solutions. Although Guido seems to be relenting slightly on the O(1) indexing requirement, so maybe we'll end up with an O(log n) solution (where n is the number of surrogates, not the length of the string). > > s[5] does not exist. You would get an IndexError indicating that it > > refers to the second half of a surrogate. > > [...] > > > len(s[k]) would be 2 if it involved a surrogate, yes. One character, > > two code units. > > Please consider trade-offs. Study advantages and disadvantages. Compare > them. Can you then seriously suggest that indexing should have 'holes'? > That it will be an IndexError if you access with an index between 0 > and len(s)??????? If you pick an index at random you will get IndexError. If you calculate the index using some combination of len, find, index, rfind, rindex you will be unaffected by my change. You can even assume the length of a character so long as you know it fits in 16 bits (ie any '\uxxxx' escape). I'm unaware of any practical use cases that would be harmed by my change, so that leaves only philosophical issues. Considering the difficulty of the problem it seems like an okay trade-off to me. > If you absolutely think support for non-BMP characters is necessary > in every program, suggesting that Python use UCS-4 by default on > all systems has a higher chance of finding acceptance (in comparison). I wish to write software that supports Unicode. Like it or not, Unicode goes beyond the BMP, so I'd be lying if I said I supported Unicode if I only handled the BMP. -- Adam Olsen, aka Rhamphoryncus From jstroud at mbi.ucla.edu Sat Apr 14 07:49:00 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Sat, 14 Apr 2007 11:49:00 GMT Subject: Python Feature Request: Add the "using" keyword which works like "with" in Visual Basic In-Reply-To: <1176549606.542551.36480@b75g2000hsg.googlegroups.com> References: <1176547372.584539.89170@q75g2000hsh.googlegroups.com> <1176549606.542551.36480@b75g2000hsg.googlegroups.com> Message-ID: jamadagni wrote: >> I like this one for some reason. Just the "using self" would save hella >> typing in a lot of classes. I would favor a convention with leading dots >> to disambiguate from other variables. This wouldn't conflict with, say, >> floats, because variable names can't begin with a number. > > Excellent. Now we don't have to worry about the "first applicable > instance" etc. Any member that begins with a dot will have the context > governer auto-prefixed by the parser. This means that nested using > statements should be like follows: > > using self: > __using .quit: > > with the dot preceding quit also. Excellent! > > But you have said "variable names can't begin with a number". The > point this, they shouldn't be able to begin with a *dot*. We are not > worried about numbers here, right? > On third or fourth read, I think you are not being sarcastic and rhetorical--sorry for my misunderstanding you--I think fatigue is affecting the little voices in my head. I'm just saying that a preceding dot is not otherwise used in the language except for perhaps floats. James From steven.bethard at gmail.com Sun Apr 1 12:26:54 2007 From: steven.bethard at gmail.com (Steven Bethard) Date: Sun, 01 Apr 2007 10:26:54 -0600 Subject: I18n issue with optik In-Reply-To: References: Message-ID: Thorsten Kampe wrote: > I guess the culprit is this snippet from optparse.py: > > # used by test suite > def _get_encoding(self, file): > encoding = getattr(file, "encoding", None) > if not encoding: > encoding = sys.getdefaultencoding() > return encoding > > def print_help(self, file=None): > """print_help(file : file = stdout) > > Print an extended help message, listing all options and any > help text provided with them, to 'file' (default stdout). > """ > if file is None: > file = sys.stdout > encoding = self._get_encoding(file) > file.write(self.format_help().encode(encoding, "replace")) > > So this means: when the encoding of sys.stdout is US-ASCII, Optparse > sets the encoding to of the help text to ASCII, too. But that's > nonsense because the Encoding is declared in the Po (localisation) > file. > > How can I set the encoding of sys.stdout to another encoding? Of > course this would be a terrible hack if the encoding of the > localisation changes or different translators use different > encodings... If print_help() is what's wrong, you should probably hack print_help() instead of sys.stdout. You could try something like:: def print_help(self, file=None): """print_help(file : file = stdout) Print an extended help message, listing all options and any help text provided with them, to 'file' (default stdout). """ if file is None: file = sys.stdout file.write(self.format_help()) optparse.OptionParser.print_help = print_help cmdlineparser = optparse.OptionParser(description=...) ... That is, you could monkey-patch print_help() before you create an OptionParser. STeVe From apardon at forel.vub.ac.be Fri Apr 20 08:25:40 2007 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 20 Apr 2007 12:25:40 GMT Subject: Do other Python GUI toolkits require this? References: <462697A6.6010007@codebykevin.com> <1177014799.004875.262060@y80g2000hsf.googlegroups.com> Message-ID: On 2007-04-20, Steve Holden wrote: > Antoon Pardon wrote: >> On 2007-04-20, Steve Holden wrote: >>> Antoon Pardon wrote: >>>> On 2007-04-19, sjdevnull at yahoo.com wrote: >>>>> On Apr 19, 6:54 am, Antoon Pardon wrote: >>>>>> I don't know how you come to the conclusion that it is a mathematical >>>>>> absurdity but consider this: If you find that common usage propagates >>>>>> something that is incorrect, should we just shrug it off or should we >>>>>> attemp a correction? >>>>> a) In English, "learning curve" is not restricted to a mathematical >>>>> plot--Webster's also defines it as "the course of progress made in >>>>> learning something". In that context, adding the adjective steep >>>>> ("extremely or excessively high...STEEP implies such sharpness of >>>>> pitch that ascent or descent is very difficult") makes sense. >>>> How much sense does it really make? Suppose we would talk about >>>> an income curve. Would you not prefer a steep curve over a shalow >>>> one? What about a productivity curve? It is all about the progress >>>> made in something. >>>> >>>> So how much sense does it make that a steep curve in earnings and >>>> productivity is good but a steep curve in learning is bad? >>>> >>> Just as much sense as that a motor car is great for driving around in >>> but bad for being run over by. Context is everything. Do *all* steep >>> curves have to be good or all bad? What the hell happened to common sense? >> >> You are just grabbing for straws. Sure context is everything. But you >> don't make a case that the context makes a difference here. Are you >> suggesting progres in productivity is good but progres in learning is bad? >> > No, I'm suggesting that in the company of thousands of people, most of > whom agree that a "steep learning curve" means, in the face of all > logic, that something is difficult to learn, you stop banging your head > against the wall and trying to "prove" them "wrong" (presumably because > it's important to you to be "right"). Thousands of people can be wrong. Now I don't particularly want to prove them wrong. But if instead of ignoring the remark as I suggested, they start trying to prove they are right, I will point out where their thinking is wrong. > As has been said already at least twice in this thread, language is > about communication. Human beings aren't always entirely rational no > matter how much we may individually strive for correctness, and > sometimes our only options are to either go with the flow or stand > valiantly, pissing into the wind. But if a wrong idea is circulating and nobody ever tries to correct it, people will continue with the wrong idea. All I did was make a simple remark, that as I suggested anyone could ignore, but that would allow those willing to learn, to further investigate. But what a terrible thing that seems to be. >> Just asserting how something can make a difference withouth arguing >> how in the particular case it actucally makes a difference is just >> a divertion tactic without real merrit. >> > In the face of a notion that all steep curves determining "progress made > in something" must be good I stand with my mouth agape. I am aware that > common usage does not concur with academic rigor, but in this particular > instance I'm with the common herd. Well that notion is entirely yours. My notion was only that progres in productivity, earnings and learning was good and thus that curves that are to be prefered tend to be the same shape for those three subjects. -- Antoon Pardon From donn at u.washington.edu Thu Apr 12 17:35:18 2007 From: donn at u.washington.edu (Donn Cave) Date: Thu, 12 Apr 2007 14:35:18 -0700 Subject: tuples, index method, Python's design References: Message-ID: In article , "Alan Isaac" wrote: > As I said: > I doubt that *anyone* who programs in Python > has not encountered the situation where they change > a tuple to a list *solely* for the purpose of getting > access to the index method. This suggests a missing > method, does it not? Who has not done this? > Name yourself! I am pleased to find myself in this company. My name is Donn Cave. I have been using Python since version 1.1, though frankly I haven't used it a lot in recent years. I have a confession to make, though. Early in my career, I used to do the opposite - given a list, I would sometimes convert it to a tuple because I had some notion that once its contents were fixed, a list would be more economically and robustly represented as a tuple. This was an error in my thinking, on a couple of levels, and I quit doing that fairly early on. Donn Cave, donn at u.washington.edu From ireyes at javeriana.edu.co Fri Apr 27 21:22:47 2007 From: ireyes at javeriana.edu.co (ireyes at javeriana.edu.co) Date: Fri, 27 Apr 2007 20:22:47 -0500 Subject: How to convert float to sortable integer in Python Message-ID: DEAR SIR, I SAW YOUR INTERNET QUESTION AND I HAVE THE SAME TROUBLE. CUOLD YOU HELP ME TO MAKE A FLOAT TO INTEGER CONVERTION? DO YOU HAVE ANY EXEL FILE THAT CAN DO THAT? REGARDS AND THANKS A LOT IVAN REYES ___________________________________ AVISO LEGAL: El presente correo electronico no representa la opinion o el consentimiento oficial de la PONTIFICIA UNIVERSIDAD JAVERIANA. Este mensaje es confidencial y puede contener informacion privilegiada la cual no puede ser usada ni divulgada a personas distintas de su destinatario. Esta prohibida la retencion, grabacion, utilizacion, aprovechamiento o divulgacion con cualquier proposito. Si por error recibe este mensaje, por favor destruya su contenido y avise a su remitente. En este aviso legal se omiten intencionalmente las tildes. Este mensaje ha sido revisado por un sistema antivirus, por lo que su contenido esta libre de virus. This e-mail has been scanned by an antivirus system, so its contents is free of viruses. From thorsten at thorstenkampe.de Sun Apr 1 09:39:50 2007 From: thorsten at thorstenkampe.de (Thorsten Kampe) Date: Sun, 1 Apr 2007 14:39:50 +0100 Subject: I18n issue with optik References: Message-ID: * Steven Bethard (Sat, 31 Mar 2007 20:08:45 -0600) > Thorsten Kampe wrote: > > I've written a script which uses Optik/Optparse to display the > > options (which works fine). The text for the help message is localised > > (with german umlauts) and when I execute the script with the localised > > environment variable set, I get this traceback[1]. The interesting > > thing is that the localised optparse messages from displays fine - > > it's only my localisation that errors. > > > > From my understanding, my script doesn't put out anything, it's > > optik/optparse who does that. My po file is directly copied from the > > optik po file (who displays fine) and modified so the po file should > > be fine, too. > > > > What can I do to troubleshoot whether the culprit is my script, optik > > or gettext? > > > > Would it make sense to post the script and the mo or po files? > > Yes, probably. Though if you can reduce it to the simplest test case > that produces the error, it'll increase your chances of having someone > look at it. The most simple test.py is: ### #! /usr/bin/env python import gettext, \ os, \ sys gettext.textdomain('optparse') gettext.install('test') from optparse import OptionParser, \ OptionGroup cmdlineparser = OptionParser(description = _('THIS SOFTWARE COMES WITHOUT WARRANTY, LIABILITY OR SUPPORT!')) options, args = cmdlineparser.parse_args() ### When I run LANGUAGE=de ./test.py --help I get the error. ### This is the test.de.po file # Copyright (C) 2006 Thorsten Kampe # Thorsten Kampe , 2006 msgid "" msgstr "" "Project-Id-Version: Template 1.0\n" "POT-Creation-Date: Tue Sep 7 22:20:34 2004\n" "PO-Revision-Date: 2005-07-03 16:47+0200\n" "Last-Translator: Thorsten Kampe \n" "Language-Team: Thorsten Kampe \n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=ISO-8859-15\n" "Content-Transfer-Encoding: 8-bit\n" "Generated-By: pygettext.py 1.5\n" msgid "THIS SOFTWARE COMES WITHOUT WARRANTY, LIABILITY OR SUPPORT!" msgstr "DIESES PROGRAMM HAT WEDER GEW?HRLEISTUNG, HAFTUNG NOCH UNTERST?TZUNG!" ### The localisation now produces an error in the localised optik files, too. Under Windows I get " File "G:\program files\python\lib\encodings \cp1252.py", line 12, in encode return codecs.charmap_encode(input,errors,encoding_table)" Is there something I have to do to put the terminal in "non-ascii output mode"? I tried ### #! /usr/bin/env python # -*- coding: ISO-8859-15 -*- print "DIESES PROGRAMM HAT WEDER GEW?HRLEISTUNG, HAFTUNG NOCH UNTERST?TZUNG!" ### ...and this worked. That means that my terminal is willing to print, right?! > You could also try posting to the optik list: > http://lists.sourceforge.net/lists/listinfo/optik-users I already did this via Gmane (although the list seems pretty dead to me). Sourceforge seems to have a bigger problem as [1] and [2] error. Sorry for the confusion but this Unicode magic is far from being rational. I guess most people just don't get it... Thorsten [1] http://sourceforge.net/mailarchive/forum.php?forum=optik-users [2] https://lists.sourceforge.net/lists/listinfo From martin at v.loewis.de Mon Apr 2 17:00:01 2007 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Mon, 02 Apr 2007 23:00:01 +0200 Subject: curses module In-Reply-To: References: Message-ID: <46116ED1.7030800@v.loewis.de> Kenneth McDonald schrieb: > I know that the curses module has a long-standing bug wherein cursor > visibility can't be set. > > This isn't criticism, I just know that the curses module is the sort of > thing that probably isn't being maintained consistently, and I for one, > have no idea how well all the new terms in common use maintain the sort > of backwards compatibility python curses will need to do its job. This isn't criticism either, but... if you know it has a long-standing bug, why didn't you submit a patch yet? If you had submitted one for Python 2.1 (say), the problem wouldn't be relevant today. If you submit one today, the problem won't be relevant for Python 2.8, or Python 3.0. Regards, Martin From marco.minerva at gmail.com Wed Apr 4 11:16:08 2007 From: marco.minerva at gmail.com (marco.minerva at gmail.com) Date: 4 Apr 2007 08:16:08 -0700 Subject: String manipulation Message-ID: <1175699768.427986.210310@l77g2000hsb.googlegroups.com> Hi all! I have a file in which there are some expressions such as "kindest regard" and "yours sincerely". I must create a phyton script that checks if a text contains one or more of these expressions and, in this case, replaces the spaces in the expression with the character "_". For example, the text Yours sincerely, Marco. Must be transformated in: Yours_sincerely, Marco. Now I have written this code: filemw = codecs.open(sys.argv[1], "r", "iso-8859-1").readlines() filein = codecs.open(sys.argv[2], "r", "iso-8859-1").readlines() mw = "" for line in filemw: mw = mw + line.strip() + "|" mwfind_re = re.compile(r"^(" + mw + ")",re.IGNORECASE|re.VERBOSE) mwfind_subst = r"_" for line in filein: line = line.strip() if (line != ""): line = mwfind_re.sub(mwfind_subst, line) print line It correctly identifies the expressions, but doesn't replace the character in the right way. How can I do what I want? Thanks in advance. -- Marco Minerva, marco.minerva at gmail.com http://blogs.ugidotnet.org/marcom From bbxx789_05ss at yahoo.com Mon Apr 16 06:12:41 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: 16 Apr 2007 03:12:41 -0700 Subject: newbie question: how to read back the dictionary from a file? In-Reply-To: <1176718258.762366.69340@q75g2000hsh.googlegroups.com> References: <1176717819.937015.9890@y80g2000hsf.googlegroups.com> <1176718258.762366.69340@q75g2000hsh.googlegroups.com> Message-ID: <1176718361.553254.242610@y5g2000hsa.googlegroups.com> s.close() From KDawg44 at gmail.com Fri Apr 27 12:11:17 2007 From: KDawg44 at gmail.com (KDawg44) Date: 27 Apr 2007 09:11:17 -0700 Subject: Learning to use wxPython Message-ID: <1177690277.346950.120860@u32g2000prd.googlegroups.com> Hi, I downloaded the wxPython demo and did an emerge wxpython (gentoo) to install. When I run the demo, I am getting this error: # python demo.py Traceback (most recent call last): File "/usr/lib/python2.4/site-packages/wx-2.6-gtk2-ansi/wx/ _misc.py", line 1286, in Notify self.notify() File "/usr/lib/python2.4/site-packages/wx-2.6-gtk2-ansi/wx/ _core.py", line 13637, in Notify self.result = self.callable(*self.args, **self.kwargs) File "/root/wxPython Demo/wxPython-2.8.3.0/demo/Main.py", line 1798, in ShowMain frame = wxPythonDemo(None, "wxPython: (A Demonstration)") File "/root/wxPython Demo/wxPython-2.8.3.0/demo/Main.py", line 1275, in __init__ self.filter = wx.SearchCtrl(leftPanel) AttributeError: 'module' object has no attribute 'SearchCtrl' What am I doing wrong? Thanks. From dickinsm at gmail.com Sun Apr 22 11:30:52 2007 From: dickinsm at gmail.com (Mark Dickinson) Date: 22 Apr 2007 08:30:52 -0700 Subject: Vector classes In-Reply-To: <1177245233.573675.274580@n59g2000hsh.googlegroups.com> References: <1177245233.573675.274580@n59g2000hsh.googlegroups.com> Message-ID: <1177255852.137047.308840@p77g2000hsh.googlegroups.com> On Apr 22, 8:33 am, Mizipzor wrote: > With 1, I can typ vec.x and vec.y, very nice. With 2, I need to do > vec.vals[0] and vec.vals[1], which makes my eyes bleed. If you add a __getitem__ method to the second vector class: def __getitem__(self, i): return self.vals[i] then you can use vecs[0] instead of vec.vals[0]. But this vector class has some other problems that you probably want to fix. For example, the __add__ method modifies the second argument: >>> a = Vector([1, 2, 3]) [1, 2, 3] >>> b = Vector([4, 5, 6]) [4, 5, 6] >>> c = a + b >>> print b.vals [5, 7, 9] Something like def __add__(self, other): return Vector(x + y for x, y in zip(self.vals, other.vals)) might work better. Similarly for the __sub__ method. Have you considered using numpy? Mark From martin at v.loewis.de Wed Apr 11 18:45:18 2007 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Thu, 12 Apr 2007 00:45:18 +0200 Subject: troubles building python 2.5 on Windows XP x64 Windows Server 2003 sp1 Platform SDK In-Reply-To: <1176306687.057275.174460@q75g2000hsh.googlegroups.com> References: <1175622506.730227.37060@p77g2000hsh.googlegroups.com> <461412C9.8090609@v.loewis.de> <1176306687.057275.174460@q75g2000hsh.googlegroups.com> Message-ID: <461D64FE.5050509@v.loewis.de> > I guess I am a little confused on the directions for the vsextcomp. I > don't see an IDE for the vsextcomp. Do you know of any explicit > directions on how to do this build? Can you please explicitly say what step you did and at what precise step you failed? 0. Install VS 2003 1. Install vsextcomp 2. open VS 2003 3. open the project files in PCbuild 4. select the AMD64 target 5. run build HTH, Martin From steve1791 at REMOVETHISNOWgmail.com Mon Apr 2 04:48:00 2007 From: steve1791 at REMOVETHISNOWgmail.com (Steve) Date: Mon, 2 Apr 2007 18:48:00 +1000 Subject: Question about text in Python Message-ID: <4610c366$0$15022$5a62ac22@per-qv1-newsreader-01.iinet.net.au> Hi, I've created a Python program that a user enteres one line of text which will then create an acronym from that text. What I want to add to the program is the abilty to rerun this process (where the user enteres another line of text) until the user has had enough and enters a blank line which would then end the program. Can anyone help with this? thanks From zefria at gmail.com Sun Apr 15 21:17:54 2007 From: zefria at gmail.com (Daniel Gee) Date: 15 Apr 2007 18:17:54 -0700 Subject: Python editor/IDE on Linux? In-Reply-To: <1176634241.244351.41990@b75g2000hsg.googlegroups.com> References: <1176575715.649316.130430@n76g2000hsh.googlegroups.com> <1176626030.729710.321520@d57g2000hsg.googlegroups.com> <1176634241.244351.41990@b75g2000hsg.googlegroups.com> Message-ID: <1176686273.987650.146430@l77g2000hsb.googlegroups.com> didn't know that one. Perhaps I'll look into Gvim (I still like to cut and paste with the mouse, even if I left that off my list). From gigs at hi.t-com.hr Wed Apr 25 17:38:15 2007 From: gigs at hi.t-com.hr (Gigs_) Date: Wed, 25 Apr 2007 23:38:15 +0200 Subject: tkinter listbox Message-ID: Hi! Im working on paint program with tkinter canvas. I have two listbox and when i click on first listbox second become deselected. I need to take one thing from first listbox and one thing from second at the same time. How to do that? thx, apologies for bad english From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Sat Apr 14 08:16:24 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Sat, 14 Apr 2007 14:16:24 +0200 Subject: wxPython, mac, wx.HSCROLL not working References: <1176364597.741079.25840@n59g2000hsh.googlegroups.com> <586qvsF2fbq3rU1@mid.individual.net> <1176392605.298630.8210@y5g2000hsa.googlegroups.com> <1176404918.079527.148440@d57g2000hsg.googlegroups.com> <587i0iF2fu57fU1@mid.individual.net> <1176417535.246590.158780@y80g2000hsf.googlegroups.com> <5895rrF2en0c0U1@mid.individual.net> <1176462973.509322.145010@q75g2000hsh.googlegroups.com> Message-ID: <58bv0oF2e7nifU2@mid.individual.net> 7stud wrote: > Huh? Are you saying you found a solution? Yes, the solution to | Where is that list? Regards, Bj?rn -- BOFH excuse #382: Someone was smoking in the computer room and set off the halon systems. From steve at holdenweb.com Sat Apr 28 11:08:23 2007 From: steve at holdenweb.com (Steve Holden) Date: Sat, 28 Apr 2007 11:08:23 -0400 Subject: EuroPython vs PyconUK In-Reply-To: References: <4630D480.7050308@gmail.com> Message-ID: EuGeNe Van den Bulke wrote: > Steve Holden wrote: > > So by this reasoning there should have been no "Python UK" conference >> for the last four years (in case you didn't know it ran as a track of >> the C/C++ conference, but ths track has now broadened to include all >> scripting languages). And what about the people who can't get the time >> and/or money to attend EuroPython? > > I am afraid there is a misunderstanding. I have no problem with PyCon UK > but would like to have elements to help me choose (the official language > of PyCon Uno Italy is Italian so that fixes it :P). > >> Diversity is good, so it isn't one vs. the other. And the UK really *is* >> part of Europe (no matter how its politicians behave) :P > > I agree that diversity is good (you won't hear me say that there are too > many web frameworks in Python :D) but isn't dilution a danger? > > If Guido was a rock star and I was a groupie, I would want to know which > festival to attend to see him on stage. I guess there is always Google > Video ;) > > More seriously in Geneva there were people from all over the place, > speakers and attendees, which is one of the reason why such conferences > are interesting (or am I deluded?). It is harder for someone from > Australia to come twice to Europe in the space of 2 months than for a > pythoneer lambda to spend a couple of days studying another web > framework to see if it fits how his brain works and the problem he's got > to solve. > > Looking at the reactions to my post, I must be wrong. I didn't mean to > offend anyone if I did. I'll go to Vilnius because I have never seen the > city and try to go to Birmingham if the program looks interesting (not > very rational or is it?). > If you're traveling from Australia or similarly distant locations then I'd have to say EuroPython would be the one where you'd see most Pythonistas from most places. regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden ------------------ Asciimercial --------------------- Get Python in your .sig and on the web. Blog and lens holdenweb.blogspot.com squidoo.com/pythonology tag items: del.icio.us/steve.holden/python All these services currently offer free registration! -------------- Thank You for Reading ---------------- From phil.aerts.tln at gmail.com Tue Apr 3 04:24:33 2007 From: phil.aerts.tln at gmail.com (phil.aerts.tln at gmail.com) Date: 3 Apr 2007 01:24:33 -0700 Subject: cli user interface ala cisco IOS or JUNOS Message-ID: <1175588673.340855.130230@q75g2000hsh.googlegroups.com> Hi, for one of my python projects I need an user interface similar to that of cisco IOS or even better Juniper JUNOS. Does anyone know of existing python modules that gives this kind of functionality ? -P From bbxx789_05ss at yahoo.com Thu Apr 12 05:50:55 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: 12 Apr 2007 02:50:55 -0700 Subject: Newbie help with array handling In-Reply-To: <1176370313.386948.260930@p77g2000hsh.googlegroups.com> References: <1176364734.439383.252930@o5g2000hsb.googlegroups.com> <1176368561.245625.251270@y5g2000hsa.googlegroups.com> <1176370313.386948.260930@p77g2000hsh.googlegroups.com> Message-ID: <1176371455.510269.43630@y5g2000hsa.googlegroups.com> On Apr 12, 3:31 am, "loial" wrote: > OK, thanks for the replies > > One other thing...I need to update the values since they are basically > totals that I am accumulating. > > How do I update a specific value for a specific key? mydict["keyvalue1"] returns the value, which in this case is a list. So, you could write: lst = mydict["keyvalue1"] lst[0] = 4 list.append("red") or you can do it directly: mydict["keyvalue1"][0] = 4 mydict["keyvalue1"].append("red") From irmen.NOSPAM at xs4all.nl Sun Apr 22 06:50:37 2007 From: irmen.NOSPAM at xs4all.nl (Irmen de Jong) Date: Sun, 22 Apr 2007 12:50:37 +0200 Subject: Select weirdness In-Reply-To: References: Message-ID: <462b3e47$0$326$e4fe514c@news.xs4all.nl> Ron Garret wrote: > Here's my code. It's a teeny weeny little HTTP server. (I'm not really > trying to reinvent the wheel here. What I'm really doing is writing a > dispatching proxy server, but this is the shortest way to illustrate the > problem I'm having): > > from SocketServer import * > from socket import * > from select import select > > class myHandler(StreamRequestHandler): > def handle(self): > print '>>>>>>>>>>>' > while 1: > sl = select([self.rfile],[],[])[0] > if sl: > l = self.rfile.readline() > if len(l)<3: break > print l, > pass > pass > print>>self.wfile, 'HTTP/1.0 200 OK' > print>>self.wfile, 'Content-type: text/plain' > print>>self.wfile > print>>self.wfile, 'foo' > self.rfile.close() > self.wfile.close() > print '<<<<<<<<<<<<' > pass > pass You shouldn't use a select() of your own inside the handle method. The socketserver takes care of that for you. What you need to do is read the input from the socket until you've reached the end-of-input marker. That marker is an empty line containing just "\r\n" when dealing with HTTP GET requests. Any reason don't want to use the BasicHTTPServer that comes with Python? Anyway, try the following instead: from SocketServer import * from socket import * from select import select class myHandler(StreamRequestHandler): def handle(self): print '>>>>>>>>>>>' while True: l = self.rfile.readline() print repr(l) if not l or l=='\r\n': break print>>self.wfile, 'HTTP/1.0 200 OK' print>>self.wfile, 'Content-type: text/plain' print>>self.wfile print>>self.wfile, 'foo' self.rfile.close() self.wfile.close() print '<<<<<<<<<<<<' def main(): server = TCPServer(('',8080), myHandler) server.serve_forever() if __name__ == '__main__': main() --Irmen From carsten at uniqsys.com Sun Apr 8 15:40:27 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Sun, 08 Apr 2007 15:40:27 -0400 Subject: tuples, index method, Python's design In-Reply-To: <7xzm5igbrb.fsf@ruckus.brouhaha.com> References: <1175867771.114540.61810@n76g2000hsh.googlegroups.com> <1175884427.779950.267220@y80g2000hsf.googlegroups.com> <1175953520.316208.241490@o5g2000hsb.googlegroups.com> <7xzm5igbrb.fsf@ruckus.brouhaha.com> Message-ID: <1176061227.3248.18.camel@localhost.localdomain> On Sun, 2007-04-08 at 07:51 -0700, Paul Rubin wrote: > Carsten Haese writes: > > > Maybe we can add such methods to the PyPy tuples for some time, to > > > experimentally see if they make the language worse :-) > > > > Adding useless features always makes a product worse. What's your use > > case for tuple.index? > > Do you not see the gratuituous inconsistency between tuples and lists > as a useless feature? What is the use case for keeping it? When a new feature is requested, the burden of proof is on the requester to show that it has uses. The use case for not having tuple.index is that there are no use cases for having it. If that answer sounds absurd, it is because your question is absurd. -Carsten From marcpp at gmail.com Tue Apr 17 13:52:03 2007 From: marcpp at gmail.com (Marcpp) Date: 17 Apr 2007 10:52:03 -0700 Subject: Pyqt calling a custom dialog and returning the vars In-Reply-To: <58ia5dF2fsd6nU1@mid.uni-berlin.de> References: <1176753980.142797.268800@e65g2000hsc.googlegroups.com> <58ia5dF2fsd6nU1@mid.uni-berlin.de> Message-ID: <1176832323.055830.58570@o5g2000hsb.googlegroups.com> On 17 abr, 00:03, "Diez B. Roggisch" wrote: > Marcpp schrieb: > > > > > I call a dialog from a principal program but cannot return the value > > of the > > variables (text box's). Here is a example... > > > from ui import Agenda > > from dialog1 import dialogo1 > > from PyQt4 import * > > import dbm > > import sys > > > class principal (QApplication): > > > def __init__(self, args): > > """ In the constructor we're doing everything to get our > > application > > started, which is basically constructing a basic > > QApplication by > > its __init__ method, then adding our widgets and finally > > starting > > the exec_loop.""" > > QApplication.__init__(self,args) > > > # We pass None since it's the top-level widget, we could in > > fact leave > > # that one out, but this way it's easier to add more dialogs > > or widgets. > > self.maindialog = ag(None) > > > self.setMainWidget(self.maindialog) > > self.maindialog.show() > > self.exec_loop() > > > class ag (Agenda): > > ... > > ... > > def _slotAddClicked(self): > > d=dialogo1() > > d.exec_() > > d.connect(d.buttonOk,SIGNAL("clicked()"),self._procesadialog1) > > Shouldn't you connect the signal _before_ the dialog is shown? > > > def _procesadialog1(): > > d=dialogo1() > > drempresa = d.dempresa.text() > > print drempresa # > > <-------------------------------------------------------- Nothing > > appears > > ... > > ... > > if __name__ == "__main__": > > app = principal(sys.argv) > > Diez How I'll do it? From steve at holdenweb.com Fri Apr 6 12:27:21 2007 From: steve at holdenweb.com (Steve Holden) Date: Fri, 06 Apr 2007 12:27:21 -0400 Subject: block scope? In-Reply-To: References: Message-ID: Neal Becker wrote: > One thing I sometimes miss, which is common in some other languages (c++), > is idea of block scope. It would be useful to have variables that did not > outlive their block, primarily to avoid name clashes. This also leads to > more readable code. I wonder if this has been discussed? > Nested scopes were put into the language for function definitions, at least. Back in around 2.0, I believe, though that's lost in the mists of time for me as it's not a feature I use. I suspect, in fact, that those nested scopes have caused more trouble that they're worth, and continue to do so. Be that as it may, I don't think there's ever been any attempt to introduce scoping blocks into the language. Any ideas how you'd like it 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 Recent Ramblings http://holdenweb.blogspot.com From Eric_Dexter at msn.com Mon Apr 30 12:29:55 2007 From: Eric_Dexter at msn.com (Eric_Dexter at msn.com) Date: 30 Apr 2007 09:29:55 -0700 Subject: Launching an independent Python program in a cross-platform way (including mac) In-Reply-To: <1177944037.400933.291060@l77g2000hsb.googlegroups.com> References: <1177889540.489960.176380@u30g2000hsc.googlegroups.com> <1177890695.308785.165580@l77g2000hsb.googlegroups.com> <838d5$4635f634$4275d90a$5047@FUSE.NET> <1177944037.400933.291060@l77g2000hsb.googlegroups.com> Message-ID: <1177950595.887985.256790@h2g2000hsg.googlegroups.com> I would like to see this as a command along with something to open web pages.. Just one command instead of trying to figure out all the different op systems. look forward to seeing your code https://sourceforge.net/projects/dex-tracker On Apr 30, 9:40 am, Andr? wrote: > On Apr 30, 10:59 am, Kevin Walzer wrote: > [snip] > > > > > > > There are extension modules on the Mac for integrating Python and > > AppleScript (the best one is appscript). However, if you want to limit > > yourself to core Python, your best best is osascript, a system > > command-tool that lets you call AppleScript code with arguments from > > other programs. This can be called via os.system. > > > The basis syntax for doing this from Python might look something like this: > > > os.system('osascript -e \'tell app \"Terminal\" to activate\'') > > > This simply launches Terminal. Note that you have to deal with quoting > > issues. The equivalent syntax from AppleScript would be: > > > tell app "Terminal" to activate > > > If you want to Terminal to run a command-line program from AppleScript, > > you can do this with the "do script" command. Code to do this could look > > something like this: > > > myscript = "python -e foo.py" > > os.system('osascript -e '\tell app \"Terminal"\ to do script %s\'', > > myscript) > > > I haven't tested this, but you get the basic idea--define the script and > > command-line paramaters in a string, then pass that to > > AppleScript/osascript as a variable. This code should launch Terminal, > > then run the external Python script. > > > HTH, > > Thanks. I managed to get something like this to work. Later, I'll > post it as an example to this thread so that other can use if for a > reference if needed. > > Andr? > > > > > Kevin > > > -- > > Kevin Walzer > > Code by Kevinhttp://www.codebykevin.com- Hide quoted text - > > - Show quoted text -- Hide quoted text - > > - Show quoted text - From aspineux at gmail.com Sun Apr 1 07:57:54 2007 From: aspineux at gmail.com (aspineux) Date: 1 Apr 2007 04:57:54 -0700 Subject: saving Python process state for later debugging In-Reply-To: <1175413189.156480.149640@o5g2000hsb.googlegroups.com> References: <1175352493.387046.32510@q75g2000hsh.googlegroups.com> <1175382476.172386.97370@q75g2000hsh.googlegroups.com> <1175413189.156480.149640@o5g2000hsb.googlegroups.com> Message-ID: <1175428674.548997.111260@p15g2000hsd.googlegroups.com> On 1 avr, 09:39, yossi.krei... at gmail.com wrote: > On Apr 1, 2:07 am, "aspineux" wrote: > > > > > Pylon has something like that.http://pylonshq.com/docs/0.9.4.1/interactive_debugger.html > > > Turbogears has the same with option tg.fancy_exception > > I could get it wrong, but these things seem to be about debugging > crashed processes "online", not saving snapshots to files for later > inspection. Can you e-mail a process snapshot to a different machine > with them, for example? I understood that you are supposed to debug > the original process, which is kept alive, via the web. I'm talking > about a situation where you have a Python program deployed to a user > who is not running a web server, and have the user send you a snapshot > as a bug report. > > -- Yossi A context in python is no more than 2 dictionaries ( globals() and locals()). You can easily serialize both to store them. You can navigate into the python stack using module inspect and generate the context for all the functions in the stack trace. This is probably no more than 50 lines of code, maybe 20 :-) You can find sample of how to get these info and use them in the sample I was reffering before. From larry.bates at websafe.com Wed Apr 4 17:43:32 2007 From: larry.bates at websafe.com (Larry Bates) Date: Wed, 04 Apr 2007 16:43:32 -0500 Subject: Newbie - needs help In-Reply-To: <1175632937.838422.236850@y66g2000hsf.googlegroups.com> References: <1175632937.838422.236850@y66g2000hsf.googlegroups.com> Message-ID: Anbeyon wrote: > Hi > > I have not yet programmed in Python but am experienced in a number o > other languages. > > I'd like to start to use Python to develop cross platform applications > but havin kust started to investigate tols, libraries etc I feel a > little overwhelmed. > > I'm hoping someone might be able to point me in the right direction. > > What I'd like to achieve is the abilty to develop applications for > both Windows and Linux (Desktop and embedded). I'd also like to be > able to develop applications that make use of TCP/IP and things like > 'Widget' libraries. > > In an ideal would like to be able to pull together Python apps with > GUI front ends in a nice IDE with a debugger. > > Does such a toolset exisit ? > > Perhaps some people can sully me some links ? > > Thanks in advance. > > Anbeyon > If you are on Windows take a look at PyScripter: http://mmm-experts.com/Products.aspx?ProductId=4 I would also recommend a copy of Python Cookbook which has LOTS of example code you can look at and use. -Larry Bats From ptmcg at austin.rr.com Mon Apr 16 00:11:44 2007 From: ptmcg at austin.rr.com (Paul McGuire) Date: 15 Apr 2007 21:11:44 -0700 Subject: pyparsing Catch-22 In-Reply-To: <1176686782.270354.164630@l77g2000hsb.googlegroups.com> References: <1176686782.270354.164630@l77g2000hsb.googlegroups.com> Message-ID: <1176696704.924584.75720@e65g2000hsc.googlegroups.com> On Apr 15, 8:26 pm, "7stud" wrote: > To the developer: > > 1) I went to the pyparsing wiki to download the pyparsing module and > try it > 2) At the wiki, there was no index entry in the table of contents for > Downloads. After searching around a bit, I finally discovered a tiny > link buried in some text at the top of the home page. > 3) Link goes to sourceforge. At sourceforge, there was a nice, green > 'download' button that stood out from the page. > 4) I clicked on the download button and got the warning: > ----- > You have selected to download the pyparsing-1.4.6 release. > > Below is a list of files contained in this release. > Before downloading, you may want to read the release notes. > ----- > > 5) Can't find any release notes, nor any button to click to download > the package. > 6) Give up in frustration. > 7) A few minutes later, I decide: I will not give up. > 8) I go back to sourceforge and start clicking every link on the page. > (Hello, porn sites! Just kidding.) Still no luck. > 9) Finally. I click on something and a download begins. I cancel it. > 10) Now I know what to click on, and I download the docs and > pyparsing-1.4.6.tar > 11) Now what? I'm new to mac os x, and I have no idea what to do. > The wiki is devoid of any installation instructions. > 12) I give up again. > > For as hard as you push pyparsing on this forum, I would think you > would make it easier to download and install your module. In my > opinion, the wiki should provide detailed installation instructions > for all supported os's, and the sourceforge downloading process is too > complicated. Me? Push? Boy, a guy posts a couple of examples, tries to help some people that are stuck with a problem, and what does he get? Called "pushy"? Sheesh! Fortunately, I get enough positive feedback from these posts that my feelings are pretty resilient these days. Anyway, thanks and point taken for the alert on this subject from the newbie's perspective. When I first wrote these installations and started the pyparsing project on SF, I was fairly newb myself - I had to ask Dave Kuhlman to write setup.py for me! So I assumed the target audience already knew the stuff I was having to learn. I assumed that setup.py was just common knowledge among the Python world. I think your suggestion of a Wiki page on this subject should fill this gap neatly, especially since pyparsing is somewhat targetted at the newb and near-newb user, one that is struggling with regexp's or some other parsing technology, and just wants to get some basic code working. The other posts in this thread contain plenty of material to start from. Also, thanks for the Mac OS X point of view, most of my work is on Windows, and a little bit on Linux, but absolutely none on Mac. And I see that I should not assume knowledge of tar, either, so I'll be sure to mention its destructive streak, in overwriting existing files with the same name as those in the archive. Once untar'ed, there *is* a file named README, with an introduction and instructions to invoke setup.py properly. But there is little harm in repeating some of this on the Wiki as well. I'm glad to see you perservered and got pyparsing installed. You can also run pyparsing.py itself, which will run a simple SQL parser test. If you have not yet found the docs or examples, *please* look over the sample code in the examples directory, and the class-level documentation in the htmldocs directory. The docs directory should also include the materials from my PyCon'06 presentations. Please post back, either here or on the Pyparsing wiki discussion pages, and let me know how your pyparsing work is progressing. -- Paul (the developer, but you can call me "Paul") From larry.bates at websafe.com Wed Apr 18 09:13:44 2007 From: larry.bates at websafe.com (Larry Bates) Date: Wed, 18 Apr 2007 08:13:44 -0500 Subject: python - dll access (ctypes or swig) In-Reply-To: <1hwq9na.98800513op6liN%aleax@mac.com> References: <1hwq9na.98800513op6liN%aleax@mac.com> Message-ID: Alex Martelli wrote: > Larry Bates wrote: > >> recently learned that you can ship COM as either an .EXE or a .DLL (nobody >> has yet let me know why). > > The "why" is pretty obvious -- you may want to be able to instantiate a > COM object either in-process, or in its own separate process, depending > on that object's nature. For example, a complete application that when > running exposes COM objects to let other processes drive/script it will > be an EXE file since it can also run independently. > > In general I'm no big fan of MS's design, but COM, despite its > imperfections, was in fact seriously good (Don Box's "Essential COM", an > excellent book, went just into enough depth to let a developer really > appreciate that, IMHO). I'm using the past tense because MS has been > trying to kill COM for a while now (but I notice that "Essential COM", > while 10 years-old, is _still_ in stock at Amazon -- so, I guess that so > far MS's attempts haven't _quite_ succeeded yet:-). > > > Alex I guess I was the only one it wasn't "obvious" to . I've always written my COM servers as .EXE files even though they cannot be run independently. What I find is "odd" is that I can create a .DLL or an .EXE of my COM server and after I register it, my application doesn't appear to know the difference. The difference seems to be hidden from the actual application and doesn't affect it (at least that I can determine). I also think COM works quite well and I've found it much easier to use than C-style DLLs that many vendors ship as their API. Most of what I've learned came from Mark/Andy's Python Programming on Win32 and trial-and-error so my knowledge is quite limited. Thanks for the info. Larry From apardon at forel.vub.ac.be Wed Apr 18 03:34:01 2007 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 18 Apr 2007 07:34:01 GMT Subject: Queue enhancement suggestion References: Message-ID: On 2007-04-17, Jean-Paul Calderone wrote: > On 17 Apr 2007 14:32:01 GMT, Antoon Pardon wrote: >>On 2007-04-17, Jean-Paul Calderone wrote: >>> On 17 Apr 2007 13:32:52 GMT, Antoon Pardon wrote: >>>>On 2007-04-17, Hendrik van Rooyen wrote: >>>> [snip] >>> >>>>> Not sure I understand this - it sounds vaguely incestous to me. >>>>> I normally use a GUI with two queues, one for input, one for >>>>> output, to two threads that front end two named pipes to >>>>> the next process - I try to avoid more than one thing reading or >>>>> writing to one end of a queue or a pipe, so the dataflow diagram >>>>> for my stuff always looks like a TinkerToy... >>>> >>>>The problem is that sometimes the gui thread has something to show >>>>too. With the added problem that the code wanting to show something >>>>doesn't know when it is executing the gui thread or an other. So >>>>it is very difficult to avoid the gui thread putting things on the >>>>queue. But since the gui thread is the single reader, it will dead >>>>lock if the queue happens to be full at the moment the gui thread >>>>want to add another item. >>>> >>> >>> This is pretty easily solved: >>> >>> def sendToGUI(event): >>> if isInGUIThread(): >>> gui.scheduleCall(event) >>> else: >>> guiQueue.put(event) >> >>No that is not a solution for the simple reason that now things >>can be shown out of order. Suppose I have a thread that shows >>the value of a certain variable. Now I have a button that can >>stop this thread and zero the variable. If I go for your >>solution a value may still be in the queue and my window >>ends up showing this last value instead of zero. >> > > Addressing that is up to the application code. Threading is tough, > there are no magic bullets. The above is a very standard tool for > addressing the concern raised earlier in this thread. It's only > *part* of a solution though, the rest of the application has to play > along. My solution is a more complete implementation of Queues, which allow a thread to register as reader, writer or reader-writer. Reader-writers are always allowed to put an element in the queue even if it is "full". Since the Reader-writer will typically only put things on the queue as a result of user interaction, the queue wont grow too large anyway. -- Antoon Pardon From aleax at mac.com Tue Apr 17 00:40:59 2007 From: aleax at mac.com (Alex Martelli) Date: Mon, 16 Apr 2007 21:40:59 -0700 Subject: strange behaviour with keyword arguments and inheritance References: <1176771364.964642.209300@b75g2000hsg.googlegroups.com> <1176773781.729037.139650@y5g2000hsa.googlegroups.com> <1176775837.140883.287360@n76g2000hsh.googlegroups.com> Message-ID: <1hwok9v.1x202xmgzzN%aleax@mac.com> Steve Holden wrote: ... > > livibetter has a better solution. the reason is that you need to > > create a new list object everytime, am I right? > > > Yes, specifically on every *call*. ...and livibetter's solution also creates a new list on every call to Child (that [] passed on to Parent.__init__ does exactly that). Alex From marcpp at gmail.com Tue Apr 24 03:55:31 2007 From: marcpp at gmail.com (Marcpp) Date: 24 Apr 2007 00:55:31 -0700 Subject: PYQT 3 communication with 2 windows In-Reply-To: <8f570$46295e4f$54d1d767$4261@news.chello.no> References: <1177015090.289961.306590@o5g2000hsb.googlegroups.com> <8f570$46295e4f$54d1d767$4261@news.chello.no> Message-ID: <1177401331.361770.266230@u32g2000prd.googlegroups.com> On 21 abr, 02:43, David Boddie wrote: > On Thursday 19 April 2007 22:38, Marcpp wrote: > > > Hi, I'm introducing to program in python + pyqt. > > I have a main window that call a second window (to introduce a info > > with textedit) > > when press the second window button I need to return to the main > > window the info > > introduced in the second window. > > I've seek in the pyqt doc examples but i don't find it. > > Have you any example? > > You could connect the button to a slot in the second window that sends > the text back to the first window. > > Here's an example that sends the text to a function. You could substitute a > class for the function to get what you want. > > import sys > from qt import * > > class Window(QWidget): > > def __init__(self, parent = None): > > QWidget.__init__(self, parent) > > self.textEdit = QTextEdit(self) > okButton = QPushButton(self.tr("&OK"), self) > self.connect(okButton, SIGNAL("clicked()"), self.sendText) > layout = QVBoxLayout(self) > layout.addWidget(self.textEdit) > layout.addWidget(okButton) > > def sendText(self): > > self.emit(PYSIGNAL("textEntered(QString)"), (self.textEdit.text(),)) > > def fn(text): > > print text > > if __name__ == "__main__": > > app = QApplication(sys.argv) > window = Window() > window.connect(window, PYSIGNAL("textEntered(QString)"), fn) > window.show() > app.setMainWidget(window) > sys.exit(app.exec_loop()) > > Note the use of PYSIGNAL() instead of SIGNAL(). With PyQt4 you would be able > to use SIGNAL() and write the emit() call in a simpler form. > > David Thankyou!!! This is that I want. From frank at chagford.com Thu Apr 26 01:27:57 2007 From: frank at chagford.com (Frank Millman) Date: 25 Apr 2007 22:27:57 -0700 Subject: MS SQL Server Extension? In-Reply-To: References: Message-ID: <1177565276.992603.210020@t39g2000prd.googlegroups.com> On Apr 25, 9:44 am, Tim Golden wrote: > Jack wrote: > > Hi all, in my next project, my Python code needs to talk to an MS SQL > > 2000 Server. Internet search gives mehttp://pymssql.sourceforge.net/ > > I wonder what module(s) people are using. My code runs on a Linux > > box so the module has to build on Linux. Any hints/pointers are welcome. > > There are several modules around which will cover this. > One of these days I'll take the post I'm about to write > and stick it on a Wiki or something because I seem to > write it about once every six months :) > > In no particular order: > > adodbapi - recently resurrected from moribundity (if > that's a word); search the list archives because I > can't remember who's working on it. > > + Win32 only (afaik) > + Covers all sorts of things as well as MSSQL > + Allows for passthrough authentication > > - Used to have some slight flakiness in it. Bloke > who's taken over maintenance says he's patched and > simplified things. Haven't tried it since. > > pymssql -http://pymssql.sf.net > > + Win32 & Linux (via FreeTDS) > > - Doesn't allow passthrough authentication > - Has some issues with Unicode > > pyodbc -http://pyodbc.sf.net > (a recent runner) > > + Win32 & Linux (via whatever *nix ODBC package) > + Apparently more actively maintained than pymssql > + (Is currently the favoured front-runner among the > sqlalchemy devs) > > - Lacks .nextset (in case that's important to you) > > Other contenders: > > mxODBC - Commercial License but a very strong > and long-standing candidate. Lacks .nextset > support. Works on *nix via iODBC etc. > > Object Craft MSSQL - Worked well for me for years > but they seemed to have abandoned it of late. > Still there. Still works. But no binaries beyond > Python 2.3. (I did try to recompile using MingW > but couldn't get it to work). Works on *nix via > FreeTDS. > > TJG An addition to the above list is the odbc module from the win32all package. I use this, and although it is not 100% DB-API 2.0 compliant, I find it quite satisfactory. Google Groups seems to be running about 12 hours behind, so my apologies if this has already been mentioned. Frank Millman From bignose+hates-spam at benfinney.id.au Tue Apr 3 01:02:10 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Tue, 03 Apr 2007 15:02:10 +1000 Subject: getattr/setattr q. References: <1175573213.682671@jubilee.claranet.pt> Message-ID: <87mz1qgiel.fsf@benfinney.id.au> Paulo da Silva writes: > In a class C, I may do setattr(C,'x',10). That would set an attribute on the class C, shared by all instances of that class. If you want to set an attribute on an instance, you need to do so on the instance object:: >>> class Foo(object): ... def __init__(self): ... setattr(self, 'bar', 10) ... >>> Foo.bar Traceback (most recent call last): File "", line 1, in ? AttributeError: type object 'Foo' has no attribute 'bar' >>> spam = Foo() >>> spam.bar 10 > Is it possible to use getattr/setattr for variables not inside > classes or something equivalent? I mean with the same result as > exec("x=10"). "Variables not inside classes or functions" are attributes of the module (so-called "global" attributes). Thus, you can use setattr on the module object:: >>> import sys >>> def foo(): ... this_module = sys.modules[__name__] ... setattr(this_module, 'bar', 10) ... >>> bar Traceback (most recent call last): File "", line 1, in ? NameError: name 'bar' is not defined >>> foo() >>> bar 10 -- \ "I'm beginning to think that life is just one long Yoko Ono | `\ album; no rhyme or reason, just a lot of incoherent shrieks and | _o__) then it's over." -- Ian Wolff | Ben Finney From grante at visi.com Mon Apr 23 12:30:30 2007 From: grante at visi.com (Grant Edwards) Date: Mon, 23 Apr 2007 16:30:30 -0000 Subject: Generate report containing pdf or ps figures? Message-ID: <132pnp6r4qg0lc2@corp.supernews.com> I need to be able to generate a PDF report which consists mostly of vector images (which I can generate as encapsulated Postscript, PDF, or SVG). What I need is a way to combine these figures into a single PDF document. Right now the reports consist entire of these figures, so I just write the figures out to temp files and then use os.system() to run ghostscript with appropriate options to combine them into a single PDF file. I'd like to be able to add some text and/or place the figures in a manner other than one per page in the output document. I've looked at ReportLab's documentation, but although it appears to be able to use bitmap images (e.g jpeg) it doesn't appear to be able to use vector images (EPS/PDF/SVG). Is there a PDF generation library that can place EPS or PDF figures on a page? -- Grant Edwards grante Yow! Is a tattoo real, like at a curb or a battleship? visi.com Or are we suffering in Safeway? From apardon at forel.vub.ac.be Mon Apr 23 03:38:38 2007 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 23 Apr 2007 07:38:38 GMT Subject: Do other Python GUI toolkits require this? References: <462697A6.6010007@codebykevin.com> <465B30B4-5BA0-459A-BE6F-1038874FA74B@jedimindworks.com> <58rq32F2fo980U1@mid.uni-berlin.de> <58uoa6F2ii7pcU1@mid.uni-berlin.de> Message-ID: On 2007-04-21, Diez B. Roggisch wrote: > Antoon Pardon schrieb: >> On 2007-04-20, Diez B. Roggisch wrote: >>>> So if you have the choice between a steep or a shalow income curve >>>> you will prefer the shalow curve because a steep curve makes you >>>> think about verticale clifs and such? >>>> >>>> The analogy with a walk is just silly because curves are not like walks. >>>> Nobody will say something like: I won't invest in that company because >>>> it has a steep profit curve or the reverse: I'll invest in this company >>>> because it has an easy looking downhill going profit curve. >>> Your whole argumentation bases on the fact that the result of the >>> learning process, and the success of it, has something to do with the >>> reached height - or y-axis-value - of your climb. >>> >>> Which is nonsense. The goal is to go from A - ignorance - to B - >>> knowledge - which both lie on the X-Axis. >> >> Well if you want to do it that way, nobody can stop you, but people >> in the habit of processing numbers usually put the time on the X-axis >> like in time spend learning or exercising and put the other value >> on the Y-axis. > > > You seem to live in a very limited world, where bezier-curves (note the > name...) > are parametrized over t, but rendered on the x/y-axis happily going > forth and back and whatnot. I'm not talking about bezier-curves or any parametric curve, because it doesn't make sense to talk about steep and shalow curves then, since there is no implication of hard/slow easy/fast associated then with steep or shalow, you might as well use polar coordinates. > If using knowledge as the x-axis and effort on the y-axis, the figure of > speech makes perfect sense. That is an after the fact interpretation. There certain rules/conventions in picking your variables when you want to draw a curve. The association of steep and shalow of a curve with some real world implication depends on those rules/conventions. If you don't follow those rules/conventions don't think you can get a message across by saying steep, because any data can be put on a steep curve if you are allowed to pick how to draw your axes. So your statement doesn't mean much more than: After I have played with the paper, turned it over, rotated it a bit, the curve looks steep. >> That is because people prefer a curve going up and down while moving >> to the right instead of going left and right while moving up. > > Which is obviously something people don't want to do in this context, > because "going down" doesn't make too much sense here, doesn't it? Or do > you want to cram the process of unlearning in the little figure of > speech as well? Then those people shouldn't refer to curves. If people want to refer to curves in order to bring a message accross then the message should make sense to those familiar with curves. I can understand that some people find that doing so, makes their message feel wrong. Not a problem, use an other metaphor. Don't twist the metaphor to get a message that feels all right to you but brings nonsense to those who are familiar with the metaphor. > But even a perfectly sense-making explanation can be found, I doubt that > you will ever acknowledge that you did make a mistake on this one - as > you always (or better never) do... As far as I can see I don't differ from most people in this respect on this news group. -- Antoon Pardon From jzgoda at o2.usun.pl Fri Apr 13 16:38:28 2007 From: jzgoda at o2.usun.pl (Jarek Zgoda) Date: Fri, 13 Apr 2007 22:38:28 +0200 Subject: Python editor/IDE on Linux? In-Reply-To: References: <1176494048.627760.323630@p77g2000hsh.googlegroups.com> Message-ID: Greg Donald napisa?(a): >> Thanks God > > No problem. > >> , there's no "PIDA for Emacs". > > Pet Industry Distributors Association ? Pfscking Ifscking Dfscking Afscking beste Editor unter die Sun ist der Vim! (they would try to convince you die PIDA means something mehr enjoyable, aber it's still der Vim) -- Jarek Zgoda http://jpa.berlios.de/ From rehceb at no.spam.plz Sat Apr 7 11:52:22 2007 From: rehceb at no.spam.plz (Rehceb Rotkiv) Date: Sat, 07 Apr 2007 10:52:22 -0500 Subject: Checking whether list element exists References: Message-ID: > In general case it won't work, because lists accept negative indexes: > http://docs.python.org/lib/typesseq.html, 3rd note. Yes, I know! I _want_ the "3rd last list element", i.e. list[-3]. But it may be that the list does not have 3 elements. In this case, list[-3] will throw an error, cf.: >>> arr = ['a','b','c'] >>> print arr[-3] a >>> print arr[-4] Traceback (most recent call last): File "", line 1, in ? IndexError: list index out of range >>> I thought maybe I could catch the error with try...except so that I do not need the if-test, but I don't know whether this is proper usage of the try...except structure. From Graham.Dumpleton at gmail.com Thu Apr 19 01:50:41 2007 From: Graham.Dumpleton at gmail.com (Graham Dumpleton) Date: 18 Apr 2007 22:50:41 -0700 Subject: Third party script debugging on remote server ... In-Reply-To: <1176943924.267007.182270@q75g2000hsh.googlegroups.com> References: <1176938153.119084.214700@d57g2000hsg.googlegroups.com> <1176939110.773939.83160@p77g2000hsh.googlegroups.com> <1176943924.267007.182270@q75g2000hsh.googlegroups.com> Message-ID: <1176961841.905310.287950@n59g2000hsh.googlegroups.com> > Hi Graeme, > > Thanks for the suggestion. Unluckily for me, it doesn't seem to be > working though ... > > I've tried it a number of different ways. I guess if I put the code > after an exception, then the code won't be called. > So I ran an error in the python script and then I called the > sys.stderr.flush() from the python shell. No luck though. > > I called on it's own, still no luck, > > Then I tried ... > > try: > > raise Exception('Please log this error') > > except: > > import sys > > sys.stderr.flush() > sys.stdout.flush() > > The error log still has no error info in it :-( .... > > Is this problem unique to me ? Those calls don't generate output themselves and exception details don't get output at the point of a try/except block. If you want to generate to Apache error log details of exception from try/except, use: import traceback import sys try: xxx except: traceback.print_exc() sys.stderr.flush() Using these flush functions from interactive debugger isn't going to show you anything as this trick is only needed with mod_python. All the functions do is force the output of any buffered data that was written out previously. Graham From duncan.booth at invalid.invalid Wed Apr 18 10:28:55 2007 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 18 Apr 2007 14:28:55 GMT Subject: Calling private base methods References: <1176374675.347453.89340@n76g2000hsh.googlegroups.com> <1176404325.211501.26610@w1g2000hsg.googlegroups.com> <1176435087.708516.66470@o5g2000hsb.googlegroups.com> <1176650850.211487.294690@y80g2000hsf.googlegroups.com> <1hwmmq4.n76p2d1k88mz5N%aleax@mac.com> <1176902245.845880.308870@b75g2000hsg.googlegroups.com> Message-ID: Isaac Rodriguez wrote: >> In real life, the skills of the two people in >> question are likely to be much closer, and since designing libraries for >> use in all kinds of applications is a really hard task, it's likelier >> than the library designer will make an error in designing his or her >> library, rather than the application programmer in using that library. > > Those are called defects or "bugs". When I find a bug in a library or > an application, I submit a bug report. I might have to work around it > for a little bit, but I don't just work around it and call it goods. > Library designers are normal programmers that work under a set of > requirements like any other programmer (application programmers > included), but when I find a bug in an application, I report it and > try to work around it until it gets fixed; I don't hack the > application or re-write my own just because a found a bug. > You appear to have led a very sheltered life if the only libraries you ever use are ones where you can always get a change to the library api in a timely manner. In the particular case where I hacked around a private variable, the library in question was burned into ROM on thousands of consumer devices. Getting the library to change simply wasn't an option. From rdhettinger at gmail.com Sun Apr 8 12:16:43 2007 From: rdhettinger at gmail.com (rdhettinger at gmail.com) Date: 8 Apr 2007 09:16:43 -0700 Subject: itertools, functools, file enhancement ideas In-Reply-To: <7xveg7rhc7.fsf_-_@ruckus.brouhaha.com> References: <7xveg7rhc7.fsf_-_@ruckus.brouhaha.com> Message-ID: <1176049003.872896.7720@d57g2000hsg.googlegroups.com> [Paul Rubin] > 1. File iterator for blocks of chars: > > f = open('foo') > for block in f.iterchars(n=1024): ... for block in iter(partial(f.read, 1024), ''): ... > iterates through 1024-character blocks from the file. The default iterator > a) def flip(f): return lambda x,y: f(y,x) Curious resemblance to: itemgetter(1,0) Raymond From mansonmuni at alexandria.cc Thu Apr 19 00:09:34 2007 From: mansonmuni at alexandria.cc (Glen) Date: Thu, 19 Apr 2007 04:09:34 GMT Subject: Beginner: Formatting text output (PyQt4) References: Message-ID: <2YBVh.4744$2v1.282@newssvr14.news.prodigy.net> On Wed, 18 Apr 2007 22:50:14 +0000, Glen wrote: Ok, obviously, my post didn't come out the way I wanted it to. In the first example from my text file below, the dictionary pairs, constructed from sorted tuples were in straight columns. When I write them to my QTextEdit, however, the columns are no longer straight. Some of the padding inserted by my call to rightJustified() are not equal to the actual size of the text, so some rows are longer than others in the text browser. I know I've encountered this before, perhaps with Java, but I can't remember the solution. How do I get the formatting of my output to the gui to reflect the output I would get to a file using the builtin write() function? Any help is appreciated. Sorry about the confusion. Thanks, G > Hello again, I don't blame anyone for not answering my last post, since > I obviously hadn't spent much time researching, but I've come a little > ways and have another question. > > How can I better format text output to a QTextEdit object? I'm > inserting 5 columns into each row. When I write the info to a file, it > looks like the following: > > 42: 115 26: 114 35: 112 19: 108 16: 107 45: 107 40: > 106 5: 105 41: 104 2: 103 > 9: 102 48: 102 15: 101 22: 101 27: 101 > 39: 101 43: 101 10: 100 6: 99 34: 99 32: 98 49: > 98 20: 97 30: 97 8: 96 17: 96 38: 96 12: 95 > 14: 95 37: 95 > 4: 94 13: 94 44: 94 36: 93 3: 92 > 24: 92 28: 92 31: 91 29: 89 7: 88 > 1: 87 18: 85 46: 85 33: 84 11: 83 > 23: 83 47: 82 25: 80 21: 79 50: 56 52: 39 51: > 38 53: 36 54: 25 55: 18 > > When I write the contents of the file to my TextEdit object it comes out > uneven, something like this: > 42: 115 26: 114 35: 112 19: 108 16: 107 45: 107 40: 106 > 5: 105 41: 104 2: 103 9: 102 48: 102 15: 101 22: 101 27: > 101 39: 101 43: 101 10: 100 6: 99 34: 99 32: 98 49: 98 > 20: 97 30: 97 8: 96 17: 96 38: 96 12: 95 14: 95 > 37: 95 4: 94 13: 94 44: 94 36: 93 3: 92 24: 92 28: > 92 31: 91 29: 89 7: 88 > 1: 87 18: 85 46: 85 33: 84 11: 83 > 23: 83 47: 82 25: 80 21: 79 50: 56 52: 39 51: 38 > 53: 36 54: 25 55: 18 > > What seems to be happening is that the font that pyqt is using is not > fixed width, so I did this: > qTxtFormat = QTextCharFormat() > qTxtFormat.setFontFixedPitch(True) > ui.textEdit.setCurrentCharFormat(qTxtFormat) > > Also, I tried using the pyqt formatting such as the following: > > qStr = QtCore.QString( QtCore.QString( str(tL2[i][0]) > ).rightJustified(2) + ':' + QtCore.QString( str(tL2[i][1]) > ).rightJustified(4) ) > This still gives me uneven columns. > > Any suggestions? > > Thanks, > > Glen From aleax at mac.com Sun Apr 22 00:54:28 2007 From: aleax at mac.com (Alex Martelli) Date: Sat, 21 Apr 2007 21:54:28 -0700 Subject: Flat DB seeking speed References: <1177216068.518970.29470@o5g2000hsb.googlegroups.com> Message-ID: <1hwxw9m.tequts1vbc9z2N%aleax@mac.com> Jia Lu wrote: > Hello all > > I see there are lots of flat db or db-like modules in the standard > python modules. > What about the keywords seeking speed of them ? > > (I want to put about 10000 articles with 10000 IDs, and I can do > searching keywords with them) > > The db-like modules are : > dbm, gdbm, dbhash,anydbm, > pickle(cPickle), shelve, marshal Your question is somewhat hard to parse (I sympathize, since English isn't my mother-tongue, either) -- "keywords seeking speed" is very hard to understand in this context. Marshal and pickle/cPickle aren't "db-like" at all -- they're just sequences of serialized objects; marshal is low-level (you can only serialize objects of some fundamental built-in types), pickle (and the faster cPickle) higher-level (you can serialize objects of many different types), but in either case there is no "seeking", "keywords" or otherwise, just sequential reloading of the objects you serialized. Handy when that's what you need -- persist a bunch of objects to a disk file, rebuild them in memory later -- but it doesn't appear to have much to do with anything in your question and I'm really perplexed as to why you think it might (what materials did you use to study these subjects, that gave you such a horrendously wrong impression?!). All forms of dbm files (including the implementation known as gdbm, as well as the lookalike one built on top of bsddb), as well as bsddb (which you don't even mention), represent on disk a map from "key" strings to "value" strings. shelve is a modest extension to this concept: it maps from "key" strings to arbitrary picklable objects (using cPickle to map such objects to and from strings of bytes). anydbm is a very thin layer on top of various dbm implementation (it uses whichdbm to make an informed guess as to what kind of dbm module was used to make a given dbm-like file, and also uses the best dbm implementation you have installed to build a new file of some dbm type). If by "keywords seeking" you mean performing full-text search, none of these modules are at all suitable. Perhaps you might want to try pylucene, , or other such third-party modules, for the purpose -- it that IS indeed your purpose. Alex From bruno.42.desthuilliers at wtf.websiteburo.oops.com Fri Apr 13 12:43:56 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Fri, 13 Apr 2007 18:43:56 +0200 Subject: function/method assigment In-Reply-To: <1176480852.643836.121930@p77g2000hsh.googlegroups.com> References: <1176480852.643836.121930@p77g2000hsh.googlegroups.com> Message-ID: <461fb2d1$0$18273$426a74cc@news.free.fr> viscroad at gmail.com a ?crit : > I have a confusion when I do some practice, the code and output are as > following, > >>>> def fun(): > print 'In fun()....' Function fun doesn't explicitelly return something, so it's return value defaults to None (nb: None is a builtin object representing 'nothing'). > >>>> testfun = fun() This calls fun, and binds the returned value (in this case, None) to name testfun > In fun().... and this is a side-effect of the execution of function fun. >>>> print testfun > None Which is the expected result >>>> testfun2 = fun This binds the function object fun to the name testfun2 (IOW, testfun2 is now an alias for fun). Remember that in Python, the parens are not optional if you want to call a function - they are in fact the 'call operator'. If you forget them, you get a reference to the function object, not the result of calling the function. >>>> print testfun2 This prints the representation of the object bound to name testfun2 - here, function fun. > >>>> print testfun2() > In fun().... > None This first calls testfun2 (which is now another name for function fun), triggering the printing of the string "in fun()..." as a side effects, then print the return value of testfun2 (aka fun), which is still None. HTH From luismgz at gmail.com Fri Apr 20 17:09:30 2007 From: luismgz at gmail.com (=?iso-8859-1?q?Luis_M=2E_Gonz=E1lez?=) Date: 20 Apr 2007 14:09:30 -0700 Subject: When are immutable tuples *essential*? Why can't you just use lists *everywhere* instead? In-Reply-To: <58sf33F2b1q8tU1@mid.individual.net> References: <1177088796.622928.224890@d57g2000hsg.googlegroups.com> <1177089206.550423.288670@q75g2000hsh.googlegroups.com> <58sf33F2b1q8tU1@mid.individual.net> Message-ID: <1177103370.022138.110320@n59g2000hsh.googlegroups.com> On Apr 20, 3:28 pm, Bjoern Schliessmann wrote: > Luis M. Gonz?lez wrote: > > I don't remember exactly where I read about it, but Guido said > > once that tuples are being kept mainly for historical reasons. > > Weren't tuples added when lists already existed? > > Regards, > > Bj?rn > > -- > BOFH excuse #101: > > Collapsed Backbone I tried googling for these comments, but I couldn't find them. Perhaps I never read them and it was just my imagination... Anyway, I suggest reading this chapter of "Dive into Python" for a good explanation of the differences between tuples and lists: http://diveintopython.org/native_data_types/tuples.html The article explains that, amongst other things, tuples are faster than lists, so if you are working with constant values (inmutables) they are more indicated than lists. luis From gagsl-py2 at yahoo.com.ar Mon Apr 30 02:11:05 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 30 Apr 2007 03:11:05 -0300 Subject: Chart drawing tool in python References: <1177897942.532255.317000@y80g2000hsf.googlegroups.com> Message-ID: En Sun, 29 Apr 2007 22:52:22 -0300, yinglcs at gmail.com escribi?: > In Perl, there is a GD module to draw custom chart. > Can you please tell me if there is an equivalent library in python? There is gdchart (google for it), but *I* prefer pychart for *my* charts. -- Gabriel Genellina From gregcorradini at gmail.com Thu Apr 5 15:25:08 2007 From: gregcorradini at gmail.com (Greg Corradini) Date: Thu, 5 Apr 2007 12:25:08 -0700 (PDT) Subject: Trouble w/ 'create table' sql on mx.ODBC Message-ID: <9860747.post@talk.nabble.com> Hello, Lately I've been using the mx.ODBC module to query Access (mdb) tables. For the life of me, I can't get the 'create table' sql command to work. I use this command in Oracle and I've seen other mx.ODBC users weave into their scripts for Access. But I still can't get this simple test run below to work (ignore the geoprocessor object for ArcGIS): #Import Python Standard Library Modules import win32com.client, sys, os, string, copy, glob import mx.ODBC.Windows as odbc # Create the Geoprocessor Object gp = win32com.client.Dispatch("esriGeoprocessing.GpDispatch.1") gp.overwriteoutput = 1 # Variables tempspace = "C:\Documents and Settings\corr1gre\Desktop\Workspace\DBFs & Shapefiles\TEST.mdb" workspace = string.replace(tempspace,"\\","/") #Conection to Access driv = 'DRIVER={Microsoft Access Driver (*.mdb)};DBQ='+workspace conn = odbc.DriverConnect(driv) curse = conn.cursor() #Upload Tbl 1 as a List of Tuples curse.execute('SELECT TISCODE,EXISTSIN,STATUS,NOTES from Mower_I') x = curse.fetchall() #Create New Table curse.execute('Create table TEST (TISCODE Integer)') curse.close() conn.close() del gp -- View this message in context: http://www.nabble.com/Trouble-w--%27create-table%27-sql-on-mx.ODBC-tf3532982.html#a9860747 Sent from the Python - python-list mailing list archive at Nabble.com. From harry.g.george at boeing.com Mon Apr 30 05:59:20 2007 From: harry.g.george at boeing.com (Harry George) Date: Mon, 30 Apr 2007 09:59:20 GMT Subject: Python ODBC References: <1177864453.282136.233030@n59g2000hsh.googlegroups.com> <1177942237.735428.214700@u30g2000hsc.googlegroups.com> Message-ID: kyosohma at gmail.com writes: > On Apr 29, 11:34 am, Harlin Seritt wrote: > > Is there a Python odbc module that will work on Linux? I have a jdbc > > connection to a DB2 server. I am looking hopefully for an open source > > solution and not a commercial one. > > > > Thanks, > > > > Harlin > > I would think the odbc module would work. We've used SQLRelay here at > work too. Here's a link on the database modules for Python: > > http://www.python.org/topics/database/modules.html > > And here's a few links on db2 with Python: > > http://www-128.ibm.com/developerworks/db2/library/tutorials/db2linux/db2proj/updated/python_db2_interface.htm > http://sourceforge.net/projects/pydb2/ > http://www-128.ibm.com/developerworks/edu/i-dw-db2pylnx-i.html > > Hope that helps. > > Mike > I've looked into it, but never got all the way to a solution. As I understand it: 1. The DBMS needs to support ODBC. DB2 does, so ok. 2. You need a client side framework and driver. Those are provided on MS Win platforms. On *NIX platforms, unixodbc and iodbc are the main players. http://www.unixodbc.org/ http://www.iodbc.org/ 3. For *NIX you need python bindings. This is where mxODBC has operated (e.g., with iodbc). But there is an OSS effort at: https://sourceforge.net/projects/pyodb -- Harry George PLM Engineering Architecture From fuzzyman at gmail.com Thu Apr 19 09:08:46 2007 From: fuzzyman at gmail.com (Fuzzyman) Date: 19 Apr 2007 06:08:46 -0700 Subject: CGI Script using Python In-Reply-To: <58our9F2fertqU1@mid.individual.net> References: <58our9F2fertqU1@mid.individual.net> Message-ID: <1176988126.090718.33150@o5g2000hsb.googlegroups.com> On Apr 19, 11:34 am, "Ralf" wrote: > Hello, > is there anybody who can help me. > I would like to use a Python Script to download Files from a Server to the > Client, to update the Client. > Downman is an example of a Python CGI which presents files for download. http://www.voidspace.org.uk/python/cgi.shtml#downman You will want to copy the part that sends the right headers (etc)... Fuzzyman > Thanx > Ralf From rzantow at gmail.com Mon Apr 2 08:54:07 2007 From: rzantow at gmail.com (rzed) Date: Mon, 02 Apr 2007 12:54:07 +0000 Subject: Clean "Durty" strings References: <1175463083.135907.128480@y80g2000hsf.googlegroups.com> <57bt02F2c9fpuU2@mid.uni-berlin.de> Message-ID: "Diez B. Roggisch" wrote in news:57bt02F2c9fpuU2 at mid.uni-berlin.de: > Ulysse wrote: > >> Hello, >> >> I need to clean the string like this : >> >> string = >> """ >> bonne mentalité mec!:) \n
bon >> pour info moi je suis un serial posteur arceleur dictateur ^^* >> \n
mais pour avoir des resultats >> probant il faut pas faire les mariolles, comme le >> "fondateur" de bvs krew \n >> mais pour avoir des resultats probant il faut pas faire les >> mariolles, comme le "fondateur" de bvs krew \n >> """ >> >> into : >> bonne mentalit?? mec!:) bon pour info moi je suis un serial >> posteur arceleur dictateur ^^* mais pour avoir des resultats >> probant il faut pas faire les mariolles, comme le "fondateur" >> de bvs krew mais pour avoir des resultats probant il faut pas >> faire les mariolles, comme le "fondateur" de bvs krew > > The obvious way that has been suggested to you at other places > is to use BeautifulSoup. > >> To do this I wold like to use only strandard librairies. > > Then you need to reprogram what BeautifulSoup does. Happy > hacking! > If the OP is constrained to standard libraries, then it may be a question of defining what should be done more clearly. The extraneous spaces can be removed by tokenizing the string and rejoining the tokens. Replacing portions of a string with equivalents is standard stuff. It might be preferable to create a function that will accept lists of from and to strings and translate the entire string by successively applying the replacements. From what I've seen so far, that would be all the OP needs for this task. It might take a half- dozen lines of code, plus the from/to table definition. -- rzed From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Fri Apr 13 06:54:51 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Fri, 13 Apr 2007 12:54:51 +0200 Subject: wxPython, mac, wx.HSCROLL not working References: <1176364597.741079.25840@n59g2000hsh.googlegroups.com> <586qvsF2fbq3rU1@mid.individual.net> <1176392605.298630.8210@y5g2000hsa.googlegroups.com> <1176404918.079527.148440@d57g2000hsg.googlegroups.com> <587i0iF2fu57fU1@mid.individual.net> <1176417535.246590.158780@y80g2000hsf.googlegroups.com> Message-ID: <5895rrF2en0c0U1@mid.individual.net> 7stud wrote: > Thanks. It looks like someone asked the same question yesterday. No -- it looks like I was a bit stressed and the first google hit or a direct jump to wxpython.org would have provided the solution :) Regards, Bj?rn -- BOFH excuse #14: sounds like a Windows problem, try calling Microsoft support From steve at holdenweb.com Thu Apr 19 07:51:35 2007 From: steve at holdenweb.com (Steve Holden) Date: Thu, 19 Apr 2007 07:51:35 -0400 Subject: About installing new Python version. In-Reply-To: <1176978617.299033.37250@n59g2000hsh.googlegroups.com> References: <1176973387.967130.27370@y80g2000hsf.googlegroups.com> <1176975545.693682.51870@q75g2000hsh.googlegroups.com> <1176976568.438207.253120@d57g2000hsg.googlegroups.com> <1176977440.265263.186450@n76g2000hsh.googlegroups.com> <1176978617.299033.37250@n59g2000hsh.googlegroups.com> Message-ID: king kikapu wrote: > On Apr 19, 12:10 pm, Ant wrote: >>> checked and everything seems to working fine. But this is an update >>> release to 2.5, i do not know what is happening when, for example, a >>> totally new Python version come out, like 2.6 or 2.7 or... >> Again just install it - it will by default install alongside Python >> 2.5 in a different directory, and set itself as the default python >> version. You'll then need to update all your third party extensions to >> ones compiled against the new version - so if you have a lot of these, >> it makes sense to wait a while before upgrading. >> >> -- >> Ant. > > Hmm...ok, i was sure that i wouldn't avoid that...The nice thing is > that 2.5.1 installed in default directory so no problem for now. > Thanks! > Good question. kk is right - with a change in *major* version (such as 2.4 to 3.5, 3.5 to 3.6) the compiled extensions will be incompatible, and will need to be recompiled. This can take a while, as extension authors frequently have other things to do besides maintain their extensions. As you have found out, though, when only the *minor* version changes you can just frop the new version in over the old and all your installed extensions and packages continue to work just fine. 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 trentm at activestate.com Tue Apr 3 21:16:47 2007 From: trentm at activestate.com (Trent Mick) Date: Tue, 03 Apr 2007 18:16:47 -0700 Subject: Where to find pywin32/win32all for Python 1.5.2? In-Reply-To: References: Message-ID: <4612FC7F.7060703@activestate.com> Jack wrote: > I searched around but could not find win32all source or binaries for earlier > versions of Python. Don't ask me why but I have to use Python 1.5.2 in this > project :) The sourceforget page only has latest versions. ActiveState does > not even have 1.5.2 for download. Is it still available somewhere? Thanks! Python 1.5.2 was release way before ActiveState started doing ActivePython, so no luck there. :( -- Trent Mick trentm at activestate.com From p.edelman at gmail.com Fri Apr 27 11:37:06 2007 From: p.edelman at gmail.com (Pieter Edelman) Date: 27 Apr 2007 08:37:06 -0700 Subject: Access to raw command line? In-Reply-To: <1177601156.426811.313490@b40g2000prd.googlegroups.com> References: <1177571070.229968.155710@t39g2000prd.googlegroups.com> <1177601156.426811.313490@b40g2000prd.googlegroups.com> Message-ID: <1177688226.810387.14080@t38g2000prd.googlegroups.com> Of course you're right about that. I think an optional GUI or wizard- like interface (in this particular case) would be best, but I was looking for an easy fix :) Thanks for the suggestion though. On Apr 26, 5:25 pm, Michele Simionato wrote: > On Apr 26, 9:04 am, Pieter Edelman wrote: > > > Hi, > > > I'm currently writing a command-line program in Python, which takes > > commands in the form of: > > ./myprog.py [OPTIONS] ARGS > > Once you start having too many arguments and options on the command > line, you might > consider using the cmd module of the standard library instead. Then > you could implement your own > expansion, and you would have portability for non-Unix system too. > > Michele Simionato From bearophileHUGS at lycos.com Sun Apr 15 15:33:29 2007 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 15 Apr 2007 12:33:29 -0700 Subject: combination function in python In-Reply-To: <1176654363.696340.283330@d57g2000hsg.googlegroups.com> References: <1176615838.830315.160210@b75g2000hsg.googlegroups.com> <1176629911.409257.149780@l77g2000hsb.googlegroups.com> <1176654363.696340.283330@d57g2000hsg.googlegroups.com> Message-ID: <1176665609.470089.211190@y80g2000hsf.googlegroups.com> Mark Dickinson: > def choose(n, k): > ntok = 1 > for t in xrange(min(k, n-k)): > ntok = ntok*(n-t)//(t+1) > return ntok With few tests, it seems this is faster than the version by Jussi only with quite big n,k. (Another test to be added, is the assert n>0 of my original version (testing that n,k seem useful too)). Bye, bearophile From clajo04 at mac.com Wed Apr 4 15:30:53 2007 From: clajo04 at mac.com (John Clark) Date: Wed, 4 Apr 2007 15:30:53 -0400 Subject: calling super() In-Reply-To: <1175714555.413502.77390@o5g2000hsb.googlegroups.com> References: <1175714555.413502.77390@o5g2000hsb.googlegroups.com> Message-ID: <00b301c776ef$c412dba0$fefea8c0@haengma> Yeah!!! One I can actually answer!!! super() only works on new-style classes - your classes don't have object anywhere in the inheritance tree so super() isn't going to help.. New-style classes are known as types, old-style classes are known as classobjs. Hope this helps, -jdc -----Original Message----- From: python-list-bounces+clajo04=mac.com at python.org [mailto:python-list-bounces+clajo04=mac.com at python.org] On Behalf Of Finger.Octopus at gmail.com Sent: Wednesday, April 04, 2007 3:23 PM To: python-list at python.org Subject: calling super() Hello, I have been trying to call the super constructor from my derived class but its not working as expected. See the code: class HTMLMain: def __init__(self): self.text = ""; print(self.text); def __del__(self): self.text = ""; print(self.text); class NewPage(HTMLMain): def __init__(self): print 'derive2 init' super(NewPage, self).__init__(); N = NewPage(); del N And here's the error message I get: Traceback (most recent call last): File "e:/PyEN/inherit.py", line 16, in N = NewPage(); File "e:/PyEN/inherit.py", line 12, in __init__ super(NewPage, self).__init__(); TypeError: super() argument 1 must be type, not classobj -- http://mail.python.org/mailman/listinfo/python-list From Szkandera.Karel at seznam.cz Sat Apr 7 07:32:26 2007 From: Szkandera.Karel at seznam.cz (=?us-ascii?Q?Szkandera=2EKarel?=) Date: Sat, 07 Apr 2007 13:32:26 +0200 (CEST) Subject: =?us-ascii?Q?Python=20=2D=20ogr2ogr?= Message-ID: <689.1545-1169-562858817-1175945546@seznam.cz> Hi, I need to do web service, which will be convert vector formats, like shapefile, dgn, mapinfo..(and other formats, which are supported in ogr2ogr). I want to do it with using ogr2ogr in the ogr python module, but i am newbie in python, so here is my questions. Is here anybody, who wrote any similar scripts and can give it me? If not, can at least anyone point me to few examples of using ogr2ogr in the ogr python module? Thank you for every answer, K.Szkandera From irmen.NOSPAM at xs4all.nl Sat Apr 21 18:13:20 2007 From: irmen.NOSPAM at xs4all.nl (Irmen de Jong) Date: Sun, 22 Apr 2007 00:13:20 +0200 Subject: how to transfer integer on socket? In-Reply-To: <1177123738.899837.65250@e65g2000hsc.googlegroups.com> References: <1177123738.899837.65250@e65g2000hsc.googlegroups.com> Message-ID: <462a8c80$0$328$e4fe514c@news.xs4all.nl> Frank Potter wrote: > Is there any easy way to transfer 4 bit integer on socket? I think you mean a 4-byte integer? Look at the struct module, anyway. --Irmen From jstroud at mbi.ucla.edu Sun Apr 29 16:13:50 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Sun, 29 Apr 2007 13:13:50 -0700 Subject: Counting In-Reply-To: References: <1177873864.502180.283390@u30g2000hsc.googlegroups.com> Message-ID: James Stroud wrote: > Andy wrote: >> Hi, the file below will print all the keywords in a file and also the >> line # of the keyword. What I couldn't figure out is to count those >> keywords per line. For example - "Line #1 has 3 keywords" >> >> Can I do like - >> >> total[j] = total[j] + numwords(k) >> "Line number %d has %d keywords" % (j, total[j]) >> >> Seems sort of "illegal" in Python? >> >> >> >> ------------------------------------------------- >> import keyword, sys, string, fileinput >> def numwords(s): >> list = string.split(s) >> return len(list) >> >> # Get the file name either from the command-line or the user >> if len(sys.argv) != 2: >> name = raw_input("Enter the file name: ") >> else: >> name = sys.argv[1] >> >> inp = open(name,"r") >> linelist = inp.readlines() >> total, words,lines = 0, 0, 0 >> >> for i in range(len(linelist)): >> line = linelist[i] >> tempwords = line.split() >> for k in tempwords: >> if keyword.iskeyword(k): >> total = total + numwords(k) >> j = i + 1 >> print" The word * %s * belongs in line number: %d" % (k, >> j) >> >> print "Total keywords in this file are: %d" %(total) >> > > You probably want something that goes a little like this: > > for i,line in enumerate(linelist): > for k in line.split(): > if keyword.iskeyword(k): > total += line.count(k) > print "The word '%s' belongs in line num: %d" % (k, i+1) > > print "Total keyords are: %d" % total > > James Oops, that over-counts, I forgot to put a continue in. Also, keeping a cache of the split line will probably be faster. for i,line in enumerate(linelist): line = line.split() for k in line: if keyword.iskeyword(k): total += line.count(k) print "The word '%s' belongs in line num: %d" % (k, i+1) continue print "Total keyords are: %d" % total James From rdm at rcblue.com Sat Apr 7 13:35:14 2007 From: rdm at rcblue.com (Dick Moores) Date: Sat, 07 Apr 2007 10:35:14 -0700 Subject: Saving output of Turtle Graphics? In-Reply-To: References: Message-ID: <20070407173528.6FC7B1E4009@bag.python.org> At 09:31 AM 4/7/2007, =?ISO-8859-2?Q?Wojciech_Mu=B3a?= wrote: >Dick Moores wrote: > > What do I do to see this? > >For example Opera 9 and Firefox 1.5+ are able to view SVG files; >there is a free plugin for IrfanView. Ha. I had tried it with Firefox 2 already, but I stupidly changed the extension to HTM first. I'll also get the IrfanView plugin. Thanks for all the help, and especially for your canvasvg.py module. Dick From steve at holdenweb.com Thu Apr 12 09:21:48 2007 From: steve at holdenweb.com (Steve Holden) Date: Thu, 12 Apr 2007 09:21:48 -0400 Subject: tuples, index method, Python's design In-Reply-To: References: <1175953520.316208.241490@o5g2000hsb.googlegroups.com> <7xzm5igbrb.fsf@ruckus.brouhaha.com> <1176200361.260546.280510@n76g2000hsh.googlegroups.com> <740c3aec0704100824m132c45fbi5c4c3ec0c0fa3a67@mail.gmail.com> Message-ID: Antoon Pardon wrote: > On 2007-04-11, Terry Reedy wrote: >> "BJrn Lindqvist" wrote in message >> news:740c3aec0704100824m132c45fbi5c4c3ec0c0fa3a67 at mail.gmail.com... >> On 4/10/07, Steve Holden wrote: >>> One might perversely allow extension to lists and tuples to allow >>> >>> [3, 4] in [1, 2, 3, 4, 5, 6] >>> >>> to succeed, but that's forcing the use case beyond normal limits. >> I'd love to have that! There are at least one million use cases for >> finding a sequence in a sequence and implementing it yourself is >> non-trivial. Plus then both list and tuple's index methods would work >> *exactly* like string's. It would be easier to document and more >> useful. A big win. >> >> ======================= >> It would be ambiguous: [3,4] in [[1,2], [3,4], [5,6]] is True now. >> >> Strings are special in that s[i] can only be a (sub)string of length 1. >> 'b' in 'abc' is True. This makes looking for longer substrings easy. >> >> However, [2] in [1,2,3] is False. IE, list[i] is not normally a list. So >> looking for sublists is different from looking for items. > > Well I think this illustrates nicely what can happen if you design by > use cases. > > Let us assume for a moment that finding out if one list is a sublist of > a second list gets considered something usefull enough to be included > in Python. Now the in operator can't be used for this because it > would create ambiguities. So it would become either a new operator > or a new method. But whatever the solution it would be different > from the string solution. > That's because strings are different from other sequences. See below. > Now if someone would have thought about how "st1 in st2" would > generalize to other sequemce if st1 contained more than one > character they probably would have found the possible inconsistency > that could create and though about using an other way than using > the in-operator for this with strings. A way that wouldn't create > ambiguities when it was considered to be extended to other sequences. > The fact is that strings are the only sequences composed of subsequences of length 1 - in other words the only sequences where type(s) == type(s[0:1]) is an invariant condition. This was discussed (at my instigation, IIRC) on python-dev when Python (2.4?) adopted the enhanced semantics for "in" on strings - formerly only tests for single characters were allowed - but wasn't thought significant enough to deny what was felt to be a "natural" usage for strings only. 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 kyosohma at gmail.com Fri Apr 27 16:20:15 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: 27 Apr 2007 13:20:15 -0700 Subject: python and COM In-Reply-To: References: Message-ID: <1177705215.575207.169710@u32g2000prd.googlegroups.com> On Apr 27, 2:50 pm, Brian Blais wrote: > Hello, > > I am trying to communicate to a Reuters feed using Python, using a particular set of > libraries called the Adfin Real Time library. I have VB code, and am trying to port > it to python, and admit I really do not understand COM objects and being a Linux guy > mainly, I don't use VB at all. I've had some marginal success, but am coming up > empty when it comes to setting up callbacks. > > For example, this works: > > import win32com.client > import time > > symb='GOOG.O' > > mylist=win32com.client.Dispatch('AdfinXRTLib.AdxRtList') > > mylist.Source="IDN_RDF" > mylist.RegisterItems(symb,"ASK") > mylist.StartUpdates(4) # Mode Image > > while mylist.ItemStatus(symb): > pass > > for i in range(100): > m=mylist.Value(symb,"ASK") > print m > time.sleep(2) > > but to get it to automatically updated quotes, in VB they do something like > > #================ > Public Class Form1 > # Dimension a Public Real Time list object that is capable of handling events > # note from me: not sure what this line does really > Dim WithEvents AdxList As New AdfinXRTLib.AdxRTList > > Public Sub AdxList_OnUpdate( ) Handles AdxList.OnUpdate > > do stuff with the updated data > > End Sub > > Private Sub Button1_Click() > > do stuff with button click > End Sub > End Class > #================ > > It seems as if the important part is the "Handles AdxList.OnUpdate", which I assume > is basically saying "call me when AdxList.OnUpdate is called". I have no idea how to > get this to point to a python function, so I can make the AdxList.OnUpdate call > python code. > > Is there a tutorial somewhere about this stuff, or is there a proper place to ask > such questions? > > thanks, > > Brian Blais > > -- > ----------------- > > bbl... at bryant.edu > http://web.bryant.edu/~bblais I found some info on Python, VB, and COM. Check out the links below: http://vb2py.sourceforge.net/ http://mail.python.org/pipermail/python-list/2005-July/332502.html http://www.oreilly.com/catalog/pythonwin32/chapter/ch12.html http://mail.python.org/pipermail/melbourne-pug/2006-April/000132.html Not sure if those will help, but they might give you some food for thought. Mike From jackson at hotmail.com Fri Apr 20 12:48:07 2007 From: jackson at hotmail.com (Bill Jackson) Date: Fri, 20 Apr 2007 09:48:07 -0700 Subject: When to clear a dictionary... Message-ID: What is the benefit of clearing a dictionary, when you can just reassign it as empty? Similarly, suppose I generate a new dictionary b, and need to have it accessible from a. What is the best method, under which circumstances? >>> import some_function >>> a = {1:2,3:4} >>> b = {1:2:4:3} >>> a.clear() >>> a.update(b) >>> a = {1:2,3:4} >>> b = {1:2,4:3} >>> for key in b: ... a[key] = b[key] >>> a = {1:2,3:4} >>> b = {1:2,4:3} >>> a = b From miles.chris at gmail.com Wed Apr 25 19:32:13 2007 From: miles.chris at gmail.com (Chris Miles) Date: 25 Apr 2007 16:32:13 -0700 Subject: freeze and problem with static libraries In-Reply-To: <1177428217.892613.125750@u32g2000prd.googlegroups.com> References: <1177428217.892613.125750@u32g2000prd.googlegroups.com> Message-ID: <1177543932.922859.128260@t38g2000prd.googlegroups.com> What command are you using to "freeze" your source? On Apr 24, 4:23 pm, Flyzone wrote: > Hi, i need to "compile" a python source (2.3.6) to make it standalone > on Solaris 9. > I get this warning on freezing my source: > > "Warning: unknown modules remain: _locale _random _socket array > binascii cStringIO datetime fcntl math pwd select strop termios time" > > in the source i have: "import os, stat, re, datetime, time, glob" > and running the frozen application I get: "ImportError: No module > named datetime" From howe.steven at gmail.com Wed Apr 18 18:19:26 2007 From: howe.steven at gmail.com (Steven Howe) Date: Wed, 18 Apr 2007 15:19:26 -0700 Subject: comparison with None In-Reply-To: <3IqdnfRnCNWPC7vbnZ2dnUVZ_jqdnZ2d@rcn.net> References: <3IqdnfRnCNWPC7vbnZ2dnUVZ_jqdnZ2d@rcn.net> Message-ID: <4626996E.1090200@gmail.com> Alan G Isaac wrote: > >>> None >= 0 > False > >>> None <= 0 > True > > Explanation appreciated. > > Thanks, > Alan Isaac > I've read and found that 'None' comparisons is not always a good idea. Better to: from types import NoneType x = None if type( x ) == NoneType: # true < code > else: # false; do something else. < more code > Steven Howe From aljosa.mohorovic at gmail.com Wed Apr 18 09:30:51 2007 From: aljosa.mohorovic at gmail.com (Aljosa Mohorovic) Date: 18 Apr 2007 06:30:51 -0700 Subject: looking for library to read ppt files In-Reply-To: <1176756401.108945.230880@y5g2000hsa.googlegroups.com> References: <1176747406.722209.126900@w1g2000hsg.googlegroups.com> <1176756401.108945.230880@y5g2000hsa.googlegroups.com> Message-ID: <1176903051.777820.216750@n59g2000hsh.googlegroups.com> > > Not really a Python question but Google turned up: it is a python question. i'm not looking for a program, i'm looking for a library. my goal is to convert ppt to jpegs but later i wish to convert to swf and maybe implement animations > I suppose you could also use the win32 module and the COM object to > grab the info from the slide and then use the PIL module to create a > jpeg. Sounds like a lot of head banging to me, but it might be an > interesting project. i can't use win32 because it should work on linux since it will be used as server-side application. From jpiitula at ling.helsinki.fi Sun Apr 15 14:45:04 2007 From: jpiitula at ling.helsinki.fi (Jussi Piitulainen) Date: 15 Apr 2007 21:45:04 +0300 Subject: combination function in python References: <1176615838.830315.160210@b75g2000hsg.googlegroups.com> <1176629911.409257.149780@l77g2000hsb.googlegroups.com> <1176654363.696340.283330@d57g2000hsg.googlegroups.com> Message-ID: Mark Dickinson writes: > Jussi Piitulainen wrote: > > > def choose(n, k): > > if 0 <= k <= n: > > ntok = 1 > > ktok = 1 > > for t in xrange(1, min(k, n - k) + 1): > > ntok *= n > > ktok *= t > > n -= 1 > > return ntok // ktok > > else: > > return 0 > > It might be even better to do the divisions as you go, rather than > leaving them all to the end. That way the intermediate results > stay smaller. So (leaving out the bounds checking) one just does: > > def choose(n, k): > ntok = 1 > for t in xrange(min(k, n-k)): > ntok = ntok*(n-t)//(t+1) > return ntok Yes, that's what I once saw done. Thanks. Its correctness is more subtle, so I prefer to add the parentheses below to emphasise that the product has to be computed before the division. I also renamed the variable to p: it's no longer n^k (falling). And I put the bounds back in. def choose(n, k): if 0 <= k <= n: p = 1 for t in xrange(min(k, n - k)): p = (p * (n - t)) // (t + 1) return p else: return 0 From jgodoy at gmail.com Wed Apr 11 17:10:38 2007 From: jgodoy at gmail.com (Jorge Godoy) Date: Wed, 11 Apr 2007 18:10:38 -0300 Subject: About Trolltech QT OpenSource license. References: <1176233376.712861.67160@o5g2000hsb.googlegroups.com> <1176237050.409742.8760@30g2000cwc.googlegroups.com> <1176285062.178372.15090@d57g2000hsg.googlegroups.com> Message-ID: <878xcyaa7l.fsf@gmail.com> Robert Kern writes: > I don't recommend it. You are talking to their salesman, not your lawyer. You > are being given a sales pitch, not legal advice. On the other hand, he's stating Trolltech's policies and agreeing / disagreeing on your understanding of their license. He's selling you his product and stating how you can / can't use it. I believe that this has some value in case they say you can't do one thing that they told you could when you were acquiring their services. I'd save those emails exchanged very carefully. -- Jorge Godoy From turbana at gmail.com Fri Apr 27 17:25:54 2007 From: turbana at gmail.com (Ian Clark) Date: Fri, 27 Apr 2007 14:25:54 -0700 Subject: creating an object from base class In-Reply-To: <1177677510.209111.148540@u32g2000prd.googlegroups.com> References: <1177677510.209111.148540@u32g2000prd.googlegroups.com> Message-ID: Quote iogilvy: > i wish to have some extended functionality added to sockets > > i can create my own socket class class mysocket(socket.socket): > > and all should be fine. Except, the sockets are created for me by the > accept method, listening on port. So how can i take the standard > socket created for me and create a 'mysocket'. I need a method that > will initialise any new properties i have added in my class, but how > can i change the class of the socket created? > Someone correct me if I'm wrong, but I don't believe it's possible to change the type of objects made from builtin classes. Though if it's a custom class you can, for example: >>> class Foo: pass >>> class Bar: pass >>> obj = Foo() >>> obj.__class__ = Bar One option is to make your custom socket a wrapper around socket.socket and then pass through the calls you don't want to handle to socket.socket. The downside to this is there are quite a lot of methods that need to be accounted for. For example: >>> class CustomSocket: >>> def __init__(self, socket): >>> self.socket = socket >>> def connect(self, address): >>> self.socket.connect( address + '.some.tld' ) >>> [etc] >>> >>> ... >>> >>> s = server_socket.accept() >>> s = CustomSocket(s) Another approach you might want to look at is populating your object at runtime through a function. This won't give it the type you want, but it will give it any methods and attributes it would have gotten from your class with the added benefit of it still being of type socket.socket. Example: >>> def modify_socket( socket ): >>> socket.cabbages = 'Yuk' >>> socket.apples = 'Yum' >>> >>> def info(): >>> print 'Cabbages? %s\nApples? %s' % (socket.cabbages, socket.apples) >>> obj.show_info = info >>> >>> ... >>> >>> s = server_socket.accept() >>> modify_socket( s ) >>> s.show_info() Cabbages? Yuk Apples? Yum >>> s.apples = 'Yummie' >>> s.show_info() Cabbages? Yuk Apples? Yummie >>> type(s) Good luck. Ian From mccredie at gmail.com Tue Apr 3 15:42:50 2007 From: mccredie at gmail.com (Matimus) Date: 3 Apr 2007 12:42:50 -0700 Subject: how to remove multiple occurrences of a string within a list? In-Reply-To: <1175627593.307674.11280@w1g2000hsg.googlegroups.com> References: <1175624433.206953.214290@n59g2000hsh.googlegroups.com> <1175625098.269660.184790@o5g2000hsb.googlegroups.com> <1175627593.307674.11280@w1g2000hsg.googlegroups.com> Message-ID: <1175629369.996644.119940@n59g2000hsh.googlegroups.com> On Apr 3, 12:13 pm, "bahoo" wrote: > On Apr 3, 2:31 pm, "Matimus" wrote: > > > It depends on your application, but a 'set' might really be what you > > want, as opposed to a list. > > > >>> s = set(["0024","haha","0024"]) > > >>> s > > > set(["0024","haha"])>>> s.remove("0024") > > >>> s > > > set(["haha"]) > > This sounds cool. > But is there a command I can convert the "set" back to a "list"? yeah... >>> l = list(s) >>> l ["haha"] From mark.m.mcmahon at gmail.com Tue Apr 10 13:38:37 2007 From: mark.m.mcmahon at gmail.com (Mark Mc Mahon) Date: Tue, 10 Apr 2007 13:38:37 -0400 Subject: ANN: pywinauto 0.3.7 now released Message-ID: <71b6302c0704101038x7653d08ax5dd237a731e36c4d@mail.gmail.com> Hi, 0.3.7 release of pywinauto is now available. pywinauto is an open-source (LGPL) package for using Python as a GUI automation 'driver' for Windows NT based Operating Systems (NT/W2K/XP/Vista?). SourceForge project page: http://sourceforge.net/projects/pywinauto Download from SourceForge http://sourceforge.net/project/showfiles.php?group_id=157379 Here is the list of changes from the previous release (0.3.6): 0.3.7 Merge of Wait changes and various bug fixes/improvements ------------------------------------------------------------------ 10-April-2007 * Added Timings.WaitUntil() and Timings.WaitUntilPasses() which handle the various wait until something in the code. Also refactored existing waits to use these two methods. * Fixed a major Handle leak in RemoteMemorBlock class (which is used extensively for 'Common' controls. I was using OpenHandle to open the process handle, but was not calling CloseHandle() for each corresponding OpenHandle(). * Added an active_() method to Application class to return the active window of the application. * Added an 'active' option to WindowSpecification.Wait() and WaitNot(). * Some cleanup of the clipboard module. GetFormatName() was improved and GetData() made a little more robust. * Added an option to findwindows.find_windows() to find only active windows (e.g. active_only = True). Default is False. * Fixed a bug in the timings.Timings class - timing values are Now accessed through the class (Timings) and not through the intance (self). * Updated ElementTree import in XMLHelpers so that it would work on Python 2.5 (where elementtree is a standard module) as well as other versions where ElementTree is a separate module. * Enhanced Item selection for ListViews, TreeViews - it is now possible to pass strings and they will be searched for. More documentation is required though. * Greatly enhanced Toolbar button clicking, selection, etc. Though more documentation is required. * Added option to ClickInput() to allow mouse wheel movements to be made. * menuwrapper.Menu.GetProperties() now returns a dict like all other GetProperties() methods. This dict for now only has one key 'MenuItems' which contains the list of menuitems (which had been the previous return value). Thanks Mark -------------------------------------------- Mark Mc Mahon Manchester, NH 03110, USA

pywinauto 0.3.7 Simple Windows GUI automation with Python. (10-Apr-07) From gbastian at pasteur.fr Sat Apr 14 03:49:32 2007 From: gbastian at pasteur.fr (gbastian at pasteur.fr) Date: Sat, 14 Apr 2007 09:49:32 +0200 (CEST) Subject: Stdout Message-ID: <33234.157.99.64.103.1176536972.squirrel@157.99.64.103> Dear Users, I am trying to recover through the python function popen3 the stdout,in,err of a launched process. I would like also to recover the stdout which you can get only through the command: command1 >& filename Do you know how I can access to that stdout by python? Thanks GIacomo From marteljuvetc at yahoo.ca Fri Apr 20 02:15:42 2007 From: marteljuvetc at yahoo.ca (chachou martel juvet) Date: Fri, 20 Apr 2007 02:15:42 -0400 (EDT) Subject: Can I place a question on the mailing list Message-ID: <337251.8564.qm@web51711.mail.re2.yahoo.com> Good Morning Dear Sir , I will like you allowing me to place question on the web. Kind Regards: Martel. --------------------------------- All new Yahoo! Mail - --------------------------------- Get a sneak peak at messages with a handy reading pane. -------------- next part -------------- An HTML attachment was scrubbed... URL: From cam.ac.uk at mh391.invalid Sun Apr 29 06:46:05 2007 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Sun, 29 Apr 2007 11:46:05 +0100 Subject: While we're talking about annoyances In-Reply-To: <1177837565.317999.244420@c35g2000hsg.googlegroups.com> References: <1177837565.317999.244420@c35g2000hsg.googlegroups.com> Message-ID: GHUM wrote: > Steven, > >> def index(sequence): >> decorated = zip(sequence, xrange(len(sequence))) >> decorated.sort() >> return [idx for (value, idx) in decorated] > > would'nt that be equivalent code? > > def index(sequence): > return [c for _,c in sorted((b,a) for a, b in > enumerate(sequence))] Or even these: def index(sequence): return sorted(range(len(sequence)), key=sequence.__getitem__) def rank(sequence): return sorted(range(len(sequence)), key=index(sequence).__getitem__) Hint: if you find yourself using a decorate-sort-undecorate pattern, sorted(key=func) or sequence.sort(key=func) might be a better idea. -- Michael Hoffman From jmazzonelli at gmail.com Sun Apr 29 15:03:53 2007 From: jmazzonelli at gmail.com (Jorge Mazzonelli) Date: Sun, 29 Apr 2007 16:03:53 -0300 Subject: Python ODBC In-Reply-To: <1177864453.282136.233030@n59g2000hsh.googlegroups.com> References: <1177864453.282136.233030@n59g2000hsh.googlegroups.com> Message-ID: <138a70320704291203r54d1a549jb44d9b3b9114a93f@mail.gmail.com> For ODBC connections you can try pyODBC. I didn't test it on Linux but it is said it works on both Windows and POSIX systems. pyODBC--> pyodbc.sourceforge.net The license is MIT License. You can also have a look here: http://sparcs.kaist.ac.kr/~tinuviel/python/database.html since it has various links on python interfaces to several databases including DB2. It contains also links to other ODBC packages for python. Jorge On 29 Apr 2007 09:34:13 -0700, Harlin Seritt wrote: > > Is there a Python odbc module that will work on Linux? I have a jdbc > connection to a DB2 server. I am looking hopefully for an open source > solution and not a commercial one. > > Thanks, > > Harlin > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From irstas at gmail.com Tue Apr 3 12:10:40 2007 From: irstas at gmail.com (irstas at gmail.com) Date: 3 Apr 2007 09:10:40 -0700 Subject: Stack experiment In-Reply-To: <5QuQh.152$9L1.108@read3.inet.fi> References: <5QuQh.152$9L1.108@read3.inet.fi> Message-ID: <1175616640.005706.152140@n76g2000hsh.googlegroups.com> tom at finland.com wrote: > Hi! Im new to Python and doing exercise found from internet. It is > supposed to evaluate expression given with postfix operator using > Stack() class. > > class Stack: > def __init__(self): > self.items = [] > > def push(self, item): > self.items.append(item) > > def pop(self): > return self.items.pop() > > def isEmpty(self): > return (self.items == []) > > def evaluatePostfix(expr): > import re > tokenList = re.split(" ([^0-9])", expr) > stack = Stack() > for token in tokenList: > if token == '' or token == ' ': > continue > if token == '+': > sum = stack.pop() + stack.pop() > stack.push(sum) > elif token == '*': > product = stack.pop() * stack.pop() > stack.push(product) > else: > stack.push(int(token)) > return stack.pop() > > print evaluatePostfix("56 47 + 2 *") > > Errormsg: > Traceback (most recent call last): > File "C:\*\postfix1.py", line 31, in > print evaluatePostfix("56 47 + 2 *") > File "C:\*\postfix1.py", line 28, in evaluatePostfix > stack.push(int(token)) > ValueError: invalid literal for int() with base 10: '56 47' > > How can I avoid the error and get desired result? Obviously your tokens are wrong since one of the tokens is '56 47' as the error message indicates. import re print re.split(" ([^0-9])", "56 47 + 2 *") It looks like you'd just want expr.split(). From matthewperpick at gmail.com Mon Apr 16 20:56:05 2007 From: matthewperpick at gmail.com (matthewperpick) Date: 16 Apr 2007 17:56:05 -0700 Subject: strange behaviour with keyword arguments and inheritance Message-ID: <1176771364.964642.209300@b75g2000hsg.googlegroups.com> Check out this toy example that demonstrates some "strange" behaviour with keyword arguments and inheritance. ================================= class Parent: def __init__(self, ary = []): self.ary = ary def append(self): self.ary.append(1) class Child(Parent): def __init__(self): Parent.__init__(self) self.append() def main(): a = Child() print a.ary b = Child() print b.ary main() ===================================== You would think the output of this program would be [1], [1]. But strangely enough the output is [1,], [1,1]. I suppose that the Parent.__class__ object is only created once and thus the keyword argument always refers to the same thing, but I don't know. I have a very rudimentary understading of python's guts, but I would still call the behaviour unexpected. Or perhaps I should rtfm? Any thoughts would be much appreciated. Thanks. From manuel.graune at koeln.de Sat Apr 7 16:52:06 2007 From: manuel.graune at koeln.de (Manuel Graune) Date: Sat, 07 Apr 2007 22:52:06 +0200 Subject: Objects, lists and assigning values References: <1175848886.065401.269260@w1g2000hsg.googlegroups.com> Message-ID: "7stud" writes: > > What book are you reading? > I worked my way through most of the online-docs. A bit to casual obviously. As printed desktop-reference I use a german book called "Python ge-packt". -- A hundred men did the rational thing. The sum of those rational choices was called panic. Neal Stephenson -- System of the world http://www.graune.org/GnuPG_pubkey.asc Key fingerprint = 1E44 9CBD DEE4 9E07 5E0A 5828 5476 7E92 2DB4 3C99 From hq4ever at gmail.com Thu Apr 12 16:17:07 2007 From: hq4ever at gmail.com (Maxim Veksler) Date: Thu, 12 Apr 2007 23:17:07 +0300 Subject: ulimit on open sockets ? In-Reply-To: <1hwbp5h.1fnai9snzd1vpN%aleax@mac.com> References: <1hwbp5h.1fnai9snzd1vpN%aleax@mac.com> Message-ID: On 4/10/07, Alex Martelli wrote: > Maxim Veksler wrote: > > > ValueError: filedescriptor out of range in select() > > """ > > > > Should I be using a different version of select or something? Or > > select typically supports 1024 FDs at most (a design limit of the > underlying operating system). You may want to try poll instead (epoll > might be better but I doubt Python supports it yet). > I've read some post the other day of a guy faced similar problem and it turns out {e,}poll is limited as well, besides I don't know how to use it so an example would be great. Now, someone I work with suggested a simple work around "Pass the list objects in groups of 1024 each time to the select.select structure". I think it's acceptable and good advice, the thing is I don't know how to implement this "the python way" (that is - with out it being ugly). Can I do modulation ( % 1024 ) on the main iterator loop? Something like: for nb_active_socket in (all_sockets % 1024): if nb_active_socket in ready_to_read: conn, addr = nb_active_socket.accept() while 1: data = conn.recv(1024) if not data: break conn.send(data) conn.close() ? Thanks for helping, Maxim. > > Alex > -- > http://mail.python.org/mailman/listinfo/python-list > -- Cheers, Maxim Veksler "Free as in Freedom" - Do u GNU ? From kyosohma at gmail.com Fri Apr 27 12:14:04 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: 27 Apr 2007 09:14:04 -0700 Subject: Accessing SQL View with Python In-Reply-To: References: <1177687490.404875.170650@s33g2000prh.googlegroups.com> Message-ID: <1177690444.149409.318620@s33g2000prh.googlegroups.com> On Apr 27, 10:29 am, Tim Golden wrote: > kyoso... at gmail.com wrote: > > Hi All, > > > I need to access a Microsoft SQL database View. Is there a way to do > > this with Python? I have done a fair share of "googling" and found > > nothing on accessing Views, just executing SQL, which I already know > > how to do. > > > I am running Windows XP, Python 2.4. > > Absolutely loads of ways. But (unless I'm missing > something here) they all involve executing SQL > which accesses a View (such as: SELECT * FROM v_info). > Have I missed the point of your question? > > TJG I figured there was. And yes, I knew you'd need to use SQL to get at the View. I just re-ran it and discovered that I am quite good at typos. I corrected the SQL and it seems to be working now. Thanks for the help. Mike From trevis.crane at gmail.com Tue Apr 24 11:53:15 2007 From: trevis.crane at gmail.com (T.Crane) Date: 24 Apr 2007 08:53:15 -0700 Subject: need help with ODE solver from scipy Message-ID: <1177429991.613640.243170@c18g2000prb.googlegroups.com> Hi, OK, I'm trying to figure out how to use the ODE solver (scipy.integrate.ode.ode). Here's what I'm doing (in iPython) y0 = [0,1,1] dt = 0.01 tEnd = 12 t0 = 0 Y = zeros([tEnd/dt, 3]) As an aside, I've used this assignment for Y in the past and it worked. When I tried it this morning I got a TypeError and a message saying I needed to use an integer. So, instead... Y = zeros([int(tEnd/dt), 3]) T = zero([int(tEnd/dt)]) index = 0 def foo(t,y): dy = zeros([3]) dy[0] = y[1]*y[2] dy[1] = -y[0]*y[2] dy[2] = -0.51*y[0]*y[1] return dy r = ode(foo).set_integrator('vode').set_initial_value(y0,t0) while r.successful() and r.t < tEnd: r.integrate(r.t+dt) Y[index] = r.y T[index] = r.t index += 1 As a further aside, this system of three coupled linear ODE's is from an example in MATLAB's documentation on their function ode45, so I know what I 'should' get. The while loop and call to ode is adapted from scipy's (very limited) documentation on scipy.integrate.ode.ode. At the end of this while loop I've gotten a few different results depending on what I have no idea. This morning another TypeError exception was thrown, saying: TypeError: Array can not be safely cast to required type. Although, to be fair this is after the output from one iteration: array([0.01, 1. , 1. ]) So, clearly this isn't working right. Does anyone have any experience using this function or anything they can contribute? thanks, trevis From steve at holdenweb.com Thu Apr 19 13:52:18 2007 From: steve at holdenweb.com (Steve Holden) Date: Thu, 19 Apr 2007 13:52:18 -0400 Subject: PythonD 2.4.2 for older Windows / DOS / DJGPP In-Reply-To: <46279af8$0$4610$61c65585@un-2park-reader-01.sydney.pipenetworks.com.au> References: <46279af8$0$4610$61c65585@un-2park-reader-01.sydney.pipenetworks.com.au> Message-ID: caddit wrote: > Hello. > > There has been some confusion as to the current version of the python > programming language available for DOS. > > This is partially due to incorrect information kept on python.org, that says > "python2.2.1 available for DOS". The actual version is currently 2.4.2. > > I am also happy to announce that a second release of PythonD. Additionally, > there are many fine module libraries hat have been made available including > Python-opengl and curses. > > The URL for PythonD has moved. > It is now http://www.caddit.net/pythond > > not that this is NOT the same as http://www.caddit.net/pythond.php, which it > was formerly. Please update your bookmarks. It would also be nice if > someone else could raise a ticket to have python.org website updated. > Submitted as http://pydotorg.python.org/pydotorg/ticket/423 Please note: it would have been helpful if you'd given the URL of the offending page! There is a "report website bug" link on each page of the python.org web site, though at present you have to email someone to get posting privileges (this is an anti-spam measure). 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 mad.vijay at gmail.com Thu Apr 12 06:23:43 2007 From: mad.vijay at gmail.com (SamG) Date: 12 Apr 2007 03:23:43 -0700 Subject: redirecting stdout to a file as well as screen In-Reply-To: References: <1176362072.527678.201150@l77g2000hsb.googlegroups.com> <1176368478.301318.35210@q75g2000hsh.googlegroups.com> Message-ID: <1176373423.576445.123220@y5g2000hsa.googlegroups.com> On Apr 12, 3:16 pm, "Gabriel Genellina" wrote: > En Thu, 12 Apr 2007 06:01:18 -0300, SamG escribi?: > > > > > On Apr 12, 1:00 pm, "Gabriel Genellina" > > wrote: > >> En Thu, 12 Apr 2007 04:14:32 -0300, SamG escribi?: > > >> > How could i make, from inside the program, to have the stdout and > >> > stderr to be printed both to a file as well the terminal(as usual). > > >> class Tee(file): > >> others = () > > >> def write(self, data): > >> file.write(self, data) > >> for f in others: > >> f.write(data) > > > This is only creating an out.log file and all the stdout and stderr > > are logged there. > > Sorry, `for f in others:` should read `for f in self.others:` > > -- > Gabriel Genellina Does not make difference, does this work for you? Im working on linux. But this code looks portable except for the file path :) From sgeiger at ncee.net Mon Apr 16 15:42:29 2007 From: sgeiger at ncee.net (Shane Geiger) Date: Mon, 16 Apr 2007 14:42:29 -0500 Subject: script for seconds in given month? In-Reply-To: <17955.45029.946528.711138@montanaro.dyndns.org> References: <1176740556.859125.221980@l77g2000hsb.googlegroups.com> <1176742604.907208.310290@l77g2000hsb.googlegroups.com> <17955.45029.946528.711138@montanaro.dyndns.org> Message-ID: <4623D1A5.4020902@ncee.net> import datetime def first_day_of_next_month( year, month ): """returns the first day of the next month >>> first_day_of_next_month(2007,5) datetime.datetime(2007, 6, 1, 0, 0) >>> first_day_of_next_month(2007,12) datetime.datetime(2008, 1, 1, 0, 0) """ oneday = datetime.timedelta(days=1) day = datetime.datetime(year, month, 1) if day.day == 1: day += oneday while day.day != 1: day += oneday return day from time import mktime def secondsInMonth(year, month): s1 = mktime((year,month,1,0,0,0,0,0,-1)) day = first_day_of_next_month(year, month) year = day.year month = day.month s2 = mktime((year,month+1,1,0,0,0,0,0,-1)) return s2-s1 year = 2007 month = 2 print secondsInMonth(year, month) skip at pobox.com wrote: > Matt> from time import mktime > Matt> def secondsInMonth(year, month): > Matt> s1 = mktime((year,month,1,0,0,0,0,0,-1)) > Matt> s2 = mktime((year,month+1,1,0,0,0,0,0,-1)) > Matt> return s2-s1 > > Probably won't work if month==12. ;-) > > Skip > -- 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 aleax at mac.com Sun Apr 15 01:02:47 2007 From: aleax at mac.com (Alex Martelli) Date: Sat, 14 Apr 2007 22:02:47 -0700 Subject: Python Feature Request: Allow changing base of member indices to 1 References: <1176546465.632410.52630@w1g2000hsg.googlegroups.com> <4620b47b$0$14410$9b622d9e@news.freenet.de> <1176557999.665663.299740@y80g2000hsf.googlegroups.com> <1176559643.450533.296850@n59g2000hsh.googlegroups.com> <1176608086.323323.154260@d57g2000hsg.googlegroups.com> Message-ID: <1hwkyis.1gd589j191njikN%aleax@mac.com> Steven D'Aprano wrote: > On Sat, 14 Apr 2007 20:34:46 -0700, Dan Bishop wrote: > > > On Apr 14, 10:55 am, Dennis Lee Bieber wrote: > > > >> The FORTRAN family had started as 1-based (F95, and Ada, now allow > >> for each array to have its own "base" => x : array (-10..10) of float). > >> Pascal, I forget... > > > > Pascal allows arbitrary array bases. It's where Ada got the idea. > > It does? Since when? Ever since Pascal existed, the syntax has been "array[lower..upper] of sometype" -- no default value for lower (neither 0 nor 1 nor other). Alex From steve at holdenweb.com Sat Apr 28 11:35:44 2007 From: steve at holdenweb.com (Steve Holden) Date: Sat, 28 Apr 2007 11:35:44 -0400 Subject: creating an object from base class In-Reply-To: References: <1177677510.209111.148540@u32g2000prd.googlegroups.com> Message-ID: Ian Clark wrote: > Quote iogilvy: >> i wish to have some extended functionality added to sockets >> >> i can create my own socket class class mysocket(socket.socket): >> >> and all should be fine. Except, the sockets are created for me by the >> accept method, listening on port. So how can i take the standard >> socket created for me and create a 'mysocket'. I need a method that >> will initialise any new properties i have added in my class, but how >> can i change the class of the socket created? >> > > Someone correct me if I'm wrong, but I don't believe it's possible to > change the type of objects made from builtin classes. Though if it's a > custom class you can, for example: > >>>> class Foo: pass >>>> class Bar: pass >>>> obj = Foo() >>>> obj.__class__ = Bar > > Yes, assuming you weren't asking a rhetorical question you will eventually run up against >>> class myClass1(object): pass ... >>> class myClass2(object): pass ... >>> mc1 = myClass1() >>> type(mc1) >>> mc1.__class__ = myClass2 >>> type(mc1) >>> 2 . __class__ = myClass1 Traceback (most recent call last): File "", line 1, in TypeError: __class__ assignment: only for heap types >>> This doesn't qualify as error message of the year, but it clearly tells you you aren't going to get around the prohibition. We also see >>> o = object >>> o.__class__ = myClass2 Traceback (most recent call last): File "", line 1, in TypeError: can't set attributes of built-in/extension type 'object' >>> which gives a much better error message. Of course it'll probably only take Alex Martelli a few minutes to find a workaround or counter-example. > One option is to make your custom socket a wrapper around > socket.socket and then pass through the calls you don't want to handle > to socket.socket. The downside to this is there are quite a lot of > methods that need to be accounted for. For example: > >>>> class CustomSocket: >>>> def __init__(self, socket): >>>> self.socket = socket >>>> def connect(self, address): >>>> self.socket.connect( address + '.some.tld' ) >>>> [etc] >>>> >>>> ... >>>> >>>> s = server_socket.accept() >>>> s = CustomSocket(s) > This technique is formally called "delegation" if you want to Google it. > > Another approach you might want to look at is populating your object > at runtime through a function. This won't give it the type you want, > but it will give it any methods and attributes it would have gotten > from your class with the added benefit of it still being of type > socket.socket. Example: > >>>> def modify_socket( socket ): >>>> socket.cabbages = 'Yuk' >>>> socket.apples = 'Yum' >>>> >>>> def info(): >>>> print 'Cabbages? %s\nApples? %s' % (socket.cabbages, socket.apples) >>>> obj.show_info = info >>>> >>>> ... >>>> >>>> s = server_socket.accept() >>>> modify_socket( s ) >>>> s.show_info() > Cabbages? Yuk > Apples? Yum >>>> s.apples = 'Yummie' >>>> s.show_info() > Cabbages? Yuk > Apples? Yummie >>>> type(s) > > Of course that approach sucks if sockets happen to have an organes or apples attribute that's used in the inner workings of the class. This is when the C++ devotees start screaming about protected and private variables. Just ignore them :-) [Note: these remarks are more for the OP than Ian] regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Skype: holdenweb http://del.icio.us/steve.holden ------------------ Asciimercial --------------------- Get Python in your .sig and on the web. Blog and lens holdenweb.blogspot.com squidoo.com/pythonology tag items: del.icio.us/steve.holden/python All these services currently offer free registration! -------------- Thank You for Reading ---------------- From kyosohma at gmail.com Thu Apr 5 14:42:51 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: 5 Apr 2007 11:42:51 -0700 Subject: defining functions In-Reply-To: <1175798327.249407.129860@o5g2000hsb.googlegroups.com> References: <1175798327.249407.129860@o5g2000hsb.googlegroups.com> Message-ID: <1175798571.350406.290230@y80g2000hsf.googlegroups.com> On Apr 5, 1:38 pm, "Andre P.S Duarte" wrote: > How do I define a function, then import it, without having to save it > in lib; like "C:\python25\lib". ? Defining a function: def someFunc(): # do something here Save the file some place. Import the sys module BEFORE you import your module. Then enter the following code: sys.path.append(r'path\to\yourFile.py') Now import your python module. This will temporarily add that path to the python path (or is it system path?) for the amount of time it takes to execute your script. Mike From gdonald at gmail.com Fri Apr 6 13:15:22 2007 From: gdonald at gmail.com (Greg Donald) Date: Fri, 6 Apr 2007 12:15:22 -0500 Subject: Why NOT only one class per file? In-Reply-To: References: <1175721799.714907.52770@o5g2000hsb.googlegroups.com> Message-ID: <15e66e4e0704061015k700f2a39o16b7acf12c1827ac@mail.gmail.com> On 4/6/07, Dennis Lee Bieber wrote: > For one liners, wouldn't > > ECHO the text line >the.file > > be more appropriate? # dd if=/dev/tty of=/dev/hda1 -- Greg Donald http://destiney.com/ From nate.finch at gmail.com Thu Apr 5 15:25:06 2007 From: nate.finch at gmail.com (Nate Finch) Date: 5 Apr 2007 12:25:06 -0700 Subject: Why NOT only one class per file? In-Reply-To: <46150c0f$0$3184$426a74cc@news.free.fr> References: <1175721799.714907.52770@o5g2000hsb.googlegroups.com> <46142acc$0$7532$426a34cc@news.free.fr> <4614b40e$0$26843$426a74cc@news.free.fr> <1175778276.603838.86500@l77g2000hsb.googlegroups.com> <46150c0f$0$3184$426a74cc@news.free.fr> Message-ID: <1175801106.797489.85730@l77g2000hsb.googlegroups.com> On Apr 5, 10:48 am, Bruno Desthuilliers wrote: > Nate Finch a ?crit : > > > So, here's a view from a guy who's not a python nut and has a long > > history of professional programming in other languages (C++, C, C#, > > Java) > > There are quite a few professional programmers here with experience on > medium to large to huge projects with different languages, you know. Sorry, I meant to go back and edit that phrase to sound less condescending. I know there are a lot of professional programmers on here, and I didn't mean to imply otherwise. It wasn't supposed to be a contrast to everyone, just introducing myself. I totally agree with you... there's a balance between too many files and files that are too large. As to the guy who writes 1000+ line classes .... dude, refactor some. You're trying to make the class do too much, almost by definition. We have *some* classes that big, and they're marked as "needs refactor". It's certainly not a common occurance, though. Usually they're UI classes, since they require a lot of verbose positioning of elements and hooking of events. And while people are reading this thread, let me plug my other thread, asking about absolute_import. I'd really love some help :) -Nate From chuancs at gmail.com Sat Apr 14 08:35:39 2007 From: chuancs at gmail.com (chuancs) Date: 14 Apr 2007 05:35:39 -0700 Subject: visit http://www.real-article.com/computer/index.php Message-ID: <1176554139.123356.181010@y5g2000hsa.googlegroups.com> The www.real-article.com website provides a ton of information about computer. In addition, you will find extensive information on leading computer to help you on your way to success. Please have a look at our computer articles, products, resources, and additional information located throughout www.real-article.com. We strive to provide only quality articles, so if there is a specific topic related to computer that you would like us to cover, please contact us at any time. visit http://www.real-article.com/computer/index.php From skip at pobox.com Tue Apr 10 15:01:26 2007 From: skip at pobox.com (skip at pobox.com) Date: Tue, 10 Apr 2007 14:01:26 -0500 Subject: Problems with curses.start_color() Message-ID: <17947.57094.921817.664598@montanaro.dyndns.org> Environment: Solaris 10, Python 2.4.2. I'm trying to convert a very simple (display-wise) program to use curses. This is my first try at using curses. I have wrapped my main: try: sys.exit(curses.wrapper(main, *sys.argv[1:])) except (KeyboardInterrupt, SystemExit): sys.exit(0) According to the docs, curses.wrapper() calls curses.start_color(), but if I don't call it myself I get this traceback when I try to use colors: Traceback (most recent call last): File "snake/scripts/message-tracker.py", line 141, in display attr = curses.color_pair(0) error: must call start_color() first If I call start_color() unconditionally I get this error: Traceback (most recent call last): File "snake/scripts/message-tracker.py", line 229, in ? sys.exit(curses.wrapper(main, *sys.argv[1:])) File "/opt/app/g++lib6/python-2.4/lib/python2.4/curses/wrapper.py", line 44, in wrapper return func(stdscr, *args, **kwds) File "snake/scripts/message-tracker.py", line 215, in main curses.start_color() File "/opt/app/g++lib6/python-2.4/lib/python2.4/curses/__init__.py", line 41, in start_color retval = _curses.start_color() error: start_color() returned ERR If I protect the call like so: try: curses.start_color() except: pass I get the first traceback again. A quick Google search didn't turn this up as an obvious problem. What have I missed? Thx, Skip From aleax at mac.com Mon Apr 2 01:04:12 2007 From: aleax at mac.com (Alex Martelli) Date: Sun, 1 Apr 2007 22:04:12 -0700 Subject: can a method access/set another's variables? References: <1175477764.549115.159410@n59g2000hsh.googlegroups.com> Message-ID: <1hvwvwk.jled8buiciriN%aleax@mac.com> asdf1234234 wrote: > My code is: > -a.py- > import b > > class A: > def __init__(self): > pass Incidentally, these last two lines are totally, utterly useless. Do NOT define special methods like this -- just omit the whole def statement and you'll have identical semantics, no wasted boilerplate, even better performance. Alex From jstroud at mbi.ucla.edu Sat Apr 7 03:50:09 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Sat, 07 Apr 2007 07:50:09 GMT Subject: block scope? In-Reply-To: <7xtzvseqzo.fsf@ruckus.brouhaha.com> References: <7xr6qwal50.fsf@ruckus.brouhaha.com> <7xtzvseqzo.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > John Nagle writes: >> In a language with few declarations, it's probably best not to >> have too many different nested scopes. Python has a reasonable >> compromise in this area. Functions and classes have a scope, but >> "if" and "for" do not. That works adequately. > > I think Perl did this pretty good. If you say "my $i" that declares > $i to have block scope, and it's considered good practice to do this, > but it's not required. You can say "for (my $i=0; $i < 5; $i++) { ... }" > and that gives $i the same scope as the for loop. Come to think of it > you can do something similar in C++. How then might one define a block? All lines at the same indent level and the lines nested within those lines? i = 5 for my i in xrange(4): if i: # skips first when i is 0 my i = 100 if i: print i # of course 100 break print i # i is between 0 & 3 here print i # i is 5 here Doesn't leave a particularly bad taste in one's mouth, I guess (except for the intended abuse). James From marcpp at gmail.com Tue Apr 24 03:54:38 2007 From: marcpp at gmail.com (Marcpp) Date: 24 Apr 2007 00:54:38 -0700 Subject: PYQT 3 communication with 2 windows In-Reply-To: <8f570$46295e4f$54d1d767$4261@news.chello.no> References: <1177015090.289961.306590@o5g2000hsb.googlegroups.com> <8f570$46295e4f$54d1d767$4261@news.chello.no> Message-ID: <1177401278.102811.104540@o40g2000prh.googlegroups.com> On 21 abr, 02:43, David Boddie wrote: > On Thursday 19 April 2007 22:38, Marcpp wrote: > > > Hi, I'm introducing to program in python + pyqt. > > I have a main window that call a second window (to introduce a info > > with textedit) > > when press the second window button I need to return to the main > > window the info > > introduced in the second window. > > I've seek in the pyqt doc examples but i don't find it. > > Have you any example? > > You could connect the button to a slot in the second window that sends > the text back to the first window. > > Here's an example that sends the text to a function. You could substitute a > class for the function to get what you want. > > import sys > from qt import * > > class Window(QWidget): > > def __init__(self, parent = None): > > QWidget.__init__(self, parent) > > self.textEdit = QTextEdit(self) > okButton = QPushButton(self.tr("&OK"), self) > self.connect(okButton, SIGNAL("clicked()"), self.sendText) > layout = QVBoxLayout(self) > layout.addWidget(self.textEdit) > layout.addWidget(okButton) > > def sendText(self): > > self.emit(PYSIGNAL("textEntered(QString)"), (self.textEdit.text(),)) > > def fn(text): > > print text > > if __name__ == "__main__": > > app = QApplication(sys.argv) > window = Window() > window.connect(window, PYSIGNAL("textEntered(QString)"), fn) > window.show() > app.setMainWidget(window) > sys.exit(app.exec_loop()) > > Note the use of PYSIGNAL() instead of SIGNAL(). With PyQt4 you would be able > to use SIGNAL() and write the emit() call in a simpler form. > > David Thankyou!!! This is that I want. From bdesth.quelquechose at free.quelquepart.fr Thu Apr 5 19:52:12 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Fri, 06 Apr 2007 01:52:12 +0200 Subject: RFC: Assignment as expression (pre-PEP) In-Reply-To: <1175802680.021987.39220@p77g2000hsh.googlegroups.com> References: <1175802680.021987.39220@p77g2000hsh.googlegroups.com> Message-ID: <461582b7$0$7529$426a74cc@news.free.fr> TimeHorse at gmail.com a ?crit : > I would like to gauge interest in the following proposal: > > Problem: > > Assignment statements cannot be used as expressions. This is by design. > Performing a list of mutually exclusive checks that require data > processing can cause excessive tabification. For example, consider > the following python snipet... > > temp = my_re1.match(exp) > if temp: > # do something with temp > else: > temp = my_re2.match(exp) > if temp: > # do something with temp > else: > temp = my_re3.match(exp) > if temp: > # do something with temp > else: > temp = my_re4.match(exp) OMG. actions = [ (my_re1, do_something_with_temp1), (my_re2, do_something_with_temp2), (my_re3, do_something_with_temp3), (my_re4, do_something_with_temp4), ] for my_re, do_something_with in actions: temp = my_re.match(exp): if temp: do_something_with(temp) break Having full-blown anonymous functions or Ruby/Smalltalk-like code blocks would be much more interesting IMHO. From bruno.42.desthuilliers at wtf.websiteburo.oops.com Thu Apr 5 04:19:44 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Thu, 05 Apr 2007 10:19:44 +0200 Subject: Resume of Steve Snow : Database SQL Applications Programmer In-Reply-To: References: Message-ID: <4614b109$0$5979$426a34cc@news.free.fr> stevesnow a ?crit : > ---------------------------------------------- > > Please forward this work experience & skills summary > to your Database & software development, MIS/IT/Software Department for review. > > ---------------------------------------------- > > Here is my full resume in Microsoft Word format. -0 Years experience in usenet posting From larry.bates at websafe.com Fri Apr 27 16:20:47 2007 From: larry.bates at websafe.com (Larry Bates) Date: Fri, 27 Apr 2007 15:20:47 -0500 Subject: python and COM In-Reply-To: References: Message-ID: <8Y-dnd_Nmce9xq_bnZ2dnUVZ_v2knZ2d@comcast.com> Brian Blais wrote: > Hello, > > I am trying to communicate to a Reuters feed using Python, using a > particular set of libraries called the Adfin Real Time library. I have > VB code, and am trying to port it to python, and admit I really do not > understand COM objects and being a Linux guy mainly, I don't use VB at > all. I've had some marginal success, but am coming up empty when it > comes to setting up callbacks. > > For example, this works: > > import win32com.client > import time > > symb='GOOG.O' > > mylist=win32com.client.Dispatch('AdfinXRTLib.AdxRtList') > > mylist.Source="IDN_RDF" > mylist.RegisterItems(symb,"ASK") > mylist.StartUpdates(4) # Mode Image > > while mylist.ItemStatus(symb): > pass > > for i in range(100): > m=mylist.Value(symb,"ASK") > print m > time.sleep(2) > > > but to get it to automatically updated quotes, in VB they do something like > > #================ > Public Class Form1 > # Dimension a Public Real Time list object that is capable of handling > events > # note from me: not sure what this line does really > Dim WithEvents AdxList As New AdfinXRTLib.AdxRTList > > Public Sub AdxList_OnUpdate( ) Handles > AdxList.OnUpdate > > do stuff with the updated data > > End Sub > > Private Sub Button1_Click() > > do stuff with button click > End Sub > End Class > #================ > > It seems as if the important part is the "Handles AdxList.OnUpdate", > which I assume is basically saying "call me when AdxList.OnUpdate is > called". I have no idea how to get this to point to a python function, > so I can make the AdxList.OnUpdate call python code. > > Is there a tutorial somewhere about this stuff, or is there a proper > place to ask such questions? > > > thanks, > > > Brian Blais > It looks like you are correct. This is a callback function that gets called when the update occurs. The only coverage of this I've found is in "Python Programming on Win32" but it is rather brief even there. I have not any event driven callbacks, so I can't help all that much. Normally you define a Python class that has methods that ADxList.OnUpdate is expecting to be able to call. Then depending on implementation you either call it with an instance of that class or you may have to wrap the instance in a COM IDispatch object by calling win32com.server.util.wrap() around an instance of the function. Sorry I can't be more helpful. -Larry From johnzenger at gmail.com Sun Apr 15 22:03:09 2007 From: johnzenger at gmail.com (John Zenger) Date: 15 Apr 2007 19:03:09 -0700 Subject: How to initialize a table of months. In-Reply-To: References: Message-ID: <1176688989.647309.227650@p77g2000hsh.googlegroups.com> On Apr 15, 9:30 pm, "Steven W. Orr" wrote: > I'm reading a logfile with a timestamp at the begging of each line, e.g., > > Mar 29 08:29:00 > > I want to call datetime.datetim() whose arg2 is a number between 1-12 so I > have to convert the month to an integer. > I wrote this, but I have a sneaky suspicion there's a better way to do it. > > mons = {'Jan':1, 'Feb':2, 'Mar':3, 'Apr':4, 'May':5, 'Jun':6, > 'Jul':7, 'Aug':8, 'Sep':9, 'Oct':10, 'Nov':11, 'Dec':12 } > > def mon2int( mon ): > global mons > return mons[mon] > > Is there a generator expression or a list comprehension thingy that would > be *betterer*? (I realize it's probably not that important but I find lots > of value in learning all the idioms.) > > TIA Well, I think you want time.strptime. >>> time.strptime("Mar 29 08:29:00", "%b %d %H:%M:%S") (1900, 3, 29, 8, 29, 0, 3, 88, -1) See http://docs.python.org/lib/node85.html However, if strptime did not exist, your dictionary solution is fine -- a tad bit slow, but easy and maintainable, which is worth a lot. From bearophileHUGS at lycos.com Sun Apr 15 08:15:18 2007 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 15 Apr 2007 05:15:18 -0700 Subject: combination function in python In-Reply-To: References: <1176615838.830315.160210@b75g2000hsg.googlegroups.com> <1176629911.409257.149780@l77g2000hsb.googlegroups.com> Message-ID: <1176639318.165822.125850@n59g2000hsh.googlegroups.com> Steven D'Aprano: > That's a naive and slow implementation. For even quite small values > of n and k, you end up generating some seriously big long ints, > and then have to (slowly!) divide them. > A better implementation would be something like this: You are right, thank you for the improvement (the advantage of the older implementation is that it's naive, so it's a bit more probably correct compared to more complex code I may write. For Python code I often tend to write a naive version first, create many testcases, slowly fixing all the corner cases (like factorial(-5)), and only later find a faster/better implementation if I have some time to do it or if I need it. If I need to do lot of binomials the gmpy by Alex helps). Bye, bearophile From robert.kern at gmail.com Tue Apr 24 13:02:54 2007 From: robert.kern at gmail.com (Robert Kern) Date: Tue, 24 Apr 2007 12:02:54 -0500 Subject: need help with ODE solver from scipy In-Reply-To: <1177429991.613640.243170@c18g2000prb.googlegroups.com> References: <1177429991.613640.243170@c18g2000prb.googlegroups.com> Message-ID: T.Crane wrote: > Hi, > > OK, I'm trying to figure out how to use the ODE solver > (scipy.integrate.ode.ode). You will get more help from the scipy-user list than you will here. http://www.scipy.org/Mailing_Lists > Here's what I'm doing (in iPython) > > y0 = [0,1,1] > dt = 0.01 > tEnd = 12 > t0 = 0 > Y = zeros([tEnd/dt, 3]) > > As an aside, I've used this assignment for Y in the past and it > worked. When I tried it this morning I got a TypeError and a message > saying I needed to use an integer. Well, the current behavior is correct. When you give us a float instead of an int for a dimension, we shouldn't guess what you want. Particularly, in this case, truncating is incorrect. I ran your code and eventually wound up with an IndexError because your iteration ran past the end of Y and T. > So, instead... > > Y = zeros([int(tEnd/dt), 3]) > T = zero([int(tEnd/dt)]) Also, a better way to do this is simply to leave these as lists and simply append to them. That way, you don't have to manage indices. > index = 0 > def foo(t,y): > dy = zeros([3]) > dy[0] = y[1]*y[2] > dy[1] = -y[0]*y[2] > dy[2] = -0.51*y[0]*y[1] > return dy > > r = ode(foo).set_integrator('vode').set_initial_value(y0,t0) > while r.successful() and r.t < tEnd: > r.integrate(r.t+dt) > Y[index] = r.y > T[index] = r.t > index += 1 > > As a further aside, this system of three coupled linear ODE's is from > an example in MATLAB's documentation on their function ode45, so I > know what I 'should' get. The while loop and call to ode is adapted > from scipy's (very limited) documentation on scipy.integrate.ode.ode. > > At the end of this while loop I've gotten a few different results > depending on what I have no idea. This morning another TypeError > exception was thrown, saying: > > TypeError: Array can not be safely cast to required type. > > Although, to be fair this is after the output from one iteration: > > array([0.01, 1. , 1. ]) > > So, clearly this isn't working right. Does anyone have any experience > using this function or anything they can contribute? I tried your example and it worked for me (after fixing the IndexError). Could you come to scipy-user with the complete code that you ran (the one above isn't the one you ran; there is at least one typo), and the full traceback of the error? -- 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 newsgroups at nospam.nowire.org Mon Apr 9 04:39:20 2007 From: newsgroups at nospam.nowire.org (=?UTF-8?B?VGhvbWFzIEtyw7xnZXI=?=) Date: Mon, 09 Apr 2007 10:39:20 +0200 Subject: Is there a simple function to generate a list like ['a', 'b', 'c', ... 'z']? In-Reply-To: <1176107364.000517.68580@q75g2000hsh.googlegroups.com> References: <1176107364.000517.68580@q75g2000hsh.googlegroups.com> Message-ID: ??????????????? schrieb: > Is there a simple function to generate a list like ['a', 'b', 'c', ... > 'z']? The range() just can generate the numeric list. There is: [ chr(i) for i in range(97, 123) ] Thomas From grante at visi.com Mon Apr 2 14:40:49 2007 From: grante at visi.com (Grant Edwards) Date: Mon, 02 Apr 2007 18:40:49 -0000 Subject: Launch script on Linux using Putty References: <1175467029.572354.138930@y66g2000hsf.googlegroups.com> <1175536278.510176.183360@l77g2000hsb.googlegroups.com> Message-ID: <1312jhhpbll3ta7@corp.supernews.com> On 2007-04-02, Michael Hoffman wrote: >>> 1. The easiest is to run nohup on your script in the background: >>> >>> $ nohup myscript.py > output.txt 2> error.txt & >>> >>> Then you can disconnect but your script will keep running. Try man nohup >>> for more information. >>> >>> 2. Use GNU screen on your remote terminal, and detach the screen instead >>> of logging off. >>> >>> 3. Set up your script to fork as a daemon. Google for ["python cookbook" >>> fork daemon] to find a few recipes for this. > > [Ulysse] >> 1. nohup seems not to be installed on my "reduced linux distribution". >> It's a OpenWrt tunning on my WRT54GL Broadband router. > > If you are running bash, you can do this: He's not running bash. He's running busybox's shell. [He'd be far better off asking his question in an OpenWRT or Busybox forum, since it's got absolutely nothing to do with Python.] -- Grant Edwards grante Yow! They don't hire at PERSONAL PINHEADS, visi.com Mr. Toad! From kirk at jobspam/mapssluder.net Thu Apr 12 11:02:06 2007 From: kirk at jobspam/mapssluder.net (Kirk Job Sluder) Date: Thu, 12 Apr 2007 15:02:06 GMT Subject: SQLite problems References: <1176371562.110295.217360@l77g2000hsb.googlegroups.com> Message-ID: bayer.justin at googlemail.com writes: > Hi there, > > I run Python 2.5 on a Mac OS X system with SQLite 3.2.8 installed via > fink. Today I stumbled over the problem, that the sqlite3 module and > sqlite3 from fink do not seem to work well together. I brought it down > to this: > > Any ideas? miss-match of versions between the fink and the Apple-supplied sqlite3? > > Regards, > -Justin > -- Kirk Job Sluder From see_signature at nospam.nowire.org Wed Apr 11 05:47:08 2007 From: see_signature at nospam.nowire.org (=?ISO-8859-1?Q?Thomas_Kr=FCger?=) Date: Wed, 11 Apr 2007 11:47:08 +0200 Subject: THREADS use 100 % CPU all the time In-Reply-To: <1176284321.528102.112740@o5g2000hsb.googlegroups.com> References: <1176284321.528102.112740@o5g2000hsb.googlegroups.com> Message-ID: matthiasjanes at gmx.net schrieb: > while (True): > pass > Does anyone know how to run this without consuming all CPU. Your while loop is taking all the CPU time. Thomas -- sinature: http://nospam.nowire.org/signature_usenet.png From skulka3 at gmail.com Thu Apr 26 19:44:14 2007 From: skulka3 at gmail.com (skulka3 at gmail.com) Date: 26 Apr 2007 16:44:14 -0700 Subject: Python CGI and Browser timeout In-Reply-To: References: <1177624109.532664.105840@t39g2000prd.googlegroups.com> Message-ID: <1177631054.673410.141610@u32g2000prd.googlegroups.com> Thanks for the response. To further clarify the details: I am printing the empty strings in a for loop. So the processing happens in a loop when all the results from the query have been already retrieved and each record is now being processed inside the loop. I also update the display periodically with the total number of records processed(which is approximately after every 1/5th chunk of the total number of records in the result). Thanks, Salil Kulkarni On Apr 26, 6:01 pm, "Sebastian Bassi" wrote: > On 26 Apr 2007 14:48:29 -0700, skul... at gmail.com wrote: > > > In order to work around this problem, I started printing empty strings > > (i.e. print "") so that the browser does not timeout. > > How do you print something while doing the query and waiting for the results? > I saw some pages that display something like: "This page will be > updated in X seconds to show the results" (X is an estimated time > depending of server load), after a JS countdown, it refresh itself and > show the result or another "This page will be updated in X seconds to > show the results". > > -- > Sebasti?n Bassi (???????) > Diplomado en Ciencia y Tecnolog?a. > GPG Fingerprint: 9470 0980 620D ABFC BE63 A4A4 A3DE C97D 8422 D43D > Club de la raz?n (www.clubdelarazon.org) From jstroud at mbi.ucla.edu Mon Apr 9 07:42:55 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Mon, 09 Apr 2007 04:42:55 -0700 Subject: Comments in ConfigParser module In-Reply-To: References: Message-ID: <4FpSh.2020$Q23.879@newssvr17.news.prodigy.net> Joel Granados wrote: > > > On 4/6/07, *James Stroud* > wrote: > > Joel Andres Granados wrote: > > Hi list: > > Any comment greatly appreciated.... > > Very clever. > -- > http://mail.python.org/mailman/listinfo/python-list > > > > clever ??? > Well I would expect that the ";" character to behave the same way that > the "#", as they are both characters that come before a comment. But it > doesn't. So I'm missing something here. Why is the different behavior > clever? > > -- > Joel Andr?s Granados > Medell?n Colombia > -- > jgranad1 at eafit.edu.co > joel.granados at ieee.org I was referring to his asking for "comments" in a post about "comments". I thought this was a clever way to conclude. I have no idea why the behavior of the module is the way it is. Seems like a bug to me, but I have not read the official .ini file specification, so I'm not sure its working correctly. Cheers, James From tactics40 at gmail.com Sun Apr 22 19:05:44 2007 From: tactics40 at gmail.com (tac-tics) Date: 22 Apr 2007 16:05:44 -0700 Subject: recursion depth problem In-Reply-To: <1177282027.798037.48210@o5g2000hsb.googlegroups.com> References: <1177267774.416169.276780@e65g2000hsc.googlegroups.com> <1177275314.846022.249000@e65g2000hsc.googlegroups.com> <1177276111.720137.315710@b75g2000hsg.googlegroups.com> <1177282027.798037.48210@o5g2000hsb.googlegroups.com> Message-ID: <1177283144.316024.284000@y80g2000hsf.googlegroups.com> Yes, you should use a for loop in this situation. Certain functional languages, such as Scheme and various LISP dialects allow for what is called "tail recursion" which effectively eliminates this problem by internally converting recursion to iteration. Python isn't really cut out for heavy recursive work, and the "Pythonic" way of doing things is through the lovely for loop. From joshusdog at gmail.com Fri Apr 27 11:25:10 2007 From: joshusdog at gmail.com (joshusdog at gmail.com) Date: 27 Apr 2007 08:25:10 -0700 Subject: building _tkinter module with .NET 2005? Message-ID: <1177687509.948452.326120@n35g2000prd.googlegroups.com> I have the Python 2.5.1 source and I'm trying to build the debug version of the _tkinter module. I've got .NET 2005 (Visual Studio 8) but the instructions in the pcbuild\readme.txt file only contain instructions for using .NET 2003 (Visual Studio 7.1). There's another readme.txt file under the pcbuild8 directory, but is almost identical to the one in the pcbuild folder. (There's some information about some new instrumented build settings, but that's about it) The instructions contained in both these readme.txt files say that the Tcl, Tk, and Tix projects must be built from the command line first, using nmake.exe in conjunction with the corresponding makefile.vc for each package. I can get this to work using .NET 2003, but not with .NET 2005. Is there an updated set of instructions somewhere for doing this with .NET 2005? Is it even possible to get it to work with the newer version of .NET? From kar1107 at gmail.com Sat Apr 14 19:49:22 2007 From: kar1107 at gmail.com (Karthik Gurusamy) Date: 14 Apr 2007 16:49:22 -0700 Subject: optparse -- anyway to find if the user entered an option? Message-ID: <1176594561.971801.211710@y80g2000hsf.googlegroups.com> Hi, I see that I can provide a default value for an option. But I couldn't find out any way if the user really entered the option or the option took that value because of default. A simple check for value with default may not always work as the user might have manually entered the same default value. Let's assume I want to take in the ip-address using -i . If user didn't give it explicitly, I am going to use socket interface to figure out this host's IP address. ip_addr_default = '100.100.100.100' parser.add_option("-i", "--ip-address", dest="ip", default=ip_addr_default, metavar="IP-ADDRESS", help="IP address. default:" + ip_addr_default + "e.g. --i=1.1.1.1" ) (options, args) = parser.parse_args() Now if options.ip == ip_addr_default, I still can't be 100% sure that the user did not type -i 100.100.100.100. Any way to figure out from options that the user typed it or not? (The reason I want to know this is if user did not mention -i, I can compute IP later using socket module) I could think of a hack of using None as default and since no user can ever enter a None value, I can be sure that the user didn't provide -i. I'm wondering if there is a cleaner approach -- something like parser.opt_seen("-i") Thanks, Karthik From michael at jedimindworks.com Thu Apr 19 05:37:04 2007 From: michael at jedimindworks.com (Michael Bentley) Date: Thu, 19 Apr 2007 04:37:04 -0500 Subject: Do other Python GUI toolkits require this? In-Reply-To: References: <462697A6.6010007@codebykevin.com> Message-ID: <465B30B4-5BA0-459A-BE6F-1038874FA74B@jedimindworks.com> On Apr 19, 2007, at 4:11 AM, Antoon Pardon wrote: > On 2007-04-19, Michael Bentley wrote: >> >> On Apr 18, 2007, at 5:11 PM, Kevin Walzer wrote: >> >>> James Stroud wrote: >>> >>>> This appears more or less unique to Objective C. It looks that with >>>> PyObjC, you have to interact with the Objective C runtime to manage >>>> memory. This is not required, thankfully, with any other GUI >>>> tookits >>>> I've seen. >>>> >>>> I think the main difference is that PyObjC is not a GUI toolkit >>>> per se, >>>> but is simply a means to make the Objective C runtime (and hence >>>> Cocoa) >>>> available via a python layer. >>>> >>>> James >>> >>> That's kind of what I thought. Memory management? In Python? >>> *shudder* >>> >>> I'm a Mac-only developer, and I keep telling myself I should >>> drink the >>> Mac-only Kool-aid of PyObjC. But Tk is burned into my brain, and >>> anything else looks and feels weird to me. Tk is so flexible that >>> it's >>> fairly easy to tweak it to look Mac-like, and it's simpler to do >>> that >>> than learn a new tookit. >> >> PyObjC is pretty slick (and since Ronald hasn't made any commits in a >> while I'm nearly certain it'll show up in the next official >> distribution of the devtools). About the time you gave up on PyQt on >> the Mac and switched over to Tkinter, I switched to PyObjC. The >> learning curve is rather steep IMO, but worth it. > > Just a throw in remark, that you may ignore if you wish, but a steep > learning curve means that the subject is easily familiarized and that > the learning period is short. > > You seem to use it as if it is the opposite. Mathematical absurdities aside, it's the common usage -- but perhaps you knew that. From michael at jedimindworks.com Sat Apr 14 00:45:52 2007 From: michael at jedimindworks.com (Michael Bentley) Date: Fri, 13 Apr 2007 23:45:52 -0500 Subject: Python editor/IDE on Linux? In-Reply-To: <461fe88c$0$6420$426a74cc@news.free.fr> References: <1176488840.672572.101830@y80g2000hsf.googlegroups.com> <461fe88c$0$6420$426a74cc@news.free.fr> Message-ID: >> >> Everybody uses vim. >> > Except for real programmers... Who instead use emacs ;-) From laurent.pointal at wanadoo.fr Mon Apr 2 16:08:46 2007 From: laurent.pointal at wanadoo.fr (Laurent Pointal) Date: Mon, 02 Apr 2007 22:08:46 +0200 Subject: Problem with global variables References: <1311u48bqkehk24@corp.supernews.com> <57ciafF2cf6qdU1@mid.individual.net> Message-ID: <461161a8$0$27400$ba4acef3@news.orange.fr> Bjoern Schliessmann wrote: > Laurent Pointal wrote: > >> And so the solution to add "global foo" before using it. > > Didn't you read his final question? Yes, and i replies: "which contains a foo assignment. As foo is not defined "global", it is considered to be local. " Maybe my explanation was not clear enough with variable foo to be considered local because there is an *assignment* to foo. A+ Laurent. From puopolo at gmail.com Mon Apr 16 20:59:22 2007 From: puopolo at gmail.com (john) Date: 16 Apr 2007 17:59:22 -0700 Subject: unittest assertRaises Problem In-Reply-To: References: <1176761622.220741.261420@y80g2000hsf.googlegroups.com> Message-ID: <1176771562.478926.215430@b75g2000hsg.googlegroups.com> On Apr 16, 6:35 pm, Jean-Paul Calderone wrote: > On 16 Apr 2007 15:13:42 -0700, john wrote: > > > > >All: > > >Hi. I am an experienced developer (15 yrs), but new to Python and have > >a question re unittest and assertRaises. No matter what I raise, > >assertRaises is never successful. Here is the test code: > > >class Foo: > > def testException(self): > > raise ValueError > > >class FooTestCase(unittest.TestCase): > > > testTryThis(self): > > f = Foo() > > self.assertRaises(ValueError, f.testException()) > > The 2nd argument to assertRaises should be a callable. assertRaises > will call it (so that it can do exception handling), so you shouldn't: > > self.assertRaises(ValueError, f.testException) > > Jean-Paul Steven, Jean-Paul: Thank you both for your answers - worked like a charm! Best, John From castironpi at gmail.com Fri Apr 27 19:07:57 2007 From: castironpi at gmail.com (castironpi at gmail.com) Date: 27 Apr 2007 16:07:57 -0700 Subject: Memory addressing In-Reply-To: References: <1177702902.156596.52510@n35g2000prd.googlegroups.com> <1177703803.179501.95300@n35g2000prd.googlegroups.com> Message-ID: <1177715277.592511.296990@h2g2000hsg.googlegroups.com> On Apr 27, 4:00 pm, Carsten Haese wrote: > On Fri, 2007-04-27 at 12:56 -0700, Simon Berube wrote: > > When you call certain objects __repr__() strings in python you often > > get the : happen. I am simply trying to > > understand how that information can be used to recreate a certain > > object that failed as per the given purpose of the __repr__() > > functions. > > It's not a requirement of repr() that the resulting string be suitable > for recreating the object. For many built-in object types, calling > eval() on their repr() will result in a copy of the object, but in > general eval(repr(obj))==obj will not be true. > > > In short, how do I used strings to recreate > > a an object. > > You don't. What you should do instead depends on what you actually need > to do, which you haven't said yet. Do you want to pass an object to > another function, do you want to make a copy of an object, or do you > want to serialize/unserialize an object to send it through time and/or > space? > > -Carsten That's what we need: a CopyMemory() routine. From bignose+hates-spam at benfinney.id.au Wed Apr 4 22:26:52 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Thu, 05 Apr 2007 12:26:52 +1000 Subject: Prevent Modification of Script? References: <1175735097.856840.177510@e65g2000hsc.googlegroups.com> Message-ID: <877isrh7yr.fsf@benfinney.id.au> "ts-dev" writes: > Is it possible to prevent modification of a python file once its been > deployed? Prevent modification by whom? You can't prevent modification by the person who owns the machine. It's in their possession, and presumably it's out of yours; they can do whatever they like. > The root of my question is verifying the integrity of the > application and the scripts being run. Is this possible, if so, how? Never put the program anywhere that someone you don't trust has access to it. -- \ "Why should I care about posterity? What's posterity ever done | `\ for me?" -- Groucho Marx | _o__) | Ben Finney From surekap at gmail.com Sun Apr 29 19:34:27 2007 From: surekap at gmail.com (Prateek) Date: 29 Apr 2007 16:34:27 -0700 Subject: fastest way to find the intersection of n lists of sets In-Reply-To: References: <1177883328.835058.138990@p77g2000hsh.googlegroups.com> Message-ID: <1177889667.450984.88970@p77g2000hsh.googlegroups.com> > For the above example, it's worth sorting lists_of_sets by the > length of the sets, and doing the short ones first. Thanks. I thought so - I'm doing just that using a simple Decorate- Sort-Undecorate idiom. > How big are the sets? If they're small, but you have a lot of > them, you may be better off with a bit-set representation, then > using AND operations for intersection. If they're huge (tens of millions > of entries), you might be better off doing sorts and merges on the > sets. I have either 2 or 3 sets (never more) which can be arbitrarily large. Most of them are small (between 0 and few elements - say less that 5). A few will be megamonstrous ( > 100,000 items) > When you ask questions like this, it's helpful to give some > background. We don't know whether this is a homework assignment, or > some massive application that's slow and you need to fix it, even > if it requires heavy implementation effort. > Its definitely not a homework assignment - its part of a commercial database query engine. Heavy implementation effort is no problem. Prateek From kushal.kumaran at gmail.com Tue Apr 3 09:26:07 2007 From: kushal.kumaran at gmail.com (Kushal Kumaran) Date: 3 Apr 2007 06:26:07 -0700 Subject: python installation destination directory In-Reply-To: <1175574838.705561.203310@n76g2000hsh.googlegroups.com> References: <1175574838.705561.203310@n76g2000hsh.googlegroups.com> Message-ID: <1175606767.236264.184830@e65g2000hsc.googlegroups.com> On Apr 3, 9:33 am, "ZMY" wrote: > Hi all, > > I am installing python 2.2 on QNX4.25 but can't get it into /usr/local/ > bin/ directory. Here is what I did: > > 1) untar Python-2.2 into directory /openqnx/Python-2.2/ > > 2) use command: > CONFIG_SHELL=/usr/local/bin/bash CC=cc RANLIB=: > ./configure --verbose --without-gcc --with-libm="" > > 3) Enabled array, math, os, struct, time, cmath modules > > 4) use command: > make SHELL=/usr/local/bin/bash > > and I got a python excutable in directory > /openqnx/Python-2.2/ > > which works well with all the modules. But I really want to have it > at /usr/local/bin > > I checked the Makefile, and it seems python should be installed in / > usr/local/bin instead, since I got following lines in Makefile: > > # Install prefix for architecture-independent files > prefix= /usr/local > > # Install prefix for architecture-dependent files > exec_prefix= ${prefix} > > Do any of you know what the problem is? > You need to do a make install. -- Kushal From mwilson at the-wire.com Sun Apr 8 11:27:24 2007 From: mwilson at the-wire.com (Mel Wilson) Date: Sun, 08 Apr 2007 11:27:24 -0400 Subject: tuples, index method, Python's design In-Reply-To: <1175973537.371754.78450@y66g2000hsf.googlegroups.com> References: <1175867771.114540.61810@n76g2000hsh.googlegroups.com> <1175884427.779950.267220@y80g2000hsf.googlegroups.com> <1175953520.316208.241490@o5g2000hsb.googlegroups.com> <1175973537.371754.78450@y66g2000hsf.googlegroups.com> Message-ID: 7stud wrote: > On Apr 7, 8:27 am, Carsten Haese wrote: >> Adding useless features always makes a product worse. What's your use >> case for tuple.index? > I'll trade you an index method for tuples for the whole complex number > facility. Actually, I've found the use cases for list.index to be kind of thin. Long before I think "Which one of these items is a 3?", I seem to have thought "dictionary". Cheers, Mel. From kay.schluehr at gmx.net Thu Apr 26 15:55:00 2007 From: kay.schluehr at gmx.net (Kay Schluehr) Date: 26 Apr 2007 12:55:00 -0700 Subject: My python annoyances so far In-Reply-To: <1177603623.774892.230390@t38g2000prd.googlegroups.com> References: <1177541453.471959.120830@c18g2000prb.googlegroups.com> <59bf34F2k27v5U1@mid.individual.net> <1177603623.774892.230390@t38g2000prd.googlegroups.com> Message-ID: <1177617300.195904.63410@t39g2000prd.googlegroups.com> On Apr 26, 6:07 pm, fli... at gmail.com wrote: > Well, why do some things in the library have to be functions, and > other things have to be class methods? > > Why aren't they all just either functions or class methods? like > perhaps ruby. A good question. Part of the answer might be that their are no abstract base classes / interfaces in the language so far. These have a particular meaning and you might ask whether some object has certain abilities like being "sizable". With ABCs or interfaces it feels natural to implement abstract methods in subclasses. Without them you can either add methods ad hoc, without any conceptual background and consistency requirements of your model, or you are going to implement interface constraints in terms of so called "protocols". A protocol is a sequence of actions which require interfaces to be present ( they are abstract algorihms / command patterns ). Special functions ( __add__, __len__, etc. ) are the mediators of protocols. For instance the meaning of len() can be understood in terms of protocols: def len(obj): return obj.__len__() Other protocols are more implicit e.g. those that couple operators to method calls. You already mentioned special methods for arithmetic operations. I sometimes like to think that Python is a language developed around protocols, and they have a strong backing in the language. With Py3K Python will become a bit more Java like, at least with regard to the supported language constructs. Kay From jstroud at mbi.ucla.edu Fri Apr 27 18:31:38 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Fri, 27 Apr 2007 15:31:38 -0700 Subject: how to create/ref globals in an alternate namespace? In-Reply-To: References: Message-ID: Steven W. Orr wrote: > On Friday, Apr 27th 2007 at 14:07 -0700, quoth James Stroud: > > =>Steven W. Orr wrote: > =>> I have two seperate modules doing factory stuff which each have the > =>> similar function2: > =>> > =>> In the ds101 module, def DS101CLASS(mname,data): > =>> cname = mname+'DS101' > =>> msg_class = globals()[cname] > =>> msg = msg_class(data) > =>> return msg > =>> > =>> and in the fdu module, > =>> > =>> def FDUCLASS(mname,data): > =>> cname = mname+'FDU' > =>> msg_class = globals()[cname] > =>> msg = msg_class(data) > =>> return msg > =>> > =>> I was thinking I'd be clever and create a common function: > =>> def procCLASS(mname, objname, data): > =>> cname = mname+objname > =>> msg_class = globals()[cname] > =>> msg = msg_class(data) > =>> return msg > =>> > =>> but the call to globals fouls it all up. Is there a way to write it so > =>> that the call to globals can be parameterized to be in the context of a > =>> specific module? > =>> > =>> Also, I need to go the other way, a la, > =>> globals()[name] = nclass > =>> > =>> Is this doable? > =>> > =>> TIA > =>> > => > =>Why do you need all of the msg_class(es) global? Why not put them into a > =>module and import the module where you need them? This would be the > =>conventional way to avoid such problems. > > The idea is that DS101 is being called in a loop in the ds101 module to > create a lot of msg_classes. The same is true for the FDUCLASS function; > it creates a lot of classes in a loop. > > In addition, I have two other functions, almost alike, in two seperate > modules (mdefs is a structure with all of the stuff needed to drive the > loops) > > def __InitDS101Classes(): > for m in mdefs: > mdef = mdefs[m] > name = mdefs[m]['name']+'DS101' > nclass = new.classobj(name,(DS101,),{}) > nclass.mdef = mdef > nclass.mid = m > globals()[name] = nclass > > > def __InitFDUClasses(): > for m in mdefs: > mdef = mdefs[m] > name = mdefs[m]['name']+'FDU' > nclass = new.classobj(name,(FDU,),{}) > nclass.mdef = mdef > nclass.mid = m > globals()[name] = nclass > > I'm trying to see if by being clever, I can factor out the common code of > the four different functions and still end up with what they create ending > up in the namespaces where they are intended to reside in. Does this make > sense or am I way off base? > > If I get your intention, the imported module idea still works: # imported.py pass # module1.py import imported imported.abc = 2 # module2.py import module1 import imported print imported.abc James From bbxx789_05ss at yahoo.com Wed Apr 11 04:18:19 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: 11 Apr 2007 01:18:19 -0700 Subject: Calling Python from Javascript? In-Reply-To: References: Message-ID: <1176279499.671534.49550@y5g2000hsa.googlegroups.com> On Apr 11, 1:50 am, Kenneth McDonald wrote: > I know that there's some work out there to let Python make use of > Javascript (Spidermonkey) via (I assume) some sort of bridging C/C++ > code. Anyone know of efforts to allow the reverse? I'd really like to > make use of Python when doing Mozilla DOM programming, and I can never > get a clear idea of when PyXPCOM might be available to those of us who > don't know the ins and outs of compiling Mozilla, and its XPCOM > structures. So if there was an easy way to simply and quickly pass even > just strings back and forth between Python and Moz Javascript, that > would make certain things a heck of a lot easier. > > Thanks, > Ken Javascript can make requests to the server, and far as I know python can be used with either cgi or apache to respond to server requests. Therefore, javascript can easily pass strings to a server side python script, and it can easily handle data sent back that is formatted as a string, XML, or JSON. I'm not sure what PyXPCOM is or why it's relevant. From kumar.mcmillan at gmail.com Thu Apr 19 17:20:11 2007 From: kumar.mcmillan at gmail.com (Kumar McMillan) Date: Thu, 19 Apr 2007 16:20:11 -0500 Subject: Deallocation of a pointer not malloced, any tips? Message-ID: I get this warning from my test suite when I introduced a segment of code: python(18603,0xa000d000) malloc: *** Deallocation of a pointer not malloced: 0x310caa3; This could be a double free(), or free() called with the middle of an allocated block; Try setting environment variable MallocHelp to see tools to help debug Always the same warning; sometimes it even segfaults python, but rarely. I only see it on Mac OS X (two separate machines), python 2.4.3 built from source via Darwin Ports. The same suite gives no such warning on a 2.4.3 production machine running Free BSD. I know what segment of code causes it but can't for the life of me think of writing it a different way in this specific application. In a nutshell, it's two sets of two nested try blocks (try, try, except, except * 2) where the inner except can re-raise a new exception if a rescue function wants to. it sounds convoluted because it is! :( I tried really hard recreating it in a test case but of course there is something too deeply buried that I can't catch. I turned on MallocHelp but just stared blankly at heaps and stack options. Is there anything I can switch on that would be helpful to anyone who might be interested in this problem? :) I also wanted to put out some feelers in case it sounds like something that is fixed elsewhere (I'm having trouble running my existing suite in 2.5 due to setuptools not working and me not having enough time to fiddle with it). -Kumar From http Sun Apr 8 16:10:16 2007 From: http (Paul Rubin) Date: 08 Apr 2007 13:10:16 -0700 Subject: tuples, index method, Python's design References: <1175867771.114540.61810@n76g2000hsh.googlegroups.com> <1175884427.779950.267220@y80g2000hsf.googlegroups.com> <1175953520.316208.241490@o5g2000hsb.googlegroups.com> <7xzm5igbrb.fsf@ruckus.brouhaha.com> Message-ID: <7x8xd2iq53.fsf@ruckus.brouhaha.com> Carsten Haese writes: > > Do you not see the gratuituous inconsistency between tuples and lists > > as a useless feature? What is the use case for keeping it? > > When a new feature is requested, the burden of proof is on the requester > to show that it has uses. The use case for not having tuple.index is > that there are no use cases for having it. If that answer sounds absurd, > it is because your question is absurd. The use case has already been discussed. Removing the pointless inconsistency between lists and tuples means you can stop having to remember it, so you can free up brain cells for implementing useful things. That increases your programming productivity. From martin at v.loewis.de Fri Apr 20 01:44:11 2007 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Fri, 20 Apr 2007 07:44:11 +0200 Subject: Python's handling of unicode surrogates In-Reply-To: References: Message-ID: <4628532B.5060104@v.loewis.de> > Thoughts, from all you readers out there? For/against? See PEP 261. This things have all been discussed at that time, and an explicit decision against what I think (*) your proposal is was taken. If you want to, you can try to revert that decision, but you would need to write a PEP. Regards, Martin (*) I don't fully understand your proposal. You say that you want "gaps in [the string's] index", but I'm not sure what that means. If you have a surrogate pair on index 4, would it mean that s[5] does not exist, or would it mean that s[5] is the character following the surrogate pair? Is there any impact on the length of the string? Could it be that len(s[k]) is 2 for some values of s and k? From 12cc104 at gmail.com Sun Apr 22 20:03:57 2007 From: 12cc104 at gmail.com (proctor) Date: 22 Apr 2007 17:03:57 -0700 Subject: recursion depth problem In-Reply-To: References: <1177267774.416169.276780@e65g2000hsc.googlegroups.com> <1177275314.846022.249000@e65g2000hsc.googlegroups.com> <1177276111.720137.315710@b75g2000hsg.googlegroups.com> <1177282027.798037.48210@o5g2000hsb.googlegroups.com> <90679236-0D2C-42EF-B93F-06A1DD561944@jedimindworks.com> Message-ID: <1177286637.930484.187180@n59g2000hsh.googlegroups.com> On Apr 22, 5:51 pm, Michael Bentley wrote: > Oops! Note to self: *ALWAYS* try code before posting to a public > forum :-( > > def binary(val, width): > print '%10s = the sum of' % val > for i in [2 ** x for x in range(width - 1, -1, -1)]: > a = val / i > print ' ' * 13 + '%s * (2 ** %s)' % (a, width) > val -= i * a > width -= 1 > > binary(233, 8) very cool. thanks a lot michael. very interesting. proctor. From jstroud at mbi.ucla.edu Tue Apr 17 03:27:38 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Tue, 17 Apr 2007 07:27:38 GMT Subject: Rapyd-Tk Pmw Notebook tutorial In-Reply-To: <1176718051.347720.200710@p77g2000hsh.googlegroups.com> References: <1176718051.347720.200710@p77g2000hsh.googlegroups.com> Message-ID: boriq wrote: > Hello, > > could anybody be so kind and write me a small tutorial about "how to > create a Pmw notebook with 3 tabs each containing 5 checkboxes" with > the help of Rapyd-Tk? > > Thanks in advance > rg, > boris > I'll do it for $200.00. I bill at $50.00/hr when I'm feeling generous. James From tejovathi.p at gmail.com Thu Apr 19 07:38:22 2007 From: tejovathi.p at gmail.com (Teja) Date: 19 Apr 2007 04:38:22 -0700 Subject: Helpbook and CHM In-Reply-To: <1176982417.221318.215750@n59g2000hsh.googlegroups.com> References: <1176979477.204864.72900@n59g2000hsh.googlegroups.com> <1176980292.290091.10420@y5g2000hsa.googlegroups.com> <1176982417.221318.215750@n59g2000hsh.googlegroups.com> Message-ID: <1176982702.528426.326770@b75g2000hsg.googlegroups.com> On Apr 19, 4:33 pm, Ravi Teja wrote: > On Apr 19, 3:58 am, Teja wrote: > > > On Apr 19, 3:48 pm, Tim Golden wrote: > > > > Teja wrote: > > > > how to generate CHM files in Boa(Python)??? > > > > http://www.rutherfurd.net/software/rst2chm/index.html > > > > TJG > > > Can't I do it in Boa constructor ??? I have seen an option in Boa to > > create a new helpbook and compile it to CHm and help files, But no > > clue how to do it....... > > Not that I know of. Which version are you using? Where in the > application did you find it? Indicate the menu's you navigated to get > to that option. > > MS HTML Help Workshop is the standard compiler for CHM files. There > are some other freeware/shareware. The workshop is simple enough > though. If u have Boa constructor 0.4.4, Go to File--->New--->helpbook Save it. After saving, click File menu option and you will find, "make HTB" and "make CHM" But I dont know how to add files and generate a complete CHM file. From martin at v.loewis.de Wed Apr 11 18:43:07 2007 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Thu, 12 Apr 2007 00:43:07 +0200 Subject: XML-RPC SSL and client side certs? In-Reply-To: References: <1176241420.420028.276030@y5g2000hsa.googlegroups.com> Message-ID: <461D647B.3040100@v.loewis.de> Jeff McNeil schrieb: > I apologize for not giving you a Python specific answer, but for the > XMLRPC services I've deployed, I front them with Apache and proxy back > to localhost:8080. > > I do all of the encryption and authentication from within the Apache > proper and rely on mod_proxy to forward validated requests on. I've > settled on basic authentication, but I see no reason why you couldn't > take advantage of mod_ssl. There is an issue with forwarding SSL connections, of course: it is not possible - at least not with the same client identity as the original user. In turn, it's not easy to forward the identity of the authenticated user, either: even though Apache will know who he is, it has no way of telling on the forwarded request. So you would have to use CGI or mod_python in this case. Regards, Martin From carles at pina.cat Fri Apr 20 18:17:00 2007 From: carles at pina.cat (Carles Pina i Estany) Date: Sat, 21 Apr 2007 00:17:00 +0200 Subject: service for file monitoring In-Reply-To: References: <1177099611.498274.323180@y5g2000hsa.googlegroups.com> Message-ID: <20070420221700.GA15457@pinux.info> Hi, On Apr/20/2007, Gabriel Genellina wrote: > En Fri, 20 Apr 2007 17:06:51 -0300, rohit > escribi?: > > > i am designing a desktop search engine using python. > > i am having a query , is there a package available that contains > > functions for retrieving the files being edited , created,deleted in > > the file system. > > For windows you can use the techniques described here: > http://tgolden.sc.sabren.com/python/win32_how_do_i/watch_directory_for_changes.html for linux, python-pyinotify. works very well! -- Carles Pina i Estany GPG id: 0x8CBDAE64 http://pinux.info Manresa - Barcelona From bignose+hates-spam at benfinney.id.au Sat Apr 14 00:28:46 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Sat, 14 Apr 2007 14:28:46 +1000 Subject: favourite IDE References: <1176422188.006169.141100@q75g2000hsh.googlegroups.com> Message-ID: <87hcrj60ld.fsf@benfinney.id.au> "azrael" writes: > Some time ago I posted a question about the favourite IDE. I finally > found it. I presume you mean "the favourite IDE of me, azrael". The threads that result, if they show anything, show that there is no one favourite IDE. -- \ "You've got to think about big things while you're doing small | `\ things, so that all the small things go in the right | _o__) direction." -- Alvin Toffler | Ben Finney From aleax at mac.com Fri Apr 27 01:08:24 2007 From: aleax at mac.com (Alex Martelli) Date: Thu, 26 Apr 2007 22:08:24 -0700 Subject: EuroPython vs PyconUK References: <4630D480.7050308@gmail.com> <1177617449.064076.250150@t38g2000prd.googlegroups.com> Message-ID: <1hx76ez.k3b9p41gyek8dN%aleax@mac.com> EuGeNe Van den Bulke wrote: > Alex Martelli, brilliant speaker and Python evangelist (in my Shu Ha > eyes anyway), lives in the States and is Italian. Busy as you'd expect > from someone working for Google, decides to make the trip to Europe for > a Python related conference, henceforth spends 3 1/2 months in Europe so > he can do Italy in June (he is listed as an organizer), Lithuania in > July and UK in September... I like the kudos, thanks!, but I'm not quite sure what you're saying about my travel plans... just to clarify, once again I'll have to miss EuroPython _and_ PythonUK, two events I attended most assiduously when I was living in Europe (but then, for two years running I've also missed PyCon, _despite_ living in the US, sigh). Besides Pycon Uno, in my short trip in early June, I hope to also visit Cracow, and perhaps give a Python talk at the University there if my Polish colleagues can arrange things, but that will be it. It's not so much about working for Google, which isn't stopping e.g. Guido from attending conferences of his choice -- it's more about my also having accepted managerial responsibilities there, which means I can't really do my "primary" job all that well by logging in remotely from my laptop:-). Alex From aleax at mac.com Tue Apr 24 10:49:46 2007 From: aleax at mac.com (Alex Martelli) Date: Tue, 24 Apr 2007 07:49:46 -0700 Subject: Python un-plugging the Interpreter References: <1hwu415.1yyvbo61efn1uqN%aleax@mac.com> Message-ID: <1hx2dgy.zizz7ir95hlgN%aleax@mac.com> Jorgen Grahn wrote: ... > > Perhaps the current wave of dual-core and quad-core CPUs in cheap > > consumer products would change people's perceptions -- I wonder... > > Maybe it would change /perceptions/, but would normal users suddenly > start running things that are (a) performance-critical, (b) written in > Python and (c) use algorithms that are possible to parallellize? That depends on what "normal" means. For the common definition (users that don't _write_ programs), it would depend on what ``developers'' release to the world. > I doubt it. (But I admit that I am a bit negative towards thread > programming in general, and I have whined about this before.) I'm no big fan of threading either, believe me. But with multi-core CPUs onrushing, exploiting them requires either that or multiple processes; and, with Windows still prevalent and not exactly a speed daemon in dealing with processes (while pretty good with threads), it would appear likely that threading's here to stay. IronPython would appear to be coming along nicely and getting acceptance in the Windows community, and I believe the underlying dotNet CLR does do threads nicely; we'll see what develops on that front, I guess. Alex From jeremy+complangpython at jeremysanders.net Mon Apr 9 10:32:56 2007 From: jeremy+complangpython at jeremysanders.net (Jeremy Sanders) Date: Mon, 09 Apr 2007 15:32:56 +0100 Subject: Managing a file buffer References: Message-ID: David Johnson wrote: > I have an application that reads video from a socket and saves it to a > file, which I then play using GStreamer. The major problem with this > approach is that the file keeps getting bigger and bigger until the disk > is full ;-) > > What I'd like to do is have a buffer, say 5MB in size, which I can point > GStreamer at. So every time I write 60K to the tail of the file, I'd need > to remove 60K from the head of the file. A named pipe may be useful to you, depending on your buffering requirements, and assuming gstreamer can play from one. e.g. http://www2.linuxjournal.com/article/2156 You can create a named pipe from python. Jeremy -- Jeremy Sanders http://www.jeremysanders.net/ From jstroud at mbi.ucla.edu Fri Apr 13 16:47:48 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Fri, 13 Apr 2007 13:47:48 -0700 Subject: Any way to refactor this? In-Reply-To: <461fe75c$0$11278$c3e8da3@news.astraweb.com> References: <461fe75c$0$11278$c3e8da3@news.astraweb.com> Message-ID: John Salerno wrote: > Setting aside, for the moment, the utility of this method or even if > there's a better way, I'm wondering if this is an efficient way to do > it. I admit, there was some copying and pasting, which is what prompts > me to ask the question. Here's the method. (I hope it looks ok, because > it looks really weird for me right now) > > def _create_3D_xhatches(): > for x in xrange(-axis_length, axis_length + 1): > if x == 0: continue > visual.cylinder(pos=(x,-hatch_length,0), > axis=(0,hatch_length*2,0), radius=hatch_radius) > visual.cylinder(pos=(x,0,-hatch_length), > axis=(0,0,hatch_length*2), radius=hatch_radius) > visual.cylinder(pos=(-hatch_length,x,0), > axis=(hatch_length*2,0,0), radius=hatch_radius) > visual.cylinder(pos=(0,x,-hatch_length), > axis=(0,0,hatch_length*2), radius=hatch_radius) > visual.cylinder(pos=(-hatch_length,0,x), > axis=(hatch_length*2,0,0), radius=hatch_radius) > visual.cylinder(pos=(0,-hatch_length,x), > axis=(0,hatch_length*2,0), radius=hatch_radius) > > Since each call to cylinder requires a slightly different format, I > figured I had to do it this way. > > Thanks. Your parameters don't follow an unambiguous pattern. Probably best is to code the parameters as a set of tuples and iterate over them. James From gdonald at gmail.com Thu Apr 5 18:00:39 2007 From: gdonald at gmail.com (Greg Donald) Date: Thu, 5 Apr 2007 17:00:39 -0500 Subject: ipython env In-Reply-To: References: <15e66e4e0704051448l3f4cb5cesead7ea356729671f@mail.gmail.com> Message-ID: <15e66e4e0704051500w43a4d54ene78296c310ebf837@mail.gmail.com> On 4/5/07, Gabriel Genellina wrote: > > NameError: name 'env' is not defined > > Try os.environ Thanks. -- Greg Donald http://destiney.com/ From jorgen.maillist at gmail.com Tue Apr 17 13:12:05 2007 From: jorgen.maillist at gmail.com (Jorgen Bodde) Date: Tue, 17 Apr 2007 19:12:05 +0200 Subject: PYTHON and GUIS and LOGIC... What First? (NEWBIE) In-Reply-To: <2FAA57395C1F914DB27CAA4C376058F2024352B9@S0-OTT-X2.nrn.nrcan.gc.ca> References: <2FAA57395C1F914DB27CAA4C376058F2024352B9@S0-OTT-X2.nrn.nrcan.gc.ca> Message-ID: <11e49df10704171012k4964870yb4ff00466b5950a4@mail.gmail.com> Hi, Basically your data model needs to be defined. It depends on your 'problem area'. It is usually good practice to keep your datamodel free of GUI elements, so that it can be easily reused. The GUI in the other hand can know everything about the public interface of the data model. I've recently started to use pyDispatcher / wx.lib.pubsub to send messages from the object model to the GUI, notifying about additions / updates so that the individual elements such as the list control showing the items, or other views are updated without you having to make sure any little data change has to be synced with the GUI. The data syncs the GUI through an abstract interface. Python is a really good language for this .. Regards, - Jorgen From exarkun at divmod.com Wed Apr 25 17:05:06 2007 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Wed, 25 Apr 2007 17:05:06 -0400 Subject: bitwise shift? In-Reply-To: Message-ID: <20070425210506.19381.1759732309.divmod.quotient.5350@ohm> On Wed, 25 Apr 2007 22:54:12 +0200, desktop wrote: >I have found a code example with this loop. > >for k in range(10, 25): > n = 1 << k; > > >I have never read Python before but is it correct that 1 get multiplied >with the numbers 10,11,12,12,...,25 assuming that 1 << k means "1 shift >left by k" which is the same as multiplying with k. No. http://python.org/doc/ref/shifting.html Jean-Paul From spradml at gmail.com Thu Apr 26 20:20:26 2007 From: spradml at gmail.com (Pradnyesh Sawant) Date: Fri, 27 Apr 2007 05:50:26 +0530 Subject: passing tuple with pyqt4 signal/slot mechanism Message-ID: <80628d680704261720y5e725de9vfcd96351c2ddf92d@mail.gmail.com> > In the first version it didn't. In the second version it did. in my case, it didn't in the second version either??? > The version of PyQt? The version of SIP? The version of Qt? python2.4: 2.4.4~c1-0ubuntu1 pyqt4: 4.0.1-1ubuntu1 python-sip4: 4.4.5-2ubuntu1 qt4: couldn't see just "qt4" in aptitude ??? (have qt4-qtconfig installed though). qt4-dev-tools not installed (is that needed?) -- warm regards, Pradnyesh Sawant -- Be yourself, everyone else is taken. --Anon From michael at jedimindworks.com Fri Apr 13 08:21:21 2007 From: michael at jedimindworks.com (Michael Bentley) Date: Fri, 13 Apr 2007 07:21:21 -0500 Subject: Arrays, Got Me Confused In-Reply-To: <000101c77dc3$d4152a00$7c3f7e00$@rawlins@thinkbluemedia.co.uk> References: <000101c77dc3$d4152a00$7c3f7e00$@rawlins@thinkbluemedia.co.uk> Message-ID: On Apr 13, 2007, at 7:04 AM, Robert Rawlins - Think Blue wrote: > #!/usr/bin/python > > # Filename: Firewall.py > > > > class Firewall: > > > > def __init__(self): > > Self.FireArray = array(c) > > > > p = Firewall() > > print p > > > > > > Throws: > > > > Traceback (most recent call last): > > File "./firewall.py", line 9, in ? > > p = Firewall() > > File "./firewall.py", line 7, in __init__ > > Self.FireArray = array(c) > > NameError: global name 'array' is not defined > > > > How can I solve this problem? from array import array -------------- next part -------------- An HTML attachment was scrubbed... URL: From gagsl-py2 at yahoo.com.ar Fri Apr 20 23:09:41 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sat, 21 Apr 2007 00:09:41 -0300 Subject: how to transfer integer on socket? References: <1177123738.899837.65250@e65g2000hsc.googlegroups.com> Message-ID: En Fri, 20 Apr 2007 23:48:58 -0300, Frank Potter escribi?: > Is there any easy way to transfer 4 bit integer on socket? Extend it to 8 bits (1 byte) and use a single character (string of length 1) > I want to send like this: > > a=5 > send_integer(socket_s,a) socket_s.send(chr(a)) > and receive like this: > a=receive_integer(socket_s) a = ord(socket_s.recv(1)) -- Gabriel Genellina From mail at microcorp.co.za Wed Apr 18 01:15:11 2007 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Wed, 18 Apr 2007 07:15:11 +0200 Subject: The smallest and largest values of numeric types References: <1176825226.633555.85860@d57g2000hsg.googlegroups.com> Message-ID: <011f01c7817b$43b75f80$03000080@hendrik> "Michael Hoffman" wrote: > 20859248300531693115643211913059311997417115606882000504639505780471641693377296 50765802242049L > > Of course performance decreases for longer longs. I once made a thing that tried to find the limit of longs and stopped when I had two or three screenfulls of numbers. I came to the conclusion that for "integer" arithmetic like this, the limit is either your memory size, or some other number that is so big that in practice you don't have to worry about it.. - Hendrik From phil at riverbankcomputing.co.uk Mon Apr 2 05:14:34 2007 From: phil at riverbankcomputing.co.uk (Phil Thompson) Date: Mon, 2 Apr 2007 09:14:34 +0000 Subject: frame of Qt program In-Reply-To: <5c62a320704020145q246e94cq4f3084fda6af8813@mail.gmail.com> References: <5c62a320704020145q246e94cq4f3084fda6af8813@mail.gmail.com> Message-ID: <200704021014.34958.phil@riverbankcomputing.co.uk> On Monday 02 April 2007 9:45 am, Marco wrote: > Hi, > I want to write a PyQt4 program, which like a graph-ssh. One side > user choose server moder, and other side(s) user choose client mode. > Both of them have a GUI, they can connect via socket. > > I have study PyQt4 for a while and learn a little socket(from W.R > Stevens Unix Networking Programming). But I donot know how to integer > both of them. > > What the frame of this kind of program looked like? Or is there some > example? Look at the network examples included with PyQt4. Particularly fortuneclient.py and fortuneserver.py. PyQt4 has its own network classes that are fully integrated with the event loop making it easy to write GUI/network applications. As threads also have an event loop its also easy to push the network handling out to separate threads. The next version of Qt will add support for SSL. Phil From neelam226013 at gmail.com Thu Apr 5 06:55:29 2007 From: neelam226013 at gmail.com (Neelam007) Date: 5 Apr 2007 03:55:29 -0700 Subject: Make a FREE Call Any Where Any Time Message-ID: <1175770529.234882.117390@l77g2000hsb.googlegroups.com> Make a FREE Call Any Where Any Time No Download, No Registration, Just Enter Mobile No. and Talk Click Below Link http://surl.in/PCOISCR283817GCJWJUK From thorsten at thorstenkampe.de Sun Apr 1 15:08:39 2007 From: thorsten at thorstenkampe.de (Thorsten Kampe) Date: Sun, 1 Apr 2007 20:08:39 +0100 Subject: I18n issue with optik References: Message-ID: * Thorsten Kampe (Sun, 1 Apr 2007 19:45:59 +0100) > Yes, I could do that but I'd rather know first if my code is wrong or > the optparse code. It might be the bug mentioned in http://mail.python.org/pipermail/python-dev/2006-May/065458.html The patch although doesn't work. From my unicode-charset-codepage- codeset-challenged point of view the encoding of sys.stdout doesn't matter. The charset is defined in the .po/.mo file (but of course optparse can't know if the message has been translated by gettext ("_"). Thorsten From jstroud at mbi.ucla.edu Sun Apr 8 22:26:37 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Mon, 09 Apr 2007 02:26:37 GMT Subject: tuples are useless??? In-Reply-To: References: Message-ID: Bart Willems wrote: > James Stroud wrote: >> ... It boils down to the fact that tuples are useless as a result >> unless you know you really need them--and you never really NEED them. > > Could you clarify that for me? I use tuples *a lot* and I really *NEED* > them - I'm building a lot of multi-tier reports where detail-level data > is pulled out of a dictionary based on a composed key. It is impossible > to build those dictionaries *without* using tuples. "Impossible" is a strong word, as is "need" (especially when in all caps). py> import md5 py> class HashedList(list): ... def __hash__(self): ... h = md5.new() ... for item in self: ... h.update(str(hash(item))) ... return int(h.hexdigest(), 16) ... py> hl = HashedList('bob', 'carol', 'ted') py> {hl:3} {['bob', 'carol', 'ted']: 3} Impossible? I wouldn't even say that this was all that difficult. James From facundo at taniquetil.com.ar Wed Apr 11 13:07:15 2007 From: facundo at taniquetil.com.ar (Facundo Batista) Date: Wed, 11 Apr 2007 17:07:15 +0000 (UTC) Subject: pop() clarification References: Message-ID: Scott wrote: > Now I know list is a bad name, but for the sake of arguement lets assume its > not a built in sequence> It's easier to use another name, than writing all that parragraph, ;) > I understand all that. What I don't understand is why all the documentation > I see says, "When removing a specific element from a list using pop() it > must be in this format: list.pop([i]). You're reading it everywhere because it's the correct syntax, ;) > At first I took that to mean that list.pop(i) would return some type of > error, but it doesn't. "i" is enclosed in square brackets because it's optional. So, list.pop(i) is a correct way to call it, as correct as list.pop(). Take note that list.pop([i]) is *not* the correct way to call it. I assume you're getting confused by the [], asuming that those means a list. No. Take a look here: http://www.python.org/doc/current/lib/typesseq-mutable.html As you see there, when an iterable is needed, it just named different, syntax do not use brackets to mean "list". > Now I'm not stupid enough to believe that I'm the first to try: >>>>list = ['this', 'is', 'an', 'example'] >>>>list.pop(1) > and have it return the desired effect of: > 'is' >>>>list > ['this', 'an', 'example'] But try this also: >>> l = ['this', 'is', 'an', 'example'] >>> l.pop([2]) Traceback (most recent call last): File "", line 1, in TypeError: an integer is required Regards, -- . Facundo . Blog: http://www.taniquetil.com.ar/plog/ PyAr: http://www.python.org/ar/ From iogilvy at attglobal.net Fri Apr 27 08:38:30 2007 From: iogilvy at attglobal.net (iogilvy at attglobal.net) Date: 27 Apr 2007 05:38:30 -0700 Subject: creating an object from base class Message-ID: <1177677510.209111.148540@u32g2000prd.googlegroups.com> i wish to have some extended functionality added to sockets i can create my own socket class class mysocket(socket.socket): and all should be fine. Except, the sockets are created for me by the accept method, listening on port. So how can i take the standard socket created for me and create a 'mysocket'. I need a method that will initialise any new properties i have added in my class, but how can i change the class of the socket created? From sbassi at clubdelarazon.org Thu Apr 26 19:06:05 2007 From: sbassi at clubdelarazon.org (Sebastian Bassi) Date: Thu, 26 Apr 2007 20:06:05 -0300 Subject: Python CGI and Browser timeout In-Reply-To: <1177624109.532664.105840@t39g2000prd.googlegroups.com> References: <1177624109.532664.105840@t39g2000prd.googlegroups.com> Message-ID: <9e2f512b0704261606u688cd5c5sf5f4f017dbbba26@mail.gmail.com> On 26 Apr 2007 14:48:29 -0700, skulka3 at gmail.com wrote: > Is there a better solution to avoid browser timeouts? Raising timeout in Apache, by default is 300 seconds. Limiting jobs size (both in the html form and from script size since you should not trust on client validations). -- Sebasti?n Bassi (???????) Diplomado en Ciencia y Tecnolog?a. GPG Fingerprint: 9470 0980 620D ABFC BE63 A4A4 A3DE C97D 8422 D43D Club de la raz?n (www.clubdelarazon.org) From michele.petrazzoDELETE at DELETEunipex.it Fri Apr 27 12:25:15 2007 From: michele.petrazzoDELETE at DELETEunipex.it (Michele Petrazzo) Date: Fri, 27 Apr 2007 16:25:15 GMT Subject: Learning to use wxPython In-Reply-To: <1177690277.346950.120860@u32g2000prd.googlegroups.com> References: <1177690277.346950.120860@u32g2000prd.googlegroups.com> Message-ID: KDawg44 wrote: > Hi, > Hi, > I downloaded the wxPython demo and did an emerge wxpython (gentoo) to > install. When I run the demo, I am getting this error: > > > # python demo.py Traceback (most recent call last): File > "/usr/lib/python2.4/site-packages/wx-2.6-gtk2-ansi/wx/ _misc.py", > line 1286, in Notify From here, I read that you are using the wx version 2.6 and the demo that you are tring are for the 2.8.3! (the last as now). So: 1) install the new 2.8 2) download the demo for the 2.6! :) Bye, Michele From aleax at mac.com Thu Apr 19 23:00:32 2007 From: aleax at mac.com (Alex Martelli) Date: Thu, 19 Apr 2007 20:00:32 -0700 Subject: What makes an iterator an iterator? References: <1hwr9pv.13v4ci6106qn0aN%aleax@mac.com> <1176936067.315082.17970@y80g2000hsf.googlegroups.com> <1hws6rd.u0a6hd78fhhpN%aleax@mac.com> Message-ID: <1hwu1v2.19iwhy91t1140nN%aleax@mac.com> Steven D'Aprano wrote: > > Calling a generator, such as this next method, returns an iterator > > object; calling it repeatedly returns many such iterator objects, and > > never raises StopIteration, thus obviously producing an unending loop. > > Thank you for that answer Alex, even though I didn't ask the question I > was wondering the same thing myself. You're welcome -- refreshing to see somebody who can actually understand and accept the answer, rather than going on unrelated tangents when one tries to help them:-). Alex From robert.kern at gmail.com Tue Apr 24 12:49:08 2007 From: robert.kern at gmail.com (Robert Kern) Date: Tue, 24 Apr 2007 11:49:08 -0500 Subject: noob questions In-Reply-To: <1177428999.023481.98160@b40g2000prd.googlegroups.com> References: <1177428999.023481.98160@b40g2000prd.googlegroups.com> Message-ID: T.Crane wrote: > I'm new to python and I seem to get different behavior depending on... > well who knows what. Here's my question concerning importation of > packages/modules. > > I want to use scipy. So at the prompt (using iPython, installed with > Enthought edition on Windows XP) I type: > > ln [1]: from scipy import * > > Now, I know integrate is a package this is in scipy. I want to use > the ode class/module that's in integrate. So I type: > > ln [2]: from integrate import * > > And I'm told > > ImportError: No module named integrate > > In order to get access to the ode class, I end up having to type: > > ln [3]: from scipy.integrate import * > > Then it works. Will someone explain to me what I'm misunderstanding? > I don't understand why after importing everything in scipy (which > includes integrate), I was told there was no module named integrate. > What gives? I there are sevarl functions (modules) that I want to use > that are a few levels down from the root package, what's the most > economical method of importing them? Everything Steve Holden said is correct. I'll just add that we do have a function that will load all of the subpackages. import scipy scipy.pkgload() from scipy import * We don't load all of the subpackages by default because we have a lot of extension modules that link to largish libraries. Loading all of them all of the time takes substantial amounts of time. Also, I don't recommend using either pkgload or "from scipy import *" in code. However, from the interactive prompt, feel free. That is precisely what these features were designed for. -- 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 bdesth.quelquechose at free.quelquepart.fr Thu Apr 5 15:47:19 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Thu, 05 Apr 2007 21:47:19 +0200 Subject: Why NOT only one class per file? In-Reply-To: References: <1175721799.714907.52770@o5g2000hsb.googlegroups.com> <46142acc$0$7532$426a34cc@news.free.fr> <4614b40e$0$26843$426a74cc@news.free.fr> Message-ID: <46154952$0$23907$426a74cc@news.free.fr> Sherm Pendley a ?crit : > Bruno Desthuilliers writes: > > >>Sherm Pendley a ?crit : >> >> >>>It's a stylistic thing, nothing more. >> >>A bit more than just 'stylistic' IMHO. It's a matter of >>convenience. Having to manage hundreds of files each with a dozen >>lines of code is a PITA. > > > Yes, but the pain in that case comes from having hundreds of trivial > classes, The fact that a class is short doesn't imply it's trivial. > not from the way in which the source for them is organized. I have to disagree. Having several, closely related objects (ie: classes, functions, etc) in a same file allow to "see the big picture", and avoids the mental overhead of navigating thru files, directories, opened windows etc. Of course, it doesn't mean that one should store the whole program in a single monster file - I usually start to rearrange things when the file grows bigger than one thousand lines. >>Having to retype the same import statements >>in hundreds of files is a PITA - and a good way to waste time and >>forget something when one has to fix these import statements (yes, >>even with the appropriate tediting tools). I wouldn't call such >>considerations "nothing more than stylistic". > > Neither would I. But then, I would describe the existence of all those > files as just the symptom - the real problem being the design that needs > all of those hundreds of trivial classes in the first place. In my book, it's huge classes and methods that are usually a smell of a design problem. Specially with languages like Python or Ruby. Factoring out code duplication usually leads to lot of small objects - and also to a significant reduction of the code base's size. > Granted, I know very little of Python. It may be the case that Python > encourages the use of hundreds of "little classes" Python being very expressive, and having powerful metaprogramming features, there's usually much less boilerplate (than in languages like Java) for a same result. So yes, it's quite usual to have small classes and functions. > - and if that is the > case, then I agree, storing each one in its own file would be rather > absurd. Indeed. That's the point (or at least part of it). > I'm more accustomed to writing classes that tend to be larger - hundreds > if not thousands of lines each, It sometimes happens that a class or function needs to be much bigger than the average. So be it. But if I found myself writing thousands-lines classes in Python, I'd start to seriously consider rethinking the whole stuff.... Heck, I have very few *modules* that are more than one thousand lines long, and almost never a single class per module. > or more - In Python ??? From aahz at pythoncraft.com Wed Apr 4 19:59:15 2007 From: aahz at pythoncraft.com (Aahz) Date: 4 Apr 2007 16:59:15 -0700 Subject: how can I clear a dictionary in python References: <1175121525.261424.72350@n76g2000hsh.googlegroups.com> Message-ID: In article , Antoon Pardon wrote: >On 2007-04-03, Aahz wrote: >> In article , >> Larry Bates wrote: >>>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. >> >> Then you should explain why you didn't answer the question that was >> asked. Answering a different question without explanation makes your >> answer irrelevant at best, wrong at worst. > >This is not true. If this different question was in fact the intended >question instead of the one actually asked. Anwering this different >question can be more usefull than answering the one actually asked. Note carefully that I did not say, "Don't answer the question you think should have been asked." What I said was, "If you answer a different question, EXPLAIN WHY." Is that so difficult to understand? -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ Why is this newsgroup different from all other newsgroups? From robert.rawlins at thinkbluemedia.co.uk Mon Apr 16 12:02:23 2007 From: robert.rawlins at thinkbluemedia.co.uk (Robert Rawlins - Think Blue) Date: Mon, 16 Apr 2007 17:02:23 +0100 Subject: file resume In-Reply-To: <1176739022.736716.245950@y80g2000hsf.googlegroups.com> References: <1176739022.736716.245950@y80g2000hsf.googlegroups.com> Message-ID: <003f01c78040$9f98ec10$decac430$@rawlins@thinkbluemedia.co.uk> Do the same again, but change that 'wb' to 'a' for append :-D should sort you out. Rob -----Original Message----- From: python-list-bounces+robert.rawlins=thinkbluemedia.co.uk at python.org [mailto:python-list-bounces+robert.rawlins=thinkbluemedia.co.uk at python.org] On Behalf Of luca72 Sent: 16 April 2007 16:57 To: python-list at python.org Subject: file resume Hello at all: if i have one file written in binary mode, how can i append others binary data to this file after the its closure. ex my_file = open('blabal', 'wb') then i write something and then my_file.close() now if i need to open it again and append other binary data how can i proceed? Regards Luca -- http://mail.python.org/mailman/listinfo/python-list From phil at riverbankcomputing.co.uk Fri Apr 27 02:58:59 2007 From: phil at riverbankcomputing.co.uk (Phil Thompson) Date: Fri, 27 Apr 2007 07:58:59 +0100 Subject: passing tuple with pyqt4 signal/slot mechanism In-Reply-To: <80628d680704261720y5e725de9vfcd96351c2ddf92d@mail.gmail.com> References: <80628d680704261720y5e725de9vfcd96351c2ddf92d@mail.gmail.com> Message-ID: <200704270758.59651.phil@riverbankcomputing.co.uk> On Friday 27 April 2007 1:20 am, Pradnyesh Sawant wrote: > > In the first version it didn't. In the second version it did. > > in my case, it didn't in the second version either??? > > > The version of PyQt? The version of SIP? The version of Qt? > > python2.4: 2.4.4~c1-0ubuntu1 > pyqt4: 4.0.1-1ubuntu1 > python-sip4: 4.4.5-2ubuntu1 > qt4: couldn't see just "qt4" in aptitude ??? > (have qt4-qtconfig installed though). > qt4-dev-tools not installed (is that needed?) Then upgrade to a current version of PyQt. Phil From oscartheduck at gmail.com Wed Apr 4 13:38:24 2007 From: oscartheduck at gmail.com (oscartheduck) Date: 4 Apr 2007 10:38:24 -0700 Subject: try... except SyntaxError: unexpected EOF while parsing Message-ID: <1175708304.034078.139020@e65g2000hsc.googlegroups.com> I have a small script for doing some ssh stuff for me. I could have written it as shell script, but wanted to improve my python skills some. RIght now, I'm not catching a syntax error as I'd like to. Here's my code: #!/usr/bin/env python import sys import os port = input("Please enter a port to connect on. If you're unsure or just want the default of port 2024 just hit enter -- ") try: if port > 65535: print "That's not a valid port number, sorry. Between 0 and 65535 is cool." sys.exit() else: cmd = 'su root -c "/usr/sbin/sshd -p %s"' % port except SyntaxError: cmd = 'su root -c "/usr/sbin/sshd -p 2024;exit"' os.system(cmd) I'm under the impression that the except should catch the syntax error and execute the "default" command, but hitting enter at the input value doesn't lead to that. Any ideas what's going wrong? From richardjones at optushome.com.au Wed Apr 18 02:07:31 2007 From: richardjones at optushome.com.au (Richard Jones) Date: Wed, 18 Apr 2007 16:07:31 +1000 Subject: Future Python Gui? References: <1176859699.906386.326720@b75g2000hsg.googlegroups.com> <1176863948.526051.186210@n76g2000hsh.googlegroups.com> Message-ID: <4625b5a2$0$22843$afc38c87@news.optusnet.com.au> kirkjobsluder wrote: > I'd say that the best bet is to learn swig and similar > bridging, expanding, and embedding mechanisms. For GUI programming this would seem overkill. Pick a GUI toolkit and it's almost guaranteed to be wrapped for use in Python already. Richard From bbxx789_05ss at yahoo.com Mon Apr 9 01:08:30 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: 8 Apr 2007 22:08:30 -0700 Subject: shelve error In-Reply-To: <1hw9lxy.ldrc541w507xyN%aleax@mac.com> References: <1175746456.995618.186190@e65g2000hsc.googlegroups.com> <1175746966.023613.178830@n76g2000hsh.googlegroups.com> <1175756092.643182.142420@n76g2000hsh.googlegroups.com> <1hw9lxy.ldrc541w507xyN%aleax@mac.com> Message-ID: <1176095310.492686.78880@p77g2000hsh.googlegroups.com> > Discussion subject changed to "Python universal build, OSX 10.3.9 and undefined symbols when > linking" by David Pratt What gives? How come you can change the title of my thread? On Apr 8, 8:14 pm, a... at mac.com (Alex Martelli) wrote: > But if you open an errata for the missing explanation for the different > default value of the flag argument (use URL > ), I'll be glad to > fix it for the next printing... In my opinion, the most valuable thing you could do for a next printing would be to expand the index to 3 times its current length. As it is now, I think the index is woefully inadequate, which I find surprising for a reference book. I haven't been able to find 3/4 of the things I have looked up in the index. For instance __get__(), __set__(), and sorted() are nowhere to be found in the index. Also, the book is brand new, yet the cover has completely separated from the spine of the book, and now the cover is only attached to the first and last pages with a bit of glue. From michael at jedimindworks.com Sun Apr 22 19:35:32 2007 From: michael at jedimindworks.com (Michael Bentley) Date: Sun, 22 Apr 2007 18:35:32 -0500 Subject: recursion depth problem In-Reply-To: <1177282027.798037.48210@o5g2000hsb.googlegroups.com> References: <1177267774.416169.276780@e65g2000hsc.googlegroups.com> <1177275314.846022.249000@e65g2000hsc.googlegroups.com> <1177276111.720137.315710@b75g2000hsg.googlegroups.com> <1177282027.798037.48210@o5g2000hsb.googlegroups.com> Message-ID: <90679236-0D2C-42EF-B93F-06A1DD561944@jedimindworks.com> On Apr 22, 2007, at 5:47 PM, proctor wrote: > On Apr 22, 4:37 pm, Michael Bentley wrote: >> On Apr 22, 2007, at 4:08 PM, proctor wrote: >> >> >> >>> On Apr 22, 2:55 pm, half.ital... at gmail.com wrote: >>>> On Apr 22, 11:49 am, proctor <12cc... at gmail.com> wrote: >> >>>>> hello, >> >>>>> i have a small function which mimics binary counting. it runs >>>>> fine as >>>>> long as the input is not too long, but if i give it input longer >>>>> than >>>>> 8 characters it gives >> >>>>> RuntimeError: maximum recursion depth exceeded in cmp >> >>>>> i'm not too sure what i am doing improperly. is there really a >>>>> lot of >>>>> recursion in this code? >> >>>>> ================== >> >>>>> import sys >> >>>>> def ch4(item, n=0): >>>>> if n < len(item): >>>>> if item[n] == '0': >>>>> item[n] = '1' >>>>> print ''.join(item) >>>>> ch4(item) >>>>> elif item[n] == '1': >>>>> item[n] = '0' >>>>> ch4(item, n+1) >> >>>>> ch4(list(sys.argv[1])) >> >>>>> ================== >> >>>>> this function expects input in the form of a string of zeros, like >>>>> this: >> >>>>> python test-bin.py 00000000 >> >>>>> and is expected to output a list of permutations like this: >> >>>>> $ python test-bin.py 0000 >>>>> 1000 >>>>> 0100 >>>>> 1100 >>>>> 0010 >>>>> 1010 >>>>> 0110 >>>>> 1110 >>>>> 0001 >>>>> 1001 >>>>> 0101 >>>>> 1101 >>>>> 0011 >>>>> 1011 >>>>> 0111 >>>>> 1111 >> >>>>> thanks for all help! >> >>>>> sincerely, >>>>> proctor >> >>>> If you just want to make it work as is....check >> >>>> sys.setrecursionlimit() >> >>>> ~Sean >> >>> very nice. thanks sean. so is the structure of my original code >>> unrescuable? i cannot rearrange it to bypass the recursion? >> >> Anything that can be done with recursion can be done without >> recursion. If you really wanted to mimic a binary counter, why not >> write a function that converts a number to binary? >> >> Then you could just count up from 0, printing the return from your >> binary conversion function... >> >> And the binary converter would be pretty easy too: just think of it >> as making change -- for a given number you just divide the number by >> each of [2 ** x for x in range(len(sys.argv[1]), 0, -1)] and append >> the string representations of the answers to a list and if the answer >> is 1, subtract that much from the number... > > cool... i'm going to have to think about this one... :-) > he he... Run this snippet and see if it makes more sense: def binary(val, width): print '%10s = the sum of' % val for i in [2 ** x for x in range(width, 0, -1)]: a = val / i print ' ' * 13 + '%s * (2 ** %s)' % (a, i) val -= i * a binary(333, 8) From martin at v.loewis.de Tue Apr 17 16:20:14 2007 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Tue, 17 Apr 2007 22:20:14 +0200 Subject: C++ extension problem In-Reply-To: <1176823014.623736.134960@l77g2000hsb.googlegroups.com> References: <1176741526.541997.52100@e65g2000hsc.googlegroups.com> <4623EE59.7020800@v.loewis.de> <1176823014.623736.134960@l77g2000hsb.googlegroups.com> Message-ID: <46252bff$0$4691$9b622d9e@news.freenet.de> > I assumed that the compiler would warn me about that kind of problem, > but I know better know. :) It's a variable argument list (...). The compiler is not supposed to give any warnings for that (although I do have a gcc patch that enables warnings for PyArg_ParseTuple). > Still, the error message is somewhat confusing. Passing incorrect parameters to variable argument lists causes undefined behavior. Anything can happen under undefined behavior, including mysterious error messages, erasure of your hard disk, and reversal of the global warming. To understand why the specific error message is printed, you would have to debug what values are passed on the stack at what point. Regards, Martin From me2 at privacy.net Mon Apr 30 02:23:58 2007 From: me2 at privacy.net (Spin Dryer) Date: Mon, 30 Apr 2007 07:23:58 +0100 Subject: Free Windows Vista Download References: <1177866404.344342.175400@h2g2000hsg.googlegroups.com> Message-ID: On Sun, 29 Apr 2007 20:23:22 -0400, ["Alvin Bruney [MVP]" ] said :- >That's a misleading post, you should indicate that this is an evaluation >copy. You did it again Sonny, making yourself look a total fool. Will you stop top posting replies to spam and _leaving the spamed site attached_. From linus at fixedstars.com.au Sat Apr 28 01:54:07 2007 From: linus at fixedstars.com.au (Linus Cohen) Date: 27 Apr 2007 22:54:07 -0700 Subject: Beginner Ping program Message-ID: <1177739647.737759.32610@u30g2000hsc.googlegroups.com> Hi all, I'm a newbie to python and programming in general, so I wanted a simple project to start off. What I'm trying to do here is write a python command-line ping program, much like the Unix and Windows ping programs. I've got this much worked out already: class ping def PING(IP, pings, size): and that's where I stop, because I realize I have no idea how to make python send ICMP request packets. My previous project(an email reader using poplib)used the stuff in section 18 of the modules index(internet protocols) but I can't seem to find an equivalent for ICMP packets. If anyone has help on this, I would really appreciate it. Cheers, Linus From bbxx789_05ss at yahoo.com Wed Apr 11 17:08:35 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: 11 Apr 2007 14:08:35 -0700 Subject: Nested dictionaries trouble In-Reply-To: <1176317876.917874.58040@n59g2000hsh.googlegroups.com> References: <1176317876.917874.58040@n59g2000hsh.googlegroups.com> Message-ID: <1176325715.951076.4790@w1g2000hsg.googlegroups.com> IamIan wrote: > Hello, > > I'm writing a simple FTP log parser that sums file sizes as it runs. I > have a yearTotals dictionary with year keys and the monthTotals > dictionary as its values. The monthTotals dictionary has month keys > and file size values. The script works except the results are written > for all years, rather than just one year. I'm thinking there's an > error in the way I set my dictionaries up or reference them... > > import glob, traceback > > years = ["2005", "2006", "2007"] > months = ["01","02","03","04","05","06","07","08","09","10","11","12"] > # Create months dictionary to convert log values > logMonths = > {"Jan":"01","Feb":"02","Mar":"03","Apr":"04","May":"05","Jun":"06","Jul":"07","Aug":"08","Sep":"09","Oct":"10","Nov":"11","Dec":"12"} > # Create monthTotals dictionary with default 0 value > monthTotals = dict.fromkeys(months, 0) > # Nest monthTotals dictionary in yearTotals dictionary > yearTotals = {} > for year in years: > yearTotals.setdefault(year, monthTotals) > > currentLogs = glob.glob("/logs/ftp/*") > > try: > for currentLog in currentLogs: > readLog = open(currentLog,"r") > for line in readLog.readlines(): > if not line: continue > if len(line) < 50: continue > logLine = line.split() > > # The 2nd element is month, 5th is year, 8th is filesize > # Counting from zero: > > # Lookup year/month pair value > logMonth = logMonths[logLine[1]] > currentYearMonth = yearTotals[logLine[4]][logMonth] > > # Update year/month value > currentYearMonth += int(logLine[7]) > yearTotals[logLine[4]][logMonth] = currentYearMonth > except: > print "Failed on: " + currentLog > traceback.print_exc() > > # Print dictionaries > for x in yearTotals.keys(): > print "KEY",'\t',"VALUE" > print x,'\t',yearTotals[x] > #print " key",'\t',"value" > for y in yearTotals[x].keys(): > print " ",y,'\t',yearTotals[x][y] > > > Thank you, > Ian 1) You have this setup: logMonths = {"Jan":"01", "Feb":"02",...} yearTotals = { "2005":{"01":0, "02":0, ....} "2006": "2007": } Then when you get a result such as "Jan", you look up "Jan" in the logMonths dictionary to get "01". Then you use "01" and the year, say "2005", to look up the value in the yearTotals dictionary. What is the point of even having the logMonths dictionary? Why not make "Jan" the key in the the "2005" dictionary and look it up directly: yearTotals = { "2005":{"Jan":0, "Feb":0, ....} "2006": "2007": } That way you could completely eliminate the lookup in the logMonths dict. 2) In this part: logMonth = logMonths[logLine[1]] currentYearMonth = yearTotals[logLine[4]][logMonth] # Update year/month value currentYearMonth += int(logLine[7]) yearTotals[logLine[4]][logMonth] = currentYearMonth I'm not sure why you are using all those intermediate steps. How about: yearTotals[logLine[4]][logLine[1]] += int(logLine[7]) To me that is a lot clearer. Or, you could do this: year, month, val = logLine[4], logLine[1], int(logLine[7]) yearTotals[year][month] += val 3) >I'm thinking there's an error in the way >I set my dictionaries up or reference them Yep. It's right here: for year in years: yearTotals.setdefault(year, monthTotals) Every year refers to the same monthTotals dict. You can use a dict's copy() function to make a copy: monthTotals.copy() Here is a reworking of your code that also eliminates a lot of typing: import calendar, pprint years = ["200%s" % x for x in range(5, 8)] print years months = list(calendar.month_abbr) print months monthTotals = dict.fromkeys(months[1:], 0) print monthTotals yearTotals = {} for year in years: yearTotals.setdefault(year, monthTotals.copy()) pprint.pprint(yearTotals) logs = [ ["", "Feb", "", "", "2007", "", "", "12"], ["", "Jan", "", "", "2005", "", "", "3"], ["", "Jan", "", "", "2005", "", "", "7"], ] for logLine in logs: year, month, val = logLine[4], logLine[1], int(logLine[7]) yearTotals[year][month] += val for x in yearTotals.keys(): print "KEY", "\t", "VALUE" print x, "\t", yearTotals[x] for y in yearTotals[x].keys(): print " ", y, "\t", yearTotals[x][y] From steve at holdenweb.com Mon Apr 16 08:30:08 2007 From: steve at holdenweb.com (Steve Holden) Date: Mon, 16 Apr 2007 08:30:08 -0400 Subject: How to tell whetehr Python script called as CGI or from command line? In-Reply-To: <1176725137.128549.131130@p77g2000hsh.googlegroups.com> References: <1176725137.128549.131130@p77g2000hsh.googlegroups.com> Message-ID: rowan at sylvester-bradley.org wrote: > I'm writing a Python script that can either be called as a Cron job or > as a web page (i.e. as a CGI in response to an HTTP request). This is > to process the mailboxes on my web server (to which I don't have > command line access) to remove old messages. How do I find out whether > the script has been called as a Cron job or as a CGI? I need to know > this so I can format the output correctly, e.g. if this is a web > request I need to start the output with "Content-type: text/html\n > \n", to do newlines by "

" or "
" etc. > > Can I just access some header line which will always have a value in a > web request, but which will be None if running from the command line > or as a Cron job, or something similar? How? > > Thanks - Rowan > The CGI standard requires that the calling server sets several environment variables, so you could test for the presence of one or more of those - this is only going to be indicative, though, since any shell could have the same variables set in its environment. import os if "QUERY_STRING" in os.environ: # CGI script might work. 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 holdenweb.com Sun Apr 1 05:45:12 2007 From: steve at holdenweb.com (Steve Holden) Date: Sun, 01 Apr 2007 05:45:12 -0400 Subject: socket read timeout In-Reply-To: <000e01c771d2$2f3dd240$03000080@hendrik> References: <17930.25631.86693.827473@montanaro.dyndns.org> <000e01c771d2$2f3dd240$03000080@hendrik> Message-ID: 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? > Yes. But you have to use non-blocking calls in your application to use them as full-duplex in your code. > I know Ethernet isn't. > Don't know much, then, do you? ;-) 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 holdenweb.com Tue Apr 3 14:49:07 2007 From: steve at holdenweb.com (Steve Holden) Date: Tue, 03 Apr 2007 14:49:07 -0400 Subject: raw_input just continues anyway? In-Reply-To: <1175623979.629946.184530@b75g2000hsg.googlegroups.com> References: <1175606844.249364.290060@o5g2000hsb.googlegroups.com> <57f489F2c787iU1@mid.individual.net> <1175611910.685578.246780@w1g2000hsg.googlegroups.com> <1175623979.629946.184530@b75g2000hsg.googlegroups.com> Message-ID: oliver at obeattie.com wrote: > How could I resolve this? > Try to keep each answer so it makes sense on its own, please. I presume you are responding to this: > In <1175611910.685578.246780 at w1g2000hsg.googlegroups.com>, > oliver at obeattie.com wrote: > >> > if __name__ == "__main__": >> > bucket_name = raw_input('Name of the bucket you wish the files to be >> > placed into? ') >> > update_s3() >> > >> > >> > Basically I pipe some files into the script - so would this cause a >> > linebreak? > > Yes of course. `raw_input()` is reading from `stdin` so the very first > line you pipe in will be assigned to `bucket_name`. > from Marc 'BlackJack' Rintsch? Essentially you seem to want to use standard input for two separate purposes: one to provide the name of a bucket (which it appears you would like to specify interactively) and the other to provide a list of filenames that your script has to process. I would suggest in that case providing the bucket name as a command-line argument. That way standard input can be limited to communicating filenames, and your pipeline doesn't need to contain two separate types of information. Your code would then become (without error checking): if __name__ == '__main__': import sys bucket_name = sys.argv[1] update_s3() I assume from this code, by the way, that update_s3() makes use of the bucket name as a global variable. While this will work it isn't best practice. You might want to consider passing bucket_name as an argument to update_s3() (and you won't need to change the code of update_s3() if you call the argument bucket_name too). Hope this serves to help rather than confuse. 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 Mon Apr 30 02:16:30 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 30 Apr 2007 03:16:30 -0300 Subject: Beginner question on threads References: Message-ID: En Sun, 29 Apr 2007 22:50:59 -0300, Teresa Hardy escribi?: > I have successfully made the threading work on a Window XP machine with > quad > processors but now I am trying to pass some variables around and am > fighting > with Lock() If there is the possibility that the same thread had acquired the lock earlier, you should use an RLock instead. Without more context, I can't tell anymore. -- Gabriel Genellina From sergio.correia at gmail.com Wed Apr 4 19:03:01 2007 From: sergio.correia at gmail.com (Sergio Correia) Date: Wed, 4 Apr 2007 19:03:01 -0400 Subject: How to open a txt file from the same folder as my module (w/out changing the working dir) Message-ID: I have a program in 'C:\Python25\Lib\site-packages\spam\spam.py' Importing and everything works fine: >>> from spam import spam But the program calls a file located on the same folder (that is: C:\Python25\Lib\site-packages\spam\). How do i do that? >>> spam.eggs() Traceback (most recent call last): File "", line 1, in datita = spam.eggs() File "C:\Python25\lib\site-packages\spam\spam.py", line 149, in JustDoIt config = open("configuration.txt", "rb").read().split('\r\n') IOError: [Errno 2] No such file or directory: 'configuration.txt' My last resort is to hard code the path for that file, but it's ugly, and I want to know if I'm missing something. Am I? Thanks a lot, Sergio From kw at codebykevin.com Fri Apr 20 09:45:16 2007 From: kw at codebykevin.com (Kevin Walzer) Date: Fri, 20 Apr 2007 09:45:16 -0400 Subject: using tkinter to display html In-Reply-To: References: Message-ID: <2e295$4628c3ed$4275d90a$24599@FUSE.NET> Stephen M. Gava wrote: > Hi all, > > I prefer using tkinter to wxpython (so sue me :) and i need to display a > lot of html in a particular app. does anyone know if one of the existing > add on tk html widgets have been wrapped for tkinter already? > > TIA for any reply, > Stephen PySol has an HTML viewer. Here's a link to some discusison about it: http://mail.python.org/pipermail/tkinter-discuss/2006-January/000614.html PySol is GPL, so if your application is also GPL, then it might be an option. -- Kevin Walzer Code by Kevin http://www.codebykevin.com From evenprimes at gmail.com Mon Apr 23 11:30:51 2007 From: evenprimes at gmail.com (Chris Cioffi) Date: Mon, 23 Apr 2007 11:30:51 -0400 Subject: When are immutable tuples *essential*? Why can't you just use lists *everywhere* instead? In-Reply-To: References: <1177088796.622928.224890@d57g2000hsg.googlegroups.com> <1177089206.550423.288670@q75g2000hsh.googlegroups.com> <58sf33F2b1q8tU1@mid.individual.net> <1177103370.022138.110320@n59g2000hsh.googlegroups.com> <1177108560.660288.171890@n76g2000hsh.googlegroups.com> Message-ID: On 23 Apr 2007 17:19:15 +0200, Neil Cerutti wrote: > So the question becomes: Why do Python dictionaries require keys > to be of an immutable type? Dictionary keys are hashed values. If you change the key, you change the hash and lose the pointer to the referenced object. Or: Because. ;-) Chris -- "A little government and a little luck are necessary in life, but only a fool trusts either of them." -- P. J. O'Rourke From jackson at hotmail.com Thu Apr 26 01:28:38 2007 From: jackson at hotmail.com (Bill Jackson) Date: Wed, 25 Apr 2007 22:28:38 -0700 Subject: Preferred Random Library In-Reply-To: <7xzm4vu33m.fsf@ruckus.brouhaha.com> References: <7xzm4vu33m.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote the following on 04/25/2007 10:17 PM: > Bill Jackson writes: >> Is there a preferred random library? > > Preferred for what? Maybe you want os.urandom(). How about for general usage...I am just asking for a very broad description of the advantages/disadvantages of each. For instance, what is the scipy.random equivalent of random.jumpahead()? From mcPas.De.Spam at mclaveauPas.De.Spam.com Mon Apr 9 06:01:48 2007 From: mcPas.De.Spam at mclaveauPas.De.Spam.com (Michel Claveau) Date: Mon, 09 Apr 2007 12:01:48 +0200 Subject: Kill thread References: <1176110066.940676.173020@e65g2000hsc.googlegroups.com> Message-ID: Hi! If you have the PID of the process (example: 1234), use this command-line : TASKKILL /F /PID 1234 -- @-salutations Michel Claveau From steve at holdenweb.com Sat Apr 7 07:05:06 2007 From: steve at holdenweb.com (Steve Holden) Date: Sat, 07 Apr 2007 07:05:06 -0400 Subject: os.path.isfile() error In-Reply-To: <1175938276.097739.28480@n76g2000hsh.googlegroups.com> References: <1175936167.548551.289600@n76g2000hsh.googlegroups.com> <1175938276.097739.28480@n76g2000hsh.googlegroups.com> Message-ID: mik3l3374 at gmail.com wrote: > On Apr 7, 4:56 pm, "7stud" wrote: >> Here's the code: >> ------------ >> import os, os.path, pprint >> >> mydir = "/Users/me/2testing" >> >> files = [file for file in os.listdir(mydir)] >> pprint.pprint(files) >> >> print os.path.join(mydir, "helloWorld.py") >> >> files = [file >> for file in os.listdir(mydir) >> if os.path.isfile(os.path.join(dir, file) ) >> ] >> >> pprint.pprint(files) >> ----output:---------------- >> >> ['.DS_Store', 'cpTest', 'dir1', 'testfile1', 'xmlFile.xml'] >> /Users/me/2testing/helloWorld.py >> Traceback (most recent call last): >> File "test1.py", line 16, in ? >> files = [file >> File "/System/Library/Frameworks/Python.framework/Versions/2.3/lib/ >> python2.3/posixpath.py", line 62, in join >> elif path == '' or path.endswith('/'): >> AttributeError: 'builtin_function_or_method' object has no attribute >> 'endswith' > > is 'dir' defined? or is it 'mydir'? > [this is for 7stud, not for the poster] Clearly it should be 'mydir', but 'dir' is also defined - it's a built-in function, which is why it has no 'endswith' method. 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 Thu Apr 12 03:56:37 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: 12 Apr 2007 00:56:37 -0700 Subject: wxPython, mac, wx.HSCROLL not working Message-ID: <1176364597.741079.25840@n59g2000hsh.googlegroups.com> Hi, I'm trying to allow for a horizontal scrollbar on a textarea, but the scrollbar won't appear when I enter a long string of text(by leaning on one character on my keyboard): import wx app = wx.App() win = wx.Frame(None, title="Text Editor", size=(150, 150) ) tb = wx.TextCtrl(win, pos=(5, 35), size=(100, 100), style=wx.TE_MULTILINE | wx.HSCROLL) win.Show() app.MainLoop() From attn.steven.kuo at gmail.com Mon Apr 16 14:11:08 2007 From: attn.steven.kuo at gmail.com (attn.steven.kuo at gmail.com) Date: 16 Apr 2007 11:11:08 -0700 Subject: script for seconds in given month? In-Reply-To: References: <1176740556.859125.221980@l77g2000hsb.googlegroups.com> <1176742604.907208.310290@l77g2000hsb.googlegroups.com> Message-ID: <1176747068.414987.178490@n59g2000hsh.googlegroups.com> On Apr 16, 10:18 am, s... at pobox.com wrote: > Matt> from time import mktime > Matt> def secondsInMonth(year, month): > Matt> s1 = mktime((year,month,1,0,0,0,0,0,-1)) > Matt> s2 = mktime((year,month+1,1,0,0,0,0,0,-1)) > Matt> return s2-s1 > > Probably won't work if month==12. ;-) > > Skip Actually, mktime as described in the C Standard does not restrict members such as tm_mon of struct tm to the range 0-11 (1-12 for the corresponding entry in the time tuple in Python). So the underlying struct in CPython may be normalized and return a perfectly valid time even if month is > 12. -- Regards, Steven From webraviteja at gmail.com Thu Apr 19 07:33:37 2007 From: webraviteja at gmail.com (Ravi Teja) Date: 19 Apr 2007 04:33:37 -0700 Subject: Helpbook and CHM In-Reply-To: <1176980292.290091.10420@y5g2000hsa.googlegroups.com> References: <1176979477.204864.72900@n59g2000hsh.googlegroups.com> <1176980292.290091.10420@y5g2000hsa.googlegroups.com> Message-ID: <1176982417.221318.215750@n59g2000hsh.googlegroups.com> On Apr 19, 3:58 am, Teja wrote: > On Apr 19, 3:48 pm, Tim Golden wrote: > > > Teja wrote: > > > how to generate CHM files in Boa(Python)??? > > > http://www.rutherfurd.net/software/rst2chm/index.html > > > TJG > > Can't I do it in Boa constructor ??? I have seen an option in Boa to > create a new helpbook and compile it to CHm and help files, But no > clue how to do it....... Not that I know of. Which version are you using? Where in the application did you find it? Indicate the menu's you navigated to get to that option. MS HTML Help Workshop is the standard compiler for CHM files. There are some other freeware/shareware. The workshop is simple enough though. From steve at holdenweb.com Fri Apr 13 09:23:25 2007 From: steve at holdenweb.com (Steve Holden) Date: Fri, 13 Apr 2007 09:23:25 -0400 Subject: mx.ODBC minor problem In-Reply-To: <9971678.post@talk.nabble.com> References: <9971678.post@talk.nabble.com> Message-ID: <461F844D.5040608@holdenweb.com> Greg Corradini wrote: > Hello all, > In a script i just wrote, my code calls a function createTables(), which > checks for an existing table and then creates it, and then immediately calls > selectSQL(), which selects from a different table and inserts on the table I > just created (see below). > > However, I continue to get an Interface Error (see below) when i run it. And > yet, if I allow the code to call createTables() and then manually call > selectSQL() after a couple seconds, the thing works fine. In short, there's > no mismatch in the number of parameters. Why would this be? I've never > experienced this before. How can i restructure my code to resolve this > problem? > --- > CODE > --- > def createTables(): > # Drop AddScript Table > try: > curse.execute('Drop table ' +countyname+'ADD_SCRIPT_TABLE') > conn.commit It may not make any difference, but you should *call* commit() in the statement above rather than just referencing it. > except: > pass > # Create AddScript Table > curse.execute('Create table ' +countyname+'ADD_SCRIPT_TABLE'+ ' (TISCODE > TEXT(12), STATUS TEXT(4))') > conn.commit() > > def selectSQL(): > sql = "Select TISCODE,STATUS from " +countyname+"0"+ " where STATUS = > 'AS'" > curse.execute(sql) > a = curse.fetchall() > curse.executemany('Insert into ' +countyname+'ADD_SCRIPT_TABLE'+ ' > (TISCODE,STATUS) values (?,?)',x) Shouldn't the second argument to executemany() be a, not x? > conn.commit() > --- > ERROR > --- > InterfaceError: mismatch in number of parameters; expected 2, found none I find this whole thing a little disturbing. I keep asking myself why you are apparently maintaining entirely separate data structures for each county instead of having the county as a data item that can be used to select appropriate rows in the normal SQL way. I suspect the correct way to proceed otherwise is to rectify the database design before going too much further. If there is any intention to be able to compare data across different counties, for example, you will be dead in the water doing it this way. If this is someone else's crappy database design that you are obliged to deal with then please accept my apologies. If it's your crappy design then fix it ;-) 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 bcwhite at pobox.com Fri Apr 27 14:45:15 2007 From: bcwhite at pobox.com (bcwhite at pobox.com) Date: 27 Apr 2007 11:45:15 -0700 Subject: wxPython (Flex)GridSizer Failing Message-ID: <1177699515.090165.232310@n35g2000prd.googlegroups.com> Python v2.5 wxPython v2.8.3.0 I've got an app that has a wx.Panel managed by a FlexGridSizer. There are 5 columns and 6 rows, all with StaticText widgets and all of similar size. Everything works fine until I Clear and re-fill the sizer a few times, then it puts all of the text in the upper-left corner. I can clear/refill the grid to my hearts contents but it doesn't fix itself. However, if I resize the main window the next clear/refill will display correctly and _sometimes_ the current fill will change and display correctly. I have an identical panel directly below it (vertical box-sizer) with the same number of columns but only 1 row and it never has a problem. Both panels are identical because it's the same custom derived class creating them and both are added to the box-sizer in an identical way. I tried changing to an (un-flexible) GridSizer and got a different display but the same problem. If anything, it occurs sooner. Any ideas on what is happening? -- Brian From Marko.Cain.23 at gmail.com Sat Apr 14 00:49:15 2007 From: Marko.Cain.23 at gmail.com (Marko.Cain.23 at gmail.com) Date: 13 Apr 2007 21:49:15 -0700 Subject: how to strip the domain name in python? Message-ID: <1176526155.679721.159870@l77g2000hsb.googlegroups.com> Hi, I have a list of url names like this, and I am trying to strip out the domain name using the following code: http://www.cnn.com www.yahoo.com http://www.ebay.co.uk pattern = re.compile("http:\\\\(.*)\.(.*)", re.S) match = re.findall(pattern, line) if (match): s1, s2 = match[0] print s2 but none of the site matched, can you please tell me what am i missing? Thank you. From b.r.willems at gmail.com Sun Apr 29 07:15:10 2007 From: b.r.willems at gmail.com (Bart Willems) Date: Sun, 29 Apr 2007 07:15:10 -0400 Subject: Any Good tools to create CSV Files? In-Reply-To: References: <1177811756.255774.315260@q75g2000hsh.googlegroups.com> Message-ID: <47%Yh.2$hc3.1@newsfe12.lga> Carsten Haese wrote: > You mean something like the csv module that is part of Python's standard > library? > >>>> import csv >>>> help(csv) You have to admit, the module name is not really intuitive... :) From sjmachin at lexicon.net Fri Apr 20 18:37:36 2007 From: sjmachin at lexicon.net (John Machin) Date: 20 Apr 2007 15:37:36 -0700 Subject: When are immutable tuples *essential*? Why can't you just use lists *everywhere* instead? In-Reply-To: <1177103370.022138.110320@n59g2000hsh.googlegroups.com> References: <1177088796.622928.224890@d57g2000hsg.googlegroups.com> <1177089206.550423.288670@q75g2000hsh.googlegroups.com> <58sf33F2b1q8tU1@mid.individual.net> <1177103370.022138.110320@n59g2000hsh.googlegroups.com> Message-ID: <1177108656.291537.182560@o5g2000hsb.googlegroups.com> On Apr 21, 7:09 am, Luis M. Gonz?lez wrote: > On Apr 20, 3:28 pm, Bjoern Schliessmann > mail-0306.20.chr0n... at spamgourmet.com> wrote: > > Luis M. Gonz?lez wrote: > > > I don't remember exactly where I read about it, but Guido said > > > once that tuples are being kept mainly for historical reasons. > > > Weren't tuples added when lists already existed? > > > Regards, > > > Bj?rn > > > -- > > BOFH excuse #101: > > > Collapsed Backbone > > I tried googling for these comments, but I couldn't find them. > Perhaps I never read them and it was just my imagination... > Anyway, I suggest reading this chapter of "Dive into Python" for a > good explanation of the differences between tuples and lists:http://diveintopython.org/native_data_types/tuples.html > > The article explains that, amongst other things, tuples are faster > than lists, so if you are working with constant values (inmutables) > they are more indicated than lists. > One inessential but very useful thing about tuples when you have a lot of them is that they are allocated the minimum possible amount of memory. OTOH lists are created with some slack so that appending etc can avoid taking quadratic time. From mmoum at woh.rr.com Sat Apr 14 21:23:16 2007 From: mmoum at woh.rr.com (Mike) Date: Sat, 14 Apr 2007 21:23:16 -0400 Subject: function with list argument defaulting to [] - what's going on here??? Message-ID: <46217e8f$0$19437$4c368faf@roadrunner.com> While trying to write a recursive function involving lists, I came across some (to me) odd behavior which I don't quite understand. Here's a trivial function showing the problem. >>> def f(l, r = []): for itm in l: r.append(itm) print r >>> a = [1,2,3] >>> f(a) [1, 2, 3] >>> f(a) [1, 2, 3, 1, 2, 3] >>> f(a) [1, 2, 3, 1, 2, 3, 1, 2, 3] I know the function is quite artificial, but it's for illustration only. Why is "r" not being reset to the empty list on subsequent calls? It seems like it should be reinitialized when not explicitly provided. Thanks in advance. Mike From tjreedy at udel.edu Wed Apr 25 12:47:54 2007 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 25 Apr 2007 12:47:54 -0400 Subject: Would You Write Python Articles or Screencasts for Money? References: <462DCCE6.9060908@taupro.com> <1hx2dvj.10ek1v51noh1otN%aleax@mac.com> Message-ID: "Steve Holden" wrote in message news:f0no98$onj$2 at sea.gmane.org... | Since it's the PSF's money I don't see why the voting shouldn't be | restricted to PSF members. Legally, I believe it *is* that way. And even as a non-member, I think it should be that way. Any expression of opinions, through a straw poll, or otherwise, is advisory. tjr From bruno.42.desthuilliers at wtf.websiteburo.oops.com Wed Apr 11 04:15:01 2007 From: bruno.42.desthuilliers at wtf.websiteburo.oops.com (Bruno Desthuilliers) Date: Wed, 11 Apr 2007 10:15:01 +0200 Subject: Does python have the static function member like C++ In-Reply-To: <1176277228.056538.268290@o5g2000hsb.googlegroups.com> References: <1176260903.362329.59370@o5g2000hsb.googlegroups.com> <1176261542.704649.240350@n76g2000hsh.googlegroups.com> <1176273559.047449.263710@n76g2000hsh.googlegroups.com> <461c895f$0$2128$426a74cc@news.free.fr> <1176277228.056538.268290@o5g2000hsb.googlegroups.com> Message-ID: <461c98a7$0$15948$426a74cc@news.free.fr> goodwolf a ?crit : > On Apr 11, 9:09 am, Bruno Desthuilliers 42.desthuilli... at wtf.websiteburo.oops.com> wrote: >> goodwolf a ?crit : >> (snip) >> >>> 1. In this case you will prefer a classmethod instead a staticmethod. >>> 2. If counter is the number of instances of class AAA then you will >>> incrase counter inside __init__ method. >>> class AAA (object): >>> counter = 0 >>> def __init__(self): >>> type(self).counter_increase() >> You can call a class method on an instance: >> self.counter_increase() >> >> And FWIW, this is probably something I'd put in the constructor (the >> __new__ method), not in the initializer. >> >>> @classmethod >>> def counter_increase(cls): >>> cls.counter += 1 >>> or >>> class AAA (object): >>> counter = 0 >>> def __init__(self): >>> type(self).counter += 1 >> Instances have a reference to their class, so you can also write this: >> self.__class__.counter += 1 > > OK, you will use something like this: > > class AAA (object): > counter = 0 > def __new__(cls): > cls.counter += 1 > return super(cls, cls).__new__(cls) return super(AAA, cls).__new__(cls) > but I think that __new__ is more "low level" and not necessary here, It's of course 'not necessary'. But (IMHO): - increasing the class's instance counter is more a responsability of the class than a responsability of the instance - and it has nothing to do with initializing the instance's state - if someone is to subclass AAA, there are fewer chances that he'll override the constructer than the initializer, and if he does, there are more chances that he won't forget to call on the parent's constructor. IOW, this is actually *because* it is 'lower level' that I think it's a better place for such operations. But YMMV, of course !-) My 2 cents... From bdesth.quelquechose at free.quelquepart.fr Wed Apr 11 16:44:24 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Wed, 11 Apr 2007 22:44:24 +0200 Subject: Creating Unique Dictionary Variables from List In-Reply-To: References: <9943321.post@talk.nabble.com> <461d27d5$0$3630$426a74cc@news.free.fr> Message-ID: <461d3f84$0$24672$426a74cc@news.free.fr> Greg Corradini a ?crit : > Bruno, > Your help is much appreciated. Then give thanks to Dennis too !-) > I will give this a try tomorrow morning and > get back on how it works. Don't worry, it just works - and it's the idiomatic solution to the problem you described. From mail at microcorp.co.za Sat Apr 14 02:19:36 2007 From: mail at microcorp.co.za (Hendrik van Rooyen) Date: Sat, 14 Apr 2007 08:19:36 +0200 Subject: tuples, index method, Python's design References: Message-ID: <010001c77e5c$e0b07460$03000080@hendrik> "Donn Cave" wrote: > > Well, yes - consider for example the "tm" tuple returned > from time.localtime() - it's all integers, but heterogeneous > as could be - tm[0] is Year, tm[1] is Month, etc., and it > turns out that not one of them is alike. The point is exactly > that we can't discover these differences from the items itself - > so it isn't about Python types - but rather from the position > of the item in the struct/tuple. (For the person who is about > to write to me that localtime() doesn't exactly return a tuple: QED) This is the point where the whole thing falls apart in my head and I get real confused - I can't find a reason why, list or tuple, the first item can't be something, the second something else, etc... About the only reason you would use a tuple is if you want to use it as a key to a dict - and then only because you have to, you can't use a list as the language stands. - Hendrik From aboudouvas at panafonet.gr Wed Apr 11 05:51:02 2007 From: aboudouvas at panafonet.gr (king kikapu) Date: 11 Apr 2007 02:51:02 -0700 Subject: About Trolltech QT OpenSource license. In-Reply-To: References: <1176233376.712861.67160@o5g2000hsb.googlegroups.com> <1176237050.409742.8760@30g2000cwc.googlegroups.com> Message-ID: <1176285062.178372.15090@d57g2000hsg.googlegroups.com> On Apr 11, 10:56 am, Robert Kern wrote: > Others have given good answers. I would only like to clarify what I think is the > source of confusion here. While the FSF and many open source advocates make a > distinction between the words "commercial" (meaning that someone derives money > from distributing the software, whether it is GPLed or not) and "proprietary" > (meaning that the software is not being distributed under an open source license > but one that restricts user's rights), Trolltech abuses the term "commercial" to > mean "proprietary" in this case. Ok, i see...So i can use Qt OS edition and earn money from this as long as i explicitly say (is a reference to a GPL in a readme text file enough for this ?) that this software is under the GPL lisence and i have the obligation to give the source code with it. I will reply to that email of Trolltec's today and i will tell them about the things mentioned here, basically just the sentence i wrote above. I see what they will reply and post it here... From __peter__ at web.de Sun Apr 1 05:20:45 2007 From: __peter__ at web.de (Peter Otten) Date: Sun, 01 Apr 2007 11:20:45 +0200 Subject: shelf membership References: Message-ID: Aaron Brady wrote: > can you shelve objects with membership? > > this gives you: > > TypeError: object does not support item assignment > dict 0 True > Exception exceptions.TypeError: 'object does not support item assignment' > in??ignored > > > ignored is a bit mysterious.??tx?in?advance. > > from shelve import * > class MyShelf(DbfilenameShelf): > ??????????def?__init__(self,?filename,?flag='c',?protocol=None,? > writeback=False, binary=None): > ??????????????????self.__dict__['ready']=False > ??????????????????DbfilenameShelf.__init__(self,?filename,?flag,?protocol,? > writeback, binary) > ??????????????????self.ready=True > ??????????def?__setattr__(self,name,value): > ??????????????????if?not?self.ready: > ??????????????????????????self.__dict__[name]=value > ??????????????????else: > ??????????????????????????print?name,?value,?self.ready > ??????????????????????????self.__dict__[name]=value > ??????????????????????????DbfilenameShelf.__setitem__(self,name,value) > > def open(filename, flag='c', protocol=None, writeback=False, binary=None): > ??????return?MyShelf(filename,?flag,?protocol,?writeback,?binary) The root cause of your problems is that you are mixing two namespaces: that of the shelved items and that used internally by DbfilenameShelf to implement the shelving functionality. While the cleanest approach is to not do it, you can make such a mix work in /some/ cases if you give precedence to the "implementation namespace". This requires that you pass by any implementation attributes pass_through_attributes = [...] def __setattr__(self, name, value): if name in pass_through_attributes: self.__dict__[name] = value # * else: # do whatever you like (*) Assuming that DbfilenameShelve is an oldstyle class and does not itself implement a __setattr__() method. >From your error message one can infer that pass_through_attributes must contain at least the name "dict"; for a complete list you have to inspect the Dbfilename source code. An approach that is slightly more robust is to wrap DbfilenameShelf -- make it an attribute of MyShelf -- and pass the relevant method calls to the attribute. Peter From gagsl-py2 at yahoo.com.ar Wed Apr 18 19:32:54 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 18 Apr 2007 20:32:54 -0300 Subject: Installing Python on NT References: Message-ID: En Wed, 18 Apr 2007 18:09:03 -0300, Schwartz, Hillary escribi?: ? -- Gabriel Genellina From tjreedy at udel.edu Wed Apr 4 16:37:02 2007 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 4 Apr 2007 16:37:02 -0400 Subject: Getting word frequencies from files which are in folder. References: <1175710660.753453.205000@n76g2000hsh.googlegroups.com><4613f24f$0$327$e4fe514c@news.xs4all.nl> <1175717246.781352.178090@e65g2000hsc.googlegroups.com> Message-ID: wrote in message news:1175717246.781352.178090 at e65g2000hsc.googlegroups.com... | | My question is how to get word frequencies from this files? | I will be glad to get any help. Go to http://groups.google.com/group/comp.lang.python/topics and search on "count word frequency" and you will find several previous posts on this topic. tjr From electronixtar at gmail.com Thu Apr 12 03:05:12 2007 From: electronixtar at gmail.com (est) Date: 12 Apr 2007 00:05:12 -0700 Subject: py script modify it's Modified Time? In-Reply-To: References: <1176290057.625687.15150@y80g2000hsf.googlegroups.com> <1176298437.784719.146850@o5g2000hsb.googlegroups.com> Message-ID: <1176361512.171541.320410@y5g2000hsa.googlegroups.com> On 4?12?, ??2?26?, "Gabriel Genellina" wrote: > En Wed, 11 Apr 2007 10:33:57 -0300, escribi?: > > > On Apr 11, 6:14 am, "est" wrote: > >> I guess os.stat() could retrieve information about ctime, mtime of a > >> path, but how can I change them? Is it possible to make it work both > >> under Win32 and Linux? > > > I am not sure if you can change a creation time of a file on NT, but > > the rest sounds possible; according to this post anyway: > > >http://mail.python.org/pipermail/python-list/2001-August/100214.html > > That post is rather old... With os.utime you can set the access and > modified time, and it's portable. > Creation time isn't stored on [the normal filesystems used by] Linux, and > on Windows you can use win32file.SetFileTime > > > It mentions using the win32 modules, which can be found here: > >http://aspn.activestate.com/ASPN/docs/ActivePython/2.4/pywin32/win32_... > > Betterhttps://sourceforge.net/projects/pywin32/ > > -- > Gabriel Genellina Thanks guys ,you are of great healp! From kay.schluehr at gmx.net Thu Apr 26 15:58:36 2007 From: kay.schluehr at gmx.net (Kay Schluehr) Date: 26 Apr 2007 12:58:36 -0700 Subject: My python annoyances so far In-Reply-To: <1177603623.774892.230390@t38g2000prd.googlegroups.com> References: <1177541453.471959.120830@c18g2000prb.googlegroups.com> <59bf34F2k27v5U1@mid.individual.net> <1177603623.774892.230390@t38g2000prd.googlegroups.com> Message-ID: <1177617516.123890.310550@r35g2000prh.googlegroups.com> On Apr 26, 6:07 pm, fli... at gmail.com wrote: > Well, why do some things in the library have to be functions, and > other things have to be class methods? > > Why aren't they all just either functions or class methods? like > perhaps ruby. A good question. Part of the answer might be that their are no abstract base classes / interfaces in the language so far. These have a particular meaning and you might ask whether some object has certain abilities like being "sizable". With ABCs or interfaces it feels natural to implement abstract methods in subclasses. Without them you can either add methods ad hoc, without any conceptual background and consistency requirements of your model, or you are going to implement interface constraints in terms of so called "protocols". A protocol is a sequence of actions which require interfaces to be present ( they are abstract algorihms / command patterns ). Special functions ( __add__, __len__, etc. ) are the mediators of protocols. For instance the meaning of len() can be understood in terms of protocols: def len(obj): return obj.__len__() Other protocols are more implicit e.g. those that couple operators to method calls. You already mentioned special methods for arithmetic operations. I sometimes like to think that Python is a language developed around protocols, and they have a strong backing in the language. With Py3K Python will become a bit more Java like, at least with regard to the supported language constructs. Kay From gagsl-py2 at yahoo.com.ar Sat Apr 21 07:06:19 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sat, 21 Apr 2007 08:06:19 -0300 Subject: Class Not Auto-Init On Import References: <2987.60099472037$1177145337@news.gmane.org> Message-ID: En Sat, 21 Apr 2007 05:46:07 -0300, Robert Rawlins - Think Blue escribi?: >> From my understanding of what I've read, the 'import' is meant to auto >> Init > my class ready for me to access its methods, but it doesn't appear too, > I'm > having to init them myself before I can access them, like this. The import statement does not "auto Init" anything, in principle. > import LocationService Here, you import the LocationService module. If it is imported by the first time, its code (at the module level) is executed. The imported module is available under the name "LocationService" in the current namespace. > Location = LocationService.LocationService() Presumably, the module LocationService defines a class of the same name; you refer to that class using LocationService.LocationService. The last () create an instance of that class; that instance is bound to the name Location. > LocationService.setIP('192.168.1.1') This may or may not be correct; here you call a (global) function setIP inside the LocationService module. > Why is this the case? Should i not just be able to access the setIP() > method > by doing LocationService.setIP('192.168.1.1') Without having to create my > own inited reference? Not enough info, without knowing how LocationService is supposed to be used. But as I said, the setIP call looks suspicious. -- Gabriel Genellina From aleax at mac.com Thu Apr 5 00:37:55 2007 From: aleax at mac.com (Alex Martelli) Date: Wed, 4 Apr 2007 21:37:55 -0700 Subject: function for counting items in a sequence References: <46146F75.9050904@gmail.com> Message-ID: <1hw2ea3.1mmluqy1an8gx4N%aleax@mac.com> Steven Bethard wrote: > Alex Martelli wrote: > > If we had a "turn sequence into bag" function somewhere > > (and it might be worth having it for other reasons): > > > > def bagit(seq): > > import collections > > d = collections.defaultdict(int) > > for x in seq: d[x] += 1 > > return d > > I use this function all the time -- I call it dicttools.count(). I'd > love to see this appear in the collections module or somewhere else in > the stdlib. Maybe you should propose it in python-dev -- it does seem a reasonable utility addition to the collections module, after all. Alex From apardon at forel.vub.ac.be Fri Apr 27 10:35:48 2007 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 27 Apr 2007 14:35:48 GMT Subject: My python annoyances so far References: <1177541453.471959.120830@c18g2000prb.googlegroups.com> <1177599046.406827.5210@t38g2000prd.googlegroups.com> <4631d5be$0$2132$426a74cc@news.free.fr> Message-ID: On 2007-04-27, Bruno Desthuilliers wrote: > 7stud a ?crit : >> flifus at gmail.com wrote: >>> Annoyances: >>> >> >> Every language has annoyances. Python is no exception. > > Sure. But we may disagree on what are actually Python's annoyances !-) That is probably why the subject says: "my annoyances" -- Antoon Pardon From steve at REMOVE.THIS.cybersource.com.au Sun Apr 15 02:19:17 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Sun, 15 Apr 2007 16:19:17 +1000 Subject: Python Feature Request: Allow changing base of member indices to 1 References: <1176546465.632410.52630@w1g2000hsg.googlegroups.com> <4620b47b$0$14410$9b622d9e@news.freenet.de> <1176557999.665663.299740@y80g2000hsf.googlegroups.com> <1176559643.450533.296850@n59g2000hsh.googlegroups.com> <1176608086.323323.154260@d57g2000hsg.googlegroups.com> <1hwkyis.1gd589j191njikN%aleax@mac.com> Message-ID: On Sat, 14 Apr 2007 22:02:47 -0700, Alex Martelli wrote: > Steven D'Aprano wrote: > >> On Sat, 14 Apr 2007 20:34:46 -0700, Dan Bishop wrote: >> >> > On Apr 14, 10:55 am, Dennis Lee Bieber wrote: >> > >> >> The FORTRAN family had started as 1-based (F95, and Ada, now allow >> >> for each array to have its own "base" => x : array (-10..10) of float). >> >> Pascal, I forget... >> > >> > Pascal allows arbitrary array bases. It's where Ada got the idea. >> >> It does? Since when? > > Ever since Pascal existed, the syntax has been "array[lower..upper] of > sometype" -- no default value for lower (neither 0 nor 1 nor other). *slaps head* Of course it does! D'oh! We always used to write array[1..n] for an n item array, which is a convention, not enforced by the compiler. -- Steve From benjamin.han at gmail.com Fri Apr 13 00:10:44 2007 From: benjamin.han at gmail.com (Ben) Date: 12 Apr 2007 21:10:44 -0700 Subject: UnicodeDecodeError when importing random? (running with -U) Message-ID: <1176437444.758338.292550@n76g2000hsh.googlegroups.com> Is the following a known bug? [temp]$ python -U Python 2.4.4 (#1, Oct 23 2006, 13:58:18) [GCC 4.1.1 20061011 (Red Hat 4.1.1-30)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import random Traceback (most recent call last): File "", line 1, in ? File "/usr/lib64/python2.4/random.py", line 834, in ? _inst = Random() File "/usr/lib64/python2.4/random.py", line 94, in __init__ self.seed(x) File "/usr/lib64/python2.4/random.py", line 108, in seed a = long(_hexlify(_urandom(16)), 16) File "/usr/lib64/python2.4/os.py", line 723, in urandom bytes += read(_urandomfd, n - len(bytes)) UnicodeDecodeError: 'ascii' codec can't decode byte 0x97 in position 0: ordinal not in range(128) From joshua at eeinternet.com Fri Apr 27 15:14:29 2007 From: joshua at eeinternet.com (Joshua J. Kugler) Date: Fri, 27 Apr 2007 11:14:29 -0800 Subject: Dedicated CPU core for Python? References: <1177607759.916727.180950@t39g2000prd.googlegroups.com> <4630e90c$0$16272$88260bb3@free.teranews.com> Message-ID: <46323f34$0$16283$88260bb3@free.teranews.com> On Thursday 26 April 2007 14:07, Gabriel Genellina wrote: > En Thu, 26 Apr 2007 15:54:38 -0300, Joshua J. Kugler > escribi?: > >> Are you talking about CPU affinity >> (http://en.wikipedia.org/wiki/Processor_affinity) or an actual CPU that >> can directory execute Python byte code? If the former, CPython only >> uses one >> CPU core right now because it's threads are all internal, and do not >> spawn system threads (IIRC). > > Python threads are OS threads: > http://docs.python.org/lib/module-thread.html > "[The thread module] is supported on Windows, Linux, SGI IRIX, Solaris > 2.x, as well as on systems that have a POSIX thread (a.k.a. ``pthread'') > implementation." Yes, that may be, but they are not true system threads, or at least do not appear to be. Threads on linux each show up as a separate process. I can have several threads in my Python program, but no additional processes show up in ps -A. I don't see how Python threads can be system threads with the GIL. But, I've been wrong before, and threads are something I have very light knowledge of. 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 mmanns at gmx.de Thu Apr 5 18:38:19 2007 From: mmanns at gmx.de (Martin Manns) Date: Thu, 5 Apr 2007 18:38:19 -0400 Subject: grandparent method with super References: <20070405161939.694d51a1@localhost> <20070405163845.2ffa8d32@localhost> <20070405171306.0264fb70@localhost> <1175810725.877562.136230@l77g2000hsb.googlegroups.com> Message-ID: <20070405183819.3b7f576b@localhost> On 5 Apr 2007 15:05:25 -0700 attn.steven.kuo at gmail.com wrote: > > class E(C,D): > def m(self): > for cls in E.__mro__: > if cls != E and cls not in E.__bases__: > cls.m(self) > break > > > ... but it's probably better that you > rethink your class hierarchy. After seeing the implications and the solutions, I will. Thank you everyone for your help Martin From ianare at gmail.com Fri Apr 6 16:07:32 2007 From: ianare at gmail.com (=?iso-8859-1?B?aWFuYXLp?=) Date: 6 Apr 2007 13:07:32 -0700 Subject: real time updating of popen, bufsize=0 problems In-Reply-To: <87zm5lff4x.fsf@smsnet.pl> References: <1175885074.694737.261430@e65g2000hsc.googlegroups.com> <87zm5lff4x.fsf@smsnet.pl> Message-ID: <1175890052.121401.274570@q75g2000hsh.googlegroups.com> On Apr 6, 3:59 pm, Rob Wolfe wrote: > "ianar?" writes: > > hey all, I'm trying to get real time updates of batch file output. > > [...] > > > So I tried subprocess: > > proc = subprocess.Popen('"C:/path/to/test.bat"', bufsize=0, > > stdout=subprocess.PIPE) > > Instead of that: > > > for line in proc.stdout: > > self.display.WriteText(line) > > try that: > > while True: > line = proc.stdout.readline() > if not line: break > self.display.WriteText(line) > > When a file is used in a for loop it works like an iterator. > You can read details here (description of method ``next``):http://docs.python.org/lib/bltin-file-objects.html > > -- > HTH, > Rob Rob, you are the man =) thanks! From sjdevnull at yahoo.com Fri Apr 27 19:03:23 2007 From: sjdevnull at yahoo.com (sjdevnull at yahoo.com) Date: 27 Apr 2007 16:03:23 -0700 Subject: Dedicated CPU core for Python? In-Reply-To: <46323f34$0$16283$88260bb3@free.teranews.com> References: <1177607759.916727.180950@t39g2000prd.googlegroups.com> <4630e90c$0$16272$88260bb3@free.teranews.com> <46323f34$0$16283$88260bb3@free.teranews.com> Message-ID: <1177715003.368831.281070@y80g2000hsf.googlegroups.com> On Apr 27, 3:14 pm, "Joshua J. Kugler" wrote: > On Thursday 26 April 2007 14:07, Gabriel Genellina wrote: > > > En Thu, 26 Apr 2007 15:54:38 -0300, Joshua J. Kugler > > escribi?: > > >> Are you talking about CPU affinity > >> (http://en.wikipedia.org/wiki/Processor_affinity) or an actual CPU that > >> can directory execute Python byte code? If the former, CPython only > >> uses one > >> CPU core right now because it's threads are all internal, and do not > >> spawn system threads (IIRC). > > > Python threads are OS threads: > >http://docs.python.org/lib/module-thread.html > > "[The thread module] is supported on Windows, Linux, SGI IRIX, Solaris > > 2.x, as well as on systems that have a POSIX thread (a.k.a. ``pthread'') > > implementation." > > Yes, that may be, but they are not true system threads, or at least do not > appear to be. Threads on linux each show up as a separate process. No they don't, they used to with LinuxThreads but with newer kernels/ thread libraries/ps they no longer show up as processes. Python threads are OS threads on Linux. If you run strace on a simple python program that generates a thread, you can see the clone() call. From bdesth.quelquechose at free.quelquepart.fr Thu Apr 12 16:09:16 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Thu, 12 Apr 2007 22:09:16 +0200 Subject: Creating Unique Dictionary Variables from List In-Reply-To: References: <461d27d5$0$3630$426a74cc@news.free.fr> Message-ID: <461e88c0$0$2124$426a74cc@news.free.fr> Steven D'Aprano a ?crit : > On Wed, 11 Apr 2007 21:03:20 +0200, Bruno Desthuilliers wrote: > > >>Greg Corradini a ?crit : >> >>>Hello All, >>>I'm attempting to create multiple dictionaries at once, each with unique >>>variable names. The number of dictionaries i need to create depends on the >>>length of a list, which was returned from a previous function. >>>The pseudo code for this problem would be: >>> >>>returnedlist = [x,y,z] >>>count = 0 >>>for i in returnedlist: >>> if count < len(returnedlist): >>> # then create a dictionary (beginning with variable dic) for each i >>>with a unique name such that >>> # my unique name would be dic + count >>> >>>Any ideas about this? >> >>Yes : use a dict to store your dicts: >> >>returnedlist = [x,y,z] >>dicts = dict() >>for num, item in enumerate(returnedlist): >> dicts['dict%s' % num] = dict() > > > Given that num is unique each time around the loop, what do you gain by > using 'dictN' for the key instead of just N (=num)? The OP wanted such names, that's all. From deets at nospam.web.de Mon Apr 16 04:11:47 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 16 Apr 2007 10:11:47 +0200 Subject: Qt4 in ubuntu References: <1176668662.770066.208350@n76g2000hsh.googlegroups.com> <58fhooF2finkjU1@mid.uni-berlin.de> <1176710644.702886.314410@y5g2000hsa.googlegroups.com> Message-ID: <58gpe3Fia6j0U1@mid.uni-berlin.de> > > Hi Diez, finally I can install a Qt4 on Kubuntu, but now I have > problems to install a Qt4Designer. > I'm introducing to Qt with python, why tutorial you recommend to me? Google for them. And use C++-tutorials, they can be easily translated to python. Diez From steve at holdenweb.com Wed Apr 4 15:41:34 2007 From: steve at holdenweb.com (Steve Holden) Date: Wed, 04 Apr 2007 15:41:34 -0400 Subject: calling super() In-Reply-To: <00b301c776ef$c412dba0$fefea8c0@haengma> References: <1175714555.413502.77390@o5g2000hsb.googlegroups.com> <00b301c776ef$c412dba0$fefea8c0@haengma> Message-ID: John Clark wrote: > Yeah!!! One I can actually answer!!! > Nice to see such enthusiasm. Well 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 Recent Ramblings http://holdenweb.blogspot.com From kyosohma at gmail.com Mon Apr 30 17:18:40 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: 30 Apr 2007 14:18:40 -0700 Subject: re-importing modules In-Reply-To: References: <8%pZh.18192$Kd3.76@newssvr27.news.prodigy.net> <1177962288.575008.48490@q75g2000hsh.googlegroups.com> Message-ID: <1177967919.968338.3300@l77g2000hsb.googlegroups.com> On Apr 30, 3:00 pm, Carsten Haese wrote: > On Mon, 2007-04-30 at 12:44 -0700, kyoso... at gmail.com wrote: > > On Apr 30, 12:49 pm, "T. Crane" wrote: > > > Hi, > > > > When troubleshooting code that's saved in a text file, I often find that I > > > want to make a change to it, re-save it, then reimport it. However, just > > > typing > > > > import myTestCode > > > > doesn't always seem to import the newer version. Is it supposed to? I find > > > that right now I often have to close my iPython window, then reopen it and > > > import my recently modified code. I know this can't be the best way to do > > > this, but I don't know what is. > > > > any suggestions/help welcome and appreciated, > > > trevis > > > Hi, > > > Another person posted the same thing today. As with that person, you > > probably need to use the reload() function. See this post for more > > details: > > >http://www.python.org/search/hypermail/python-1993/0342.html > > > Mike > > In addition to the warning that reload() does not recursively reload > modules that the reloaded module depends on, be warned that reloading a > module does not magically affect any functions or objects from the old > version that you may be holding on to. For example: > > Module code: > # dog.py > class dog(object): > def bark(self): print "Arf!" > > Interactive session:>>> import dog > >>> d = dog.dog() > >>> d.bark() > Arf! > >>> # Now the module code is being changed in another window... > >>> reload(dog) > > >>> # A new dog instance will now say Woof: > >>> d2 = dog.dog() > >>> d2.bark() > Woof! > >>> # But the dog instance from before still says Arf: > >>> d.bark() > > Arf! > > This may or may not be a problem for you, but the bottom-line is that > reload must be used with caution. > > -Carsten Carsten, Very good point. I don't recall ever seeing that explained before. Thanks! Mike From bdesth.quelquechose at free.quelquepart.fr Mon Apr 2 15:28:20 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Mon, 02 Apr 2007 21:28:20 +0200 Subject: Error when trying to pass list into function. In-Reply-To: <1175539402.046635.196310@b75g2000hsg.googlegroups.com> References: <1175539402.046635.196310@b75g2000hsg.googlegroups.com> Message-ID: <46115078$0$1542$426a34cc@news.free.fr> erikcw a ?crit : > Hi, > > I'm getting the following error when I try to pass a list into a > function. > > My List: crea =[(u'218124172', u'536', u'32394'), (u'218320282', > u'1323', u'77931')] > > Traceback (most recent call last): > File "wa.py", line 118, in ? > curHandler.walkData() > File "wa.py", line 49, in walkData > self.results[parent][child]['results'] = self.calculate(crea) > #pass in list of tuples > TypeError: calculate() takes exactly 1 argument (2 given) > > def calculate(dta): > #stub > > How can I make this work? In Python, the first argument of an instance method is the instance on which it has to operate [1]. IOW, your problem is with the definition of calculate(). You want: class DontKnowWhat(object): def calculate(self, data): # code here [1] you don't have to pass this argument - this will be handled by Python - but you need to declare it. HTH From nagle at animats.com Tue Apr 24 15:20:26 2007 From: nagle at animats.com (John Nagle) Date: Tue, 24 Apr 2007 12:20:26 -0700 Subject: Simple sqlite3 question In-Reply-To: References: <1177434225.721012.271040@r35g2000prh.googlegroups.com> Message-ID: <8KsXh.15$M55.6@newssvr17.news.prodigy.net> Jerry Hill wrote: > On 24 Apr 2007 10:03:45 -0700, cjl wrote: > >> When I run the script and there is no file named optiondata, one is >> created and the correct data is added to it. If I run the script >> again then the data from the first run seems to be replaced with the >> data from the second run. I expected that the data from the second run >> would be appended to the database file, not replace it. > > > It sounds like you're not calling conn.commit() before you close the > database. By default sqlite (and any other DBAPI 2.0 compliant sql > wrapper) will start in transactional mode. You need to commit() your > transactions or they will be rolled back when you close the database > connection. If you don't want to call commit on your own, you can > switch the database into autocommit mode by setting the isolation > level to None when you open the connection, like this: > > conn = sqlite3.connect('.\optiondata', isolation_level=None) Don't do that; make the commit calls. Otherwise you'll be back here complaining about how bad stuff happened when two copies of the program ran at the same time. John Nagle From sbassi at clubdelarazon.org Sat Apr 14 10:37:11 2007 From: sbassi at clubdelarazon.org (Sebastian Bassi) Date: Sat, 14 Apr 2007 11:37:11 -0300 Subject: Making a tree out of a 2 column list Message-ID: <9e2f512b0704140737hd93c5c8i91121d5f4408d625@mail.gmail.com> I have a two column list like: 2,131 6,335 7,6 8,9 10,131 131,99 5,10 And I want to store it in a tree-like structure. So if I request 131, it should return all the child of 131, like 2, 10 and 5 (since 5 is child of 10). If I request 335, it should return: 6 and 7. If I request 9, it should return 8. I guess I could use tuples or dictionaries to do it, but I can't figure out how. Best, SB. -- Sebasti?n Bassi Diplomado Ciencia y Tecnolog?a. Club de la raz?n (www.clubdelarazon.org) From could.net at gmail.com Fri Apr 20 22:48:58 2007 From: could.net at gmail.com (Frank Potter) Date: 20 Apr 2007 19:48:58 -0700 Subject: how to transfer integer on socket? Message-ID: <1177123738.899837.65250@e65g2000hsc.googlegroups.com> Is there any easy way to transfer 4 bit integer on socket? I want to send like this: a=5 send_integer(socket_s,a) and receive like this: a=receive_integer(socket_s) Sending and receiving is in binary form, not transfer it to string. Is there any easy way to do this? From larry.bates at websafe.com Wed Apr 18 19:38:03 2007 From: larry.bates at websafe.com (Larry Bates) Date: Wed, 18 Apr 2007 18:38:03 -0500 Subject: Python COM iterator In-Reply-To: References: Message-ID: Carsten Haese wrote: > On Tue, 2007-04-17 at 16:54 -0500, Larry Bates wrote: >> Does anyone know if there is a way to make a Python COM object >> act like a proper iterator in VB/Delphi? > > I don't use COM, VB, or Delphi, but Google turned up these two > references: > http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcn7/html/vaconUsingForEach.asp http://17slon.com/blogs/gabr/2007/03/fun-with-enumerators-part-1.html > > Judging from those links, an object is iterable in VB and Delphi (or as > they call it, it is enumerable) if it exposes a GetEnumerator method > that returns an enumerator. The enumerator in turn needs to expose a > MoveNext method and a Current property. > > Assuming that the Enumerable and the Enumerator are allowed to be the > same object, you'll probably need code that looks something like this: > > class foo: > _public_methods_=['GetEnumerator','MoveNext'] > # You'll need to figure out how to expose "self.Current" > > def __init__(self): > self.numbers=[1,2,3,4,5,6,7,8] > self.Current = None > > def MoveNext(self): > try: > self.Current = self.numbers.pop(0) > return True > except IndexError: > return False > > def GetEnumerator(self): > return self > > Good luck, > > Carsten. > > I looked over the links and what you have proposed seems to make sense, but I can't make it work. I have the following class defined and registered. class foo: _public_methods_=['GetEnumerator','MoveNext'] _public_attrs_=['Current'] _reg_clsid_='{FC2A0E7B-E428-4414-B1C4-60373BB12102}' _reg_progid_="Syscon.foo" def __init__(self): self.numbers=[1,2,3,4,5,6,7,8] self.Current = None def MoveNext(self): try: self.Current = self.numbers.pop(0) rtnval=True except IndexError: self.Current=None rtnval=False def GetEnumerator(self): return self Then I do: >>> import win32com.client >>> typelib='Syscon.foo' >>> F=win32com.client.Dispatch(typelib) >>> for x in F: ... print x ... Traceback (most recent call last): File "", line 1, in File "C:\Python25\lib\site-packages\win32com\client\dynamic.py", line 228, in __getitem__ raise TypeError, "This object does not support enumeration" TypeError: This object does not support enumeration >>> but this works fine: >>> F.MoveNext() >>> F.Current 1 >>> F.MoveNext() >>> F.Current 2 >>> I'm stumped. -Larry From bobjohnson11 at gmail.com Sat Apr 7 13:36:58 2007 From: bobjohnson11 at gmail.com (RobJ) Date: 7 Apr 2007 10:36:58 -0700 Subject: Is http://cheeseshop.python.org/pypi/ having issues Message-ID: <1175967418.642658.46930@l77g2000hsb.googlegroups.com> Has any one noticed any issues with http://cheeseshop.python.org/pypi/ ? I have been trying for hours to install packages (using easy_install) but the connection keeps timing out. Any Help would be a appreciated. Rob J From jstroud at mbi.ucla.edu Fri Apr 6 08:13:33 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Fri, 06 Apr 2007 12:13:33 GMT Subject: Getting Stack Trace on segfault Message-ID: Hello All, The built-in mac osx vecLib is segfaulting in some cases--A very fun fact to find out the hard way over two nights of work. I also spent an embarrassing amount of time figuring out just where. Although I'm in quite a self-congratulatory mood right now, in the future, I feel like I could save a lot of time by coercing the interpreter to spew forth method calls to stderr. Is this possible? I would hope to produce something hauntingly reminiscent of [] my_function [my_function] another_function [my_function -> another_function] yet_a_deeper_function Presentation, of course, is irrelevant. I read the docs on pdb, but it did not seem to do what I want--unless, of course, I missed something. James From eopadoan at altavix.com Fri Apr 20 10:20:33 2007 From: eopadoan at altavix.com (Eduardo "EdCrypt" O. Padoan) Date: Fri, 20 Apr 2007 11:20:33 -0300 Subject: Python Feature Request: Explicit variable declarations In-Reply-To: <1177076403.252004.127640@p77g2000hsh.googlegroups.com> References: <1176546078.934340.253810@y5g2000hsa.googlegroups.com> <1177076403.252004.127640@p77g2000hsh.googlegroups.com> Message-ID: > The thoughts of the inventor of Python on "Adding Optional Static > Typing to Python" are at http://www.artima.com/weblogs/viewpost.jsp?thread=86641 > . I wonder if the idea will be implemented in Python 3.0. No. He says it in another newer post and in PEP 3099, AFAIK. -- EduardoOPadoan (eopadoan->altavix::com) Bookmarks: http://del.icio.us/edcrypt From s.mientki at id.umcn.nl Fri Apr 27 09:10:11 2007 From: s.mientki at id.umcn.nl (stef) Date: Fri, 27 Apr 2007 15:10:11 +0200 Subject: getting rid of EOL character ? Message-ID: <268cc$4631f634$83aef404$27224@news1.tudelft.nl> hello, In the previous language I used, when reading a line by readline, the EOL character was removed. Now I'm reading a text-file with CR+LF at the end of each line, Datafile = open(filename,'r') line = Datafile.readline() now this gives an extra empty line print line and what I expect that should be correct, remove CR+LF, gives me one character too much removed print line[,-2] while this gives what I need ??? print line[,-1] Is it correct that the 2 characters CR+LF are converted to 1 character ? Is there a more automatic way to remove the EOL from the string ? thanks, Stef Mientki From bellman at lysator.liu.se Thu Apr 5 05:45:41 2007 From: bellman at lysator.liu.se (Thomas Bellman) Date: Thu, 5 Apr 2007 09:45:41 +0000 (UTC) Subject: Prevent Modification of Script? References: <1175735097.856840.177510@e65g2000hsc.googlegroups.com> <1175743177.489242.214700@w1g2000hsg.googlegroups.com> Message-ID: "ts-dev" wrote: > Please correct any wrong assumptions that I might be making.. > In a compiled application its not impossible to by pass the code.. but > its not so easy. The huge amount of existing viruses targeting binaries seems to indicate that binary-only distribution does not deter attackers very well. Your assumption that the availability of source code makes your program a more vulnerable is likely wrong. > The script could easily be > modified to by-pass authentication and encryption could be disabled. Relying on authentication done at the client end is doomed to fail. Doing so is similar to asking people to put the lock in the door before opening it. It doesn't matter how good a lock is or how obscure the inside of the lock is if the lock isn't an integral part of the door; a burglar will simply bring his own lock, to which he of course has the key, and use that. > Perhaps this is just a side-effect of being a > scripted language - not a flaw, just me trying to use it for something > its not well suited for. No. To be blunt, it is an effect of you not knowing enough about security. (Don't feel too bad about it. I have made similar mistakes myself, but after many years working with computer security I have managed to learn not to do *that* particular error again; I hope...) -- Thomas Bellman, Lysator Computer Club, Link?ping University, Sweden "Life IS pain, highness. Anyone who tells ! bellman @ lysator.liu.se differently is selling something." ! Make Love -- Nicht Wahr! From robert.rawlins at thinkbluemedia.co.uk Fri Apr 27 06:42:37 2007 From: robert.rawlins at thinkbluemedia.co.uk (Robert Rawlins - Think Blue) Date: Fri, 27 Apr 2007 11:42:37 +0100 Subject: Re-ocurring Events In-Reply-To: <004901c788a9$b42c2130$1c846390$@rawlins@thinkbluemedia.co.uk> References: <3891950377467154133@unknownmsgid> <003001c7889c$f1fb6a50$d5f23ef0$@rawlins@thinkbluemedia.co.uk> <4631B8FE.8000405@limsi.fr> <004901c788a9$b42c2130$1c846390$@rawlins@thinkbluemedia.co.uk> Message-ID: <005601c788b8$c7abe600$5703b200$@rawlins@thinkbluemedia.co.uk> Ok, Almost done now, it seems to be working a real charm at the moment. I need a little help on performing a quick if statement against a date string. I have couple of date strings returned by s.attributes.getNamedItem("start").nodeValue s.attributes.getNamedItem("end").nodeValue and I need to do and conditional that ensures start is before today's date/time and end is after today's date/time. The string looks like: '2007-01-01 00:00:00' Do I have to convert this to a proper time object to do the comparison? Or can I do it as a string? Thanks, Rob -----Original Message----- From: python-list-bounces+robert.rawlins=thinkbluemedia.co.uk at python.org [mailto:python-list-bounces+robert.rawlins=thinkbluemedia.co.uk at python.org] On Behalf Of Robert Rawlins - Think Blue Sent: 27 April 2007 09:55 To: 'Laurent Pointal' Cc: python-list at python.org Subject: RE: Re-ocurring Events Thanks for getting back to me Laurent. I've now made some pretty tidy progress on this and -think- it's going to shape up nicely, I'm just working on converting my date strings from the XML into a date_struct and we should be good to go. I'll keep you all posted. Rob -----Original Message----- From: Laurent Pointal [mailto:laurent.pointal at limsi.fr] Sent: 27 April 2007 09:49 To: Robert Rawlins - Think Blue Subject: Re: Re-ocurring Events Robert Rawlins - Think Blue a ?crit : > Thank you guys for your suggestions. > > I've been having a look at that launchd stuff from apple but couldn?t really > see how that applies to my requirements. I was not thinking about launchd itself, but about its XML configuration files which manage timed events, as you need. > I've been putting some serious thought into how this should work as its > essentially the final part of the puzzle for my application, I'll have a > fully working model for my application. > > I've been thinking about the possibility of using a combination of xpath to > search the XML with some loops which change the date. As events won't ever > be set to start before 01-01-2007 I can set that as the ceiling for my loop. > So when I'm searching for weekly events, I 'simply' take today's date and > time and loop from now until 01-01-2007 decrementing the date by a week each > iteration of the loop and then search the XML for events in that date, make > sense? > > I know that's a fairly intensive way of doing it, but if it works it works. > > Now, the loop is where I'm really struggling, I've not done any looping with > dates, can anyone give me a hand with this? How can I loop back in time from > now to beginning of 07 a week at a time? Do we have some form of dateAdd() I > can use with a while loop? Perhaps. See datetime module, eventually third party mxDatetime. > Date = (now) > While date > 2007-01-01: > Date = dateAdd(date, -1, w) > > Something to that effect? Then I can quickly xpath for every iteration of > the loop. A+ Laurent. -- Laurent POINTAL CNRS-LIMSI d?pt. CHM, groupes AMI et PS Courriel: laurent.pointal at limsi.fr (prof) laurent.pointal at laposte.net (perso) Ouebe: http://www.limsi.fr/Individu/pointal/ T?l. 01 69 85 81 06 (prof) Fax. 01 69 85 80 88 -- http://mail.python.org/mailman/listinfo/python-list From KDawg44 at gmail.com Mon Apr 23 16:36:45 2007 From: KDawg44 at gmail.com (KDawg44) Date: 23 Apr 2007 13:36:45 -0700 Subject: Learning Python - First Project In-Reply-To: <1177353879.444542.163020@p77g2000hsh.googlegroups.com> References: <1177339942.371167.93970@b75g2000hsg.googlegroups.com> <1177353879.444542.163020@p77g2000hsh.googlegroups.com> Message-ID: <1177360605.074895.302020@b58g2000hsg.googlegroups.com> On Apr 23, 1:44 pm, kyoso... at gmail.com wrote: > On Apr 23, 9:52 am, KDawg44 wrote: > > > > > Hi, > > > I am new to Python and am trying to write a little front end to > > another application in Python. > > > What I want is to have a gui pop up listing some items with several > > buttons. The guts of the program I am not having any trouble with but > > the GUI part I am (or more accurately, the transition between GUI > > pieces). > > > The first GUI that pops up lists some groups in a listbox and gives > > the user the choice to create a new group, open a group, rename the > > group, or delete the group. The new group and rename group buttons > > pop up a dialog gui asking for the name/new name. The Open Group is > > to open another GUI listing projects within that group in a list with > > similar options (New Project, Open Project, Rename Project, Delete > > Project). > > > My question is, how should I create all these GUIs? Should each GUI > > be its own class with its own __init__? Then is the first GUI the > > root (how I have it set up now) and all other GUIs using Toplevel()? > > > I hope this makes sense (because it only sort of makes sense in my > > head). > > > THanks for any suggestions. > > I am assuming you are using Tkinter for your GUI front-end. You should > be able to just use standard dialog boxes for your "new group" and > "rename group" dialogs and a custom hand-coded dialog for the other > one. All three can be called with ShowModal() instead of Toplevel(). > And yes, the custom dialog would work best if you made it into a > separate class. > > You could also put that information for the GUI that list projects > into a "tree" widget of some sort, maybe with a splitter window. I > haven't had much luck with Tkinter's tree widgets though. PMW and Tix > both have rather poor docs unless you enjoy man pages. You might check > out wxPython instead. It has an excellent demo that is very good at > showing you not only what all it can do, but how it is done:www.wxpython.org. > > Good luck! > > Mike Thanks very much for your suggestions. I think i will look into wxPython, though I will finish this little app in tkinter since I am almost done with it. THanks for your help. From tgrav at mac.com Fri Apr 20 15:58:57 2007 From: tgrav at mac.com (Tommy Grav) Date: Fri, 20 Apr 2007 15:58:57 -0400 Subject: matplotlib basic question In-Reply-To: References: <1177016327.543985.34500@o5g2000hsb.googlegroups.com> <1177092157.763869.77600@o5g2000hsb.googlegroups.com> <76C22CF3-C355-4670-90AC-02054B0B9F8F@mac.com> Message-ID: On Apr 20, 2007, at 3:49 PM, Robert Kern wrote: > Tommy Grav wrote: >> On Apr 20, 2007, at 2:44 PM, Robert Kern wrote: >>> Colin J. Williams wrote: >>> >>>> I'm not sure that scipy has been updated to Python 2.5 >>> ? scipy certainly works with 2.5. Are you referring to something >>> else perhaps? >> >> A side question: Is there any plans of updating the scipy.org >> Superpack bundle >> for Mac OS X to work with 2.5? > > You would have to ask Chris Fonnesbeck. It's not an "official" > binary inasmuch > as scipy has official binaries. Okidoki. This is the last reason for me not upgrading to 2.5 as I have a hard time compiling things from scratch :) Cheers Tommy From aleax at mac.com Tue Apr 10 01:00:26 2007 From: aleax at mac.com (Alex Martelli) Date: Mon, 9 Apr 2007 22:00:26 -0700 Subject: RFC: Assignment as expression (pre-PEP) References: <1175802680.021987.39220@p77g2000hsh.googlegroups.com> <1176171797.184061.196520@b75g2000hsg.googlegroups.com> Message-ID: <1hwbp28.xpul1y1vyggigN%aleax@mac.com> Adam Atlas wrote: > Hasn't this been discussed many many times before? I think Guido has > been favourable to the idea of allowing :=, but that was a long time > ago, and I don't think anything ever came of it. > > Personally, if anything, I'd like to see more use of the 'as' keyword > as in Python 2.5's new 'with' statement. Assignment is basically what > it adds to the statement, so if anything we should reuse it in other > statements for consistency. > > if my_re1.match(exp) as temp: > # do something with temp > elif my_re2.match(exp) as temp: > # do something with temp > elif my_re3.match(exp) as temp: > # do something with temp > elif my_re4.match(exp) as temp: > # do something with temp > > As others have mentioned, your particular instance is probably > evidence that you need to restructure your code a little bit, but I do > agree that "x = y; if x: ..." is a common enough idiom that it > warrants a shortcut. And reusing "as", I think, is nice and readable, > and it's an advantage that it doesn't require adding any new keywords > or symbols. Actually, I agree with you. Unfortunately, I doubt python-dev will, but the chance is good enough that it's probably worth proposing there (ideally together with a patch to implement it, just to avoid any [otherwise likely] whines about this being difficult to implement:-). Alex From reder at ieee.org Sat Apr 21 02:11:32 2007 From: reder at ieee.org (Leonard J. Reder) Date: Sat, 21 Apr 2007 06:11:32 GMT Subject: Python and XML? In-Reply-To: <4627631A.6030606@web.de> References: <46209A55.9070102@web.de> <46217DAE.7040501@ieee.org> <4621F54A.3010008@web.de> <4627631A.6030606@web.de> Message-ID: <4629AB13.7050609@ieee.org> Stefan, This package is looking better I tried the validation example, but it did not work with 1.3beta so I grabbed 1.2. If objectify works well I think this is a great pick for anyone using xml. Please post to me and the python announce when 1.3 is released. thanks, Len Stefan Behnel wrote: > Hi, > > Leonard J. Reder wrote: >> Stefan Behnel wrote: >>> http://codespeak.net/lxml/objectify.html >> Looks like this stuff might do what I want. Need to work through the >> example. >> >> Are you the author? > > Yup! :) > > >> Why is this better then using gnossis? > > lxml is faster and supports more XML standards. It's also more flexible in > that it allows you to replace element classes at basically any granularity and > thus add things to the Element API or even replace it as you see fit, without > loosing the standard XML features. You can even do that at the C-level, in > case you really need high-performance. > > See the "extending lxml" section in the side menu at > http://codespeak.net/lxml/dev/ > especially: > http://codespeak.net/lxml/dev/element_classes.html > > Stefan -- =================================== Leonard J. Reder Home office email : reder at ieee.org Lab email : reder at jpl.nasa.gov Lab web page : http://reder.jpl.nasa.gov =================================== From rokkamraja at gmail.com Mon Apr 16 15:13:45 2007 From: rokkamraja at gmail.com (Raja) Date: 16 Apr 2007 12:13:45 -0700 Subject: Printing Using Python Message-ID: <1176750825.770991.141640@y80g2000hsf.googlegroups.com> Hi, Attached is the code . I want my program to save the current printer job properties and , when I reconnect the printer at a latter date , i need to print the saved job . Can you please help with my code ? How to print a document at a later stage and any errors in my code ? import win32ui import win32con myprinter_name = "" # get the name from your Printers folder printer_properties=[] def save(): pHandle = win32print.OpenPrinter(myprinter_name) properties = win32print.GetPrinter(pHandle, 2) pDevModeObj = properties["pDevMode"] printer_properties.append(pDevModeObj.FormName) printer_properties.append(pDevModeObj.PaperSize) printer_properties.append(pDevModeObj.Orientation) printer_properties.append(pDevModeObj.Color) printer_properties.append(pDevModeObj.Copies) printer_properties.append(pDevModeObj.DefaultSource) win32print.ClosePrinter(pHandle) def apply(): hprinter = win32print.OpenPrinter(myprinter_name) devmode = win32print.GetPrinter(hprinter, 2)["pDevMode"] devmode.FormName=printer_properties[0] devmode.PaperSize=printer_properties[1] devmode.Orientation=printer_properties[2] devmode.Color=printer_properties[3] devmode.Copies=printer_properties[4] devmode.DefaultSource=printer_properties[5] hdc = win32gui.CreateDC("WinPrint",myprinter_name,devmode) dc = win32ui.CreateDCFromHandle(hdc) dc.StartDoc('My Python Document') dc.StartPage() dc.EndPage() dc.EndDoc() del dc You help is greatly appreciated. Thank You, Raja. From spradml at gmail.com Fri Apr 27 02:05:47 2007 From: spradml at gmail.com (Pradnyesh Sawant) Date: Fri, 27 Apr 2007 11:35:47 +0530 Subject: pyqt4 signal/slot using PyObject* and shortcut In-Reply-To: <80628d680704262259o46d06926n6d5f7b9e375c08b2@mail.gmail.com> References: <80628d680704262259o46d06926n6d5f7b9e375c08b2@mail.gmail.com> Message-ID: <80628d680704262305k779c59fkc4535619a6c06594@mail.gmail.com> On 4/27/07, Pradnyesh Sawant wrote: > Hello, i have the following code: > ################################################################# > import time > import sys > from PyQt4 import QtGui, QtCore > > class Counter(QtCore.QThread): > def __init__(self): > QtCore.QThread.__init__(self) > def run(self): > cntr = 0 > while cntr < 10: > cntr += 1 > self.emit(QtCore.SIGNAL("showCntr1(PyObject*)"), (cntr, > "a")) # line 1 > self.emit(QtCore.SIGNAL("showCntr2"), (cntr, "a")) > # line 2 > time.sleep(0.2) > class Gui(QtGui.QDialog): > def __init__(self, parent = None): > QtGui.QDialog.__init__(self, parent) > frameStyle = QtGui.QFrame.Sunken | QtGui.QFrame.Panel > > self.lCntr = QtGui.QLabel() > self.lCntr.setFrameStyle(frameStyle) > loGrd = QtGui.QGridLayout() > loGrd.addWidget(self.lCntr, 0, 0) > self.setLayout(loGrd) > self.setWindowTitle(self.tr("Counter")) > def showCntr1(self, val): > print val, str(val) > self.lCntr.setText(str(val)) > def showCntr2(self, val): > print val, str(val) > self.lCntr.setText(str(val)) > if __name__ == "__main__": > app = QtGui.QApplication(sys.argv) > dialog = Gui() > cntr = Counter() > cntr.start() > QtCore.QObject.connect(cntr, QtCore.SIGNAL("showCntr1(PyObject*)"), > dialog.showCntr1, QtCore.Qt.QueuedConnection) > QtCore.QObject.connect(cntr, QtCore.SIGNAL("showCntr2"), > dialog.showCntr1, QtCore.Qt.QueuedConnection) There's a small bug in the above line, it should be dialog.showCntr2, and not dialog.showCntr1. However, even with this change, the output shown below remains the same :( > sys.exit(dialog.exec_()) > ################################################################# > If i comment out "line 1", then i get the following output: > 0.2 0.2 > 0.2 0.2 > 0.2 0.2 > 0.2 0.2 > 0.2 0.2 > 0.2 0.2 > 0.2 0.2 > 0.2 0.2 > 0.2 0.2 > 0.2 0.2 > Notice that 0.2 is the time value of the sleep instruction. Why is > this happening? > > On the other hand, if i comment out "line 2", then i get the following output: > (, 'a') (, ) > (, 'a') (, ) > (, 'a') (, ) > (, 'a') (, ) > (, 'a') (, ) > (, 'a') (, ) > (, 'a') (, ) > (, 'a') (, ) > (, 'a') (, ) > (, 'a') (, ) > What i get from the above is that a reference to "cntr" is being > passed, but by the time the gui thread is actually run, both the > values (cntr and "a") have been destroyed, hence the NULL values. > ***How do i circumvent this problem?*** > > Lastly, if i don't comment out any of line 1 or 2, then i get the foll output: > (<__main__.Gui object at 0xb6a8f12c>, (<__main__.Gui object at > 0xb6a8f12c>, (<__main__.Gui object at 0xb6a8f12c>, (<__main__.Gui > object at 0xb6a8f12c>, (<__main__.Gui object at 0xb6a8f12c>, > (<__main__.Gui object at 0xb6a8f12c>, (<__main__.Gui object at > 0xb6a8f12c>, (<__main__.Gui object at 0xb6a8f12c>, (<__main__.Gui > object at 0xb6a8f12c>, (<__main__.Gui object at 0xb6a8f12c>, > (<__main__.Gui object at 0xb6a8f12c>, (<__main__.Gui object at > 0xb6a8f12c>, (<__main__.Gui object at 0xb6a8f12c>, (<__main__.Gui > object at 0xb6a8f12c>, (<__main__.Gui object at 0xb6a8f12c>, > (<__main__.Gui object at 0xb6a8f12c>, (<__main__.Gui object at > 0xb6a8f12c>, (<__main__.Gui object at 0xb6a8f12c>, .......... > i don't know what this means??? Can anyone kindly explain what's happening... > > I'm using: > python: 2.4.4~c1-0ubuntu1 > qt4-dev-tools: not installed > python-qt4: 4.0.1-1ubuntu1 > sip4: (4.4.5-2ubuntu1 > os: ubuntu edgy > -- > warm regards, > Pradnyesh Sawant > -- > Be yourself, everyone else is taken. --Anon > -- warm regards, Pradnyesh Sawant -- Be yourself, everyone else is taken. --Anon From tejovathi.p at gmail.com Thu Apr 19 06:44:37 2007 From: tejovathi.p at gmail.com (Teja) Date: 19 Apr 2007 03:44:37 -0700 Subject: Helpbook and CHM Message-ID: <1176979477.204864.72900@n59g2000hsh.googlegroups.com> How to create a helpbook and display it using python(in Boa). Also, how to generate CHM files in Boa(Python)??? Any pointers please................ From jackson at hotmail.com Thu Apr 19 17:24:37 2007 From: jackson at hotmail.com (Bill Jackson) Date: Thu, 19 Apr 2007 14:24:37 -0700 Subject: Better dict of dicts Message-ID: I have a dictionary of dictionaries where the keys are typically very long tuples and repeated in each inner dictionary. The dictionary representation is nice because it handles sparseness well...and it is nice to be able to look up values based on a string rather than a number. However, since my keys are quite long, I worry that I am wasting a lot of memory. I'm looking for better data structures. Here is an example: >>> a = {"string_1": {"string_2":1, ... "string_3":5, ... "string_4":10}, ... "string_2": {"string_2":12, ... "string_6":2, ... "string_1":4}} So as my strings get longer and longer, it seems that the dictionary of dictionary representation is less and less efficient. My thought was to subclass the dictionary structure.... keys = {"string_1":1, "string_2":2, "string_3":3, "string_4":4, "string_6":5} Then the underlying dictionary of dictionaries would look like: a = {1:{2:1,3:5,4:10},2:{2:12,5:2,1:4}} Somehow I need to intercept every possible call though....such that a["string_1"]["string_2"] actually calls a[1][2] and a.keys() returns ["string_1", "string_2", "string_3"....] rather than [1,2,3,4,5] etc. Ideally, I would like the option to have different key hashes for the rows and columns as well. Any ideas? From carl at personnelware.com Fri Apr 13 15:47:57 2007 From: carl at personnelware.com (Carl K) Date: Fri, 13 Apr 2007 14:47:57 -0500 Subject: attribute save restore In-Reply-To: References: <7_ydnZt7B8WqSILbnZ2dnUVZ_uOmnZ2d@comcast.com> Message-ID: Steven Bethard wrote: > Carl K wrote: >> Is there a more elegant way of coding this: >> >> x=o.p # save .p >> o.p=0 >> o.m() >> o.p=x # restore .p >> >> seems very push/pop to me - like there should be a way that doesn't >> need a var (x) or the save/set lines should be done in one command. > > With the appropriate context manger, you could write this as:: > > with setting(o, 'p', 2): > o.m() > > Here's the code:: > > >>> from __future__ import with_statement > >>> @contextlib.contextmanager > ... def setting(obj, name, value): > ... old_value = getattr(obj, name) > ... setattr(obj, name, value) > ... try: > ... yield obj > ... finally: > ... setattr(obj, name, old_value) > ... > >>> class C(object): > ... def __init__(self, x): > ... self.x = x > ... def m(self): > ... print self.x > ... > >>> c = C(1) > >>> with setting(c, 'x', 2): > ... c.m() > ... > 2 > >>> print c.x > 1 > > Of course, that just wraps up the same push/pop behavior you're doing > into a context manager. Thanks. As I was eating lunch I came up with: x,o.p = o.p,0 Which I am pretty sure is just bad :) I need to cut back on the hot sauce. > >> (personally I think .m would better be implemented by passing in a >> parameter, but that isn't my choice.) > > Yep, that's the right answer. You should complain to whoever created > this API. Will do. Something is buggy anyway, so as long as I am commenting... Carl K From mensanator at aol.com Sun Apr 22 23:45:44 2007 From: mensanator at aol.com (mensanator at aol.com) Date: 22 Apr 2007 20:45:44 -0700 Subject: recursion depth problem In-Reply-To: <1177294411.144709.24650@l77g2000hsb.googlegroups.com> References: <1177267774.416169.276780@e65g2000hsc.googlegroups.com> <1177275314.846022.249000@e65g2000hsc.googlegroups.com> <1177276111.720137.315710@b75g2000hsg.googlegroups.com> <1177286778.918119.7490@e65g2000hsc.googlegroups.com> <1177294411.144709.24650@l77g2000hsb.googlegroups.com> Message-ID: <1177299944.699429.170000@b75g2000hsg.googlegroups.com> On Apr 22, 9:13???pm, proctor <12cc... at gmail.com> wrote: > On Apr 22, 7:10 pm, Dennis Lee Bieber wrote: > > > > > > > On 22 Apr 2007 17:06:18 -0700, proctor <12cc... at gmail.com> declaimed the > > following in comp.lang.python: > > > > > ? ? else: > > > > ? ? ? ? # only one of carry in, b1, or b2 is set > > > ? ? ? ? ? ? ? ? ? ? ? ? #or none is set! Missed the 0,0,0 condition > > > > > ? ? ? ? return (0, b1 + b2 + c) > > > > thank you. ?you guys are keeping me busy! > > > ? ? ? ? Heh... I'm sure what I scratched together could be optimized more > > (make functions out of the input/output conversions; add some error > > checking on input data, allow for non-list arguments in adder()...) > > > ? ? ? ? After all, if one wants a binary counter, one should implement a > > binary addition operation, and basic digital has ways... Unfortunately, > > Python now has a Boolean type, so boolean AND/OR doesn't give the > > desired results... And using bitwise seems wasteful However... > > replace the badd() with the following obscure thing if you really want > > to get close to hardware emulation... > > > def badd(b1, b2, ci=0): > > ? ? """ > > ? ? ? ? badd(b1, b2, ci) => (co, sum) > > ? ? """ > > ? ? (co1, hs1) = (b1 & b2, b1 ^ b2) > > ? ? (co2, hs2) = (ci & hs1, ci ^ hs1) > > ? ? return (co1 | co2, hs2) > > > ? ? ? ? A pair of "half-adders"; and the extra bit to make a "full-adder". > > It wouldn't be efficient to do it as one long return, just due to > > duplicated (b1 ^ b2) sub-terms > > > return ( (b1 & b2) | (ci & (b1 ^ b2)), (ci ^ (b1 ^ b2))) > > > but it does work > > -- > > ? ? ? ? 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/ > > :-) > > this is good stuff. ?for learning especially! ?thank you again! I once made a complete full adder in perl with strings so that I could have unlimited precision (this is before I found out about Big Arithmetic libraries). Since I was only doing the Collatz Conjecture, all I needed was to multiply by 3 (shift left by appending '0' to string and adding to original string using the full adder), dividing by two (shift right by slicing off rightmost character from string) and incrementing (pre-set the carry bit to '1'). It worked perfectly. But it was slower than snake shit. > > proctor From bbxx789_05ss at yahoo.com Wed Apr 18 19:09:44 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: 18 Apr 2007 16:09:44 -0700 Subject: Newbie: import In-Reply-To: <1176914096.493758.77120@o5g2000hsb.googlegroups.com> References: <1176914096.493758.77120@o5g2000hsb.googlegroups.com> Message-ID: <1176937784.549769.306250@b75g2000hsg.googlegroups.com> On Apr 18, 10:34 am, genk... at gmail.com wrote: > I thought import used relative paths from either the python executable > or the script being executed. I have a script pulling in code from an > arbitrary directory. How is this happening? > > It's a RHEL 4 environment by the way. I couldn't find any relevant > environment variables. > > Thanks from a newbie for any insight. >From the online python tutorial here: http://docs.python.org/tut/ There is this: ---------- 6.1.1 The Module Search Path When a module named spam is imported, the interpreter searches for a file named spam.py in the current directory, and then in the list of directories specified by the environment variable PYTHONPATH. This has the same syntax as the shell variable PATH, that is, a list of directory names. When PYTHONPATH is not set, or when the file is not found there, the search continues in an installation-dependent default path; on Unix, this is usually .:/usr/local/lib/python. Actually, modules are searched in the list of directories given by the variable sys.path which is initialized from the directory containing the input script (or the current directory), PYTHONPATH and the installation-dependent default. This allows Python programs that know what they're doing to modify or replace the module search path. Note that because the directory containing the script being run is on the search path, it is important that the script not have the same name as a standard module, or Python will attempt to load the script as a module when that module is imported. This will generally be an error. See section 6.2, ``Standard Modules,'' for more information. ---------- You can use the following trick to import one of your own modules when your module isn't in the current directory(and doesn't happen to be in PYTHONPATH or the default path): import sys sys.path.append("relative path or absolute path to dir with the module") # temporarily changes sys.path import mymodule From Leisure.210 at gmail.com Sat Apr 28 20:59:16 2007 From: Leisure.210 at gmail.com (Leisure.210 at gmail.com) Date: 28 Apr 2007 17:59:16 -0700 Subject: SEO - Search Engine Optimization - Seo Consulting Message-ID: <1177808356.681710.42980@n76g2000hsh.googlegroups.com> Free Seo Consulting http://seo-optimizer.blogspot.com/ From carsten at uniqsys.com Sat Apr 21 22:45:11 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Sat, 21 Apr 2007 22:45:11 -0400 Subject: Can __init__ not return an object? In-Reply-To: References: Message-ID: <1177209911.3201.1.camel@localhost.localdomain> On Sat, 2007-04-21 at 22:36 -0400, Steven W. Orr wrote: > When I go to create an object I want to be able to decide whether the > object is valid or not in __init__, and if not, I want the constructor to > return something other than an object, (like maybe None). > [...] > Or would raising an > exception in the constructor be appropriate? Raising an exception is perfectly appropriate. -Carsten From collinstocks at gmail.com Thu Apr 5 14:30:33 2007 From: collinstocks at gmail.com (Collin Stocks) Date: Thu, 5 Apr 2007 14:30:33 -0400 Subject: Can we make a local variable in a function as global variable??? In-Reply-To: <1175764774.260576.286420@y66g2000hsf.googlegroups.com> References: <1175764774.260576.286420@y66g2000hsf.googlegroups.com> Message-ID: <4c0048df0704051130k23b282av778059aa2fd64eb4@mail.gmail.com> As for me, I find this problem annoying, but easy to solve. My solution is: >>> this=__import__(__name__) To set global variable spam to 4, I say: >>> this.spam=4 This always works, and is much more convenient than: >>> global spam >>> spam=4 and then worry about local variables also named spam. On 5 Apr 2007 02:19:34 -0700, sairam wrote: > > I have some local variables defined in one method and Can I make those > variables as global variables? If so , can any one explain me how can > I do that > > > Thanks, > Sairam > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From subscriber123 at gmail.com Wed Apr 11 18:15:58 2007 From: subscriber123 at gmail.com (Subscriber123) Date: Wed, 11 Apr 2007 18:15:58 -0400 Subject: Python Web Servers and Page Retrievers In-Reply-To: <4c0048df0704111508u1fbccadbwa164b6c598f89659@mail.gmail.com> References: <4c0048df0704081442w7a25ee2bqe2b13229dc37769e@mail.gmail.com> <4c0048df0704111508u1fbccadbwa164b6c598f89659@mail.gmail.com> Message-ID: <4c0048df0704111515g5c93c1f8g7cbbeb1736ab67c2@mail.gmail.com> And yes, I do have two email addresses that I use for Python-List On 4/11/07, Collin Stocks wrote: > > I tried it, and when checking it using a proxy, saw that it didn't really > work, at least in the version that I have (urllib v1.17 and urllib2 v2.5). > It just added that header onto the end, therefore making there two > User-Agent headers, each with different values. I might add that my script > IS able to retrieve search pages from Google, whereas both urllibs are > FORBIDDEN with the headers that they use. > > On 4/8/07, Max Erickson wrote: > > > > Subscriber123 wrote: > > > urllib, or urllib2 for advanced users. For example, you can > > > easily set your own headers when retrieving and serving pages, > > > such as the User-Agent header which you cannot set in either > > > urllib or urllib2. > > > > Sure you can. See: > > > > http://www.diveintopython.org/http_web_services/user_agent.html > > > > (though the behavior was changed for python 2.3 to make setting the > > user agent work better) > > > > > > max > > > > > > -- > > http://mail.python.org/mailman/listinfo/python-list > > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: From larry.bates at websafe.com Mon Apr 30 09:23:27 2007 From: larry.bates at websafe.com (Larry Bates) Date: Mon, 30 Apr 2007 08:23:27 -0500 Subject: How to convert float to sortable integer in Python In-Reply-To: References: Message-ID: <4tednQylRK5BcKjbnZ2dnUVZ_qiqnZ2d@comcast.com> ireyes at javeriana.edu.co wrote: > DEAR SIR, > I SAW YOUR INTERNET QUESTION AND I HAVE THE SAME TROUBLE. > CUOLD YOU HELP ME TO MAKE A FLOAT TO INTEGER CONVERTION? > DO YOU HAVE ANY EXEL FILE THAT CAN DO THAT? > REGARDS AND THANKS A LOT > > IVAN REYES > > ___________________________________ > > AVISO LEGAL: El presente correo electronico no representa la opinion o el consentimiento oficial de la PONTIFICIA UNIVERSIDAD JAVERIANA. Este mensaje es confidencial y puede contener informacion privilegiada la cual no puede ser usada ni divulgada a personas distintas de su destinatario. Esta prohibida la retencion, grabacion, utilizacion, aprovechamiento o divulgacion con cualquier proposito. Si por error recibe este mensaje, por favor destruya su contenido y avise a su remitente. > En este aviso legal se omiten intencionalmente las tildes. > > Este mensaje ha sido revisado por un sistema antivirus, por lo que su contenido esta libre de virus. > This e-mail has been scanned by an antivirus system, so its contents is free of viruses. You have given us an ill defined problem. 1) If you want to convert float to int just use int() function. s=int(f) 2) If you want to keep some fractional part of the float multiply it by 10, 100, 1000, 10000, ... depending on how many digits of precision you wish to retain and then take int(). s=int(f*10000) would retain 4 digits of precision and throw away the remainder. 3) You can sort on float just fine, so why do you need int()? -Larry From arkanes at gmail.com Fri Apr 6 12:41:24 2007 From: arkanes at gmail.com (Chris Mellon) Date: Fri, 6 Apr 2007 11:41:24 -0500 Subject: block scope? In-Reply-To: References: Message-ID: <4866bea60704060941v261d2fe8r56ed8426354b9276@mail.gmail.com> On 4/6/07, Neal Becker wrote: > One thing I sometimes miss, which is common in some other languages (c++), > is idea of block scope. It would be useful to have variables that did not > outlive their block, primarily to avoid name clashes. This also leads to > more readable code. I wonder if this has been discussed? > Block scope as a way to prevent name clashes is usually solved by refactoring (in C++, too) - if you can't disambiguate locals in a function it's usually a sign that your function does to much and needs to be broken up. Block scope as a way to control object lifetimes (automatic variables, or RAII) is addressed (in 2.5) by context managers or (pre-2.5) try/finally blocks. From rrr at ronadam.com Sat Apr 14 19:18:36 2007 From: rrr at ronadam.com (Ron Adam) Date: Sat, 14 Apr 2007 18:18:36 -0500 Subject: Pydoc Rewrite Discussion at doc-sig list. In-Reply-To: References: <461F9E9C.2070901__24323.6438873739$1176477461$gmane$org@ronadam.com> Message-ID: Colin J. Williams wrote: > Ron Adam wrote: >> If anyone is interested in participating in discussing the details of the >> PyDoc rewrite/refactoring I've been working on, a discussion is being >> started on the doc-sig list. >> >> Doc-Sig at python.org >> >> The goal of this discussion will be to get it to a final finished form so a >> patch can be submitted and a final discussion can take place on the >> python-dev list at a later date. >> >> Thanks and Regards, >> Ron Adam >> > Are there features which exist or planned for Pydoc and which are not > available with epydoc? They are really two different things. Epydoc is an application for producing documentation, Pydoc is more of a live introspection tool. Pydoc *is* primarily the console help function. Many users don't realize that when they use the help() function they are using Pydoc. Since Epidoc is a stand alone application, it has much more freedom to add and extend what it does. Probably Epidoc will always be ahead of Pydoc when it comes to generating separate stand alone documentation. Pydoc produces interactive documentation as needed, it doesn't normally produce any files as you use it. For example while you are working on a project you can be viewing the Pydoc output in a web browser, make changes, and then refresh the browser page to see those changes. Same goes for the builtin help() function and interactive help in console mode. Pydoc can produce both text and html files, but that isn't it's main use. There are several reasons for rewriting Pydoc. One is that as both a tool and a library module, it has developed incrementally over time and is currently limited more so than it should be for both as a tool and as a library module to be used by other programs. It has also gotten to the point where it's not as easy to maintain as it could be. What I'm doing is addressing these issues by making it a package and breaking it down into more modular parts. I'm not trying to make a lot of changes to the output as I see that as a separate issue. But by rewriting the code that produces that output to be more modular, flexible, and easier to maintain, it will make producing better output much easier to do. As a better library tool box, it may be that other tools can use the Pydoc package as a base to build on. So it is a goal to make the basic parts of Pydoc extendable and flexible, but at the same time keeping the interface to each part clear and simple. Some of these parts may be relocated other packages depending on what they do. Are there any specific features you are interested in? Cheers, Ron From gagsl-py2 at yahoo.com.ar Sun Apr 1 03:50:53 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sun, 01 Apr 2007 04:50:53 -0300 Subject: shelf membership References: <1175386940.317989.202070@e65g2000hsc.googlegroups.com> Message-ID: En Sat, 31 Mar 2007 21:22:20 -0300, John Machin escribi?: > On Apr 1, 8:02 am, Aaron Brady wrote: >> can you shelve objects with membership? >> >> this gives you: >> >> TypeError: object does not support item assignment >> dict 0 True >> Exception exceptions.TypeError: 'object does not support item >> assignment' >> in ignored >> >> > ignored is a bit mysterious. tx in advance. >> > > Please supply the *full* traceback, using copy/paste. Not this time. Exceptions in __del__ are ignored and all you got is that message. To the OP: This comes from Shelf.__del__, which in turn calls close(), which tries to set the internal dict to 0 (?!). You may try overriding close() - but what do you want to achieve, exactly? -- Gabriel Genellina From ptmcg at austin.rr.com Fri Apr 27 15:44:07 2007 From: ptmcg at austin.rr.com (Paul McGuire) Date: 27 Apr 2007 12:44:07 -0700 Subject: My newbie annoyances so far In-Reply-To: <3zqYh.1800$uJ6.1494@newssvr17.news.prodigy.net> References: <1177688082.758043.133920@r30g2000prh.googlegroups.com> <3zqYh.1800$uJ6.1494@newssvr17.news.prodigy.net> Message-ID: <1177703047.193921.164800@r35g2000prh.googlegroups.com> On Apr 27, 12:42 pm, John Nagle wrote: > Dennis Lee Bieber wrote: > > On 27 Apr 2007 08:34:42 -0700, Paul McGuire > > declaimed the following in comp.lang.python: > > >>deficient - ternary expressions are now part of the language after > >>years of refugees from C and C++ asking how to write "a = b ? c : d", > >>and now they'll get to puzzle/gripe over mapping this to "a = c if b > >>else d". But as a newbie, you need to invest a little more time and > > > And I'll probably ignore those expressions whenever I do get around > > to 2.5+... That syntax, in my mind, just... stinks... > > ALGOL used "expression IF"; you could write > > x := (IF a > b THEN a ELSE b); > > but that doesn't map well to an indentation-based language. > > A syntax suitable for Python, now that there's a bool type, might > be to define ".if()" for "bool". Then one could write > > (a > b).if(a,b) > > which is better than adding an operator. > > Such things are useful in formatting expressions. > > msg = 'Unit is %s' % (unitstatus.if("on","off"),) > > but not really essential. > > John Nagle I think a big part of the current syntax is that it still supports short-circuiting. In x if a else y y never has to be evaluated if condition a is true. When calling a.if(x,y), both x and y have to be evaluated. -- Paul From http Wed Apr 11 00:26:45 2007 From: http (Paul Rubin) Date: 10 Apr 2007 21:26:45 -0700 Subject: itertools, functools, file enhancement ideas References: <7xveg7rhc7.fsf_-_@ruckus.brouhaha.com> <1176049003.872896.7720@d57g2000hsg.googlegroups.com> <7x8xd2rfik.fsf@ruckus.brouhaha.com> <1176233189.570853.27830@o5g2000hsb.googlegroups.com> Message-ID: <7xejmrcz96.fsf@ruckus.brouhaha.com> "Klaas" writes: > Still don't see much advantage over writing a lambda (except perhaps > speed). Well, it's partly a matter of avoiding boilerplate, especially with the lambdaphobia that many Python users seem to have. From arkanes at gmail.com Tue Apr 10 14:04:18 2007 From: arkanes at gmail.com (Chris Mellon) Date: Tue, 10 Apr 2007 13:04:18 -0500 Subject: tuples, index method, Python's design In-Reply-To: <1176226682.3430.86.camel@dot.uniqsys.com> References: <1176210960.3430.20.camel@dot.uniqsys.com> <740c3aec0704100810g5f962e8eu614fbaedecf3608e@mail.gmail.com> <1176219856.3430.76.camel@dot.uniqsys.com> <740c3aec0704101021i1fd79ef2l99eac4ced1e252d9@mail.gmail.com> <1176226682.3430.86.camel@dot.uniqsys.com> Message-ID: <4866bea60704101104r4600d281h135286b66378f4d4@mail.gmail.com> On 4/10/07, Carsten Haese wrote: > On Tue, 2007-04-10 at 19:21 +0200, BJ?rn Lindqvist wrote: > > On 4/10/07, Carsten Haese wrote: > > > > > opponents = tuple(x for x in p if x is not current_player) > > > > > > > > > Your alternative is wrong because it wont raise ValueError if > > > > current_player is not present in the tuple. Please revise your > > > > "solution." > > > > > > You have a point. Here is my revised solution: > > > > > > assert current_player in p > > > opponents = tuple(x for x in p if x is not current_player) > > > > > > The added advantage is that AssertionError is better than IndexError for > > > conveying that a severe program bug has occurred. > > > > Assertions are not checked when you run scripts with -O. > > Right. Which is why you use assert to guard against situations that > should never happen, and you determine in unit tests that they, in fact, > don't happen. Realistically, in a game loop such as > > while not game_has_ended: > for current_player in p: > player_does_something(current_player) > I'm curious why someone would even consider using a tuple in this case regardless. I think that much of the desire for tuple.index is because people use a tuple where they could have a list, but either a) some vestige of B&D language programming comes out and they want to make sure a caller can't mutate it or b) they decide it's not going to change and use the "immutable list" version of the tuple. The first reason is clearly perverse, and can be discounted. The second means this is not so much about tuple.index as it is about appropriate data types. It's not going to be resolved by use cases, because clearly the only use of tuple.index is when you're using it as an immutable list, as in this case. Any use case where you'd want to search a tuple can be rewritten (trivially) as a list. So the solution for the dissenters is to justify the need for a frozen list, not to justify index on tuples. The only use case which even approaches reasonableness in this thread is the binary parsing example (where the position of a value in an unpacked binary blob might be something you need to know). This is a rare enough use case and is easy enough to work around (convert it to a list, write a helper function) that I don't think it's worth any language change overhead at all. From jan.m.danielsson at gmail.com Fri Apr 13 18:59:07 2007 From: jan.m.danielsson at gmail.com (Jan Danielsson) Date: Sat, 14 Apr 2007 00:59:07 +0200 Subject: mod_python & Cookie - unexpected dictionary value Message-ID: <46200b3b$1@griseus.its.uu.se> Hello all, I'm sure I'm not using this right, but I don't understand what I'm doing wrong. What I want is to get all the cookies from the request, then extract the 'sessId' cookie. I'm using this code: ----------------- from mod_python import Cookie [---] def index(req, sessId = None): cookies = Cookie.get_cookies(req) if not sessId and cookies.has_key('sessId'): sessId = cookies['sessId'] sess = Session(req, sessId) httphdr(req) ----------------- (Note: The Session() constructor will attempt to set the cookie, and httphdr() is responsible for the send_http_header() call). This is the part I don't understand. If the sessId cookie exists, it will fail because the returned sessId object will be a Cookie object. If I print str(sessId), I will get the output "sessId=blah". The cookie is set using: c = Cookie.Cookie('sessId', 'blah') c.expires = time.time() + 60*30 Cookie.add_cookie(req, c) So, the part I don't understand is why sessId = cookies['sessId'] ... is returning a Cookie-object. I would have expected to get a string containing "blah"? I can get this to work, by doing this: cookies = Cookie.get_cookies(req) c = str(cookies['sessId']).split('=', 1) ...then use c[1]. Is that the proper way? Seems kind of strange to store the cookies in a dictonary without being able to use the benefits of them? -- Kind regards, Jan Danielsson ------------ And now a word from our sponsor ------------------ Want to have instant messaging, and chat rooms, and discussion groups for your local users or business, you need dbabble! -- See http://netwinsite.com/sponsor/sponsor_dbabble.htm ---- From steve at holdenweb.com Thu Apr 5 07:20:59 2007 From: steve at holdenweb.com (Steve Holden) Date: Thu, 05 Apr 2007 07:20:59 -0400 Subject: shelve error In-Reply-To: <1175756092.643182.142420@n76g2000hsh.googlegroups.com> References: <1175746456.995618.186190@e65g2000hsc.googlegroups.com> <1175746966.023613.178830@n76g2000hsh.googlegroups.com> <1175756092.643182.142420@n76g2000hsh.googlegroups.com> Message-ID: 7stud wrote: > On Apr 4, 10:22 pm, mik3l3... at gmail.com wrote: >> how did you generate aaa.txt? > > Ok, I got it to work by supplying a filename that didn't previously > exist. Neither the book I am reading, "Beginning Python: From Novice > to Professional" nor the book I am using as a reference, "Python in > Nutshell", happens to mention that important fact. > > It seems to make sense that you have to open a file as writable in order to be able to change its contents, though, doesn't it? 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 spradml at gmail.com Wed Apr 11 13:21:15 2007 From: spradml at gmail.com (Pradnyesh Sawant) Date: Wed, 11 Apr 2007 22:51:15 +0530 Subject: output of top on a linux box Message-ID: <80628d680704111021q28823000g1fa443c07a04d5c9@mail.gmail.com> > Can you pull the same information from /proc/stat as opposed to using > a pipe to top? The first line(s) should contain (at least): > > cpu usermode, lowprio, system, idle, hz. Thanks a lot for the help. I finally decided to go with your suggestion. -- warm regards, Pradnyesh Sawant -- Be yourself......everyone else is taken. --Anon From carsten at uniqsys.com Fri Apr 20 09:00:08 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Fri, 20 Apr 2007 09:00:08 -0400 Subject: Byte-Array to String In-Reply-To: <004d01c78329$1e5f7a60$5b1e6f20$@rawlins@thinkbluemedia.co.uk> References: <000f01c7828f$8b8ce770$a2a6b650$@rawlins@thinkbluemedia.co.uk> <46278FF4.9070505@gmail.com> <004d01c78329$1e5f7a60$5b1e6f20$@rawlins@thinkbluemedia.co.uk> Message-ID: <1177074008.3412.12.camel@dot.uniqsys.com> On Fri, 2007-04-20 at 09:51 +0100, Robert Rawlins - Think Blue wrote: > Morning Steve, > > > > That stuff looks mighty promising, I did play around with the > toString() function yesterday but couldn?t get the damned thing > working. That's because Steven seems to have given you suboptimal advice. The thing you're working with is a dbus.Array of dbus.Byte, not a Python array, so Python's standard array module is not going to help you. When you work with an API function and you don't know what to do with the results of calling that function, the documentation for that API should be your first place to look for help. I don't know what you're referencing, but Google tells me that the python-dbus API is documented here: http://dbus.freedesktop.org/doc/dbus-python/api/ So, what do you do with a dbus.Array full of instances of dbus.Byte? Let's look at their documentation, http://dbus.freedesktop.org/doc/dbus-python/api/dbus.Array-class.html and http://dbus.freedesktop.org/doc/dbus-python/api/dbus.Byte-class.html, respectively. The page about dbus.Array tells us that it inherits from list, so you should be able to do indexed access into it and iterate over it. dbus.Byte inherits from int, and the documentation says that a dbus.Byte can be converted to a character (string of length 1) by calling str or chr on it. So, to get a string from your dbus.Array, you could do something like this: s = "" for b in myDbusArray: s += chr(b) However, it's better (faster) to use the join idiom for building a string char-by-char: s = "".join(chr(b) for b in myDbusArray) That ought to give you the string you're asking for. HTH, Carsten. From bj_666 at gmx.net Mon Apr 23 03:40:10 2007 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Mon, 23 Apr 2007 09:40:10 +0200 Subject: Python and Javascript equivalence References: <1177295347.006598.168930@n59g2000hsh.googlegroups.com> Message-ID: In <1177295347.006598.168930 at n59g2000hsh.googlegroups.com>, Prateek wrote: > Try creating a dict with sequential numeric keys. > > If you already have a list called my_list, you can do: > > com_array = dict(zip(range(len(my_list)), my_list)) com_array = dict(enumerate(my_list)) That doesn't create the intermediate lists. Ciao, Marc 'BlackJack' Rintsch From isaac.rodriguez at comcast.net Thu Apr 19 11:17:00 2007 From: isaac.rodriguez at comcast.net (Isaac Rodriguez) Date: 19 Apr 2007 08:17:00 -0700 Subject: Calling private base methods In-Reply-To: References: <1176374675.347453.89340@n76g2000hsh.googlegroups.com> <1176404325.211501.26610@w1g2000hsg.googlegroups.com> <1176435087.708516.66470@o5g2000hsb.googlegroups.com> <1176650850.211487.294690@y80g2000hsf.googlegroups.com> <1hwmmq4.n76p2d1k88mz5N%aleax@mac.com> <1176902245.845880.308870@b75g2000hsg.googlegroups.com> Message-ID: <1176995820.855309.304040@e65g2000hsc.googlegroups.com> > You appear to have led a very sheltered life if the only libraries you ever > use are ones where you can always get a change to the library api in a > timely manner. > The thing here is that we are not talking about my life. I may not have expressed my self correctly, but you are not understanding the point I am trying to make. You can say that you don't like C++ or Java because they put too much restriction when members are declared private. That you prefer Python's approach because in a time of need it will make your life easier. All that is fine with me. It is just a matter of taste. But the truth is that C++ and Java made a decision to do that for a reason, and the times when you have to work around those language features come once in a blue moon; they are the exception, not the rule, and you don't implement features in a language, or for that matter in an application, to simplify the exceptions; you try to implement the most common scenarios. Which features you add to your programs? The features your customers' ask for because they need them and they use them all the time or the ones that you like to implement even if they are not ever used? Thanks, - Isaac From claudio.grondi at freenet.de Sun Apr 15 16:46:25 2007 From: claudio.grondi at freenet.de (Claudio Grondi) Date: Sun, 15 Apr 2007 22:46:25 +0200 Subject: is laziness a programer's virtue? In-Reply-To: <1176654319.273907.167280@q75g2000hsh.googlegroups.com> References: <1176654319.273907.167280@q75g2000hsh.googlegroups.com> Message-ID: Xah Lee wrote: > [SOME FURTHER TROLLING DISTRIBUTED TO MULTIPLE NEWSGROUPS] For those who are relatively new here in comp.lang.python and not aware of the troll: It seems, that Xah still haven't learned from the impact of past abuse reports on his Internet access and tries again to pollute Usenet after a longer time of inactivity. Claudio Grondi From swq22 at yahoo.com Thu Apr 26 16:45:23 2007 From: swq22 at yahoo.com (swq22 at yahoo.com) Date: Thu, 26 Apr 2007 22:45:23 +0200 Subject: http pipelining Message-ID: Which python module is capable of pipelining http requests? (I know httplib can send mulitple requests per tcp connection, but in a strictly serial way. ) From steve at holdenweb.com Sun Apr 22 18:07:57 2007 From: steve at holdenweb.com (Steve Holden) Date: Sun, 22 Apr 2007 18:07:57 -0400 Subject: Building browser-like GET request In-Reply-To: <1177192075.699770.304600@d57g2000hsg.googlegroups.com> References: <1177192075.699770.304600@d57g2000hsg.googlegroups.com> Message-ID: Bj?rn Keil wrote: [...] > > I hope that helped and I wasn't telling things you already new. > As a sidenote: For the task you describe I'd rather use an actual > sniffer - such as Wireshark (http://en.wikipedia.org/wiki/Wireshark), > than logs of a Proxy... Not sure wether Wireshark works under Windows, > though. On a point of information, Wireshark wokrs very effectively under Windows. The only thing you shouldn't expect to be able to do is tap into the loopback network, and that's down to the Windows driver structure. 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 livibetter at gmail.com Mon Apr 16 19:37:18 2007 From: livibetter at gmail.com (livibetter) Date: 16 Apr 2007 16:37:18 -0700 Subject: UpdateLayeredWindow in pywin32 Message-ID: <1176766638.627412.240750@o5g2000hsb.googlegroups.com> Hi! I am trying to making an On-Screen Display, which is implemented by wx.Frame. Basically I created a wx.Frame with style like super(OSDBase, self).__init__(parent, id, title, style = wx.STAY_ON_TOP | wx.FRAME_NO_TASKBAR | wx.TRANSPARENT_WINDOW | wx.NO_BORDER) self.SetTransparent(128) But if I try to draw an image with alpha channel(like PNG format), I always get a background behind this image. But I don't want the background. Then I read this article, http://www.codeproject.com/csharp/OSDwindow.asp The demo program is written in C#. I understand that I need to use UpdateLayeredWindow to update visual content of a layered window. But I always got an error: Traceback (most recent call last): File "osd_post.py", line 60, in osd.Update() File "osd_post.py", line 56, in Update 2) pywintypes.error: (87, 'UpdateLayeredWindow', 'The parameter is incorrect.') I am not sure did I use UpdateLayeredWindow correctly. Any help would be appreciated. My Python is 2.5, pywin32 is 210, wxPython is 2.8.1 UpdateLayeredWindow Function Help from MSDN: http://msdn2.microsoft.com/en-us/library/ms633556.aspx UpdateLayeredWindow Function Help from pywin32: http://aspn.activestate.com/ASPN/docs/ActivePython/2.4/pywin32/win32gui__UpdateLayeredWindow_meth.html My source code: """pyitctrl - OSD""" # Created Date : 2007/03/14 # Author: livibetter import wx, winxpgui, win32con class OSDBase(wx.Frame): def __init__(self, parent, id, title): super(OSDBase, self).__init__(parent, id, title, style = wx.STAY_ON_TOP | wx.FRAME_NO_TASKBAR | wx.TRANSPARENT_WINDOW | wx.NO_BORDER) self.SetTransparent(128) print hex(winxpgui.GetWindowLong(self.GetHandle(), win32con.GWL_EXSTYLE)) print winxpgui.GetLayeredWindowAttributes(self.GetHandle()) self.img = wx.Image("icon.png") self.bmp = self.img.ConvertToBitmap() w, h = self.bmp.GetWidth(), self.bmp.GetHeight() self.SetClientSize( (w, h) ) def Update(self): print "Update" screenDC = winxpgui.GetDC(winxpgui.GetDesktopWindow()) print screenDC cScreenDC = winxpgui.CreateCompatibleDC(0) print cScreenDC (w, h) = self.GetSizeTuple() bmp = wx.EmptyBitmap(w, h) tmpDC = wx.MemoryDC() tmpDC.SelectObject(bmp) tmpDC.SetBackground(wx.Brush("BLACK")) tmpDC.Clear() tmpDC.DrawBitmap(self.bmp,0,0, True) tmpDC.Destroy() del tmpDC winxpgui.SelectObject(cScreenDC, bmp.GetHandle()) winxpgui.UpdateLayeredWindow(self.GetHandle(), screenDC, self.GetPositionTuple(), self.GetSizeTuple(), cScreenDC, (0,0), 0, (0,0,128,1), win32con.ULW_ALPHA) app = wx.App(False) osd = OSDBase(None, wx.ID_ANY, 'OSD Frame') osd.Update() osd.Show() app.MainLoop() From miki.tebeka at gmail.com Mon Apr 2 10:03:28 2007 From: miki.tebeka at gmail.com (Miki) Date: 2 Apr 2007 07:03:28 -0700 Subject: Parallel ping problems python puzzler In-Reply-To: <1175509753.092714.281990@n76g2000hsh.googlegroups.com> References: <1175509753.092714.281990@n76g2000hsh.googlegroups.com> Message-ID: <1175522608.589651.137580@n76g2000hsh.googlegroups.com> Hello, > def run(self): > # -w 1 option to ping makes it timeout after 1 second > pingcmd="/bin/ping -c 2 -q -i 0.3 -w 1 %s >/dev/null" % ip Not sure, but "ip" should be "self.ip", this might cause the problem. HTH, -- Miki http://pythonwise.blogspot.com From gagsl-py2 at yahoo.com.ar Thu Apr 12 23:59:38 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Fri, 13 Apr 2007 00:59:38 -0300 Subject: Using python to delta-load files into a central DB References: Message-ID: En Thu, 12 Apr 2007 23:51:22 -0300, Chris Nethery escribi?: > Yes, they are tab-delimited text files that will change very little > throughout the day. > But, this is messy, antiquated 80s junk, nonetheless. Ugh... > Rows are designated either by a row type or they contain a comment. Each > row type has an identity value, but the 'comment' rows do not. The > comment > rows, however, are logically associated with the last occurring row type. > When I generate my bulk insert file, I add the identity of the last > occurring row type to the comment rows, and generate and populate an > additional identity column in order to retain the order of the comments. > Generally rows will either be added or changed, but sometimes rows will > be > removed. Typically, only 1-5 new rows will be added to a file in a given > day, but users sometimes make manual corrections/deletions to older rows > and > sometimes certain column values are recalculated. http://tgolden.sc.sabren.com/python/win32_how_do_i/watch_directory_for_changes.html You could keep a copy of all files - let's say, as they were yesterday. When you want to process the changes, iterate over all files and see if they are newer than your copy. You could use the filecmp module: http://docs.python.org/lib/module-filecmp.html For each modified file: load it, and process the comments adding the associated row type and the identity. Just do the same with the "yesterday" file. (I assume they're not so big that you can keep both in memory). You have then two lists of lines; then, use the functions in module difflib to detect the changed lines; based on those results, generate your database inserts/deletes/updates. This way you will not process the unchanged files, and inside each file, you will ignore unchanged lines. At least in principle it should be faster than redoing all from scratch each time... > Did I mention that the header contains another implied hierarchy? > Fortunately, I can just ignore it and strip it off. good - I imagine it's enough work as it is now... -- Gabriel Genellina From steve at REMOVE.THIS.cybersource.com.au Fri Apr 20 22:18:34 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Sat, 21 Apr 2007 12:18:34 +1000 Subject: When are immutable tuples *essential*? Why can't you just use lists *everywhere* instead? References: <1177088796.622928.224890@d57g2000hsg.googlegroups.com> <1177089206.550423.288670@q75g2000hsh.googlegroups.com> <58sf33F2b1q8tU1@mid.individual.net> <1177103370.022138.110320@n59g2000hsh.googlegroups.com> <1177108560.660288.171890@n76g2000hsh.googlegroups.com> Message-ID: On Fri, 20 Apr 2007 15:36:00 -0700, seberino at spawar.navy.mil wrote: > > >> The article explains that, amongst other things, tuples are faster >> than lists, so if you are working with constant values (inmutables) >> they are more indicated than lists. > > Thanks. I thought Python's design wasn't so concerned with > optimizations. > Adding a new type "just" for optimization reasons seems perhaps > unnecessary. I could be wrong. It's times like this I want to cry... >>> adict = {(1,2): "parrot"} Try replacing that tuple with a list. "Just optimization" my eye! -- Steven. From steve at holdenweb.com Tue Apr 24 13:18:12 2007 From: steve at holdenweb.com (Steve Holden) Date: Tue, 24 Apr 2007 13:18:12 -0400 Subject: Feedback on Until recipe In-Reply-To: <1177430903.027128.86480@o40g2000prh.googlegroups.com> References: <1177430903.027128.86480@o40g2000prh.googlegroups.com> Message-ID: Thomas Nelson wrote: > Occasionally someone posts to this group complaining about the lack of > "repeat ... until" in python. I too have occasionally wished for such > a construct, and after some thinking, I came up with the class below. > I'm hoping to get some feedback here, and if people besides me think > they might use it someday, I can put it on the python cookbook. I'm > pretty happy with it, the only ugly thing is you have to use a > lambda. Ideally i'd like to just see > while Until(i<3) > but that doesn't work. > Please tell me what you think, and thanks for your time. > > Tom > > class Until: > """ > >>> i = 0 > >>> while Until(lambda: i<3): > ... print "hello" > ... i += 1 > hello > hello > hello > >>> while Until(lambda: i<2): #note i still equals 3 here > ... print "hello" > hello > """ > yet = True > def __init__(self, mybool): > if self.__class__.yet or mybool(): > self.__class__.yet = False > self.ans = True > else: > self.__class__.yet = True > self.ans = False > > def __nonzero__(self): > return self.ans > First of all, I have to say it reads horribly. "while Until(...)" is supposed to remind us of a *repeat* loop? Secondly it isn't really what you want because the condition is still being evaluated before the loop body is executed, when the idea of a repeat loop is to terminate the loop after at least one iteration once the condition is true. This is not strictly equivalent to your conditions. Temporal logic is tricky. By the way, isn't it always true that self.ans == not self.__class__.yet (and why use a class variable, by the way, doesn't this stop you from using nested loops)? That's about all I can think of offhand. Sorry if it seems a bit negative. I'm hoping it will spur you on to a better solution. regards Steve regards Steve -- Steve Holden +1 571 484 6266 +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 jgodoy at gmail.com Fri Apr 20 17:19:52 2007 From: jgodoy at gmail.com (Jorge Godoy) Date: Fri, 20 Apr 2007 18:19:52 -0300 Subject: Do other Python GUI toolkits require this? References: <1177014799.004875.262060@y80g2000hsf.googlegroups.com> Message-ID: <871wiepwuf.fsf@gmail.com> Dennis Lee Bieber writes: > But is it a "wrong idea" if 999 people interpret the phrase one way, > and just 1 insists upon an interpretation that, while correct in a small > technical area, results in misunderstanding when speaking with the other > 999? You remind me of my grandpa: if all soldiers but one are marching with the "wrong" foot ahead, who's wrong? -- Jorge Godoy From deets at nospam.web.de Mon Apr 16 13:50:01 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 16 Apr 2007 19:50:01 +0200 Subject: Compare regular expressions In-Reply-To: References: Message-ID: <58hrabF2g9sfqU1@mid.uni-berlin.de> Thomas Dybdahl Ahle schrieb: > Hi, I'm writing a program with a large data stream to which modules can > connect using regular expressions. > > Now I'd like to not have to test all expressions every time I get a line, > as most of the time, one of them having a match means none of the others > can have so. > > But ofcource there are also cases where a regular expression can > "contain" another expression, like in: > "^strange line (\w+) and (\w+)$" and "^strange line (\w+) (?:.*?)$" in > which case I'd like to first test the seccond and only if it mathces test > the seccond. > > Do anybody know if such a test is possible? > if exp0.contains(exp1): ... It's not. For the simplest of expressions one might come up with a relation between them, but even that would be hard. General case? No chance. Diez From kyosohma at gmail.com Tue Apr 3 09:58:03 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: 3 Apr 2007 06:58:03 -0700 Subject: XML DTD analysis, diffing ... In-Reply-To: <1175608328.341381.97040@b75g2000hsg.googlegroups.com> References: <1175603926.371027.69390@e65g2000hsc.googlegroups.com> <1175606848.838850.18150@w1g2000hsg.googlegroups.com> <1175608328.341381.97040@b75g2000hsg.googlegroups.com> Message-ID: <1175608683.127425.114890@n59g2000hsh.googlegroups.com> On Apr 3, 8:52 am, "olive" wrote: > Mike, > > I know all of these tools and I already suspected xmlproc as a good > candidate. > > The problem is I can't download it for the moment since Lars website > is blocked here at my work and PyXML is dead. > > Maybe there is an alternative download link ? > > Thank you for the Cookbook recipe anyway. > > Olivier. When I go to the xmlproc website, it states that it is now a part of the PyXML package, which can be found on Soureforge here: http://pyxml.sourceforge.net/ Mike From samfeltus at gmail.com Mon Apr 30 02:59:43 2007 From: samfeltus at gmail.com (SamFeltus) Date: 29 Apr 2007 23:59:43 -0700 Subject: SonomaSunshine Get's a Little Peppier Message-ID: <1177916383.119425.210920@e65g2000hsc.googlegroups.com> http://samfeltus.com/as3/codetalking.html SonomaSunshine - The Redneck Riviera's Best Python Powered Folk Art Server :) From spamtrap at dot-app.org Wed Apr 25 17:10:54 2007 From: spamtrap at dot-app.org (Sherm Pendley) Date: Wed, 25 Apr 2007 17:10:54 -0400 Subject: bitwise shift? References: Message-ID: desktop writes: > for k in range(10, 25): > n = 1 << k; > > I have never read Python before but is it correct that 1 get > multiplied with the numbers 10,11,12,12,...,25 assuming that 1 << k > means "1 shift left by k" which is the same as multiplying with k. Shift left is *not* the same as multiplying by k. It is the same as multi- plying by 2^k. That is, 1<<10 = 1024, 1<<11 = 2048, 1<<12 = 4096, etc. sherm-- -- Web Hosting by West Virginians, for West Virginians: http://wv-www.net Cocoa programming in Perl: http://camelbones.sourceforge.net From a.schmolck at gmail.com Wed Apr 4 11:39:39 2007 From: a.schmolck at gmail.com (Alexander Schmolck) Date: 04 Apr 2007 16:39:39 +0100 Subject: String manipulation References: <1175699768.427986.210310@l77g2000hsb.googlegroups.com> Message-ID: All the code is untested, but should give you the idea. marco.minerva at gmail.com writes: > Hi all! > > I have a file in which there are some expressions such as "kindest > regard" and "yours sincerely". I must create a phyton script that > checks if a text contains one or more of these expressions and, in > this case, replaces the spaces in the expression with the character > "_". For example, the text > > Yours sincerely, Marco. > > Must be transformated in: > > Yours_sincerely, Marco. > > Now I have written this code: > > filemw = codecs.open(sys.argv[1], "r", "iso-8859-1").readlines() > filein = codecs.open(sys.argv[2], "r", "iso-8859-1").readlines() > > mw = "" > for line in filemw: > mw = mw + line.strip() + "|" One "|" too many. Generally, use join instead of many individual string +s. mwfind_re_string = "(%s)" % "|".join(line.strip() for line in filemw) > mwfind_re = re.compile(r"^(" + mw + ")",re.IGNORECASE|re.VERBOSE) mwfind_re = re.compile(mwfind_re_string),re.IGNORECASE) > mwfind_subst = r"_" > > for line in filein: That doesn't work. What about "kindest\nregard"? I think you're best of reading the whole file in (don't forget to close the files, BTW). > line = line.strip() > if (line != ""): > line = mwfind_re.sub(mwfind_subst, line) > print line > > It correctly identifies the expressions, but doesn't replace the > character in the right way. How can I do what I want? Use the fact that you can also use a function as a substitution. print mwfind_re.sub(lambda match: match.group().replace(' ','_'), "".join(line.strip() for line in filein)) 'as From Eric_Dexter at msn.com Mon Apr 16 00:45:21 2007 From: Eric_Dexter at msn.com (Eric_Dexter at msn.com) Date: 15 Apr 2007 21:45:21 -0700 Subject: Getting started with python In-Reply-To: <1176685541.604911.57630@d57g2000hsg.googlegroups.com> References: <1176598011.463543.96990@q75g2000hsh.googlegroups.com> <1176645201.901480.277030@d57g2000hsg.googlegroups.com> <1176685541.604911.57630@d57g2000hsg.googlegroups.com> Message-ID: <1176698721.165581.231610@n59g2000hsh.googlegroups.com> On Apr 15, 8:05 pm, chengzhiannahu... at gmail.com wrote: > On Apr 15, 9:53 am, "Eric_Dex... at msn.com" wrote: > > > > > > > On Apr 14, 7:46 pm, "Eric" wrote: > > > > Hello, after reading some of the book Programming Python it seems that > > > python is something I would like to delve deeper into. The only thing > > > is, I have no idea what I should try and write. So I was hoping that > > > someone here could help point me to a group/project that would be a > > > good starting place for a person with limited python knowledge, but > > > that is willing to learn whatever is necessary. I'm hoping that with a > > > goal I can start to learn python instead of just playing around with > > > it. Thanks. > > > I have a little sub-project where I generate random numbers to a music > > file (a simpe ascii format that works in a grid)http://www.stormpages.com/edexter/csound.htmlorif you see some other > > part of it you would like to work on or expand..https://sourceforge.net/projects/dex-trackerIhaven't added the sub- > > project yet but I can upload it to some google space if you are > > intrested.. (uses wxwindows and python 2.5) > > I just installed Python 2.5 a few days ago. I like to play with > csound. > However, I am a window user knowing Java and C#. I do not have any > experience with unix system and c. I appreciate if you would send me > some instructions and examples to get me started so that In the > future, I can use midi input and get ourput from csound with a final > objective to generate some music not representable by midi. > > Chin- Hide quoted text - > > - Show quoted text - Csound is based on c but as a csound user you don't realy need to know... just take the instruments that are already available for free.. Dex Tracker is just an interface to make it easier and provide other tools.. more info on csound including manuals exc can be found at http://www.csounds.com From martin at v.loewis.de Sat Apr 7 18:13:22 2007 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sun, 08 Apr 2007 00:13:22 +0200 Subject: 1 Thread = 3 interpreter launched ??? In-Reply-To: <1175957690.323531.50820@o5g2000hsb.googlegroups.com> References: <1175957690.323531.50820@o5g2000hsb.googlegroups.com> Message-ID: <46181782.7020008@v.loewis.de> > When creating the thread, Python forks 2 times and thus consume me > around 60% of RAM ! > It's very critical, am i missed something ? In case Diez's answer isn't clear: you misinterpret the data you see. That each process is listed with 4172kB memory doesn't mean they consume 12000kB together. Instead, they consume 4172kB together, as all data are shared across all threads. Regards, Martin From kw at codebykevin.com Thu Apr 19 14:10:49 2007 From: kw at codebykevin.com (Kevin Walzer) Date: Thu, 19 Apr 2007 14:10:49 -0400 Subject: Future Python Gui? In-Reply-To: <1177004764.222101.185880@l77g2000hsb.googlegroups.com> References: <1176859699.906386.326720@b75g2000hsg.googlegroups.com> <1176923448.998078.170760@e65g2000hsc.googlegroups.com> <46267C84.8040505@codebykevin.com> <1176941169.750013.216660@e65g2000hsc.googlegroups.com> <4caef$4626b6f4$4275d90a$19707@FUSE.NET> <1176952141.007295.272000@e65g2000hsc.googlegroups.com> <46275BED.3050808@codebykevin.com> <1177004764.222101.185880@l77g2000hsb.googlegroups.com> Message-ID: <4627B0A9.1010008@codebykevin.com> bcwhite at pobox.com wrote: > What is the benefit of calling similar widgets for both modules within > the same code? Why wouldn't I call everything via Tile? (i.e. "from > Tile import *" and not import Tkinter at all) Because Tile depends on Tkinter, and also, not everything from Tkinter is in Tile (text widget, menus, etc). -- Kevin Walzer Code by Kevin http://www.codebykevin.com From surekap at gmail.com Sun Apr 29 18:01:06 2007 From: surekap at gmail.com (Prateek) Date: 29 Apr 2007 15:01:06 -0700 Subject: help in debugging file.seek, file.read Message-ID: <1177884066.570052.186820@y5g2000hsa.googlegroups.com> I have a wierd sort of problem. I'm writing a bunch of sets to a file (each element is a fixed length string). I was originally using the built-in sets type but due to a processing issue, I had to shift to a Python implementation (see http://groups.google.com/group/comp.lang.python/browse_thread/thread/77e06005e897653c/12270083be9a67f6). I'm using Raymond Hettinger's very graciously provided TransactionSet recipe from http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/511496 My old code was pretty speedy but the new code is quite slow and according to some hotshot profiles it has nothing to do with the new TransactionSet. *Some* of the file.seek and file.read calls occasionally block for insane amounts (>10s) of time when reading no more than 45 bytes of data from the file. So when I'm running load- tests, this eventually happens like so: Each i_id statement is the time taken for 100 successive commits. Each RTH (Read Table Header) statement is the time taken for a single read call for 45 bytes of data # sz__TABLE_HEADER_FORMAT__ is 45 hdr = os.read(f.fileno(), sz__TABLE_HEADER_FORMAT__) #hdr = f.read(sz__TABLE_HEADER_FORMAT__) # Tried this as well Loading items... i_id: 0 0.000111103057861 i_id: 100 1.01557397842 i_id: 200 1.14013886452 i_id: 300 1.16142892838 i_id: 400 1.16356801987 i_id: 500 1.36410307884 i_id: 600 1.34421014786 i_id: 700 1.30385017395 i_id: 800 1.48079919815 i_id: 900 1.41147589684 RTH: 0.582525968552 RTH: 2.77490496635 i_id: 1000 5.16863512993 i_id: 1100 1.73725795746 i_id: 1200 1.56621193886 i_id: 1300 1.81338000298 i_id: 1400 1.69464302063 i_id: 1500 1.74725604057 i_id: 1600 2.35222291946 i_id: 1700 1.85096788406 i_id: 1800 2.20518493652 i_id: 1900 1.94831299782 i_id: 2000 2.03350806236 i_id: 2100 2.32529306412 i_id: 2200 2.44498205185 RTH: 0.105868816376 i_id: 2300 3.65522289276 i_id: 2400 4.2119910717 i_id: 2500 4.21354198456 RTH: 0.115046024323 RTH: 0.122591972351 RTH: 2.88115119934 RTH: 10.5908679962 i_id: 2600 18.8498170376 i_id: 2700 2.42577004433 i_id: 2800 2.47392010689 i_id: 2900 2.88293218613 So I have no idea why this is happening (it is also happening with seek operations). Any guidance on how to debug this? thanks, Prateek From michael at jedimindworks.com Mon Apr 16 06:11:37 2007 From: michael at jedimindworks.com (Michael Bentley) Date: Mon, 16 Apr 2007 05:11:37 -0500 Subject: How to generate a continuous string In-Reply-To: <1176717806.754728.9600@y80g2000hsf.googlegroups.com> References: <1176717806.754728.9600@y80g2000hsf.googlegroups.com> Message-ID: <0B987F50-56DE-4B6D-AFF9-EFB738D2E25C@jedimindworks.com> On Apr 16, 2007, at 5:03 AM, ????????????? ?? wrote: > How to generate a continuous string, like this > "aaaaaaaaaaaaaaaaaaaaaaa" > the number of characters is dynamic. Is there a module or function > implement this string ? > such as: duplicate_string(char, num) It's even easier than that -- just multiply: >>> 'a' * 32 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' From al at taslab.com Wed Apr 25 11:06:22 2007 From: al at taslab.com (Alex Taslab) Date: Wed, 25 Apr 2007 17:06:22 +0200 Subject: key detect Message-ID: <1177513582.6587.19.camel@pktbl> Hi everybody, does anyone know how to detect a key press from a keyboard. Well I do know how to do that, but i need to detect just one press and ignore the others. I mean, my program checks an input from the outside (a sensor) and i emulate that signal as a keypress, but the sensor doesn`t send the signal as a unique pulse y just keeps sending signal during some seconds, so that is like to be pressing one key for a period of time. How can i take that first press of a key and ignore the others? I am using pygtk. thanks everybody! From tubby at bandaheart.com Thu Apr 12 14:54:53 2007 From: tubby at bandaheart.com (tubby) Date: Thu, 12 Apr 2007 14:54:53 -0400 Subject: odd unicode error In-Reply-To: <461E7C9B.20505@v.loewis.de> References: <461E7C9B.20505@v.loewis.de> Message-ID: Martin v. L?wis wrote: >> path += '/' + b >> UnicodeDecodeError: 'ascii' codec can't decode byte 0xd0 in position 1: >> ordinal not in range(128) >> >> Any ideas? > > path is a Unicode string, b is a byte string and contains the > byte \xd0. > > The problem is that you have a directory with file names in it that > cannot be converted to Unicode strings, using the file system > encoding. If you can't fix the file system, you have to make > search_path a byte string. > > Regards, > Martin I fixed it... I didn't tell the whole story. The interface uses wxpython. It returns a unicode pathname that os.walk() uses. I changed that pathname with str() and now, it no longer barfs. From kyosohma at gmail.com Wed Apr 4 13:40:27 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: 4 Apr 2007 10:40:27 -0700 Subject: Write to a binary file In-Reply-To: References: Message-ID: <1175708427.607882.268950@p77g2000hsh.googlegroups.com> On Apr 4, 11:40 am, "Thomi Aurel RUAG A" wrote: > Hy > I'm using Python 2.4.2 on an ARM (PXA-270) platform (linux-2.6.17). > My Goal is to write a list of bytes down to a file (opened in binary > mode) in one cycle. The crux is that a '0x0a' (line feed) will break the > cycle of one writing into several pieces. Writing to a "simple" file, > this wouldn't cause any problem. > > Assuming - without questioning ;-) - that a device file (/dev/*) has to > be written in one cycle because one write call will be interpreted as > one "transaction". The write behaviour on line feed's isn't really > usefull because such "transactions" would be broken up into serveral > pieces and therefore for the device into several "transactions". > > Is there a possibility to write a list of bytes "en bloc" to a binary > file? (without the interpreting of the line feed's) > Opening a file i binary mode (i.e "wb") seems not to be enough. > > Thank you for any help > Aurel I don't know if these will help or not, but they all have info on binary file writing: http://mail.python.org/pipermail/python-list/2001-September/105529.html http://docs.python.org/tut/node9.html http://www-128.ibm.com/developerworks/opensource/library/os-python8/ If your data is a bunch of strings, have to tried just concatenating them into one variable and writing that? If Python is the only program you will use to read the data, you should be able to pickle it. Mike From michael at jedimindworks.com Sat Apr 14 02:00:08 2007 From: michael at jedimindworks.com (Michael Bentley) Date: Sat, 14 Apr 2007 01:00:08 -0500 Subject: Append data to a list within a dict In-Reply-To: <7xejmnbj0x.fsf@ruckus.brouhaha.com> References: <7xejmnbj0x.fsf@ruckus.brouhaha.com> Message-ID: <1D590950-A85A-48AB-865E-3D17C288F542@jedimindworks.com> On Apr 14, 2007, at 12:51 AM, Paul Rubin wrote: > Is this a class exercise? Hint: > 1) figure out how to access the list of the 'two' key > 2) append 'twofour' to it. damn. From deets at nospam.web.de Wed Apr 4 06:49:07 2007 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 04 Apr 2007 12:49:07 +0200 Subject: optparse option prefix References: Message-ID: <57he53F2cm33sU1@mid.uni-berlin.de> > > (3) Create a filter module that reads sys.argv, replaces leading "+" signs > with "-" signs, and then stuffs it back into sys.argv before optparse gets > to see it. That's not even necessary, the optparser will work on a passed argument list. No need to alter sys.argv. Diez From hg at nospam.org Sat Apr 7 05:36:05 2007 From: hg at nospam.org (hg) Date: Sat, 07 Apr 2007 11:36:05 +0200 Subject: Pyserial example program error: win32file.SetupComm reports 'Incorrect function.' References: Message-ID: <5LPRh.37770$Ng1.19596@newsfe19.lga> Ron Jackson wrote: > Dennis Lee Bieber wrote: >> On Wed, 07 Feb 2007 11:14:39 -0800, Ron Jackson >> declaimed the following in >> comp.lang.python: >> >> >>>I am using Python 2.5 on Windows XP. I have installed Pyserial and >>>win32all extensions. >>> >> >> 2.4 on XP Pro SP2... >> >> >>>When I try to run the example program scan.py (included below), or any >>>other program using pyserial, as soon as it hits the statement: >>> >>>s = serial.Serial(i) >>> >> >> >>>>>import serial >>>>>for i in range(256): >> >> ... try: >> ... print i, >> ... s = serial.Serial(i) >> ... print s.portstr >> ... s.close() >> ... except serial.SerialException: >> ... print >> ... >> 0 COM1 >> 1 >> 2 COM3 >> 3 >> 4 >> 5 >> 6 >> 7 >> 8 >> 9 >> 10 >> 11 >> and on and on... >> >> >>>What do I need to do to fix this? Thanks for the help! >> >> >> Does the serial port module require a compile for use with 2.5? >> Well, with only one download since Python 2.2, guess not... >> >> Something glitched in win32? Sorry, I don't know... However, since >> those are Python source files, you could always plug in some debugging >> lines around that win32 call to see what actually is there. Do you have >> any unnatural serial ports on the machine? (Like a USB<>serial >> converter?) > > Trying your program, I get the same error 'Incorrect function.': > > Traceback (most recent call last): > File "", line 4, in > s = serial.Serial(i) > File "C:\Python25\Lib\site-packages\serial\serialutil.py", line 156, in > __init__ > self.open() > File "C:\Python25\lib\site-packages\serial\serialwin32.py", line 57, in > open > win32file.SetupComm(self.hComPort, 4096, 4096) > error: (1, 'SetupComm', 'Incorrect function.') > > > I tried PySerial on a laptop, also running XP Home SP2, and both the > example program and the program you suggested work fine on the laptop. > > The desktop computer that is giving me the error doesn't have any > unnatural serial ports on it currently. The laptop worked fine, either > with a USB device emulating COMM6 present or with the USB device > disconnected. > > I checked and both machines are running the same version of win32file, > which is site-packages\win32\win32file.pyd, 88 KB dated 9/22/2006. > > So my question is: > > Why would the statement win32file.SetupComm(self.hComPort, 4096, 4096) > > work just fine on one machine and not the other? > > win32file.pyd can't be opened like a .py file, and I don't know what the > rather cryptic error 'Incorrect function.' is trying to tell me. Does > anyone who is familiar with win32file have an idea what the problem is? > > Thanks for the help! > > -- Ron I am now facing your problem ... on a machine that used to work fine. Have you figured it out ? Could it be a conflict between pyserial and pywin32 ? hg From thn at mail.utexas.edu Tue Apr 3 14:53:50 2007 From: thn at mail.utexas.edu (Thomas Nelson) Date: 3 Apr 2007 11:53:50 -0700 Subject: how to remove multiple occurrences of a string within a list? In-Reply-To: <1175624433.206953.214290@n59g2000hsh.googlegroups.com> References: <1175624433.206953.214290@n59g2000hsh.googlegroups.com> Message-ID: <1175626430.679217.238430@o5g2000hsb.googlegroups.com> bahoo wrote: > Hi, > > I have a list like ['0024', 'haha', '0024'] > and as output I want ['haha'] > > If I > myList.remove('0024') > > then only the first instance of '0024' is removed. > > It seems like regular expressions is the rescue, but I couldn't find > the right tool. > > Thanks! > bahoo It's hard to imagine using regular expressions here. Here's a simple attempt: def removeall(mylist,obj): while obj in mylist: mylist.remove(obj) Or, if you don't need the changes in place: [x for x in mylist if x!= obj] Tom From whamil1 at entergy.com Mon Apr 30 13:50:58 2007 From: whamil1 at entergy.com (Hamilton, William ) Date: Mon, 30 Apr 2007 12:50:58 -0500 Subject: Dict Copy & Compare In-Reply-To: <000e01c78b18$03457cb0$09d07610$@rawlins@thinkbluemedia.co.uk> Message-ID: <588D53831C701746A2DF46E365C018CE01D2CA82@LITEXETSP001.etrsouth.corp.entergy.com> > -----Original Message----- > From: python-list-bounces+whamil1=entergy.com at python.org [mailto:python- > list-bounces+whamil1=entergy.com at python.org] On Behalf Of Robert Rawlins - > Think Blue > Sent: Monday, April 30, 2007 6:09 AM > To: 'Tim Golden' > Cc: python-list at python.org > Subject: RE: Dict Copy & Compare > > On quick question, how can I order a dict by the 'values' (not keys) > before > looping? Is that possible? > The easiest way I can think of is to create a new dict that's reversed. reverseDict = {} for key in dict1: if dict1[key] not in reverseDict: reverseDict[dict1[key]]=[key] else: reverseDict[dict1[key]].append(key) This gives you a dictionary that has the old dict's values as keys, and the old dict's keys as lists of values. You can then sort the keys of this dict and do what you want with it. Of course, the values in dict1 have to be valid dictionary keys for this to work. If they aren't, you may be able to get away with converting them to strings. --- -Bill Hamilton From kjellmf at gmail.com Mon Apr 23 13:43:22 2007 From: kjellmf at gmail.com (Kjell Magne Fauske) Date: 23 Apr 2007 10:43:22 -0700 Subject: Generate report containing pdf or ps figures? In-Reply-To: <132pnp6r4qg0lc2@corp.supernews.com> References: <132pnp6r4qg0lc2@corp.supernews.com> Message-ID: <1177350202.388337.131110@d57g2000hsg.googlegroups.com> On Apr 23, 6:30 pm, Grant Edwards wrote: > I need to be able to generate a PDF report which consists > mostly of vector images (which I can generate as encapsulated > Postscript, PDF, or SVG). What I need is a way to combine > these figures into a single PDF document. Right now the > reports consist entire of these figures, so I just write the > figures out to temp files and then use os.system() to run > ghostscript with appropriate options to combine them into a > single PDF file. > > I'd like to be able to add some text and/or place the figures > in a manner other than one per page in the output document. > > I've looked at ReportLab's documentation, but although it > appears to be able to use bitmap images (e.g jpeg) it doesn't > appear to be able to use vector images (EPS/PDF/SVG). > > Is there a PDF generation library that can place EPS or > PDF figures on a page? If you are familiar with LaTeX, an easy solution would be to automatically generate a LaTeX document that includes your images. This also allows you to add captions, scale the images and much more. You can then run the generated document through pdflatex and you have a nice looking report. Regards, Kjell Magne Fauske http://www.fauskes.net From paul at boddie.org.uk Tue Apr 10 06:19:21 2007 From: paul at boddie.org.uk (Paul Boddie) Date: 10 Apr 2007 03:19:21 -0700 Subject: tuples, index method, Python's design In-Reply-To: References: <1175867771.114540.61810@n76g2000hsh.googlegroups.com> <1175884427.779950.267220@y80g2000hsf.googlegroups.com> <1175953520.316208.241490@o5g2000hsb.googlegroups.com> <7xzm5igbrb.fsf@ruckus.brouhaha.com> Message-ID: <1176200361.260546.280510@n76g2000hsh.googlegroups.com> On 10 Apr, 11:48, Antoon Pardon wrote: > On 2007-04-10, Duncan Booth wrote: > > > There is a cost to every new language feature: it has to be implemented, > > documented, maintained, and above all learned by the users. Good design > > involves, in part, not adding to these burdens except where there is a > > benefit at least equal to the cost. > > So what is the easiest to learn: "All sequences have an index method" or > "Such and so sequences have an index method and others don't" I think this observation leads to insights both at the end-user level and at the implementer level. Tuples and lists are sequences; the index method can be defined generically for all sequences; adding such a method to the tuple type can be done with barely any changes to the implementation taken from the list type. This leads to the observation that a generic index method (defined as a function in the implementation) could be made to work with both lists and tuples, and that various other methods might also be defined similarly, although things like append, extend and other mutating methods wouldn't be appropriate for a tuple. > Which of the above is the easiest to document? > > Now with implementation and maintaining. If you would start with a class > of sequence which classes like tuple and list would inherit from, then > there also would be a single function to be implemented and maintained. > It would just be usable in more types. There isn't a "big win" in this case: the intersection of useful methods between mutable and immutable sequence types is rather small. Nevertheless, providing a slightly deeper abstract class hierarchy might be appropriate, and this is being considered for Python 3000. [...] > The same happened with the ternary operator. Every use case someone > could come up with was rejected by rewriting the code without using > a ternary operator. AFAICS the only reason the ternary operator > finaly got introduced was because a python developer was bitten by an > illusive bug, introduced by one of the idioms that was often used as a > way to simulate a ternary operator. The ternary operator, whilst providing new and occasionally useful functionality, is rather "badly phrased" in my opinion: when used, it's a bit like reading one natural language and suddenly having the grammar of another in use for the rest of the sentence. Paul From sam_spam_cat at verizon.net Sun Apr 22 21:00:41 2007 From: sam_spam_cat at verizon.net (Sam the Cat) Date: Mon, 23 Apr 2007 01:00:41 GMT Subject: Python and Javascript equivalence Message-ID: Hey All, I am writing some COM code in Python to control photoshop. Several functions of PS require an "Array" argument. In the examples of VBscript or javascript the Array type is used. I have tried what would appear to be the equivalent in Python -- Lists and Tuples -- but to no avail. Anyone have any insight on what via the COM interface is equivalent to an Array in javascript ? Cheers Sam From lorenzo at diespammerhethurmans.com Sat Apr 7 14:28:47 2007 From: lorenzo at diespammerhethurmans.com (Lorenzo Thurman) Date: Sat, 07 Apr 2007 13:28:47 -0500 Subject: Mail not setting timestamp In-Reply-To: <1175923152.762487.273780@n76g2000hsh.googlegroups.com> References: <1175923152.762487.273780@n76g2000hsh.googlegroups.com> Message-ID: Gabriel Genellina wrote: > Lorenzo Thurman wrote: > >> I'm using the Mimewriter and mimetools modules to create html messages. >> They work OK, except that when the messages are received, they always >> have the timestamp of 12/31/1969. I've looked through both packages and >> can't find anything that would allow me to manually set it. Can someone >> help me out? > > The date goes into the message headers, like From, To, Subject... > message.add_header("Date", "Thu, 22 Jun 2006 23:18:15 -0300") > > -- > Gabriel Genellina > Thanks for the reply. When I try this though, I get an error: Traceback (most recent call last): File "./synctest.py", line 202, in ? message = createhtmlmail(html, text, subject) File "./synctest.py", line 49, in createhtmlmail writer.addheader("Date", theDate) File "/usr/lib/python2.4/MimeWriter.py", line 100, in addheader lines = value.split("\n") AttributeError: 'datetime.datetime' object has no attribute 'split' I'm trying to use a variable for the date, since of course, it should always be 'now'. someDate = datetime.datetime.now() writer.addheader("Date", someDate) Hard coding a date, like your example, works just fine. Any ideas? From aleax at mac.com Sun Apr 15 22:29:08 2007 From: aleax at mac.com (Alex Martelli) Date: Sun, 15 Apr 2007 19:29:08 -0700 Subject: combination function in python References: <1176615838.830315.160210@b75g2000hsg.googlegroups.com> <1176629911.409257.149780@l77g2000hsb.googlegroups.com> <1176669548.436118.176300@e65g2000hsc.googlegroups.com> <1176683797.421863.16980@o5g2000hsb.googlegroups.com> Message-ID: <1hwml95.f7x14fnsb22aN%aleax@mac.com> mensanator at aol.com wrote: > > You could take it up with the gmpy author and > > induce him to get gmpy included in the standard distro if you are so > > inclined. > > Alex Martelli knows more about that subject than I and > it would be pointless for me to bug him about it. gmpy is LGPL (because so is the underlying GMP) and therefore very unlikely to be included in the Python distribution, whose core committers, collectively, choose laxer, looser licensing labels. Of course, there being no "secret algorithm" for the computation of binary coefficients in GMP, reimplementing comb "from scratch" (_without_ peeking at GMP's sources, so it can get a normal Python license) as a Python extension with similar performance to gmpy.comb is a SMOP (for which I'm not the best candidate, since I may in the past have peeked at GMP's sources, and although I don't consciously recall anything about the binary-coefficients computation [except that there was nothing particularly exciting about it:-)] we surely don't want to risk the FSF suing the PSF, now do we...). Alex From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Sat Apr 14 17:16:04 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Sat, 14 Apr 2007 23:16:04 +0200 Subject: That might be the case for more complex objects... References: <1176546078.934340.253810@y5g2000hsa.googlegroups.com> <1176557734.456820.275780@p77g2000hsh.googlegroups.com> <7saUh.37$4S1.2@newsfe12.lga> Message-ID: <58cukkF2gfre9U1@mid.individual.net> Bart Willems wrote: > I can try this in interactive mode: > >>> a = 5 > >>> b = a > >>> a += 1 > >>> print b > 5 > > So, if /a/ and /b/ where pointing to the *same* "5" in memory, They do: >>> a = 5 >>> b = a >>> a is b True >>> a += 1 >>> a is b False ... but not after a is rebound to a new int. > then I would expect b to be increased, just as a. But after > increasing a, b is still 5... int objects are immutable. Thus, when rebinding a (as happens here in "a += 1"), a new instance of int is created and "a" points to it. > By the way, a classic language like C has features like this too; > they're called pointers. C's int* behaves differently. Regards, Bj?rn -- BOFH excuse #163: no "any" key on keyboard From Florian.Lindner at xgm.de Sun Apr 22 13:58:00 2007 From: Florian.Lindner at xgm.de (Florian Lindner) Date: Sun, 22 Apr 2007 19:58:00 +0200 Subject: Convert from/to struct_time Message-ID: Hello, I have a struct_time and a datetime object and need compare them. Is there any function that converts either of these two to another? Thanks, Florian From thinker at branda.to Thu Apr 5 10:55:22 2007 From: thinker at branda.to (Thinker) Date: Thu, 05 Apr 2007 22:55:22 +0800 Subject: AW: Write to a binary file In-Reply-To: <131a2eeq2feuefe@corp.supernews.com> References: <131a2eeq2feuefe@corp.supernews.com> Message-ID: <46150DDA.2040807@branda.to> Grant Edwards wrote: > On 2007-04-05, Thomi Aurel RUAG A wrote: > > >> A simplified test programm to compare the function for opening >> a file i used ("file()") and your suggested "os.open()" showed >> different behaviour. >> >> My simple testprogramm: >> >> --- START --- >> import os >> >> msg = chr(0x02) + chr(0x36) + chr(0x00) + chr(0x01) + chr(0x0a) + >> chr(0xb0) + chr(0x77) >> >> f = os.open('/dev/pytest', os.O_RDWR) >> os.write(f,msg) >> os.close(f) >> >> f = file('/dev/pytest', 'wb') >> f.write(msg) >> f.close() >> --- END --- >> >> The "pytest" device is a very simple device-driver which >> prints out (using "printk()") the buffer delivered to the >> write function in a hexadecimal format ("Pytest write> [buffer >> in hex format]"). >> >> The output was: >> --- Start --- >> Pytest write> 02 36 00 01 0a b0 77 >> Pytest write> 02 36 00 01 0a >> Pytest write> b0 77 >> --- END --- >> > > I'm surprised that the normal file object's write method does > that -- especially for a "binary" file. IMO, it's a bug when a > binary file object treats 0x0a differently than other byte > values. But, using the file object to read/write a device is > probably not a good idea because of undefined behavior like > that. File objects also do their own buffering, which I > suspect isn't what you want. > Why not try to create a file object with bufsize = 0 ? for ex: --------- fo = file('/dev/pytest', 'wb', 0) fo.write(....) fo.close() -------- -- Thinker Li - thinker at branda.to thinker.li at gmail.com http://heaven.branda.to/~thinker/GinGin_CGI.py From samjnaa at gmail.com Sat Apr 14 07:20:06 2007 From: samjnaa at gmail.com (jamadagni) Date: 14 Apr 2007 04:20:06 -0700 Subject: Python Feature Request: Add the "using" keyword which works like "with" in Visual Basic In-Reply-To: References: <1176547372.584539.89170@q75g2000hsh.googlegroups.com> Message-ID: <1176549606.542551.36480@b75g2000hsg.googlegroups.com> > I like this one for some reason. Just the "using self" would save hella > typing in a lot of classes. I would favor a convention with leading dots > to disambiguate from other variables. This wouldn't conflict with, say, > floats, because variable names can't begin with a number. Excellent. Now we don't have to worry about the "first applicable instance" etc. Any member that begins with a dot will have the context governer auto-prefixed by the parser. This means that nested using statements should be like follows: using self: __using .quit: with the dot preceding quit also. Excellent! But you have said "variable names can't begin with a number". The point this, they shouldn't be able to begin with a *dot*. We are not worried about numbers here, right? From cam.ac.uk at mh391.invalid Mon Apr 16 14:26:19 2007 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Mon, 16 Apr 2007 19:26:19 +0100 Subject: subprocess confusion In-Reply-To: References: Message-ID: Tim Arnold wrote: > If 'machine' value is different than the current machine name, I want to > remsh the command to that machine, but obviously I misunderstood the > preexec_fn arg. I don't think the return value of preexec_fn is used for anything. You can use to do things like set process group IDs in the child. For your use, everything needs to be args. If you are using Python 2.5, and log is a file, you want: from __future__ import with_statement with log: if machine != socket.gethostname(): command = "/bin/remsh %s %s" % (machine, command) subprocess.check_call(command, shell=True, env=env, stderr=subprocess.STDOUT, stdout=log) The semantics are slightly different, since log will always close this way, while in the other example, you have left it open if there is an exception. -- Michael Hoffman From pekka.jarvinen at gmail.com Fri Apr 20 00:41:44 2007 From: pekka.jarvinen at gmail.com (=?iso-8859-1?q?Pekka_J=E4rvinen?=) Date: 19 Apr 2007 21:41:44 -0700 Subject: Calculating CIDR blocks In-Reply-To: <1177032744.375099.248380@q75g2000hsh.googlegroups.com> References: <1177032744.375099.248380@q75g2000hsh.googlegroups.com> Message-ID: <1177044104.267820.19200@o5g2000hsb.googlegroups.com> On 20 huhti, 04:32, Pekka J?rvinen wrote: > # I have list of free IP addresses. One IP per line. Now I'm trying to > # share them to CIDR blocks /24 - /32. For example: if 1.1.1.0 - > 1.1.1.255 > # is free, it returns list['1.1.1.0/24'] but let's say that 1.1.1.1 is > # used, then function should return list['1.1.1.128/25', > # '1.1.1.127/26', '1.1.1.32/27', etc until free block doesn't fit]. > > import string > import network > #http://cheeseshop.python.org/pypi/Adytum-NetCIDR/0.0.1 > > ips = ['192.168.0.0', '192.168.0.1', '192.168.0.2', '192.168.0.3', > '192.168.0.4', '192.168.0.5', '192.168.0.6', '192.168.0.7', > '192.168.0.8', '192.168.0.9', '192.168.0.10', '192.168.0.11', > '192.168.0.12', '192.168.0.13', '192.168.0.14', '192.168.0.15', > '192.168.0.16', '192.168.0.17', '192.168.0.18', '192.168.0.19', > '192.168.0.20', '192.168.0.21', '192.168.0.22', '192.168.0.23', > '192.168.0.24', '192.168.0.25', '192.168.0.26', '192.168.0.27', > '192.168.0.28', '192.168.0.29', '192.168.0.30', '192.168.0.31', > '192.168.0.32', '192.168.0.33', '192.168.0.34', '192.168.0.35', > '192.168.0.36', '192.168.0.37', '192.168.0.38', '192.168.0.39', > '192.168.0.40', '192.168.0.41', '192.168.0.42', '192.168.0.43', > '192.168.0.44', '192.168.0.45', '192.168.0.46', '192.168.0.47', > '192.168.0.48', '192.168.0.49', '192.168.0.50', '192.168.0.51', > '192.168.0.52', '192.168.0.53', '192.168.0.54', '192.168.0.55', > '192.168.0.56', '192.168.0.57', '192.168.0.58', '192.168.0.59', > '192.168.0.60', '192.168.0.61', '192.168.0.62', '192.168.0.63', > '192.168.0.64', '192.168.0.65', '192.168.0.66', '192.168.0.67', > '192.168.0.68', '192.168.0.69', '192.168.0.70', '192.168.0.71', > '192.168.0.72', '192.168.0.73', '192.168.0.74', '192.168.0.75', > '192.168.0.76', '192.168.0.77', '192.168.0.78', '192.168.0.79', > '192.168.0.80', '192.168.0.81', '192.168.0.82', '192.168.0.83', > '192.168.0.84', '192.168.0.85', '192.168.0.86', '192.168.0.87', > '192.168.0.88', '192.168.0.89', '192.168.0.90', '192.168.0.91', > '192.168.0.92', '192.168.0.93', '192.168.0.94', '192.168.0.95', > '192.168.0.96', '192.168.0.97', '192.168.0.98','192.168.0.99', > '192.168.0.100', '192.168.0.101', '192.168.0.102', '192.168.0.103', > '192.168.0.104', '192.168.0.105', '192.168.0.106', '192.168.0.107', > '192.168.0.108', '192.168.0.109', '192.168.0.110', '192.168.0.112', > '192.168.0.113', '192.168.0.114', '192.168.0.115', '192.168.0.116', > '192.168.0.117', '192.168.0.118', '192.168.0.119', '192.168.0.120', > '192.168.0.121', '192.168.0.122', '192.168.0.123', '192.168.0.124', > '192.168.0.125', '192.168.0.126', '192.168.0.127', '192.168.0.128', > '192.168.0.129', '192.168.0.130', '192.168.0.131', '192.168.0.132', > '192.168.0.133', '192.168.0.134', '192.168.0.135', '192.168.0.136', > '192.168.0.137', '192.168.0.138', '192.168.0.139', '192.168.0.140', > '192.168.0.141', '192.168.0.142', '192.168.0.143', '192.168.0.144', > '192.168.0.145', '192.168.0.146', '192.168.0.147', '192.168.0.148', > '192.168.0.149', '192.168.0.150', '192.168.0.151', '192.168.0.152', > '192.168.0.153', '192.168.0.154', '192.168.0.155', '192.168.0.156', > '192.168.0.157', '192.168.0.158', '192.168.0.159', '192.168.0.160', > '192.168.0.161', '192.168.0.162', '192.168.0.163', '192.168.0.164', > '192.168.0.165', '192.168.0.166', '192.168.0.167', '192.168.0.168', > '192.168.0.169', '192.168.0.170', '192.168.0.171', '192.168.0.172', > '192.168.0.173', '192.168.0.174', '192.168.0.175', '192.168.0.176', > '192.168.0.177', '192.168.0.178', '192.168.0.179', '192.168.0.180', > '192.168.0.181', '192.168.0.182', '192.168.0.183', '192.168.0.184', > '192.168.0.185', '192.168.0.186', '192.168.0.187', '192.168.0.188', > '192.168.0.189', '192.168.0.190', '192.168.0.191', '192.168.0.192', > '192.168.0.193', '192.168.0.194', '192.168.0.195', '192.168.0.196', > '192.168.0.197', '192.168.0.198', '192.168.0.199', '192.168.0.200', > '192.168.0.201', '192.168.0.202', '192.168.0.203', '192.168.0.204', > '192.168.0.205', '192.168.0.206', '192.168.0.207', '192.168.0.208', > '192.168.0.209', '192.168.0.210', '192.168.0.211', '192.168.0.212', > '192.168.0.213', '192.168.0.214', '192.168.0.215', '192.168.0.216', > '192.168.0.217', '192.168.0.218', '192.168.0.219', '192.168.0.220', > '192.168.0.221', '192.168.0.222', '192.168.0.223', '192.168.0.224', > '192.168.0.225', '192.168.0.226', '192.168.0.227', '192.168.0.228', > '192.168.0.229', '192.168.0.230', '192.168.0.231', '192.168.0.232', > '192.168.0.233', '192.168.0.234', '192.168.0.235', '192.168.0.236', > '192.168.0.237', '192.168.0.238', '192.168.0.239', '192.168.0.240', > '192.168.0.241', '192.168.0.242', '192.168.0.243', '192.168.0.244', > '192.168.0.245', '192.168.0.246', '192.168.0.247', '192.168.0.248', > '192.168.0.249', '192.168.0.250', '192.168.0.251', '192.168.0.252', > '192.168.0.253', '192.168.0.254', '192.168.0.255'] > # note: 192.168.0.111 is missing > > cidrs = [24, 25, 26, 27, 28, 29, 30, 31, 32] > > free = [] > > for cidr in cidrs: > c = 0 > for ip in ips: > ip_addr = network.CIDR("%s/32" % ip) > my_network = "%s/%d" % (ip, cidr) > network_CIDR = network.CIDR(my_network) > myn = network.Networks([network_CIDR]) > > freelist = [] > > if len(free) > 0: > for i in free: > freelist.append(network.CIDR("%s" % i)) > > freeh = network.Networks(freelist) > > net_len = network_CIDR.getHostCount() > > if ip_addr in myn and ip_addr not in freeh: > c = c + 1 > if c == net_len: > hr = network.CIDR(my_network).getHostRange() > free.append("%s/%s" % (hr[0], cidr)) > c = 0 > > print free > > # Outputs: > # ['192.168.0.128/25', '192.168.0.64/26', '192.168.0.32/27', > '192.168.0.16/28', '192.168.0.8/29', '192.168.0.4/30'] > # That 192.168.0.64/26 cannot be there because it's 192.168.0.64 - > 192.168.0.127 and 192.168.0.111 does not exist in ips list! > # Any ideas? Little changes: for cidr in cidrs: c = 0 for ip in ips: ip_addr = network.CIDR("%s/32" % ip) my_network = "%s/%d" % (ip, cidr) network_CIDR = network.CIDR(my_network) myn = network.Networks([network_CIDR]) freelist = [] if len(free) > 0: for i in free: freelist.append(network.CIDR("%s" % i)) freeh = network.Networks(freelist) net_len = network_CIDR.getHostCount() if ((network_CIDR in myn) and (network_CIDR not in freeh)): c = c + 1 if ((c + 2) == net_len): hr = network.CIDR(my_network).getHostRange() free.append("%s/%s" % (hr[0], cidr)) c = 0 print free now outputs: ['192.168.0.128/25', '192.168.0.0/26', '192.168.0.64/27', '192.168.0.96/28', '192.168.0.112/28'] Which is much better, but now 192.168.0.96/28 includes that 192.168.0.111, so no go. 192.168.0.96/28 must be split into smaller pieces still. From olsonas at gmail.com Tue Apr 24 15:58:37 2007 From: olsonas at gmail.com (Drew) Date: 24 Apr 2007 12:58:37 -0700 Subject: Blank rows resulting from simple csv script Message-ID: <1177444717.188536.20340@r3g2000prh.googlegroups.com> Hi all - I've written a simple script to read a .csv file and then write out rows to a new file only if the value in the 4th column is a 0. Here's the code: import csv reader = csv.reader(open('table_export.csv','rb')) writer = csv.writer(open('new_jazz.csv','w')) for row in reader: if row[3] == '0': writer.writerow(row) This is writing out the correct rows, however it is writing a blank row between each of the rows written out. Any ideas? Thanks, Drew From timr at probo.com Sat Apr 21 17:02:31 2007 From: timr at probo.com (Tim Roberts) Date: Sat, 21 Apr 2007 21:02:31 GMT Subject: CGI Script using Python References: <58our9F2fertqU1@mid.individual.net> Message-ID: "Ralf" wrote: > >is there anybody who can help me. >I would like to use a Python Script to download Files from a Server to the >Client, to update the Client. Remember, though, that a CGI script cannot actually put files anywhere. You can certainly download files to the client browser, but the user will have to be involved to tell the browser where to store the incoming file. Doing anything else would be a security hole. -- Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From skip at pobox.com Wed Apr 4 09:05:01 2007 From: skip at pobox.com (skip at pobox.com) Date: Wed, 4 Apr 2007 08:05:01 -0500 Subject: heap doesn't appear to work as described In-Reply-To: <1175676343.513378.205790@y80g2000hsf.googlegroups.com> References: <1175641694.226975.258820@n76g2000hsh.googlegroups.com> <17938.58082.317522.331513@montanaro.dyndns.org> <1175676343.513378.205790@y80g2000hsf.googlegroups.com> Message-ID: <17939.41597.268425.67773@montanaro.dyndns.org> >>>> My book says that in a heap, a value at position i will be than the >>>> values at positions 2*i and 2*i + 1. >> I am sure your book either uses 1-based arrays or a 0-based arrays >> with the first not used. The need to keep these alternatives in mind >> is an unfortunate fact of programming life. > My book uses lists. Yes, but is the first element of the list addressed as element 1 or element 0? Terry was doing the transformation from 1-based to 0-based indexing to demonstrate that the invariants you described were the same as those maintained by Python's heapq module. Skip From cam.ac.uk at mh391.invalid Fri Apr 13 21:34:15 2007 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Sat, 14 Apr 2007 02:34:15 +0100 Subject: Python editor/IDE on Linux? In-Reply-To: References: Message-ID: Jack wrote: > I wonder what everybody uses for Python editor/IDE on Linux? I'll let you in on a little secret. We all use Emacs. Those who claim to use vim are just trying to prevent you from ever becoming a successful Python programmer, and therefore reduce competition. -- Michael Hoffman From israphelr at googlemail.com Sun Apr 22 14:40:28 2007 From: israphelr at googlemail.com (israphelr at googlemail.com) Date: 22 Apr 2007 11:40:28 -0700 Subject: pickled object, read and write.. Message-ID: <1177267228.603237.113070@n59g2000hsh.googlegroups.com> Hi all. I have to put together some code that reads high scores from a saved file, then gives the user the opportunity to add their name and score to the high scores list, which is then saved. Trouble is, I can't tell the program to read a file that doesn't exist, that generates an error. So I must have a file created, problem HERE is everytime the program is run, it will overwrite the current list of saved high scores. Advice would be much appreciated. From DustanGroups at gmail.com Sat Apr 21 19:36:11 2007 From: DustanGroups at gmail.com (Dustan) Date: 21 Apr 2007 16:36:11 -0700 Subject: Suggestion: str.itersplit() In-Reply-To: <1177192448.271776.154840@n76g2000hsh.googlegroups.com> References: <1177160280.784224.53460@b58g2000hsg.googlegroups.com> <1177192448.271776.154840@n76g2000hsh.googlegroups.com> Message-ID: <1177198571.218581.116690@q75g2000hsh.googlegroups.com> On Apr 21, 4:54 pm, attn.steven.... at gmail.com wrote: > On Apr 21, 5:58 am, Dustan wrote: > > > >From my searches here, there is no equivalent to java's > > > StringTokenizer in python, which seems like a real shame to me. > > > However, str.split() works just as well, except for the fact that it > > creates it all at one go. I suggest an itersplit be introduced for > > lazy evaluation, if you don't want to take up recourses, and it could > > be used just like java's StringTokenizer. > > > Comments? > > If your delimiter is a non-empty string, you > can use an iterator like: > > def it(S, sub): > start = 0 > sublen = len(sub) > while True: > idx = S.find(sub,start) > if idx == -1: > yield S[start:] > raise StopIteration > else: > yield S[start:idx] > start = idx + sublen > > target_string = 'abcabcabc' > for subs in it(target_string,'b'): > print subs Thanks. Well, now I know it can be implemented in a reasonably efficient manner in pure python (ie without having side-efect strings that aren't of any use, as with concatenation). That's what I was mainly concerned about. I feel that it could be a builtin function (seriously, the world wouldn't end if it was, and nor would python), but this'll work. That's my last word on the subject. > For something more complex, > you may be able to use > re.finditer. > > -- > Hope this helps, > Steven From kay.schluehr at gmx.net Mon Apr 2 14:17:03 2007 From: kay.schluehr at gmx.net (Kay Schluehr) Date: 2 Apr 2007 11:17:03 -0700 Subject: Shed Skin Python-to-C++ Compiler 0.0.21, Help needed In-Reply-To: <1175513253.595204.220110@o5g2000hsb.googlegroups.com> References: <576vhbF2ca1guU1@mid.individual.net> <1175376373.241744.6220@y80g2000hsf.googlegroups.com> <1175413310.295953.230840@e65g2000hsc.googlegroups.com> <1175455529.936887.249170@e65g2000hsc.googlegroups.com> <1175496721.899984.193690@n76g2000hsh.googlegroups.com> <1175509861.292455.226280@b75g2000hsg.googlegroups.com> <1175511923.323321.30220@n76g2000hsh.googlegroups.com> <1175513253.595204.220110@o5g2000hsb.googlegroups.com> Message-ID: <1175537817.989894.125020@b75g2000hsg.googlegroups.com> On Apr 2, 1:27 pm, "Paul Boddie" wrote: > On 2 Apr, 13:05, bearophileH... at lycos.com wrote: > > > > > There is some possibility that Python 3.1 will have what you ask for:http://www.python.org/dev/peps/pep-3108/ > > Prior to that PEP being written/published, I made this proposal: > > http://wiki.python.org/moin/CodingProjectIdeas/StandardLibrary/Restru... > > After being brought to the attention of the PEP's author, it seems to > have been swept under the carpet on the Wiki, but it's a more radical > proposal in a number of ways than the PEP seems to be. > > Paul Note that the conflict of putting modules on top level or better within separate packages is not an either-or decision from a programmers point of view who just wants to access those modules. A top level module like lib or std can be pretty virtual since you can create modules at runtime whenever you try to import them. I used this strategy for a project where editing objects in separate files leaded to a better overview compared to one large file containing all definitions. However I created one module at runtime that served as a common access point for all these particular definitions that were tedious to import separately and would have required file system lookups quite often. This might even allow multiple classifications but I haven't experimented with them yet. Kay From http Sun Apr 15 21:19:17 2007 From: http (Paul Rubin) Date: 15 Apr 2007 18:19:17 -0700 Subject: Getting started with python References: <1176598011.463543.96990@q75g2000hsh.googlegroups.com> <1176608302.928513.274400@y5g2000hsa.googlegroups.com> <%LyUh.10121$YL5.5753@newssvr29.news.prodigy.net> Message-ID: <7x4pnh6rqi.fsf@ruckus.brouhaha.com> Steve Holden writes: > You'd be worth more if you'd used elif and omitted the continue > statements, but for a first solution it's acceptable. > > For better readability I'd have used > if i % 5 == 0 I think I'd be more concerned about getting rid of the i%15 test. What if a few more words get added? def fizzbuzz(n): words = ((3, 'Fizz'), (5, 'Buzz'), (7, 'Jazz'), (11, 'Pizzazz')) r = ''.join(b for a,b in words if n%a == 0) return r or str(n) for i in xrange(1,101): print fizzbuzz(i) From pythoncurious at gmail.com Mon Apr 16 12:56:44 2007 From: pythoncurious at gmail.com (pythoncurious at gmail.com) Date: 16 Apr 2007 09:56:44 -0700 Subject: script for seconds in given month? In-Reply-To: <1176740556.859125.221980@l77g2000hsb.googlegroups.com> References: <1176740556.859125.221980@l77g2000hsb.googlegroups.com> Message-ID: <1176742604.907208.310290@l77g2000hsb.googlegroups.com> On Apr 16, 6:22 pm, "edfialk" wrote: > Hi, does anyone happen to know of a script that would return the > number of seconds in a month if I give it a month and a year? > something like this might work, it should event handle DST correctly. You could read up on mktime() if you want to make sure. from time import mktime def secondsInMonth(year, month): s1 = mktime((year,month,1,0,0,0,0,0,-1)) s2 = mktime((year,month+1,1,0,0,0,0,0,-1)) return s2-s1 /Matt From admin at loial.co.uk Tue Apr 17 04:01:55 2007 From: admin at loial.co.uk (loial) Date: 17 Apr 2007 01:01:55 -0700 Subject: Handling sorted dictionaries Message-ID: <1176796915.492317.203190@p77g2000hsh.googlegroups.com> The following code gives the error d=sortedmachines[machine] TypeError: list indices must be integers What works for the unsorted dictionary does not work for the sorted dictionary. Can anyone help? machinekey = "111111" machines = {} machines[machinekey]=[1,0,0,0,0,0,0,0,0,0,0,0,0] machinekey = "222222" machines[machinekey]=[0,1,0,0,0,0,0,0,0,0,0,0,0] ddd=0 for machine in machines.keys(): d=machines[machine] print machine print d [ddd] sortedmachines=sorted(machines) for machine in sortedmachines: d=sortedmachines[machine] print machine print d [ddd] From david at boddie.org.uk Fri Apr 20 20:43:58 2007 From: david at boddie.org.uk (David Boddie) Date: Sat, 21 Apr 2007 02:43:58 +0200 Subject: PYQT 3 communication with 2 windows References: <1177015090.289961.306590@o5g2000hsb.googlegroups.com> Message-ID: <8f570$46295e4f$54d1d767$4261@news.chello.no> On Thursday 19 April 2007 22:38, Marcpp wrote: > Hi, I'm introducing to program in python + pyqt. > I have a main window that call a second window (to introduce a info > with textedit) > when press the second window button I need to return to the main > window the info > introduced in the second window. > I've seek in the pyqt doc examples but i don't find it. > Have you any example? You could connect the button to a slot in the second window that sends the text back to the first window. Here's an example that sends the text to a function. You could substitute a class for the function to get what you want. import sys from qt import * class Window(QWidget): def __init__(self, parent = None): QWidget.__init__(self, parent) self.textEdit = QTextEdit(self) okButton = QPushButton(self.tr("&OK"), self) self.connect(okButton, SIGNAL("clicked()"), self.sendText) layout = QVBoxLayout(self) layout.addWidget(self.textEdit) layout.addWidget(okButton) def sendText(self): self.emit(PYSIGNAL("textEntered(QString)"), (self.textEdit.text(),)) def fn(text): print text if __name__ == "__main__": app = QApplication(sys.argv) window = Window() window.connect(window, PYSIGNAL("textEntered(QString)"), fn) window.show() app.setMainWidget(window) sys.exit(app.exec_loop()) Note the use of PYSIGNAL() instead of SIGNAL(). With PyQt4 you would be able to use SIGNAL() and write the emit() call in a simpler form. David From jstroud at mbi.ucla.edu Sat Apr 28 16:01:59 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Sat, 28 Apr 2007 13:01:59 -0700 Subject: how can I put an Exception as the key of a hash table In-Reply-To: <1177786431.935154.89510@y5g2000hsa.googlegroups.com> References: <1177786431.935154.89510@y5g2000hsa.googlegroups.com> Message-ID: yinglcs at gmail.com wrote: > I want to keep track of the number of different exception happens in > my python program: > > ErrorHash = {} > > try: > > # come code ... > > except Exception, e: > print e > errcode = e > > if (ErrorHash.has_key(errcode)): > ErrorFailNo = ErrorHash[errcode] > > ErrorHash[errcode] = ErrorFailNo + 1 > > else: > ErrorHash[errcode] = 1 > > > But when i print out the ErrorHash like this: > > print ErrorHash > > i get an empty string. Can you please tell me how can I put an > Exception as the key of a hash table ? Or how can i dump out all the > content of the hashtable. > > Thank you. > First, you may want errcode = str(e) instead of errcode = e Second, the empty string is probably because the Exception is instantiated without a string. E.g.: >>> str(Exception()) '' Third, you must not be showing us everything, because an Exception can be used as a key, but does not give an empty string upon printing. You are definitely not showing us what it looks like when you print ErrorHash, which would be helpful. Fourth, that you are creating a table of error codes means that you are attempting to transmogrify the way python handles exceptions into some paradigm you have used in a language like FORTRAN and thus are not using exceptions in their intended way. You might describe the reason you are generating error codes and gather suggestions about a more pythonic (i.e. reasonable) approach. James From gnewsg at gmail.com Thu Apr 5 06:47:59 2007 From: gnewsg at gmail.com (billiejoex) Date: 5 Apr 2007 03:47:59 -0700 Subject: low level networking in python In-Reply-To: <4613d7a2$0$331$e4fe514c@news.xs4all.nl> References: <1175615037.137052.70980@w1g2000hsg.googlegroups.com> <4613d7a2$0$331$e4fe514c@news.xs4all.nl> Message-ID: <1175770079.372292.259410@n76g2000hsh.googlegroups.com> > I wish to do some low level network stuff using python. > I've googled somewhat and came up with pylibpcap[1], trouble is I > can't compile it on my Ubuntu 6.10 workstation. I would suggest pcapy: http://oss.coresecurity.com/projects/pcapy.html Higher level, easier Object-Oriented API and support for multi- threading. Here's an example showing a simple sniffer app: http://oss.coresecurity.com/impacket/sniff.py Anyway, what kind of 'low-level network stuff' we're talking about? From tim at tdw.net Thu Apr 5 19:14:24 2007 From: tim at tdw.net (Tim Williams) Date: Fri, 6 Apr 2007 00:14:24 +0100 Subject: way to extract only the message from pop3 In-Reply-To: References: <1175628970.874615.127020@y80g2000hsf.googlegroups.com> Message-ID: <9afea2ac0704051614l738f8e06j2380c787b2bfcfc@mail.gmail.com> On 05/04/07, Collin Stocks wrote: > On 3 Apr 2007 12:36:10 -0700, flit wrote: > > Hello All, > > > > Using poplib in python I can extract only the headers using the .top, > > there is a way to extract only the message text without the headers? > > > so get two strings: only headers, and the whole message. > find the length of the headers, and chop that off the beginning of the whole > message: > > > message=whole_message[len(headers):None] > This way you have to perform 2 downloads, the headers and the whole message. Then join them both into strings and subtract one from the other by slicing or other means. (other means? body = whole_message.replace(headers,'' ) or maybe not ! :) ) The body starts at the first blank line after the Subject: header, in practice this is the first blank line. This is a good starting point for something simple like my earlier suggestion: msg = '\r\n'.join( M.retr(i+1)[1] ) # retrieve the email into string hdrs,body = msg.split('\r\n\r\n',1) # split it into hdrs & body If the original poster required the body to be seperated from the headers (and I received a private reply from the OP to my original post that suggested it probably was) then splitting a joined whole message at the first blank line is sufficient and only requires 1 download without using the email module If the OP required just the text parts extracted from the message then it gets a bit trickier, the email module is the way to go but not quite how a previous poster used it. Consider an email that routed through my (python) SMTP servers and filters today,. Content: ['text/plain', 'text/html', 'message/delivery-status', 'text/plain', 'text/plain', 'text/plain', 'unknown', 'message/rfc822', 'text/plain', 'text/html'] Is text/html a text part or an html part for this exercise ? :) You need to walk the parts and use something like # part.get_content_maintype() requires a further call # to get_content_subtype() , so use # part.get_content_type() instead. required = ['text/plain', 'text/tab-separated-values'] for part in EMAIL_OBJ.walk(): text_parts = [] if part.get_content_type() in required: text_parts.append(part) print ('\r\n' + '='*76 +'\r\n').join(text_parts) # print all the text parts seperated by a line of '=' # end Whether you use the email module or not, you need to join the retrieved message into a string. You can use \n but if you plan to push the text back out in an email '\r\n' is required for the SMTP sending part. Your client may or may not convert \n to \r\n at sending time :) HTH :) -- Tim Williams From steve at holdenweb.com Fri Apr 20 04:59:07 2007 From: steve at holdenweb.com (Steve Holden) Date: Fri, 20 Apr 2007 04:59:07 -0400 Subject: Do other Python GUI toolkits require this? In-Reply-To: References: <462697A6.6010007@codebykevin.com> <1177014799.004875.262060@y80g2000hsf.googlegroups.com> Message-ID: Antoon Pardon wrote: > On 2007-04-19, sjdevnull at yahoo.com wrote: >> On Apr 19, 6:54 am, Antoon Pardon wrote: >>> I don't know how you come to the conclusion that it is a mathematical >>> absurdity but consider this: If you find that common usage propagates >>> something that is incorrect, should we just shrug it off or should we >>> attemp a correction? >> a) In English, "learning curve" is not restricted to a mathematical >> plot--Webster's also defines it as "the course of progress made in >> learning something". In that context, adding the adjective steep >> ("extremely or excessively high...STEEP implies such sharpness of >> pitch that ascent or descent is very difficult") makes sense. > > How much sense does it really make? Suppose we would talk about > an income curve. Would you not prefer a steep curve over a shalow > one? What about a productivity curve? It is all about the progress > made in something. > > So how much sense does it make that a steep curve in earnings and > productivity is good but a steep curve in learning is bad? > Just as much sense as that a motor car is great for driving around in but bad for being run over by. Context is everything. Do *all* steep curves have to be good or all bad? What the hell happened to common sense? >> Trying to apply a mathematical definition to an English-language >> phrase is prone to incorrect outcomes. >> >> b) The purpose of language is to communicate. In English, if a phrase >> now means something in common usage, then that is (one of) its current >> definition(s)--this is possibly different from some other languages >> where there is an attempt to have an "officially sanctioned" set of >> definitions and spellings that may differ from common usage. If you >> find that everyone else means something when they say a phrase, you'd >> best learn what they mean if you want to be speaking the same language >> (and hence be able to communicate with them). > > But the problem is that even if this would be only a way to communicate > in englishi, a lot of people get the wrong idea about real curves from > this idiom, as this thread shows. So even if you only want to communicate > one specific idea that comes accross as intended, you also propagate > a lot of nonsense with it. > Well, I have to bow to your expertise when it comes to propagating nonsense. 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 olsonas at gmail.com Thu Apr 12 08:41:20 2007 From: olsonas at gmail.com (Drew) Date: 12 Apr 2007 05:41:20 -0700 Subject: Code Explaination: Spelling correction code In-Reply-To: <_tqdnfpprqGxOoDbnZ2dnUVZ_uTinZ2d@comcast.com> References: <1176345676.300560.78020@n59g2000hsh.googlegroups.com> <_tqdnfpprqGxOoDbnZ2dnUVZ_uTinZ2d@comcast.com> Message-ID: <1176381680.678201.233880@b75g2000hsg.googlegroups.com> On Apr 11, 11:27 pm, Steven Bethard wrote: > Drew wrote: > > I recently saw this website:http://www.norvig.com/spell-correct.html > > > All the code makes sense to me save one line: > > > def known_edits2(word): > > return set(e2 for e1 in edits1(word) for e2 in edits1(e1) if e2 in > > NWORDS) > > This is the same as: > > result = set() > for e1 in edits1(word): > for e2 in edits1(e1): > if e2 in NWORDS: > result.add(e2) > return result > > The thing between the ``set(`` and ``)`` is called a generator > comprehension if you'd like to look into it further. > > STeVe Steve - Thanks for the response. I'm somewhat familiar with generator/list comprehension but was unsure how multiple statements were evaluated when chained together. From your explanation, I'm assuming they are evaluated from the "inside out" rather than left to right or right to left. Does the mean that the comprehension on the inside is always evaluated first? Thanks, Drew From mad.vijay at gmail.com Thu Apr 12 05:01:18 2007 From: mad.vijay at gmail.com (SamG) Date: 12 Apr 2007 02:01:18 -0700 Subject: redirecting stdout to a file as well as screen In-Reply-To: References: <1176362072.527678.201150@l77g2000hsb.googlegroups.com> Message-ID: <1176368478.301318.35210@q75g2000hsh.googlegroups.com> On Apr 12, 1:00 pm, "Gabriel Genellina" wrote: > En Thu, 12 Apr 2007 04:14:32 -0300, SamG escribi?: > > > How could i make, from inside the program, to have the stdout and > > stderr to be printed both to a file as well the terminal(as usual). > > A very minimal example: > > import sys > > class Tee(file): > others = () > > def write(self, data): > file.write(self, data) > for f in others: > f.write(data) > > tee = Tee(r"c:\temp\output.log","wt") > tee.others = [sys.stdout, sys.stderr] > sys.stdout = sys.stderr = tee > > print dir(sys) > sys.foo # error > > -- > Gabriel Genellina This is only creating an out.log file and all the stdout and stderr are logged there. From aleax at mac.com Sat Apr 7 20:00:42 2007 From: aleax at mac.com (Alex Martelli) Date: Sat, 7 Apr 2007 17:00:42 -0700 Subject: itertools, functools, file enhancement ideas References: <7xveg7rhc7.fsf_-_@ruckus.brouhaha.com> Message-ID: <1hw7lfg.112hjgqyt48vN%aleax@mac.com> Paul Rubin wrote: > I just had to write some programs that crunched a lot of large files, > both text and binary. As I use iterators more I find myself wishing > for some maybe-obvious enhancements: > > 1. File iterator for blocks of chars: > > f = open('foo') > for block in f.iterchars(n=1024): ... > > iterates through 1024-character blocks from the file. The default iterator > which loops through lines is not always a good choice since each line can > use an unbounded amount of memory. Default n in the above should be 1 char. the simple way (letting the file object deal w/buffering issues): def iterchars(f, n=1): while True: x = f.read(n) if not x: break yield x the fancy way (doing your own buffering) is left as an exercise for the reader. I do agree it would be nice to have in some module. > 2. wrapped file openers: > There should be functions (either in itertools, builtins, the sys > module, or whereever) that open a file, expose one of the above > iterators, then close the file, i.e. > def file_lines(filename): > with f as open(filename): > for line in f: > yield line > so you can say > > for line in file_lines(filename): > crunch(line) > > The current bogus idiom is to say "for line in open(filename)" but > that does not promise to close the file once the file is exhausted > (part of the motivation of the new "with" statement). There should > similarly be "file_chars" which uses the n-chars iterator instead of > the line iterator. I'm +/-0 on this one vs the idioms: with open(filename) as f: for line in f: crunch(line) with open(filename, 'rb') as f: for block in iterchars(f): crunch(block) Making two lines into one is a weak use case for a stdlib function. > 3. itertools.ichain: > yields the contents of each of a sequence of iterators, i.e.: > def ichain(seq): > for s in seq: > for t in s: > yield t > this is different from itertools.chain because it lazy-evaluates its > input sequence. Example application: > > all_filenames = ['file1', 'file2', 'file3'] > # loop through all the files crunching all lines in each one > for line in (ichain(file_lines(x) for x in all_filenames)): > crunch(x) Yes, subtle but important distinction. > 4. functools enhancements (Haskell-inspired): > Let f be a function with 2 inputs. Then: > a) def flip(f): return lambda x,y: f(y,x) > b) def lsect(x,f): return partial(f,x) > c) def rsect(f,x): return partial(flip(f), x) > > lsect and rsect allow making what Haskell calls "sections". Example: > # sequence of all squares less than 100 > from operator import lt > s100 = takewhile(rsect(lt, 100), (x*x for x in count())) Looks like they'd be useful, but I'm not sure about limiting them to working with 2-argument functions only. Alex From editor at musicwords.net Tue Apr 3 11:40:23 2007 From: editor at musicwords.net (Jim Aikin) Date: Tue, 3 Apr 2007 08:40:23 -0700 Subject: pyc file [Newbie Question] References: Message-ID: Thanks, Steven. I'm sure that answers the question. The Tutorial is very good, but there are numerous topics that it slides past (as it would have to do, in order to avoid being ten times as long). I haven't yet gotten deep enough into Python to even know where to look for a full explanation of what "import" does or what alternatives there might be to using it. --JA From wojciech_mula at poczta.null.onet.pl.invalid Sat Apr 7 09:50:26 2007 From: wojciech_mula at poczta.null.onet.pl.invalid (=?ISO-8859-2?Q?Wojciech_Mu=B3a?=) Date: Sat, 07 Apr 2007 15:50:26 +0200 Subject: Saving output of Turtle Graphics? In-Reply-To: References: Message-ID: Dick Moores wrote: > I accidentally stumbled across the Turtle Graphics module (turtle.py) > the other day and have been having some fun with it. > > Now I'm wondering if there is a way to build into a script the saving of > each window just before it is cleared. For example, here are a couple > that I've saved by screen capture: > > Turtle module uses Tk canvas element to draw graphics ('_canvas' attribute). I've written module, that exports canvas graphics to SVG file: http://wmula.republika.pl/proj/canvas2svg/ -- it may be useful for you. w. From gagsl-py2 at yahoo.com.ar Sat Apr 28 15:48:21 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Sat, 28 Apr 2007 16:48:21 -0300 Subject: python function in pipe References: <1177779539.094507.47080@h2g2000hsg.googlegroups.com> Message-ID: En Sat, 28 Apr 2007 13:58:59 -0300, escribi?: > On Apr 28, 6:37 am, Bart wrote: >> Im using module that gives errors to stderr/stdout (generated by SWIG) >> Problem is that I need to parse this errors/information from module. >> os.popen3 looks nice but this executes command not function. > > Perhaps you're looking for the unittest module? > > You can use assertRaises if an exception is raised > by the function. > You can also redirect sys.stderr and sys.stdout as needed > and test the captured strings with assertEquals. Maybe I'm wrong, but I think this won't help the OP with his problem. As I understand it, he has a C function that uses stdout and stderr to report errors (perhaps using printf, fprintf, perror and similar functions) and he wants to call it from Python. Reassigning sys.stdout/stderr in Python won't help. One way would be to make an executable from the C code, and call it using the subprocess module or some popen variant. How to pass arguments depends on the application, and may not be efficient. Another way would be to change the C code, adding a FILE parameter (let's call it logfile) and replacing every printf("...", xxx) with fprintf(logfile, "...", xxx); the same for related functions. Yet another way, and perhaps the easiest and less intrusive on the C code, would be to use freopen to replace stdout and stderr with another file (and going back again at the end!). -- Gabriel Genellina From paul at boddie.org.uk Tue Apr 3 09:56:01 2007 From: paul at boddie.org.uk (Paul Boddie) Date: 3 Apr 2007 06:56:01 -0700 Subject: XML DTD analysis, diffing ... In-Reply-To: <1175608328.341381.97040@b75g2000hsg.googlegroups.com> References: <1175603926.371027.69390@e65g2000hsc.googlegroups.com> <1175606848.838850.18150@w1g2000hsg.googlegroups.com> <1175608328.341381.97040@b75g2000hsg.googlegroups.com> Message-ID: <1175608561.664908.61620@d57g2000hsg.googlegroups.com> On 3 Apr, 15:52, "olive" wrote: > > I know all of these tools and I already suspected xmlproc as a good > candidate. > > The problem is I can't download it for the moment since Lars website > is blocked here at my work and PyXML is dead. > > Maybe there is an alternative download link ? Isn't xmlproc part of PyXML anyway? Detailed public information about various PyXML packages suggests that it is. For example: http://packages.debian.org/unstable/python/python-xml Paul From grante at visi.com Wed Apr 25 13:10:03 2007 From: grante at visi.com (Grant Edwards) Date: Wed, 25 Apr 2007 17:10:03 -0000 Subject: Python not giving free memory back to the os get's me in real problems ... References: <1177510121.882503.145560@n15g2000prd.googlegroups.com> <_LidnenBcrz7-rLbnZ2dnUVZ_tCtnZ2d@comcast.com> <59990rF2ja6c7U3@mid.dfncis.de> <132uv54ncsspm91@corp.supernews.com> Message-ID: <132v2rbgjm66d24@corp.supernews.com> On 2007-04-25, Steven Howe wrote: >> I'm a bit fuzzy on this, but I don't think there _is_ a >> practical way to "return memory to the OS" in many OSes. For >> example in Unix the C library uses the sbrk() call to increase >> the size of the data segment when additional memory is needed >> to handle soemthing like malloc() calls. >> >> In theory, one can use brk() to reduce the size of the data >> segment, but I think making the segment smaller will produce >> undefined behavior if any of the standard C library's dynamic >> memory routines (e.g. malloc/free) have ever been used by the >> program prior to the call to brk(). > > Interesting questions. What happens when an object is > 'cleaned' up by using the 'del' command. Does the memory space > stay in the python process, get handed back to the OS, or some > combination of both? Assuming the python interpreter free()s the memory, my understanding is that on Unixes the memory is returned to the pool used by malloc(), but is not returned to the OS since there isn't a practical way to ensure that the memory at the "end" of the data segment is not used. In theory, you could walk the data structures used by free/malloc and try to figure out if a free() should allow brk() to be called to reduce the data segment size. That would only happen if the free() call was freeing data that was at the "end" of the data segment. It's possible that some standard C libraries do that, but most of what I remember reading implies that they don't. I don't really keep current on libc details, so my info might be way out of date. Asking on the gnu libc mailing list would probably provide a more authoritative answer. I'd wager that they even know what other non-Gnu libc implementations do. > I remember 'C' on VMS at least, could be coerced into return > memory on block boundaries. You can call brk() in a C program to reduce the size of the data segment, but that may result in free and malloc breakage because you've returned (behind their back) some of the memory they are managing. > 'C++' was suppose to have garbage collect, but I was always > doubtful it worked well. -- Grant Edwards grante Yow! Why is everything made at of Lycra Spandex? visi.com From sjmachin at lexicon.net Sun Apr 29 08:23:38 2007 From: sjmachin at lexicon.net (John Machin) Date: 29 Apr 2007 05:23:38 -0700 Subject: Could zipfile module process the zip data in memory? In-Reply-To: <1177847479.803195.12820@c35g2000hsg.googlegroups.com> References: <1177845313.798239.71580@o5g2000hsb.googlegroups.com> <1177847479.803195.12820@c35g2000hsg.googlegroups.com> Message-ID: <1177849418.399837.55670@l77g2000hsb.googlegroups.com> On Apr 29, 9:51 pm, ??????????????? wrote: > On Apr 29, 7:37 pm, "Daniel Nogradi" wrote: > > > > I made a C/S network program, the client receive the zip file from the > > > server, and read the data into a variable. how could I process the > > > zipfile directly without saving it into file. > > > In the document of the zipfile module, I note that it mentions the > > > file-like object? what does it mean? > > > > class ZipFile( file[, mode[, compression[, allowZip64]]]) > > > Open a ZIP file, where file can be either a path to a file (a > > > string) or a file-like object. > > > Yes it is possible to process the content of the zipfile without > > saving every file: > > > [untested] > > > from zipfile import ZipFile > > from StringIO import StringIO > > > zipp = ZipFile( this_is_the_zip_file_from_your_server, 'r' ) > > for name in zipp.namelist( ): > > content = zipp.read( name ) > > s = StringIO( ) > > s.write( content ) > > # now the file 'name' is in 's' (in memory) > > # you can process it further > > # ............ > > s.close( ) > > zipp.close( ) > > > HTH, > > Daniel > > Thanks! > Maybe my poor english makes you confusion:-). The client receive the > zip file data from the server, and keep these data as a variable, not > as a file in harddisk. such as "zipFileData", but the first argument > of the "ZipFile" is filename. I would like to let the ZipFile() open > the file from "zipFileData" directly but not file in harddisk > > zipp = ZipFile( this_is_the_zip_file_from_your_server, 'r' ) > ^ I don't have this file, all its data > is in a variable. Try something like this: from zipfile import ZipFile from StringIO import StringIO filelikeobj = StringIO(zipFileData) zipp = ZipFile(filelikeobj, 'r') for name in zipp.namelist(): # etc etc etc From steve at REMOVE.THIS.cybersource.com.au Sat Apr 28 21:00:31 2007 From: steve at REMOVE.THIS.cybersource.com.au (Steven D'Aprano) Date: Sun, 29 Apr 2007 11:00:31 +1000 Subject: Numbers and truth values References: <1hxa95b.13zrrmv1wucw71N%aleax@mac.com> Message-ID: On Sat, 28 Apr 2007 23:54:01 +0200, Szabolcs wrote: > But I still think that it is an inconsistency to allow to redefine a > _value_ like True or False (not a built-in function that may have been > missing in earlier versions). Saying True = 2 is just like saying 3 = 2. Well, it might seem that way, but it isn't really. It's more like having built-in names One = 1 Zero = 0 (plus some special code so that when you say "print One" it prints "One" rather than 1) in Python. You wouldn't be surprised to be able to redefine One = 2 there, would you? The ability to shadow built-ins is a fact of life in the Python world. Python has a lot of built-ins, and very few keywords, and that situation is unlikely to change. As Alex explained, the philosophy is not to slow the compiler and interpreter down with checks against those sort of problems directly, but to trust the programmer to call external tools like pylint and pychecker if they want. It may be that True and False will (like None before it) be moved from the built-ins category into the keyword category, but I don't think that's the most pressing problem in Python. -- Steven. From half.italian at gmail.com Sat Apr 14 14:54:23 2007 From: half.italian at gmail.com (half.italian at gmail.com) Date: 14 Apr 2007 11:54:23 -0700 Subject: Minimal Linux system to run Python In-Reply-To: References: Message-ID: <1176576862.959162.267680@p77g2000hsh.googlegroups.com> You basically just want to create a new startup mode, with only the needed modules loaded, and then set the system to boot up into that mode. I messed around with it a bit awhile ago, and managed to modify run-level 3 to accomplish what i wanted. After it had done one part of its thing, a python script would set the run-level to the one I had defined, reboot into that mode,and execute what I needed. When finished, it would change run-level back to 5 and restart to get the user back to where he was. I can't remember the exact paths, but the boot modes are at /etc/init.d/init5/ , init4, init3, etc. You can choose which is called at boot in a file called 'initconfig' I think. It will take some experimentation to figure out which modules are absolutely necessary for even python to run. It seems that I had some problems running the script in single-user mode, so I went to run- level 3 and modified it a bit. If you're still looking for help on Monday I can give you more details. ~Sean On Apr 14, 10:53 am, Chaz Ginger wrote: > I have a need for the minimal Linux system to run Python. Basically I > want the system to boot up and instead of starting up Init/etc. I would > love it to run python (and a python script I have written). > > Before embarking on doing it myself I was wondering if anyone knew of > just such a system? > > Peace, > Chaz From stefan.behnel-n05pAM at web.de Sat Apr 14 06:58:15 2007 From: stefan.behnel-n05pAM at web.de (Stefan Behnel) Date: Sat, 14 Apr 2007 12:58:15 +0200 Subject: XML/encoding/prolog/python hell... In-Reply-To: <1175179882.563945.199760@n59g2000hsh.googlegroups.com> References: <1175103659.463125.39370@y66g2000hsf.googlegroups.com> <570b3oF2b2uk9U1@mid.uni-berlin.de> <1175179882.563945.199760@n59g2000hsh.googlegroups.com> Message-ID: <4620B3C7.5020201@web.de> with lxml (although untested): fscked wrote: > import os,sys > import csv from lxml.etree import Element, SubElement, ElementTree, tostring > root = Element("{Boxes}boxes") > myfile = open('ClientsXMLUpdate.csv') > csvreader = csv.reader(myfile) > > for row in csvreader: > mainbox = SubElement(root, "{Boxes}box") > r2 = csv.reader(myfile) > b = r2.next() > mainbox.put("city", b[10]) [...] ElementTree(root).write('test.xml', "UTF-8", xml_declaration=True, pretty_print=True) Hope it helps, Stefan From bdesth.quelquechose at free.quelquepart.fr Mon Apr 23 16:45:26 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Mon, 23 Apr 2007 22:45:26 +0200 Subject: Dictionaries and dot notation In-Reply-To: <2424549.70D5anvh5e@beaureve.gmx.net> References: <23087554.X5dcTmlj7P@beaureve.gmx.net> <462b842e$0$28548$426a74cc@news.free.fr> <2424549.70D5anvh5e@beaureve.gmx.net> Message-ID: <462d1163$0$8481$426a74cc@news.free.fr> Martin Drautzburg a ?crit : > Daniel Nogradi wrote: > > > >>>>What if I want to create a datastructure that can be used in dot >>>>notation without having to create a class, i.e. because those >>>>objects have no behavior at all? >>> >>>A class inheriting from dict and implementing __getattr__ and >>>__setattr__ should do the trick... >> >> >>It can do the trick but one has to be careful with attributes that are >>used by dict such as update, keys, pop, etc. Actually it's noted in a >>comment at >>http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/361668 why the >>whole idea (attribute access of dictionaries) is a bad idea and I tend >>to agree. > > > Oh thank you. So all I have to do is have my object's class implement > __setattr__ and __getattr__, or derive it from a class that does so? > And I could save my "attributes" anywhere within my instance variables. > So I could even add a dictionary whose name does not conflict with what > python uses and whose key/value pairs hold the attributes I want to > access with dot notation and delegate all the python attributes to > their native positions? Oh I see, thats tricky. I still need to be > aware of the builtin stuff one way or the other. Yeps. FWIW, Daniel is right to raise a warning here, and I should have think one more minute before posting - since in fact in this case you don't care about dict-like behaviour. > Interesting. From ramashish.lists at gmail.com Fri Apr 20 09:43:28 2007 From: ramashish.lists at gmail.com (Ramashish Baranwal) Date: 20 Apr 2007 06:43:28 -0700 Subject: setDaemon problem. In-Reply-To: <58rk68F2hof6mU1@mid.uni-berlin.de> References: <1177057029.688992.160020@o5g2000hsb.googlegroups.com> <58rk68F2hof6mU1@mid.uni-berlin.de> Message-ID: <1177076608.110673.305970@d57g2000hsg.googlegroups.com> > > Hi, > > > I am facing an issue in daemonizing a thread using setDaemon method. > > Here is my code- > > > import time > > from threading import Thread > > > class MThread(Thread): > > def run(self): > > f = open('/tmp/t.log', 'w') > > for i in range(10): > > f.write('Iteration %d\n' % i) > > time.sleep(1) > > f.close() > > > if __name__ == "__main__": > > t = MThread() > > t.setDaemon(True) > > print 'Starting thread' > > t.start() > > > The scripts runs all fine, but nothing gets logged to "/tmp/t.log". > > However when I run the same script without setting thread as daemon > > (no call to t.setDaemon), everything works fine. > > > Am I missing anything? > > Yes. You miss the documentation of setDaemon. It is _not_ a > PROCESS-daemonization recipe - which you can get here: > > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66012 > > Instead, it means that the thread started is considered not to be worth > waiting for when the main thread exits. Which it does immediately in > your code, resulting in nothing written in the logfile. > > I think the name setDaemon is somewhat unfortunate. > Thanks Diez, I was also wondering about "daemonizing" a thread, but I interpreted that it would daemonize the process which it didn't. I think setDaemon should be renamed to setDetached or something similar. Ram From robert.kern at gmail.com Tue Apr 17 11:12:59 2007 From: robert.kern at gmail.com (Robert Kern) Date: Tue, 17 Apr 2007 10:12:59 -0500 Subject: The smallest and largest values of numeric types In-Reply-To: References: Message-ID: Lou Pecora wrote: > In article , tom at finland.com wrote: > >> Hi! >> How can I determine the smallest and largest values of numeric types >> (for example int) possible in my system? I think there exists a function >> for this task but I don't know it. > > There is or was a module called "kinds" which was an implementation of > PEP 0242. I have it and it gives the values you are looking for (and > more). But I don't know where I got it. I think it was once > distributed with Macpython on MacPython.org, but I'm not sure. I've > searched for it, but nothing shows up except my own questions about it > from many years ago and they have no clues. I'm surprised they also didn't turn up my replies to those questions. > Does anyone know where this package is? Or what might replace it. It > is very useful. It used to be distributed with Numeric. http://numpy.cvs.sourceforge.net/numpy/kinds/ numpy exposes the same information for floating point types with its finfo class. Nothing particular for ints. -- 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 claird at lairds.us Tue Apr 24 14:42:47 2007 From: claird at lairds.us (Cameron Laird) Date: Tue, 24 Apr 2007 18:42:47 +0000 Subject: Generate report containing pdf or ps figures? References: <132pnp6r4qg0lc2@corp.supernews.com> <132sa3jkr5uv0a9@corp.supernews.com> Message-ID: <7mv1g4-jtn.ln1@lairds.us> In article <132sa3jkr5uv0a9 at corp.supernews.com>, Grant Edwards wrote: . . . >part of a Win32 application. You can pretty much except a >Linux platform to have ghostscript available, but for Win32 >users it'll have to be bundled. :/ . . . >It's too bad that ReportLab can't use vector image formats such >as PDF or SVG. I would have thought that sticking a PDF image >into a PDF document would be a pretty straight-forward thing to >do, but it must not be something in high demand. . . . I want to make sure we're all keeping up with each other, so I'll make explicit a couple of points, despite the risk of redundancy: A. Bundling GS is a little touchy, depending on what you mean by that. Check out its license. My summary: it's feasible, but not as trans- parent as the technology in isolation might suggest. B. As Steve's already noted, the for-fee ReportLab *does* (at least some of) the things you want. From brochu121 at gmail.com Thu Apr 5 14:01:09 2007 From: brochu121 at gmail.com (brochu121 at gmail.com) Date: 5 Apr 2007 11:01:09 -0700 Subject: Looping issues Message-ID: <1175796069.501575.157410@w1g2000hsg.googlegroups.com> What I am trying to do is compare two files to each other. If the 2nd file contains the same line the first file contains, I want to print it. I wrote up the following code: correct_settings = open("C:\Python25\Scripts\Output \correct_settings.txt","r") current_settings = open("C:\Python25\Scripts\Output\output.txt","r") for line in correct_settings: for val in current_settings: if val == line: print line + " found." correct_settings.close() current_settings.close() For some reason this only looks at the first line of the correct_settings.txt file. Any ideas as to how i can loop through each line of the correct_settings file instead of just looking at the first? From gagsl-py2 at yahoo.com.ar Mon Apr 9 08:47:28 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Mon, 09 Apr 2007 09:47:28 -0300 Subject: Nice "bug" to loose a contest References: <1176029528.528010.210230@n59g2000hsh.googlegroups.com> <1176032438.921825.42730@b75g2000hsg.googlegroups.com> <1176121156.470714.256010@y80g2000hsf.googlegroups.com> Message-ID: En Mon, 09 Apr 2007 09:19:16 -0300, escribi?: > Yeah, I've noticed that too, altough I'm clueless on how stdio handles > that differently. Now I'm wondering, what's the behaviour of the > Python snippet that reads from stdout in Windows.. Can someone on > Windows try it and report please? It does the right thing: py> print sys.stdout.readlines() Traceback (most recent call last): File "", line 1, in IOError: [Errno 9] Bad file descriptor -- Gabriel Genellina From nobody at invalid.com Wed Apr 11 18:40:09 2007 From: nobody at invalid.com (Erik Johnson) Date: Wed, 11 Apr 2007 16:40:09 -0600 Subject: rexec & Bastion ? References: <461d6064$1@nntp.zianet.com> Message-ID: <461d639b@nntp.zianet.com> I mean, of course, rexec (not recec) and Bastion From attn.steven.kuo at gmail.com Mon Apr 16 18:33:33 2007 From: attn.steven.kuo at gmail.com (attn.steven.kuo at gmail.com) Date: 16 Apr 2007 15:33:33 -0700 Subject: unittest assertRaises Problem In-Reply-To: <1176761622.220741.261420@y80g2000hsf.googlegroups.com> References: <1176761622.220741.261420@y80g2000hsf.googlegroups.com> Message-ID: <1176762813.783153.235360@b75g2000hsg.googlegroups.com> On Apr 16, 3:13 pm, "john" wrote: > All: > > Hi. I am an experienced developer (15 yrs), but new to Python and have > a question re unittest and assertRaises. No matter what I raise, > assertRaises is never successful. Here is the test code: > > class Foo: > def testException(self): > raise ValueError > > class FooTestCase(unittest.TestCase): > > testTryThis(self): > f = Foo() > self.assertRaises(ValueError, f.testException()) > The second argument should be a callable object, not the result from invoking that callable object. Thus, change self.assertRaises(ValueError, f.testException()) to self.assertRaises(ValueError, f.testException) -- Hope this helps, Steven From Marko.Cain.23 at gmail.com Sat Apr 14 11:36:17 2007 From: Marko.Cain.23 at gmail.com (Marko.Cain.23 at gmail.com) Date: 14 Apr 2007 08:36:17 -0700 Subject: how to strip the domain name in python? In-Reply-To: References: <1176526155.679721.159870@l77g2000hsb.googlegroups.com> Message-ID: <1176564977.498635.171600@n59g2000hsh.googlegroups.com> On Apr 14, 12:02 am, Michael Bentley wrote: > On Apr 13, 2007, at 11:49 PM, Marko.Cain... at gmail.com wrote: > > > > > Hi, > > > I have a list of url names like this, and I am trying to strip out the > > domain name using the following code: > > >http://www.cnn.com > >www.yahoo.com > >http://www.ebay.co.uk > > > pattern = re.compile("http:\\\\(.*)\.(.*)", re.S) > > match = re.findall(pattern, line) > > > if (match): > > s1, s2 = match[0] > > > print s2 > > > but none of the site matched, can you please tell me what am i > > missing? > > change re.compile("http:\\\\(.*)\.(.*)", re.S) to re.compile("http:\/ > \/(.*)\.(.*)", re.S) Thanks. I try this: but when the 'line' is http://www.cnn.com, I get 's2' com, but i want 'cnn.com' (everything after the first '.'), how can I do that? pattern = re.compile("http:\/\/(.*)\.(.*)", re.S) match = re.findall(pattern, line) if (match): s1, s2 = match[0] print s2 From larry.bates at websafe.com Thu Apr 19 15:13:52 2007 From: larry.bates at websafe.com (Larry Bates) Date: Thu, 19 Apr 2007 14:13:52 -0500 Subject: NFS Help In-Reply-To: <1177009383.764076.286710@b58g2000hsg.googlegroups.com> References: <1177007562.103413.310390@o5g2000hsb.googlegroups.com> <1177009383.764076.286710@b58g2000hsg.googlegroups.com> Message-ID: <4627BF70.5000701@websafe.com> Clement wrote: > On Apr 19, 11:44 pm, Larry Bates wrote: >> Clement wrote: >>> how to get the file from NFS share in python...... >> NFS share is mounted on your local directory, you get to it >> the same way you would any other file (e.g. go to the mount >> point and get the file). >> >> -Larry > > I want to know how to do it programatically > What operating system are you on? If it is Linux you mount the NFS share and it becomes a subdirectory on your normal filesystem. You get the file by accessing it from the subdirectory. -Larry From aleax at mac.com Thu Apr 19 23:00:31 2007 From: aleax at mac.com (Alex Martelli) Date: Thu, 19 Apr 2007 20:00:31 -0700 Subject: What makes an iterator an iterator? References: <1hwr9pv.13v4ci6106qn0aN%aleax@mac.com> <1176936067.315082.17970@y80g2000hsf.googlegroups.com> <1hws6rd.u0a6hd78fhhpN%aleax@mac.com> <1176961515.450458.189530@p77g2000hsh.googlegroups.com> Message-ID: <1hwu1em.1tnjyg91wzltipN%aleax@mac.com> 7stud wrote: ... > > repeatedly calls....[type(_t).next(t)] > > As far as I can tell, if the call was actually _t.next(), the code I > asked about would work. However, the name look up for 'next' when you All of your following lamentations are predicated on this assumption, it would seem. Very well, let's put it to the text, as Python makes it so easy..: >>> class sic: pass ... >>> _t = sic() >>> def nexter(): ... yield 23 ... >>> _t.next = nexter >>> for i in range(10): ... print _t.next() ... See? a loop that calls _t.next() and only terminates when that raises StopIteration will never exit when _t.next is a generator function (as opposed to *the result of calling* a generator function, which is an *iterator object*). This applies when _t.next is looked up on the instance, as we ensured we were in this toy example, just as much as when it's coming from type(_t) -- which is why in this context the distinction is pedantic, and why it was definitely not crucial, as you appear (on the basis of this false idea you have) to think it was, in the Nutshell (where I went for readability rather than pedantic precision in this instance). If you want to implement a class whose next method internally uses a generator, that's pretty easy, e.g.: class sane(object): def __init__(self, sentence='four scores and twenty years ago'): def agenerator(): for word in sentence.split(): yield word self._thegen = agenerator() def __iter__(self): return self def next(self): return self._thegen.next() there -- easy, innit? You just have to understand the difference between calling a generator function, and calling the next method of the object (iterator) which is returned by that function when called:-). Alex From surekap at gmail.com Sun Apr 29 20:54:16 2007 From: surekap at gmail.com (Prateek) Date: 29 Apr 2007 17:54:16 -0700 Subject: help in debugging file.seek, file.read In-Reply-To: <1177885227.832869.35580@u30g2000hsc.googlegroups.com> References: <1177884066.570052.186820@y5g2000hsa.googlegroups.com> <1177885227.832869.35580@u30g2000hsc.googlegroups.com> Message-ID: <1177894456.629348.286800@q75g2000hsh.googlegroups.com> On Apr 30, 3:20 am, Prateek wrote: > Sorry, I forgot to mention - the RTH line only prints when the time > taken is > 0.1 second (so that I don't pollute the output with other > calls that complete normally) I have some more information on this problem. Turns out the issue is with buffer syncing. I was already doing a flush operation on the file after every commit (which flushes the user buffers). I added an os.fsync call which fixed the erratic behavior. But the code is still horribly slow... 122s vs around 100s (without the fsync). Since fsync flushes the kernel buffers, I'm assuming this has something to do with my O/S (Mac OS 10.4.9 Intel - Mac Book Pro 2.33Ghz Core 2 Duo, 2GB RAM). Can anybody help? From reder at ieee.org Sun Apr 15 21:01:41 2007 From: reder at ieee.org (Leonard J. Reder) Date: Mon, 16 Apr 2007 01:01:41 GMT Subject: Python and JMS? In-Reply-To: References: Message-ID: <4622CAE5.7070006@ieee.org> Thanks Jarek, Yes indeed, we are using ActiveMQ and I did see the StomPy python package. But I also saw that it said stomp was done as a student project that ended. Maybe I will try hjb for now - all I need to do is listen for messages on a certain topic. Maybe some of our internal people will pick stom and make it better for the future though. Len Jarek Zgoda wrote: > Leonard J. Reder napisa?(a): > >> I would like to write some Python to monitor a JMS middleware software bus. >> JMS being Java Messaging Service. Can anyone recommend a Python >> wrapper to JMS for this? My goal is to listen for XML being transfered >> over >> a JMS implementation. All the applications so far are in Java. > > Quick googling for "python jms" yields http://hjb.python-hosting.com/ as > 1st result and for a long time this seems the only solution that works. > Unfortuantely, it's functionality is severely limited. > > If you happen to use ActiveMQ, you can try to use stomp protocol, but > this isn't a standard (I don't know any other implementation of queuing > software that uses this). > -- =================================== Leonard J. Reder Home office email : reder at ieee.org Lab email : reder at jpl.nasa.gov Lab web page : http://reder.jpl.nasa.gov =================================== From kyosohma at gmail.com Mon Apr 30 13:26:04 2007 From: kyosohma at gmail.com (kyosohma at gmail.com) Date: 30 Apr 2007 10:26:04 -0700 Subject: Launching an independent Python program in a cross-platform way (including mac) In-Reply-To: <1177950595.887985.256790@h2g2000hsg.googlegroups.com> References: <1177889540.489960.176380@u30g2000hsc.googlegroups.com> <1177890695.308785.165580@l77g2000hsb.googlegroups.com> <838d5$4635f634$4275d90a$5047@FUSE.NET> <1177944037.400933.291060@l77g2000hsb.googlegroups.com> <1177950595.887985.256790@h2g2000hsg.googlegroups.com> Message-ID: <1177953964.316273.53660@y80g2000hsf.googlegroups.com> On Apr 30, 11:29 am, "Eric_Dex... at msn.com" wrote: > I would like to see this as a command along with something to open web > pages.. Just one command instead of trying to figure out all the > different op systems. look forward to seeing your code > > https://sourceforge.net/projects/dex-tracker > > On Apr 30, 9:40 am, Andr? wrote: > > > On Apr 30, 10:59 am, Kevin Walzer wrote: > > [snip] > > > > There are extension modules on the Mac for integrating Python and > > > AppleScript (the best one is appscript). However, if you want to limit > > > yourself to core Python, your best best is osascript, a system > > > command-tool that lets you call AppleScript code with arguments from > > > other programs. This can be called via os.system. > > > > The basis syntax for doing this from Python might look something like this: > > > > os.system('osascript -e \'tell app \"Terminal\" to activate\'') > > > > This simply launches Terminal. Note that you have to deal with quoting > > > issues. The equivalent syntax from AppleScript would be: > > > > tell app "Terminal" to activate > > > > If you want to Terminal to run a command-line program from AppleScript, > > > you can do this with the "do script" command. Code to do this could look > > > something like this: > > > > myscript = "python -e foo.py" > > > os.system('osascript -e '\tell app \"Terminal"\ to do script %s\'', > > > myscript) > > > > I haven't tested this, but you get the basic idea--define the script and > > > command-line paramaters in a string, then pass that to > > > AppleScript/osascript as a variable. This code should launch Terminal, > > > then run the external Python script. > > > > HTH, > > > Thanks. I managed to get something like this to work. Later, I'll > > post it as an example to this thread so that other can use if for a > > reference if needed. > > > Andr? > > > > Kevin > > > > -- > > > Kevin Walzer > > > Code by Kevinhttp://www.codebykevin.com-Hide quoted text - > > > - Show quoted text -- Hide quoted text - > > > - Show quoted text - Opening web pages cross-platform can be done with the "webbrowser" module: http://docs.python.org/lib/module-webbrowser.html Mike From carsten at uniqsys.com Tue Apr 10 10:20:31 2007 From: carsten at uniqsys.com (Carsten Haese) Date: Tue, 10 Apr 2007 10:20:31 -0400 Subject: tuples, index method, Python's design In-Reply-To: References: <1175867771.114540.61810@n76g2000hsh.googlegroups.com> <1175884427.779950.267220@y80g2000hsf.googlegroups.com> <1175953520.316208.241490@o5g2000hsb.googlegroups.com> <7xzm5igbrb.fsf@ruckus.brouhaha.com> <1176200361.260546.280510@n76g2000hsh.googlegroups.com> Message-ID: <1176214831.3430.49.camel@dot.uniqsys.com> On Tue, 2007-04-10 at 09:57 -0400, Steve Holden wrote: > I hear the screams of "just add the index() method to tuples and have > done with it" and, to an extent, can sympathize with them. But that way > lies creeping featurism and the next thing you know we'll have a ternary > operator in the language - oh wait, we do now! It would indeed be much easier to just give up. However, the resistance to tuple.index is more than a generic resistance to feature creep. As I have demonstrated elsewhere on this thread, any use case for tuple.index will be inherently obfuscated. Code clarity is a major design goal of Python, and adding tuple.index would be contrary to this goal. I'm just a user with no influence on the development of Python itself, but in my humble opinion, the non-existence of tuple.index is more pythonic than its existence would be. -Carsten From jiang.haiyun at gmail.com Mon Apr 30 10:32:20 2007 From: jiang.haiyun at gmail.com (jiang.haiyun at gmail.com) Date: 30 Apr 2007 07:32:20 -0700 Subject: Problem with PyQt4 Message-ID: <1177943540.857556.235210@y80g2000hsf.googlegroups.com> Hi, I am having some serious problems with PyQT4, when i run pyqt script, I always get 'Segmentation fault'. the script is simple: ====================== %less qttest.py from PyQt4 import QtGui, QtCore import sys if __name__ == '__main__': app = QtGui.QApplication(sys.argv) w = QtGui.QMainWindow() w.show() app.exec_() ====================== When I run it , it crashes. ====================== %python qttest.py Segmentation fault (core dumped) ===================== And the output with '-v' argument is : ========================= %python -v qttest.py # installing zipimport hook import zipimport # builtin # installed zipimport hook # /usr/local/lib/python2.4/site.pyc matches /usr/local/lib/python2.4/ site.py import site # precompiled from /usr/local/lib/python2.4/site.pyc # /usr/local/lib/python2.4/os.pyc matches /usr/local/lib/python2.4/ os.py import os # precompiled from /usr/local/lib/python2.4/os.pyc import posix # builtin # /usr/local/lib/python2.4/posixpath.pyc matches /usr/local/lib/ python2.4/posixp ath.py import posixpath # precompiled from /usr/local/lib/python2.4/ posixpath.pyc # /usr/local/lib/python2.4/stat.pyc matches /usr/local/lib/python2.4/ stat.py import stat # precompiled from /usr/local/lib/python2.4/stat.pyc # /usr/local/lib/python2.4/UserDict.pyc matches /usr/local/lib/ python2.4/UserDic t.py import UserDict # precompiled from /usr/local/lib/python2.4/ UserDict.pyc # /usr/local/lib/python2.4/copy_reg.pyc matches /usr/local/lib/ python2.4/copy_re g.py import copy_reg # precompiled from /usr/local/lib/python2.4/ copy_reg.pyc # /usr/local/lib/python2.4/types.pyc matches /usr/local/lib/python2.4/ types.py import types # precompiled from /usr/local/lib/python2.4/types.pyc # /usr/local/lib/python2.4/warnings.pyc matches /usr/local/lib/ python2.4/warning s.py import warnings # precompiled from /usr/local/lib/python2.4/ warnings.pyc # /usr/local/lib/python2.4/linecache.pyc matches /usr/local/lib/ python2.4/lineca che.py import linecache # precompiled from /usr/local/lib/python2.4/ linecache.pyc import encodings # directory /usr/local/lib/python2.4/encodings # /usr/local/lib/python2.4/encodings/__init__.pyc matches /usr/local/ lib/python2 .4/encodings/__init__.py import encodings # precompiled from /usr/local/lib/python2.4/encodings/ __init__. pyc # /usr/local/lib/python2.4/codecs.pyc matches /usr/local/lib/python2.4/ codecs.py import codecs # precompiled from /usr/local/lib/python2.4/codecs.pyc import _codecs # builtin # /usr/local/lib/python2.4/encodings/aliases.pyc matches /usr/local/ lib/python2. 4/encodings/aliases.py import encodings.aliases # precompiled from /usr/local/lib/python2.4/ encodings/a liases.pyc # /usr/local/lib/python2.4/encodings/gb2312.pyc matches /usr/local/lib/ python2.4 /encodings/gb2312.py import encodings.gb2312 # precompiled from /usr/local/lib/python2.4/ encodings/gb 2312.pyc dlopen("/usr/local/lib/python2.4/lib-dynload/_codecs_cn.so", 2); import _codecs_cn # dynamically loaded from /usr/local/lib/python2.4/ lib- dynload / _codecs_cn.so dlopen("/usr/local/lib/python2.4/lib-dynload/_multibytecodec.so", 2); import _multibytecodec # dynamically loaded from /usr/local/lib/ python2.4/lib- dy nload/ _multibytecodec.so Python 2.4.3 (#2, Oct 15 2006, 05:32:11) [GCC 3.4.6 [FreeBSD] 20060305] on freebsd6 Type "help", "copyright", "credits" or "license" for more information. import PyQt4 # directory /usr/local/lib/python2.4/site-packages/PyQt4 # /usr/local/lib/python2.4/site-packages/PyQt4/__init__.pyc matches / usr/local/ l ib/ python2.4/site-packages/PyQt4/__init__.py import PyQt4 # precompiled from /usr/local/lib/python2.4/site-packages/ PyQt4/__i nit__.pyc dlopen("/usr/local/lib/python2.4/site-packages/PyQt4/QtGui.so", 2); dlopen("/usr/local/lib/python2.4/site-packages/sip.so", 2); import sip # dynamically loaded from /usr/local/lib/python2.4/site- packages/ sip. so dlopen("/usr/local/lib/python2.4/site-packages/PyQt4/QtCore.so", 2); import PyQt4.QtCore # dynamically loaded from /usr/local/lib/python2.4/ site-pack ages/PyQt4/QtCore.so import PyQt4.QtGui # dynamically loaded from /usr/local/lib/python2.4/ site-packa ges/PyQt4/QtGui.so Segmentation fault (core dumped) %python -v qttest.py # installing zipimport hook import zipimport # builtin # installed zipimport hook # /usr/local/lib/python2.4/site.pyc matches /usr/local/lib/python2.4/ site.py import site # precompiled from /usr/local/lib/python2.4/site.pyc # /usr/local/lib/python2.4/os.pyc matches /usr/local/lib/python2.4/ os.py import os # precompiled from /usr/local/lib/python2.4/os.pyc import posix # builtin # /usr/local/lib/python2.4/posixpath.pyc matches /usr/local/lib/ python2.4/posixpath.py import posixpath # precompiled from /usr/local/lib/python2.4/ posixpath.pyc # /usr/local/lib/python2.4/stat.pyc matches /usr/local/lib/python2.4/ stat.py import stat # precompiled from /usr/local/lib/python2.4/stat.pyc # /usr/local/lib/python2.4/UserDict.pyc matches /usr/local/lib/ python2.4/UserDict.py import UserDict # precompiled from /usr/local/lib/python2.4/ UserDict.pyc # /usr/local/lib/python2.4/copy_reg.pyc matches /usr/local/lib/ python2.4/copy_reg.py import copy_reg # precompiled from /usr/local/lib/python2.4/ copy_reg.pyc # /usr/local/lib/python2.4/types.pyc matches /usr/local/lib/python2.4/ types.py import types # precompiled from /usr/local/lib/python2.4/types.pyc # /usr/local/lib/python2.4/warnings.pyc matches /usr/local/lib/ python2.4/warnings.py import warnings # precompiled from /usr/local/lib/python2.4/ warnings.pyc # /usr/local/lib/python2.4/linecache.pyc matches /usr/local/lib/ python2.4/linecache.py import linecache # precompiled from /usr/local/lib/python2.4/ linecache.pyc import encodings # directory /usr/local/lib/python2.4/encodings # /usr/local/lib/python2.4/encodings/__init__.pyc matches /usr/local/ lib/python2.4/encodings/__init__.py import encodings # precompiled from /usr/local/lib/python2.4/encodings/ __init__.pyc # /usr/local/lib/python2.4/codecs.pyc matches /usr/local/lib/python2.4/ codecs.py import codecs # precompiled from /usr/local/lib/python2.4/codecs.pyc import _codecs # builtin # /usr/local/lib/python2.4/encodings/aliases.pyc matches /usr/local/ lib/python2.4/encodings/aliases.py import encodings.aliases # precompiled from /usr/local/lib/python2.4/ encodings/aliases.pyc # /usr/local/lib/python2.4/encodings/gb2312.pyc matches /usr/local/lib/ python2.4/encodings/gb2312.py import encodings.gb2312 # precompiled from /usr/local/lib/python2.4/ encodings/gb2312.pyc dlopen("/usr/local/lib/python2.4/lib-dynload/_codecs_cn.so", 2); import _codecs_cn # dynamically loaded from /usr/local/lib/python2.4/ lib-dynload/_codecs_cn.so dlopen("/usr/local/lib/python2.4/lib-dynload/_multibytecodec.so", 2); import _multibytecodec # dynamically loaded from /usr/local/lib/ python2.4/lib-dynload/_multibytecodec.so Python 2.4.3 (#2, Oct 15 2006, 05:32:11) [GCC 3.4.6 [FreeBSD] 20060305] on freebsd6 Type "help", "copyright", "credits" or "license" for more information. import PyQt4 # directory /usr/local/lib/python2.4/site-packages/PyQt4 # /usr/local/lib/python2.4/site-packages/PyQt4/__init__.pyc matches / usr/local/lib/python2.4/site-packages/PyQt4/__init__.py import PyQt4 # precompiled from /usr/local/lib/python2.4/site-packages/ PyQt4/__init__.pyc dlopen("/usr/local/lib/python2.4/site-packages/PyQt4/QtGui.so", 2); dlopen("/usr/local/lib/python2.4/site-packages/sip.so", 2); import sip # dynamically loaded from /usr/local/lib/python2.4/site- packages/sip.so dlopen("/usr/local/lib/python2.4/site-packages/PyQt4/QtCore.so", 2); import PyQt4.QtCore # dynamically loaded from /usr/local/lib/python2.4/ site-packages/PyQt4/QtCore.so import PyQt4.QtGui # dynamically loaded from /usr/local/lib/python2.4/ site-packages/PyQt4/QtGui.so Segmentation fault (core dumped) ============================================= And the output of the gdb is : =========================================== %gdb --args python qttest.py GNU gdb 6.1.1 [FreeBSD] Copyright 2004 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-marcel-freebsd"...(no debugging symbols found)... (gdb) run Starting program: /usr/local/bin/python qttest.py (no debugging symbols found)...(no debugging symbols found)...(no debugging symbols found)...(no debugging symbols found)...warning: Unable to get location for thread creation breakpoint: generic error [New LWP 100113] (no debugging symbols found)...(no debugging symbols found)...[New Thread 0x811f000 (LWP 100113)] (no debugging symbols found)...(no debugging symbols found)...(no debugging symbols found)... Program received signal SIGSEGV, Segmentation fault. [Switching to Thread 0x811f000 (LWP 100099)] 0x2887cb6d in typeinfo name for sipQApplication () from /usr/local/lib/ python2.4/site-packages/PyQt4/QtGui.so (gdb) ========================================== My system is FreeBSD 6.2 release, i386, all softwares were installed from ports. and the Qt4 examples/demos work perfectly. Please help me. Thanks very much in advance. Regards, jiang.haiyun From duncan.booth at invalid.invalid Tue Apr 3 04:01:15 2007 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 3 Apr 2007 08:01:15 GMT Subject: pyc file [Newbie Question] References: Message-ID: Steven D'Aprano wrote: > On Mon, 02 Apr 2007 23:44:41 -0700, Jim Aikin wrote: > >> Working through the tutorial, I created a file called fibo.py in my >> text editor, and imported it into Idle. It worked as expected. I then >> edited the file and resaved it. I used del fibo, followed by import >> fibo. > > That probably won't cause a full re-import. del fibo will only delete > the reference called "fibo". The underlying module object will still > exist until it is garbage-collected. It will only be garbage-collected > if it isn't being used. Chances are, the module *is* being used > somewhere, so when you call "import fibo" the import machinery simply > gives you a new reference to the old module object. > The underlying module won't be garbage collected. If nowhere else, it will still be accessible as sys.modules['fibo'] From hlubenow2 at gmx.net Mon Apr 9 18:49:48 2007 From: hlubenow2 at gmx.net (hlubenow) Date: Tue, 10 Apr 2007 00:49:48 +0200 Subject: Check for keypress on Linux xterm ? Message-ID: Hello, I'd like to check, if a single key is pressed on a Linux xterm. This code waits for a key to be pressed and returns the character: -------------------------------------------- #!/usr/bin/env python import sys import tty import termios fd = sys.stdin.fileno() old_settings = termios.tcgetattr(fd) def getOneKey(): try: tty.setcbreak(sys.stdin.fileno()) ch = sys.stdin.read(1) return ord(ch) finally: termios.tcsetattr(fd, termios.TCSADRAIN, old_settings) while True: a = chr(getOneKey()) print a -------------------------------------------- My problem is, I don't want my program to wait for the keypress. I just want to check, if a key is currently pressed and if not, I'd like to continue with my program (like "INKEY$" in some BASIC-dialects). I tried several things: - event-handling from pygame: But that would open a pygame-window, I don't need. - same thing for window-managers like Tkinter. - threads: I couldn't do it (especially return values from thread-functions to the main-program). - curses: "nodelay()" or "halfdelay()" sound interesting. Maybe; but don't know how right now. I even wouldn't be able to "print" then ... - python-Xlib: Too complicated for me too right now; perhaps, if documentation becomes more complete. Does anybody know a code example (for Linux xterm) that does it ? TIA H. From bbxx789_05ss at yahoo.com Thu Apr 12 05:46:20 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: 12 Apr 2007 02:46:20 -0700 Subject: redirecting stdout to a file as well as screen In-Reply-To: <1176370557.392734.156530@y80g2000hsf.googlegroups.com> References: <1176362072.527678.201150@l77g2000hsb.googlegroups.com> <1176363641.493358.62560@y5g2000hsa.googlegroups.com> <1176370557.392734.156530@y80g2000hsf.googlegroups.com> Message-ID: <1176371179.950019.202260@l77g2000hsb.googlegroups.com> On Apr 12, 3:35 am, "SamG" wrote: > On Apr 12, 12:40 pm, "Ant" wrote: > > > > > On Apr 12, 8:14 am, "SamG" wrote: > > > > How could i make, from inside the program, to have the stdout and > > > stderr to be printed both to a file as well the terminal(as usual). > > > One way would be to create a custom class which has the same methods > > as the file type, and held a list of file-like objects to write to. > > e.g. > > > class multicaster(object): > > def __init__(self, filelist): > > self.filelist = filelist > > > def write(self, str): > > for f in self.filelist: > > f.write(str) > > def writelines(self, str_list): > > #etc > > > Then assign stdout and stderr to a new instance of one of these > > objects: > > > mc = multicaster([sys.stdout, sys.stderr, log_file]) > > sys.stdout = mc > > sys.stderr = mc > > > HTH > > I have written this.... > > import sys > > class multicaster(object): > def __init__(self, filelist): > self.filelist = filelist > > def write(self, str): > for f in self.filelist: > f.write(str) > > log_file='out.log' > mc = multicaster([sys.stdout, sys.stderr, log_file]) > sys.stdout = mc > sys.stderr = mc > > print "Hello" > > And i get this when i run the porgram. > > HelloHelloTraceback (most recent call last): > Traceback (most recent call last): > > Kindly advice! Try: log_file = open("out.log", "w") From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Thu Apr 26 06:52:01 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Thu, 26 Apr 2007 12:52:01 +0200 Subject: Access to raw command line? References: <1177571070.229968.155710@t39g2000prd.googlegroups.com> Message-ID: <59beihF2k1cbdU2@mid.individual.net> Pieter Edelman wrote: > ./myprog.py -t *.gpx *.jpg > > This seems like a sensible option at first sight, but it's > difficult to implement because the wildcard is expanded by the > shell, (in *nix only) > so sys.argv gets a list containing "-t", all .gpx files and > all .jpg files. With this list, there's no way to tell which files > belong to the "-t" switch and which are arguments (other than > using the extension). > > One possible way to work around this is to get the raw command > line and do the shell expansions ourselves from within Python. > Ignoring the question of whether it is worth the trouble, does > anybody know if it is possible to obtain the raw (unexpanded) > command line? Breaking the "de-facto standards" isn't a good idea, IMHO. > Alternatively, does anybody have suggestion of how to do this in > a clean way? First, you could define another wildcard character, or let users escape the * like this: ./myprog.py -t \*.gpx \*.jpg Let users give a list of files to process, and default to looking for the same filename without image extension and with ".gpx". E. g.: ./myprog.py -t .gpx *.jpg will expand to: ./myprog.py -t .gpx a.jpg b.jpg [...] z.jpg What your program's "policy" would be depends on its exact function. I'm thinking about if the program silently fails if it doesn't find a .gpx file for one .jpg, for example, or if it complains about it. Regards, Bj?rn -- BOFH excuse #380: Operators killed when huge stack of backup tapes fell over. From bdesth.quelquechose at free.quelquepart.fr Wed Apr 11 18:36:04 2007 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Thu, 12 Apr 2007 00:36:04 +0200 Subject: text file vs. cPickle vs sqlite a design question In-Reply-To: References: Message-ID: <461d59b1$0$27586$426a74cc@news.free.fr> Dag a ?crit : > I have an application which works with lists of tuples of the form > (id_nr,'text','more text',1 or 0). I'll have maybe 20-50 or so of these > lists containing anywhere from 3 to over 30000 tuples. The actions I > need to do is either append a new tuple to the end of the list, display > all the tuples or display all the tuples where the last element is a 1 > > Basically what I'm wondering is the best way to store these data stuctures > to disc. As the subject mentioned I've basically got three approaches. > Store each list as a text file, pickle each list to file or shove the > whole thing into a bunch of database tables. I can see pros and cons > with each approach. Does anybody have any advice as to whether any of > these approaches is obviously better than any other? Seems that so far, you get as many different opinion as answers - not sure this will help much :-/ From mail at timgolden.me.uk Sat Apr 7 12:09:29 2007 From: mail at timgolden.me.uk (Tim Golden) Date: Sat, 07 Apr 2007 17:09:29 +0100 Subject: How to tell when a file is opened In-Reply-To: <1175960486.759715.317140@y80g2000hsf.googlegroups.com> References: <1175960486.759715.317140@y80g2000hsf.googlegroups.com> Message-ID: <4617C239.3040100@timgolden.me.uk> Adam wrote: > I want to know if it possible to tell when a file is opened. However I > don't want it to be the last access time. I want to know how many > times a file opened so I can generate statistics of file usage. > > I will be wanting to watch all files on a server so this will be on > quite a large scale. So checking a directory on a loop for accesses > won't work. > > Maybe some way to monitor the Open Files section of Computer > Management? > > I check through Tim Golden's site but nothing jumped out at me. > Any pointers would be great. I take it from the fact that you mention my site (and your reference to "Computer Management") that you're looking at Win32? It's always best to be explicit when you're asking for help; a lot of people on this list will be using Linux or Mac where the answers are probably very different. This is no small task you've set yourself! As far as I know, you're going to have to go down to the level of change journals for this kind of thing. (Search for "NTFS change journal"). Although you might think: the filesystem knows when files are being accessed; can't I hook into that directly? I think the answer is: no. But I could be wrong. TJG From aleax at mac.com Sat Apr 28 22:05:12 2007 From: aleax at mac.com (Alex Martelli) Date: Sat, 28 Apr 2007 19:05:12 -0700 Subject: Any Good tools to create CSV Files? References: <1177811756.255774.315260@q75g2000hsh.googlegroups.com> Message-ID: <1hxanod.1phvqatu23j33N%aleax@mac.com> johnny wrote: > Any Good tools to create CSV Files? ReportLab only creates pdf > files. I need something to create CSV files. Alex From jackson at hotmail.com Thu Apr 19 19:11:26 2007 From: jackson at hotmail.com (Bill Jackson) Date: Thu, 19 Apr 2007 16:11:26 -0700 Subject: Better dict of dicts In-Reply-To: <4627E28C.1050406@v.loewis.de> References: <4627E28C.1050406@v.loewis.de> Message-ID: Martin v. L?wis wrote the following on 04/19/2007 02:43 PM: > Bill Jackson schrieb: >> I have a dictionary of dictionaries where the keys are typically very >> long tuples and repeated in each inner dictionary. > > What I don't understand here: you say the keys are tuples, yet later, > you show that the keys are strings. Which one is it? Sorry, I was just lazy. The keys will always be tuples...tuple of strings, tuples of numbers, tuples of objects....simply tuples. > Instead of doing that, I would use a procedure called "interning". > You may want to use the builtin intern function, or your can > come up with your own interning: > > interns = {} > def local_intern(s): > return interns.setdefault(s, s) > > Then, instead of > > a[k1][k2] = value > > do > > a[local_intern(k1)][local_intern(k2)] = value > > then all strings occur only once as keys, as long as the interns > dictionary isn't cleared. > So, my structure is something like this: a = {tuple_1: {tuple_2:value_1, tuple_3:value_2}, tuple_4: {tuple_1:value_3, tuple_3:value_4} tuple_5: {tuple_2:value_5, tuple_3:value_6, tuple_4:value_7}} Since the tuples from the inner dictionaries and the outer dictionaries are frequently the same, I would benefit from using a single intern function. Then, the tuples will always be "pointing" to the values stored in the intern dictionary. Now suppose there is little overlap between the keys for the outer dictionary and the inner dictionaries...but still much overlap between the various inner dictionaries. Then, there is no point in using an intern function for the outer dictionary, but still a benefit for the inner dictionary. Thus, something like the following would be appropriate: a[k1][local_intern(k2)] = value Have I understood this properly? From aspineux at gmail.com Sun Apr 8 06:49:28 2007 From: aspineux at gmail.com (aspineux) Date: 8 Apr 2007 03:49:28 -0700 Subject: How to set program name in Python : success Message-ID: <1176029367.964548.38380@d57g2000hsg.googlegroups.com> here is the trick I found # ( exec -a "pgm.py" python < pgm.py ) & # ps ax | grep pgm.py 22334 pts/2 S+ 0:00 pgm.py this solution works on linux and probably all BSD too, but don't let specify any arguments. If someone know a better solution .... From bbxx789_05ss at yahoo.com Wed Apr 11 00:10:47 2007 From: bbxx789_05ss at yahoo.com (7stud) Date: 10 Apr 2007 21:10:47 -0700 Subject: install wxPython In-Reply-To: References: Message-ID: <1176264647.781568.188480@w1g2000hsg.googlegroups.com> On Apr 9, 2:20 pm, Marco wrote: > Hi, > > I have a problem to install wxPython on my MacBook (Pythonversion 2.5). > If would install the wxPython (python setup.py install), then I got > this error: > > Traceback (most recent call last): > File "/Users/marco/Desktop/flexo1/wxpython/wxPython-src-2.8.3.0/ > wxPython/setup.py", line 49, in > copy_file('config.py', 'wx/build', update=1, verbose=1) > File "/Users/marco/python//lib/python2.5/distutils/file_util.py", > line 119, in copy_file > "can't copy '%s': doesn't exist or not a regular file" % src > distutils.errors.DistutilsFileError: can't copy 'config.py': doesn't > exist or not a regular file > > Where is the problem and how could i fix it? > > Thx for your answers. > marco I just installed wxPython successfully on an imac. My imac came with python 2.3.5 pre-installed along with some version of wxPython--I was able to run a hello world wxPython program by typing: $ pythonw wxHelloWorld.py First, I installed a "framework" build of a newer version of python(I chose 2.4.4 since the download said it has more modules for macs). The download was called: python-2.4.4-macosx2006-10-18.dmg The new python version was automatically installed in /Applications/ MacPython2.4/. Then I downloaded the wxPython version for Macs with python version 2.4. It was called: wxPython2.8-osx-unicode-2.8.3.0-universal10.4-py2.4.dmg. From apardon at forel.vub.ac.be Thu Apr 12 06:38:47 2007 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 12 Apr 2007 10:38:47 GMT Subject: tuples, index method, Python's design References: <1176210960.3430.20.camel@dot.uniqsys.com> <740c3aec0704100810g5f962e8eu614fbaedecf3608e@mail.gmail.com> <1176219856.3430.76.camel@dot.uniqsys.com> <740c3aec0704101021i1fd79ef2l99eac4ced1e252d9@mail.gmail.com> <1176226682.3430.86.camel@dot.uniqsys.com> <4866bea60704101104r4600d281h135286b66378f4d4@mail.gmail.com> <740c3aec0704101534y3c65f5a7je382f97e1f6301b7@mail.gmail.com> <1176305859.581010.199600@n76g2000hsh.googlegroups.com> <1176372362.350332.216710@b75g2000hsg.googlegroups.com> Message-ID: On 2007-04-12, Paul Boddie wrote: > On 12 Apr, 09:37, Antoon Pardon wrote: >> >> Why then does python itself provide immutables? I find this reasoning >> more than baffling. There has been all these arguments about why >> it is best to use immutables as dictionary keys. > > You've answered your own question. Well since it was meant as a rethorical question that is hardly surprising. But may be I should work harder on my rethorical skill since you missed that. -- Antoon Pardon From bignose+hates-spam at benfinney.id.au Sat Apr 14 00:34:05 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Sat, 14 Apr 2007 14:34:05 +1000 Subject: Python editor/IDE on Linux? References: Message-ID: <87d52760ci.fsf@benfinney.id.au> Michael Hoffman writes: > Jack wrote: > > I wonder what everybody uses for Python editor/IDE on Linux? > > I'll let you in on a little secret. We all use Emacs. Those who > claim to use vim are just trying to prevent you from ever becoming a > successful Python programmer, and therefore reduce competition. I use Emacs, with Vim emulation, running with WordStar keybindings, on a Dvorak keymapping. It took me seven years to learn how to use it, but it was worth it. Keeps the pesky workmates from using my computer. -- \ "The surest way to corrupt a youth is to instruct him to hold | `\ in higher esteem those who think alike than those who think | _o__) differently." -- Friedrich Nietzsche | Ben Finney From steve at holdenweb.com Fri Apr 6 22:46:53 2007 From: steve at holdenweb.com (Steve Holden) Date: Fri, 06 Apr 2007 22:46:53 -0400 Subject: Cant access http://cheeseshop.python.org/ or wiki In-Reply-To: <1175907505.093655.259100@o5g2000hsb.googlegroups.com> References: <1175907505.093655.259100@o5g2000hsb.googlegroups.com> Message-ID: John Machin wrote: > On Apr 7, 10:43 am, cyb wrote: >> For some reason I can ping these two sites fine, but when I try to go to >> them I cannot get to them. Normal python.org homepage works just fine. >> This is preventing me from getting setuptools and using pyOpenGL =( >> >> I'm using COmcast in savannah, GA > > FWIW: Same story for me with the cheeseshop; I'm in Australia. > Possibilities: (a) it's become a a Norwegian blue cheeseshop (b) it's > Lent; try fishshop.python.org > > The wiki's been bashed by spiders today. The offending IP addresses have now been filtered out and service should be back to normal. 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 bill.sloman at ieee.org Sun Apr 22 20:17:40 2007 From: bill.sloman at ieee.org (bill.sloman at ieee.org) Date: 22 Apr 2007 17:17:40 -0700 Subject: *** Dr G Polya BRILLIANTLY analyses the Virgina Shooting Incident *** In-Reply-To: References: <1177266754.126153.202760@b58g2000hsg.googlegroups.com> Message-ID: <1177287460.376404.323520@b58g2000hsg.googlegroups.com> On Apr 22, 8:49 pm, Jim Thompson wrote: > Ignorant Bastard Poster > > On 22 Apr 2007 11:32:34 -0700, therm... at india.com wrote: > > >Dr Gideon Polya published some 130 works in a 4 decade scientific > >career, most recently a huge pharmacological reference text > >"Biochemical Targets of Plant Bioactive Compounds" (Taylor & Francis, > >New York & London, 2003), and is currently editing a completed book on > >global avoidable mortality (numerous articles on this matter can be > >found by a simple Google search for "Gideon Polya" and on his > >websites: > > >Here is the BRILLIANT AND INCISIVE ANALYSIS: > > >http://countercurrents.org/polya230407.htm<------ > > >Dr Polya, we are incredibly proud of you. God Bless you for your > >courage. Note that Dr. Polya comes from Tasmania - the Australian state where I was born. Meanwhile, Jim's decline continues - he has now committed top posting. Institutionalisation can't be far away. -- Bill Sloman, Nijmegen From sjmachin at lexicon.net Tue Apr 24 20:52:12 2007 From: sjmachin at lexicon.net (John Machin) Date: Wed, 25 Apr 2007 10:52:12 +1000 Subject: Where's the source code for __builtin__? In-Reply-To: <1177457545.075398.204990@r3g2000prh.googlegroups.com> References: <1177457545.075398.204990@r3g2000prh.googlegroups.com> Message-ID: <462EA63C.6080805@lexicon.net> On 25/04/2007 9:32 AM, Dustan wrote: > I've been paging through the source code for various C modules in > python, and wanted to find the source of some of the builtin > functions. I searched through the Modules, Objects, Python, and Parser > folder, searched docs.python.org, searched the archived messages of > this group, searched the web, and got absolutely nowhere in finding a > __builtin__.c, or anything that contains the builtin source code. > > Help? > What's the 2nd file (in alphabetical order) in the Python folder? From phil at riverbankcomputing.co.uk Thu Apr 26 10:36:20 2007 From: phil at riverbankcomputing.co.uk (Phil Thompson) Date: Thu, 26 Apr 2007 15:36:20 +0100 Subject: passing tuple with pyqt4 signal/slot mechanism In-Reply-To: <80628d680704260716r7eda5c8va695a25b1db70490@mail.gmail.com> References: <80628d680704260716r7eda5c8va695a25b1db70490@mail.gmail.com> Message-ID: <200704261536.20332.phil@riverbankcomputing.co.uk> On Thursday 26 April 2007 3:16 pm, Pradnyesh Sawant wrote: > Hello, > I have a pyqt4 code in which i'm trying the signal/slot mechanism. The > (stripped) code is as follows: > > class D(QtCore.QThread): > def __init__(self): > QtCore.QThread.__init__(self) > tpl = ("Primary", "priSec") > print "tpl:", tpl > self.emit(QtCore.SIGNAL("setLabel"), tpl) > class Gui(QtGui.QDialog): > def __init__(self, parent = None): > QtGui.QDialog.__init__(self, parent) > def setLabel(self, tpl): > print "####tpl:", tpl > print "**********tpl:", str(tpl) > return > if __name__ == "__main__": > app = QtGui.QApplication(sys.argv) > dialog = Gui() > d = D() > QtCore.QObject.connect(d, QtCore.SIGNAL("setLabel"), > dialog.setLabel, QtCore.Qt.QueuedConnection) > sys.exit(dialog.exec_()) > > The output i'm getting is as follows: > > tpl: ('Primary', 'priSec') > ####tpl: (,) > **********tpl: ((((((((,),),),),),),),) > > Can anyone kindly tell me what's happening here? Why is the tuple > ("Primary", "priSec") getting converted to this thingy? And > what is this thingy anyways (It looks to be a deeply nested tuple, but > am not sure). Works for me in that the setLabel() isn't executed at all - but then you are emitting the signal before connecting it. Also my crystal ball isn't telling me what versions you are using or what platform you are on. Phil From tkpmep at hotmail.com Thu Apr 26 10:45:43 2007 From: tkpmep at hotmail.com (tkpmep at hotmail.com) Date: 26 Apr 2007 07:45:43 -0700 Subject: Generalized range Message-ID: <1177598743.352743.290730@t39g2000prd.googlegroups.com> I need to create ranges that can start and end with real numbers. Searching this newsgroup brought me to a function that I then modified as follows: def myRange(iMin, iMax=None, iStep=1): """Extends range to real numbers. Wherever possible, use Python's range . In other cases, make the behavior follow the spirit of Python's range """ epsilon = 1.e-8 if iMax == None and iStep == 1: return range(int(iMin)) elif type(iMin).__name__.lower() in ('int', 'long') and \ type(iMax).__name__.lower() in ('int', 'long') and \ type(iStep).__name__.lower() in ('int', 'long') and iStep != 0: return range( iMin, iMax, iStep) elif iMin <= iMax and iStep > 0: return [ iMin+i*iStep for i in range( int(math.ceil((iMax - iMin - epsilon)/iStep)) )] elif iMin >= iMax and iStep < 0: return [ iMin+i*iStep for i in range(-int(math.ceil((iMin - iMax + epsilon)/iStep)) )] else: raise ValueError, 'Cannot construct a range with steps of size ' + str(iStep) + ' between ' + str(iMin) + ' and ' + str(iMax) The one part of my implementation that has me a bit queasy (i.e. works in my current application, but I can see it misbehaving elsewhere) is the addition/subtraction of a fixed epsilon to ensure that my rounding goes the right way. A clean implementation would modify epsilon based on the achievable level of precision given the particular values of iMax, iMin and iStep. I suspect this requires a detailed understanding of the implementation of floating point arithmetic, and would appreciate hearing any thoughts you might have on gilding this lily. Sincerely Thomas Philips From martin at v.loewis.de Fri Apr 13 01:51:21 2007 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Fri, 13 Apr 2007 07:51:21 +0200 Subject: compiling modules with VS 2008 for python 2.4 prepared with Visual Studio 2003 In-Reply-To: References: <1hw2ak4.1cxnvt81nzd971N%aleax@mac.com> Message-ID: <461f1a5a$0$996$9b622d9e@news.freenet.de> > well, instructions were clear enough for me. What is hard to get why it > could not use free M$ compiler which is presumably produces compatible > objects and libraries. This presumption is incorrect. The compiler does *not* create compatible objects and libraries. It links with msvcr8.dll, whereas Python is linked with mscvr71.dll; Microsoft does not support mixing CRTs. Regards, Martin From sgeiger at ncee.net Mon Apr 9 20:50:36 2007 From: sgeiger at ncee.net (Shane Geiger) Date: Mon, 09 Apr 2007 19:50:36 -0500 Subject: How can I import functions from another python file In-Reply-To: References: <1176152771.761958.310740@w1g2000hsg.googlegroups.com> Message-ID: <461ADF5C.8030805@ncee.net> >> Hi, >> i have 2 python files in *different directory* , how can I import >> python functions from 1 python file to another? >> >> i get this error: >> import task >> ImportError: No module named task/ >> >> > > > The directory that module is in must by on your python > path in order to import it. That's not exactly correct. You *can* import from files that aren't in your sys.path. What follows is a full-working (with python 2.5) example. Perhaps ihooks is going to be obsolete at some point, but it works now. See PEP 302 for more info. (I'm not sure how to modify this example to work with a newer import mechanism or else I would provide it to you.) import os def writefile(f, data, perms=750): open(f, 'w').write(data) and os.chmod(f, perms) foobar = """ print "this is from the foobar module" def x(): print "This is the x function." """ writefile('/tmp/foobar.py', foobar) # File:ihooks-example-1.py import ihooks, imp, os, sys def import_from(filename): "Import module from a named file" if not os.path.exists(filename): sys.stderr.write( "WARNING: Cannot import file." ) loader = ihooks.BasicModuleLoader() path, file = os.path.split(filename) name, ext = os.path.splitext(file) m = loader.find_module_in_dir(name, path) if not m: raise ImportError, name m = loader.load_module(name, m) return m foo = import_from("/tmp/foobar.py") print foo.x print foo.x() print foo.x() > You can do it by modifying > sys.path or by setting the PYTHONPATH env variable. > > > $ mkdir otherdir > $ cat > otherdir/amod.py > def afunc(): > return 'found' > $ python > >>>> import amod >>>> > Traceback (most recent call last): > File "", line 1, in ? > ImportError: No module named amod > >>>> import sys >>>> sys.path.append('otherdir') >>>> import amod >>>> amod.afunc() >>>> > 'found' > -- 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 gagsl-py2 at yahoo.com.ar Wed Apr 11 02:49:38 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 11 Apr 2007 03:49:38 -0300 Subject: __file__ References: <1176250851.946892.273550@l77g2000hsb.googlegroups.com> Message-ID: En Tue, 10 Apr 2007 21:20:51 -0300, 7stud escribi?: > I'm having trouble understanding what the definition of __file__ is. > With this program: > > ------ > #data.py: > > def show(): > print __file__ > > if __name__ == "__main__": > show() > ------- > > if I run data.py with the prompt pointing to the directory that > contains data.py, then __file__ produces a filename: > > data.py [cut: other examples showing different paths to data.py] __file__ corresponds to the filename used to locate and load the module, whatever it is. When the module is found on the current directory (corresponding to '' in sys.path), you get just the filename; if sys.path contains a relative path, that's what you get; the same for any absolute path. Whatever path worked to find and load the module, that's stored as __file__. If you plan to use it, it's a good idea to make it early into an absolute path (using os.path.abspath(__file__)) just in case the current directory changes. > And some modules have __file__ in their __dict__ and some don't: > pprint.pprint(sys.__dict__) sys is a builtin module: no sys.py/sys.pyc exists, so __file__ is meaningless. -- Gabriel Genellina From andre.roberge at gmail.com Sat Apr 28 15:57:49 2007 From: andre.roberge at gmail.com (=?iso-8859-1?B?QW5kcuk=?=) Date: 28 Apr 2007 12:57:49 -0700 Subject: My Python annoyances Message-ID: <1177790269.523160.276060@l77g2000hsb.googlegroups.com> I'm really annoyed at Python - and not for the reasons already mentioned on this list. Everyone know that programming is supposed to be a dark art, nearly impossible to learn. Computer code is supposed to be something impossible to read to the common person and yet reveal their secrets to the initiated - just remember the code displayed in the Matrix... Python takes all of that away. It is just too readable. Even beginners can quickly learn to read code written by experts. To make it even friendlier to beginners, Python uses ugly double underscores both as prefix and suffix on "magic methods" to be invoked only by more advanced programmers. What's the fun in hiding the complexity so that beginners can stay away from potential problems. And why, oh why, does raw_input() have to go? Here was at least one good example of something that gave a hint (what does "raw" mean?) at the underlying complexity. Combined with the evil of the hidden eval in the more obvious input(), there was at least a chance to trip beginners into doing something "dangerous". Alas, that will no longer be the case... Python does not even make good use of weird symbols like $ and @ and % to define variable types like Perl does. Now, that's a language to learn if you want to be respected. I think that Georg Brandl had it right in his recent proposal: http://mail.python.org/pipermail/python-dev/2007-April/072419.html If not Perl, perhaps Python should be inspired by a language like C++, full of arcane stuff and, thankfully, requiring typing declaration. This dynamic typing thing makes it just too easy to write working programs quickly, especially combined with the ease of use of the interpreter. And this other thing called "duck typing" is just too flexible to use. No, Python should be more difficult. It should take a full two minutes to compile a "Hello World" program on a modern computer. Also, this "docstring" business has to go. Any programmer should, as a rite of passage, have to spend countless hours reading obscure documentation to learn other people's code before finding out what methods can be used and how they should be used. Having to use things like "dir" and "help" just makes it too easy. And don't get me started about the absence of curly braces to define blocks of code. What's the fun in making it so darn visually easy to define such blocks of code, removing the possibility of creating subtle bugs due to the misplacement of a curly bracket. No sir, with Python, the structure has to be obvious at a glance - newbies can see it just as well as experts, thereby decreasing the aura surrounding the latter. This is not fair for people that have spent dozens of hours in learning to program using Python! And don't talk to me about functions, classes and methods, not to mention modules. Python makes it too easy to write code in many different styles, trying to please people who like to write only object-oriented code as well as those that follow the more traditional procedural approach. Even "functional" type people find their way to write code in their preferred method using Python. This is not right. Fortunately, Python has incorporated some newbie-unfriendly features, like metaclasses and, to a lesser extent, decorators which, at last, make use of a special character. There should be more of these, to make Python something more challenging to learn. Programming should be more difficult than this - otherwise, how can programmers be respected by the common folks? --- Andr? From tavares at fe.up.pt Wed Apr 4 10:32:12 2007 From: tavares at fe.up.pt (tavares at fe.up.pt) Date: 4 Apr 2007 07:32:12 -0700 Subject: Symposium "Computational Methods in Image Analysis" within the USNCCM IX Congress - Announce & Call for Papers Message-ID: <1175697132.384372.283720@o5g2000hsb.googlegroups.com> --------------------------------------------------------------------------------------------------------------------------------------------- (Apologies for cross-posting) Symposium "Computational Methods in Image Analysis" National Congress on Computational Mechanics (USNCCM IX) San Francisco, CA, USA, July 22 - 26 2007 http://www.me.berkeley.edu/compmat/USACM/main.html We would appreciate if you could distribute this information by your colleagues and co-workers. --------------------------------------------------------------------------------------------------------------------------------------------- Dear Colleague, Within the National Congress on Computational Mechanics (USNCCM IX), to be held in San Francisco, CA, USA, July 22 - 26 2007, we are organizing the Symposium "Computational Methods in Image Analysis". Examples of some topics that will be considered in that symposium are: Image acquisition, Image processing and analysis, Image segmentation, 3D Vision, Motion analysis, Pattern recognition, Objects recognition, Medical imaging and Tools and applications. Due to your research activities in those fields, we would like to invite you to submit an abstract and participate in the symposium "Computational Methods in Image Analysis". For instructions and submission, please access to the congress website at: http://www.me.berkeley.edu/compmat/USACM/main.html. Please note, when submitting your abstract you should select "Computational Methods in Image Analysis". Important dates: - Deadline for abstract submissions: May 1, 2007 - Final selection of abstracts: May 15, 2007 - Deadline for early registration: May 22, 2007 - Deadline for CD-ready abstracts: June 1, 2007 - Deadline for regular registration: July 15, 2007 We would appreciate if you could distribute this information by your colleagues and co-workers. Kind regards, Jo?o Manuel R. S. Tavares Renato Natal Jorge Yongjie Zhang Dinggang Shen (Symposium organizers) From redtiger84 at googlemail.com Tue Apr 10 09:39:19 2007 From: redtiger84 at googlemail.com (Christoph Krammer) Date: 10 Apr 2007 06:39:19 -0700 Subject: Broken pipe with os.popen3() Message-ID: <1176212359.463506.105120@n76g2000hsh.googlegroups.com> Hello everybody, I try to use an external OCR tool to convert some binary image data to text. The image is in one variable, the text should be converted to another. I use the following code: (si, so, se) = os.popen3('ocrad') si.write(frame) si.close() messagetext += so.read() This code leads to a broken pipe error. I think this is because of the command already writing data to stdout after getting the first part of the input. But when I change the order of the code lines, i.e. opening the reading pipe so before writing to si, the program hangs, because no data is written to stdout before the first bytes are written to stdin. Any idea how to solve this issue? How do I read and write simultaneously? Thanks in advance, Christoph From cam.ac.uk at mh391.invalid Wed Apr 18 08:52:38 2007 From: cam.ac.uk at mh391.invalid (Michael Hoffman) Date: Wed, 18 Apr 2007 13:52:38 +0100 Subject: X root Operator help In-Reply-To: <1176898887.530470.222830@p77g2000hsh.googlegroups.com> References: <1176898887.530470.222830@p77g2000hsh.googlegroups.com> Message-ID: lucidparadox wrote: > I'm currently new to Python and I haven't been able to find the > operator/math function to find the square root or even the x root of a > number. For square root, use math.sqrt(y) For x root use y**(1/x) > I'm rewriting a program that I wrote in BASIC that does the > math of a quadratic equation (user puts in a, b, and c values) and > tells the user whether it has 1 root, 2 roots, or no real roots and > displays the roots if it has real roots. In floating point arithmetic, the naive way of calculating both roots always using the formula (-b +/- sqrt(b**2 - 4*a*c))/2*a will give you inaccurate results sometimes. See . For a better formula, see how r_1 and r_2 are defined in . -- Michael Hoffman From larry.bates at websafe.com Thu Apr 19 16:08:47 2007 From: larry.bates at websafe.com (Larry Bates) Date: Thu, 19 Apr 2007 15:08:47 -0500 Subject: Significance of "start" parameter to string method "endswith" In-Reply-To: <1177012694.726434.142660@q75g2000hsh.googlegroups.com> References: <1177012694.726434.142660@q75g2000hsh.googlegroups.com> Message-ID: Boris Du?ek wrote: > Hello, > > what is the use-case of parameter "start" in string's "endswith" > method? Consider the following minimal example: > > a = "testing" > suffix="ing" > a.endswith(suffix, 2) > > Significance of "end" is obvious. But not so for "start". > > Let's assume the "end" parameter is not used - then the function > should simple check that the last "len(suffix)" characters of "a" are > equal to "ing", no matter where we start (the function does not *scan* > the string from the "start", does it?) > Only case where it would make difference is if we had start + > len(suffix) < len(a) (excuse possible "of-by-one" error :-) > Then the function would never return True. But is there a real use > case when we would test for endswith like this? (knowing that it must > return false?) > > Thanks for any ideas/experience. > Boris > Seems like a convenience I've never used. >>> a="abcdef" >>> a.endswith('cd',2,4) True >>> a[2:4].endswith('cd') True -Larry From jzgoda at o2.usun.pl Wed Apr 4 15:31:58 2007 From: jzgoda at o2.usun.pl (Jarek Zgoda) Date: Wed, 04 Apr 2007 21:31:58 +0200 Subject: calling super() In-Reply-To: <1175714555.413502.77390@o5g2000hsb.googlegroups.com> References: <1175714555.413502.77390@o5g2000hsb.googlegroups.com> Message-ID: Finger.Octopus at gmail.com napisa?(a): > Hello, I have been trying to call the super constructor from my > derived class but its not working as expected. See the code: > > class HTMLMain: > def __init__(self): > self.text = ""; > print(self.text); > def __del__(self): > self.text = ""; > print(self.text); > > class NewPage(HTMLMain): > def __init__(self): > print 'derive2 init' > super(NewPage, self).__init__(); This should read: super(HTMLMain, self).__init__() I think it's just a quick-type-typo. ;) -- Jarek Zgoda http://jpa.berlios.de/ From steve at holdenweb.com Thu Apr 5 15:16:25 2007 From: steve at holdenweb.com (Steve Holden) Date: Thu, 05 Apr 2007 15:16:25 -0400 Subject: Can we make a local variable in a function as global variable??? In-Reply-To: <4c0048df0704051130k23b282av778059aa2fd64eb4@mail.gmail.com> References: <1175764774.260576.286420@y66g2000hsf.googlegroups.com> <4c0048df0704051130k23b282av778059aa2fd64eb4@mail.gmail.com> Message-ID: Collin Stocks wrote: > As for me, I find this problem annoying, but easy to solve. My solution is: > > >>> this=__import__(__name__) > > To set global variable spam to 4, I say: > > >>> this.spam=4 > > This always works, and is much more convenient than: > > >>> global spam > >>> spam=4 > > and then worry about local variables also named spam. > That's truly horrible. And what if you have a local variable called "this"? 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 Tue Apr 24 14:04:41 2007 From: nogradi at gmail.com (Daniel Nogradi) Date: Tue, 24 Apr 2007 20:04:41 +0200 Subject: Would You Write Python Articles or Screencasts for Money? In-Reply-To: <1hx2dvj.10ek1v51noh1otN%aleax@mac.com> References: <462DCCE6.9060908@taupro.com> <1hx2dvj.10ek1v51noh1otN%aleax@mac.com> Message-ID: <5f56302b0704241104m48d571c8r2c9816c5062eb658@mail.gmail.com> [Alex] > When cash is involved, it's important to avoid even the > slightest hint of a suggestion of a suspicion of a conflict of interest I propose the non-PSF sponsored Grand Prize For Successfully Squeezing 4 Of's In A Single Sentence should be received by Alex Martelli this month :) From bignose+hates-spam at benfinney.id.au Sun Apr 29 07:53:04 2007 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Sun, 29 Apr 2007 21:53:04 +1000 Subject: While we're talking about annoyances References: Message-ID: <878xcbflcv.fsf@benfinney.id.au> "BJ?rn Lindqvist" writes: > On the other hand, there seem to be some progress that could be made > to reduce the amount of work in writing documentation. > Documentation in Esperanto instead of English maybe? Lojban is both easier to learn world-wide than Euro-biased Esperanto, and computer-parseable. Seems a better[0]_ choice for computer documentation to me. .. _[0] ignoring the fact that it's spoken by even fewer people than Esperanto. -- \ "The greater the artist, the greater the doubt; perfect | `\ confidence is granted to the less talented as a consolation | _o__) prize." -- Robert Hughes | Ben Finney From ocollioud at gmail.com Tue Apr 3 10:12:36 2007 From: ocollioud at gmail.com (olive) Date: 3 Apr 2007 07:12:36 -0700 Subject: XML DTD analysis, diffing ... In-Reply-To: <1175608328.341381.97040@b75g2000hsg.googlegroups.com> References: <1175603926.371027.69390@e65g2000hsc.googlegroups.com> <1175606848.838850.18150@w1g2000hsg.googlegroups.com> <1175608328.341381.97040@b75g2000hsg.googlegroups.com> Message-ID: <1175609556.640954.301950@e65g2000hsc.googlegroups.com> Thanks Paul and Mike, I've found the good link and just downloaded pyXML. Olive. From sjmachin at lexicon.net Sat Apr 28 09:22:45 2007 From: sjmachin at lexicon.net (John Machin) Date: 28 Apr 2007 06:22:45 -0700 Subject: Program runs in all directories, except one.. In-Reply-To: References: Message-ID: <1177766565.118899.232620@e65g2000hsc.googlegroups.com> On Apr 28, 9:50 pm, "Theo v. Werkhoven" wrote: > Goodday, > > Something strange going on here. > A piece of code I wrote bombs out in one of de directories under $HOME, > but not in others. [snip] > def shiftout(numoctets): > os.system('clear') > ser = serial.Serial(0) > from array import array > octarray = [0] > for i in range(0,numoctets-1): > octarray.append(0) > > for octet in range(numoctets,0,-1): > octarray[octet-1]=1 > for shift in range(0,8): > strg = array("B",octarray).tostring() The above statement appears to be where the error manifests itself. Possibilities: (1) array is bound to a list (2) the result of array("B", octarray) has an attribute tostring which is bound to a list. Option (1) seems less implausible. I'd be replacing that line by: print "octet %r, shift %r, array %r" % (octet, shift, array) array_b = array("B", octarray) print "array_b %r" % array_b print "array_b.tostring %r" % array_b.tostring strg = array_b.tostring() You haven't shown us all of your code -- is array mentioned elsewhere? What other imports are you doing? Do you have a file called array.py in the offending directory? [I believe that this wouldn't matter, because builtin modules like array can't be overridden by a file-based module of the same name, but I could be wrong] What platform and what version of Python? HTH, John From tjandacw at yahoo.com Fri Apr 13 08:54:02 2007 From: tjandacw at yahoo.com (timw.google) Date: 13 Apr 2007 05:54:02 -0700 Subject: list of datasaources with pyodbc Message-ID: <1176468842.456183.186180@o5g2000hsb.googlegroups.com> How do I get a list of datasources with pyodbc? I know that with mx.ODBC.Windows I can use the DataSources method to get a dictionay containing the datasources. Is there a similar way to do this with pyodbc? Thanks in advance. From david at boddie.org.uk Tue Apr 24 18:11:47 2007 From: david at boddie.org.uk (David Boddie) Date: Wed, 25 Apr 2007 00:11:47 +0200 Subject: Generate report containing pdf or ps figures? References: <132pnp6r4qg0lc2@corp.supernews.com> <132sa3jkr5uv0a9@corp.supernews.com> <7mv1g4-jtn.ln1@lairds.us> Message-ID: <5d988$462e80a4$54d1d767$14779@news.chello.no> On Tuesday 24 April 2007 20:42, Cameron Laird wrote: > I want to make sure we're all keeping up with each other, so > I'll make explicit a couple of points, despite the risk of > redundancy: > A. Bundling GS is a little touchy, depending on > what you mean by that. Check out its license. > My summary: it's feasible, but not as trans- > parent as the technology in isolation might > suggest. I'm surprised you don't have more suggestions, Cameron, given that you collect links to PDF convertors. ;-) http://phaseit.net/claird/comp.text.pdf/PDF_converters.html > B. As Steve's already noted, the for-fee ReportLab > *does* (at least some of) the things you want. Another interesting approach might be to look at other members of ReportLab's family tree: http://sping.sourceforge.net/ http://sping.sourceforge.net/notesPDF/index.html However, it doesn't seem that either are capable of inserting the kinds of vector files you are using. It may be worth writing a quick and dirty PDF writer using an existing backend library, though I can imagine that the hard work would involve reading the different input formats you want to use. Anyway, for future reference, the following projects might prove to be inspiring: http://pyx.sourceforge.net/ http://pybrary.net/pyPdf/ David From jstroud at mbi.ucla.edu Tue Apr 3 19:29:23 2007 From: jstroud at mbi.ucla.edu (James Stroud) Date: Tue, 03 Apr 2007 16:29:23 -0700 Subject: Parsing a setup file In-Reply-To: References: Message-ID: Tommy Grav wrote: > Hi, > > I have a setup file for some numerical simulation code written in C > that looks like this: > > dt 0.1 > time 0.0 > nupdate 10 > noutput 100 > ntotal 10000 > G 39.476926421373015 > Sun 1.00000597682 > mplanet 9.547861040430418e-4 > 3.409530427945 3.635870038323 .03424028779975 > -2.0471057839802485 2.0178211484578044 -9.730193916219667e-4 > mplanet 2.8558373315055975e-4 > 6.612079829705 6.386934883415 -.1361443021015 > -1.5268292602445992 1.4623064051166743 6.108354829704997e-3 > mplanet 4.372731645458918e-5 > 11.16769742623 16.04343604329 .3617849409933 > -1.1927379555398092 .7563317049955387 -7.950313544811802e-3 > particle > 5.0 0.2 10.5 > 0.0 0.0 10.0 > particle > 6.0 0.1 5.5 > 0.0 180.0 -10.0 > > there can be any number of mplanet and particle enteries in the the file. > As I am working on porting this code to python I am trying to figure out > an efficient way of parsing such data into the program. I have the freedom > to play around with the setup file(s) which is nice. I have played > around with > cfgparse, which I like, and made a file like this > > [DEFAULT] > dt = 0.1 > time = 0.0 > > and so on, but that does not give me a good way of parsing in the list of > mplanets and particles. I can write my own little parser to handle a file > that contains only the mplanets or particles, but I am wondering if > there are > any parsers out there that will handle this type of data? Or is there a > way to organize my setup file that would simplify the input that I am > missing? > > Cheers > Tommy pyaml is good for this kind of thing. No parser needed. Also, you may be mistaken about ConfigParser, you just need to indent line continuations (and who says the syntactical meaning of whitespace is not a good thing?). E.g.: euler 6% cat test.conf [stuff] mplanet = 4.372731645458918e-5 11.16769742623 16.04343604329 .3617849409933 -1.1927379555398092 .7563317049955387 -7.950313544811802e-3 py> from ConfigParser import ConfigParser py> c = ConfigParser() py> c.read('test.conf') ['test.conf'] py> c.items('stuff') [('mplanet', '4.372731645458918e-5\n11.16769742623 16.04343604329 .3617849409933\n-1.1927379555398092 .7563317049955387 -7.950313544811802e-3')] James From john.pye at gmail.com Sat Apr 7 08:28:59 2007 From: john.pye at gmail.com (John Pye) Date: 7 Apr 2007 05:28:59 -0700 Subject: subprocess.Popen output to file? Message-ID: <1175948939.049050.74630@l77g2000hsb.googlegroups.com> Hi all I am trying to set up a python script to manage backups of a mysql database the 'right way' using pipes. I want to send the output of the 'mysqldump' command to a file. Using a normal shell script this would be easy using a ">" operator. What is the efficient and best way to do this using pure python, bearing in mind that it will be too much data to keep in memory? I presume using the subprocess module, but how to get the output to a file? It's not really documented, AFAICS. Cheers JP From ruiligc at earthlink.net Mon Apr 23 07:34:42 2007 From: ruiligc at earthlink.net (Ray) Date: Mon, 23 Apr 2007 11:34:42 GMT Subject: TK-grid problem, please help In-Reply-To: References: <3CgWh.23821$PL.17381@newsread4.news.pas.earthlink.net> Message-ID: Hi, Thanks for the help. I was trying to find a book "Python TK" something on last Friday. but didn't find it :-) I know those codes are in poor design, because I wrote those sample code to show the idea about what I need. the real code is working with mysql. however, I'm really new in python. (I start learning it on last Wednesday). Thanks again for the help! Ray James Stroud wrote: > > > Using grid_forget() is probably optimization overkill, but may be handy > for slower computers where you can watch the widgets appear one by one > (older than about 5 years--for example original mac ibook). Also, you > should get a good book on Tkinter because your design here will pretty > difficult to maintain and is not very flexible. > > But...if you want to know how it might be done with grid_forget using > the code you already have (i.e. making widgets only if necessary): > > > #START# > from Tkinter import * > from tkMessageBox import showerror > def mygrid(text): > ######## how to use grid_forget() to clean the grid??########### > numrows = len(frame3.rows) > try: > count=int(text) > except: > showerror('Entry Error', > '''Hey, "%s" don't make an int, Fool!''' % text, > parent=frame3) > return 'break' > for i in range(count): > if i < numrows: > cols = frame3.rows[i] > else: > cols = [Entry(frame3, relief=RIDGE) for j in range(4)] > frame3.rows.append(cols) > for j in range(4): > e = cols[j] > e.grid(row=i, column=j, sticky=NSEW) > e.delete(0,END) > e.insert(END, '%d.%d' % (i, j)) > for i in range(i+1, numrows): > for e in frame3.rows[i]: > e.grid_forget() > > > root=Tk() > > frame1=Frame(root, width=150, height=100) > frame1.pack() > > text=Entry(frame1) > text.pack(side=LEFT) > > button=Button(frame1, text='generate grid', command=(lambda: > mygrid(text.get()))) > > button.pack() > > frame2=Frame(root, width=150, height=100) > frame2.pack() > > button2=Button(frame2, text='exit', command=root.quit) > button2.pack() > > frame3=Frame(root, width=150, height=300) > # adding an attribute here > frame3.rows = [] > frame3.pack() > > root.mainloop() > #END# > > Notice also the necessity for the "e.delete(0, END)" line to get the > desired text in the entries. > > Also demonstrated is how to handle poor input. > > *Note* > Remember to always call the user "Fool" when he does something stupid. > > > James From steve at holdenweb.com Wed Apr 11 12:44:36 2007 From: steve at holdenweb.com (Steve Holden) Date: Wed, 11 Apr 2007 12:44:36 -0400 Subject: Parsing log in SQL DB to change IPs to hostnames In-Reply-To: <1176295161.448113.253650@w1g2000hsg.googlegroups.com> References: <1176219463.407804.315560@y80g2000hsf.googlegroups.com> <1176221494.813800.78580@y80g2000hsf.googlegroups.com> <1176231258.626137.228220@d57g2000hsg.googlegroups.com> <92%Sh.21541$tD2.14028@newsread1.news.pas.earthlink.net> <1176295161.448113.253650@w1g2000hsg.googlegroups.com> Message-ID: KDawg44 wrote: [ ... ] > > ohhh okay. thanks so much. I knew that it came out as strings, i > guess it makes sense that I would have to send it back IN as a > string. Changed that and now it works! THanks so much. > > I just specified once specific field so that it would not change the > whole db on a test run. > > Thanks so much. > It's great that you solved your problem, but please disabuse yourself of the notion that the database returns everything as strings: >>> curs.execute("SELECT * from contact") >>> data = curs.fetchone() >>> for item in data: ... print type(item) ... >>> 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 phd at phd.pp.ru Wed Apr 11 11:52:26 2007 From: phd at phd.pp.ru (Oleg Broytmann) Date: Wed, 11 Apr 2007 19:52:26 +0400 Subject: SQLObject 0.8.2 Message-ID: <20070411155226.GC21492@phd.pp.ru> Hello! I'm pleased to announce the 0.8.2 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 Development: http://sqlobject.org/devel/ 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.8.2 News and changes: http://sqlobject.org/News.html What's New ========== News since 0.8.1 ---------------- * Fixed ConnectionHub.doInTransaction() - if the original connection was processConnection - reset processConnection, not threadConnection. * Fixed a bug in DateValidator caused by datetime being a subclass of date. * Fixed test_deep_inheritance.py - setup classes in the correct order (required for Postgres 8.0+ which is strict about referential integrity). For a more complete list, please see the news: http://sqlobject.org/News.html Oleg. -- Oleg Broytmann http://phd.pp.ru/ phd at phd.pp.ru Programmers don't die, they just GOSUB without RETURN. From __peter__ at web.de Wed Apr 25 03:02:38 2007 From: __peter__ at web.de (Peter Otten) Date: Wed, 25 Apr 2007 09:02:38 +0200 Subject: trinary operator - if then else References: <1177484290.449378.93720@t38g2000prd.googlegroups.com> Message-ID: Alchemist wrote: > What is Python's version for the trinary if..then..else operator? true_value if condition else false_value > Does Python 2.4 support it? No, it requires 2.5 or later. Peter From Jun.Jin.act at gmail.com Mon Apr 16 22:10:37 2007 From: Jun.Jin.act at gmail.com (Jun.Jin.act+group.python@gmail.com) Date: 16 Apr 2007 19:10:37 -0700 Subject: strange behaviour with keyword arguments and inheritance In-Reply-To: <1176773781.729037.139650@y5g2000hsa.googlegroups.com> References: <1176771364.964642.209300@b75g2000hsg.googlegroups.com> <1176773781.729037.139650@y5g2000hsa.googlegroups.com> Message-ID: <1176775837.140883.287360@n76g2000hsh.googlegroups.com> On Apr 17, 9:36 am, livibetter wrote: > On Apr 17, 8:56 am, "matthewperpick" wrote: > > > Check out this toy example that demonstrates some "strange" behaviour > > with keyword arguments and inheritance. > > > ================================= > > > class Parent: > > def __init__(self, ary = []): > > self.ary = ary > > This should work: > > class Parent: > def __init__(self, ary = []): > self.ary = list(ary) > > And FYIhttp://groups.google.com/group/comp.lang.python/browse_thread/thread/... livibetter has a better solution. the reason is that you need to create a new list object everytime, am I right? From apardon at forel.vub.ac.be Wed Apr 11 09:13:20 2007 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 11 Apr 2007 13:13:20 GMT Subject: tuples, index method, Python's design References: <1175867771.114540.61810@n76g2000hsh.googlegroups.com> <1175884427.779950.267220@y80g2000hsf.googlegroups.com> <1175953520.316208.241490@o5g2000hsb.googlegroups.com> <7xzm5igbrb.fsf@ruckus.brouhaha.com> <1176200361.260546.280510@n76g2000hsh.googlegroups.com> <1176214831.3430.49.camel@dot.uniqsys.com> Message-ID: On 2007-04-11, Steven D'Aprano wrote: > On Wed, 11 Apr 2007 08:57:43 +0200, Hendrik van Rooyen wrote: > >> I can write: >> >> L = [a,b,c,d,e,f] >> T= (a,b,c,d,e,f) >> >> The difference between the two things is that I can add to >> and change L, but not T. > > No, that's *one* difference between the two things. There are other > differences, e.g. the obvious is that they are different types (and > therefore different string representations), but also some not so obvious: > >>>> hash((1,2,3)) > -378539185 > >>>> hash([1,2,3]) > Traceback (most recent call last): > File "", line 1, in > TypeError: list objects are unhashable > > > >> Now it seems to me that whatever argument is used to justify the >> existence of: >> >> n = L.index(d) >> >> can be used to justify the existence of: >> >> n = T.index(d) >> >> and vice versa. > > That depends on what you the purpose of lists and tuples are. Yes, they > are both sequences, but they have different uses. Ball-peen hammers and > tack hammers are both hammers, but they have different purposes and > therefore different functionality. Likewise for tuples and lists: > > Lists are designed for sequences of homogeneous items, e.g.: > > L = [1, 2, 4, 8, 16, 32] > while tuples are designed to be more like structs or records, with > heterogeneous items, e.g.: > > T = ("Fred", 32, 12.789, {}, None, '\t') I think you are confused. Last time I heard this homogeneous items stuf, it had nothing to do with the types being the same. They were homogeneous because they somehow belonged together and heterogeneous because they just happened to live together. Similarity of type played no part in calling the data homogeneous or heterogeneous. -- Antoon Pardon From dsampson at NRCan.gc.ca Thu Apr 19 08:49:05 2007 From: dsampson at NRCan.gc.ca (Sampson, David) Date: Thu, 19 Apr 2007 08:49:05 -0400 Subject: Do other Python GUI toolkits require this? In-Reply-To: References: <462697A6.6010007@codebykevin.com> <465B30B4-5BA0-459A-BE6F-1038874FA74B@jedimindworks.com> Message-ID: <2FAA57395C1F914DB27CAA4C376058F2024B84DD@S0-OTT-X2.nrn.nrcan.gc.ca> I don't know how this whole things started, But it is funny on both sides. And hilarious from the outside. It sounds like university Banter really. And who can avoid getting their 2 cents in. Honestly And people say computers are all about science. You guys prove that we are all as much tech geeks and semantic geeks. >From my own experiential education background, and currently trying to learn python I would say my exposure to python as a scripting language is a logical extension to my knowledge of DOS and BASH scripting so in that respect I am on a shallow learning curve. That is little effort (say 5 on the X axis) over a given time (say 10 y). Now, my goal is to take what I had learn about VB6 over the last number of months to modify a chunk of in-house software My learning curve was steeper. That is I had the same amount of time (10 y) but I had to put in some more effort, so a moderate curve using 10 X as my peak, or point where I plateau. However where I as a newbie am having a hard time is programming a GUI and full application using python (hence why I saw the topic), and understanding OOP. Therefore right now I feel as though I am on a steep learning curve. So maybe 20 or 30 on the X and I still have the same amount of time. To further support this I took the first result of google (of course the worlds most authoritative resource on randomness) and went to this BLOG (worlds best phenomena of random and unsubstantiated opinions). http://createwhatmattersmost.blogspot.com/2006/10/learning-curve-explain ed.html And found this I guess I'm approaching the "knee" of the learning curve, that magical transition point on the learning at which you begin to generate results far out of proportion to time and energy expended. This tells me my understanding is the common accepted one of X= Effort, Y= time or productivity ... But really productivity is a function of time. C'mon now folks, if this is university banter the least I should see is some referencing. Thanks for demonstrating my own lack of will power and propensity to engage in both of your OCB. Now I must get back to my steep learning curve or else I will be back on the street. Cheers -----Original Message----- From: python-list-bounces+dsampson=nrcan.gc.ca at python.org [mailto:python-list-bounces+dsampson=nrcan.gc.ca at python.org] On Behalf Of Steve Holden Sent: April 19, 2007 08:25 To: python-list at python.org Subject: Re: Do other Python GUI toolkits require this? Antoon Pardon wrote: > On 2007-04-19, Steve Holden wrote: >> Michael Bentley wrote: >>> On Apr 19, 2007, at 4:11 AM, Antoon Pardon wrote: >>> >>>> On 2007-04-19, Michael Bentley wrote: >> [...] The >>>>> learning curve is rather steep IMO, but worth it. >>>> Just a throw in remark, that you may ignore if you wish, but a >>>> steep learning curve means that the subject is easily familiarized >>>> and that the learning period is short. >>>> >>>> You seem to use it as if it is the opposite. >>> Mathematical absurdities aside, it's the common usage -- but perhaps >>> you knew that. >>> >>> >> Perhaps in Belgium they prefer climbing mountains over walking up and >> down gentle hills? Or possibly they will simply pick any nit that is >> carelessly left within range? > > If it is just a nit, why don't you ignore my remark as I suggested? > Because I suffer from the quixotic urge to help stamp out obsessive compulsive behavior on c.l.py? This is self-defeating, of course, since it makes me appear obsessive compulsive in my own right ... > Now suppose I give you a graph that shows you how different people are > making progress. Would you prefer the rather flat curves instead of > the steep curves because the latter gives you the idea of someone > having to conquer huge obstacles or would you choose the steep curve > because they show you someone is getting results fast? > Suppose I should you a hill you have to climb? Would you rather don mountain boots and crampons to climb 3,000 feet up a vertical cliff or would you rather amble up, say, Ben Lomond with the other tourists? Clearly you have no wish to bow before common usage. be careful this doesn't put you in a universe with only one inhabitant. We all have to get along. obsessive-compulsive-ly y'rs - 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 -- http://mail.python.org/mailman/listinfo/python-list From sergio.correia at gmail.com Thu Apr 5 02:31:21 2007 From: sergio.correia at gmail.com (Sergio Correia) Date: Thu, 5 Apr 2007 01:31:21 -0500 Subject: How to open a txt file from the same folder as my module (w/out changing the working dir) In-Reply-To: References: Message-ID: Larry, Gabriel Thanks for the replies. Both ways work great. Sergio On 4/4/07, Gabriel Genellina wrote: > En Wed, 04 Apr 2007 20:14:37 -0300, Larry Bates > escribi?: > > > Sergio Correia wrote: > >> I have a program in 'C:\Python25\Lib\site-packages\spam\spam.py' > >> > >> Importing and everything works fine: > >>>>> from spam import spam > >> > >> But the program calls a file located on the same folder (that is: > >> C:\Python25\Lib\site-packages\spam\). > >> > >> How do i do that? > > > > The problem is that C:\Python25\Lib\site-packages\spam is not > > the current working directory when you run the program. If it were, > > and if configuration.txt is in that directory it WILL find it. If > > you are running this from a shortcut make the working directory > > C:\Python25\Lib\site-packages\spam > > If changing the working directory is not possible/convenient, use the > module __file__ attribute (spam.__file__) to obtain the directory where > spam.py resides. > > -- > Gabriel Genellina > > -- > http://mail.python.org/mailman/listinfo/python-list > From Martin.Drautzburg at web.de Mon Apr 23 02:42:39 2007 From: Martin.Drautzburg at web.de (Martin Drautzburg) Date: Mon, 23 Apr 2007 08:42:39 +0200 Subject: Namespaces/introspection: collecting sql strings for validation References: <1921780.hifcbgjtIO@beaureve.gmx.net> <1177282603.660437.181440@e65g2000hsc.googlegroups.com> Message-ID: <3179196.dXgDsb4XXT@beaureve.gmx.net> George Sakkis wrote: > Yes, there is: use an ORM to do the SQL generation for you. Check out > SQLAlchemy, it will buy you much more than what you asked for. Might look, though in general I don't like OR mappers much. Having SQL generated feels as strange as having python code generated. Too much magic, too many layers. I think it is better to simply learn SQL. And I don't really believe in OO databases much. OO databases have been around for several decades and still have not reached the maturity of relational databases. My feeling is that OO and persistence to not play together well. From bjourne at gmail.com Tue Apr 10 18:34:16 2007 From: bjourne at gmail.com (=?ISO-8859-1?Q?BJ=F6rn_Lindqvist?=) Date: Wed, 11 Apr 2007 00:34:16 +0200 Subject: tuples, index method, Python's design In-Reply-To: <4866bea60704101104r4600d281h135286b66378f4d4@mail.gmail.com> References: <1176210960.3430.20.camel@dot.uniqsys.com> <740c3aec0704100810g5f962e8eu614fbaedecf3608e@mail.gmail.com> <1176219856.3430.76.camel@dot.uniqsys.com> <740c3aec0704101021i1fd79ef2l99eac4ced1e252d9@mail.gmail.com> <1176226682.3430.86.camel@dot.uniqsys.com> <4866bea60704101104r4600d281h135286b66378f4d4@mail.gmail.com> Message-ID: <740c3aec0704101534y3c65f5a7je382f97e1f6301b7@mail.gmail.com> > > while not game_has_ended: > > for current_player in p: > > player_does_something(current_player) > > > > I'm curious why someone would even consider using a tuple in this case > regardless. I think that much of the desire for tuple.index is because > people use a tuple where they could have a list, but either a) some > vestige of B&D language programming comes out and they want to make Maybe someone had to much alcohol when they were coding? Maybe they don't know better? Maybe they thought that an index method on a sequence made sense? Who are you to spoil their fun? Could it be that YOU are the B&D person? -- mvh Bj?rn From kw at codebykevin.com Wed Apr 18 18:11:50 2007 From: kw at codebykevin.com (Kevin Walzer) Date: Wed, 18 Apr 2007 18:11:50 -0400 Subject: Do other Python GUI toolkits require this? In-Reply-To: References: Message-ID: <462697A6.6010007@codebykevin.com> James Stroud wrote: > This appears more or less unique to Objective C. It looks that with > PyObjC, you have to interact with the Objective C runtime to manage > memory. This is not required, thankfully, with any other GUI tookits > I've seen. > > I think the main difference is that PyObjC is not a GUI toolkit per se, > but is simply a means to make the Objective C runtime (and hence Cocoa) > available via a python layer. > > James That's kind of what I thought. Memory management? In Python? *shudder* I'm a Mac-only developer, and I keep telling myself I should drink the Mac-only Kool-aid of PyObjC. But Tk is burned into my brain, and anything else looks and feels weird to me. Tk is so flexible that it's fairly easy to tweak it to look Mac-like, and it's simpler to do that than learn a new tookit. -- Kevin Walzer Code by Kevin http://www.codebykevin.com From mathedman at hotmail.com.CUT Wed Apr 18 17:39:17 2007 From: mathedman at hotmail.com.CUT (mathedman at hotmail.com.CUT) Date: Wed, 18 Apr 2007 21:39:17 GMT Subject: ??? POLICE AND CITY/UNIVERSITY OFFICIALS INCOMPETENCE LEADS TO 33 KILLED BY KOREAN-ALQAEDA TERRORIST ??? References: <1176818165.135834.214220@y80g2000hsf.googlegroups.com> Message-ID: On 17 Apr 2007 06:56:05 -0700, thermate at india.com wrote: So many of the talking-head rants about VPI are idiotic. 1) bomb scares should have ak\lerted officials --blah blah blah The fact is that on a large university campus bomb threats are almost as common as exams! (there is a correlation!) They are quietly checked out without emptying dorms or CLASSROOMS. 2)VPI is not a "schoolhouse: and the students are NOT kids. The stiudents are adults. In fact, it is a violation of federal law for a university officials to discuss a student's performasnce with the parents! 3) Lock-down-- INSANE VPI is a small city.About 30,000 people, dozens of buildings ( some a mile apart) on 2600 acres (more than 3 times the size of NY's Central Park. It is not fenced or walled. The grounds and even the hallways of classroom buildings are coinsidered "public" Select your favorite city of 30,000 people. Consider: police are called to an apartment building to investigate reported gunshots. They find two dead and questioning leads to reports that the killer left "town". Do they lock down the entire town? Of course not --- it's not feasable --- Nor would they notify all residents of danger -- there was no reason to believe there was --- VPI of such a "city" --- and police already had a "person of interest" for the two killings --- a gun "enthusiast" ---the boyfriend of the dead girl. I have spent many years on university campuses. But, I have never had any association with VPI and ave never been there. From duncan.booth at invalid.invalid Fri Apr 13 03:30:39 2007 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 13 Apr 2007 07:30:39 GMT Subject: Calling private base methods References: <1176374675.347453.89340@n76g2000hsh.googlegroups.com> <1176404325.211501.26610@w1g2000hsg.googlegroups.com> <1176435087.708516.66470@o5g2000hsb.googlegroups.com> Message-ID: "7stud" wrote: >> Really, it does work (probably). There are other ways to get at private >> members in C++ but this is the easiest. > > I can also access private methods of a class if my sister backspaces > over "private" and types "public" instead. > > In your example, no private methods were ever created, and therefore > you are not accessing private methods. > Are you being deliberately obtuse? The methods are private throughout the program *except* for the one source file where you do this trick. It won't work if the compiler mangles the protection into the name, but I have used this successfully with a C++ library where I absolutely couldn't do what I needed without getting at a private method. The fact that I had to resort to this trick is a big indication of course that genuinely private members (as opposed to a 'keep off' naming convention) are a bad idea in general. If the name does get mangled then you may of course have to do other much messier tricks to get at the address of the function and then call it. From ocollioud at gmail.com Wed Apr 4 07:29:48 2007 From: ocollioud at gmail.com (olive) Date: 4 Apr 2007 04:29:48 -0700 Subject: how to build a forum in Python? In-Reply-To: <1175672984.836097.21610@n76g2000hsh.googlegroups.com> References: <1175672984.836097.21610@n76g2000hsh.googlegroups.com> Message-ID: <1175686188.212319.292750@q75g2000hsh.googlegroups.com> http://code.google.com/p/diamanda/ From duncan.booth at invalid.invalid Thu Apr 5 16:22:30 2007 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 5 Apr 2007 20:22:30 GMT Subject: RFC: Assignment as expression (pre-PEP) References: <1175802680.021987.39220@p77g2000hsh.googlegroups.com> Message-ID: TimeHorse at gmail.com wrote: > Performing a list of mutually exclusive checks that require data > processing can cause excessive tabification. For example, consider > the following python snipet... > > temp = my_re1.match(exp) > if temp: > # do something with temp > else: > temp = my_re2.match(exp) > if temp: > # do something with temp > else: > temp = my_re3.match(exp) > if temp: > # do something with temp > else: > temp = my_re4.match(exp) > Can you come up with a real example where this happens and which cannot be easily rewritten to provide better, clearer code without the indentation? I'll admit to having occasionally had code not entirely dissimilar to this when first written, but I don't believe it has ever survived more than a few minutes before being refactored into a cleaner form. I would claim that it is a good thing that Python makes it obvious that code like this should be refactored. From gagsl-py2 at yahoo.com.ar Thu Apr 26 03:20:21 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 26 Apr 2007 04:20:21 -0300 Subject: Access to raw command line? References: <1177571070.229968.155710@t39g2000prd.googlegroups.com> Message-ID: En Thu, 26 Apr 2007 04:04:30 -0300, Pieter Edelman escribi?: > Now, one of the users has quite a lot of info files, and asked me if > it's possible to use a wildcard in specifying these, so he would just > have to do: > ./myprog.py -t *.gpx *.jpg > > This seems like a sensible option at first sight, but it's difficult > to implement because the wildcard is expanded by the shell, so > sys.argv gets a list containing "-t", all .gpx files and all .jpg > files. With this list, there's no way to tell which files belong to > the "-t" switch and which are arguments (other than using the > extension). I can't verify right now, but I think that using -t "*.gpx" would avoid the shell expansion. (Or perhaps '*.gpx' or \*.gpx or even -t*.gpx) -- Gabriel Genellina From spamtrap at dot-app.org Thu Apr 5 21:16:07 2007 From: spamtrap at dot-app.org (Sherm Pendley) Date: Thu, 05 Apr 2007 21:16:07 -0400 Subject: Why NOT only one class per file? References: <1175721799.714907.52770@o5g2000hsb.googlegroups.com> <46142acc$0$7532$426a34cc@news.free.fr> <4614b40e$0$26843$426a74cc@news.free.fr> <46154952$0$23907$426a74cc@news.free.fr> <46158702$0$18849$426a74cc@news.free.fr> Message-ID: Bruno Desthuilliers writes: > Sherm Pendley a ?crit : >> Bruno Desthuilliers writes: >> >> >>>Sherm Pendley a ?crit : >>> >>>In my book, it's huge classes and methods that are usually a smell of >>>a design problem. >> >> >> Obviously we're reading different books. > > Obviously. But I didn't gain this knowledge from books. Obviously, you have no sense of humor. > FWIW, I'd be interested if you'd let us know about any book pretending > that monster classes are good design !-) You've already decided that "monster classes" are bad design, and that anything conflicting with your belief is mere pretense. Why should I waste my time debating when you've already made up your mind? >> But that's OK - I'm not on a crusade to convince everyone to work my way. >> If "one class per file" doesn't work well for you, don't write that way. >> All I'm saying is, what works well for you isn't necessarily what works >> well for everyone. > > It seems that it works well for almost anyone having some real-world > experience with languages like Python. I didn't say otherwise. You're arguing a false dichotomy; the fact that one approach works well does not prove that others won't work equally well. I'm not saying that your preferred style is wrong; I'm just saying that it's a matter of preference, not a universal truth. sherm-- -- Web Hosting by West Virginians, for West Virginians: http://wv-www.net Cocoa programming in Perl: http://camelbones.sourceforge.net From scott.daniels at acm.org Sun Apr 22 15:09:52 2007 From: scott.daniels at acm.org (Scott David Daniels) Date: Sun, 22 Apr 2007 12:09:52 -0700 Subject: Namespaces/introspection: collecting sql strings for validation In-Reply-To: <1921780.hifcbgjtIO@beaureve.gmx.net> References: <1921780.hifcbgjtIO@beaureve.gmx.net> Message-ID: <132ncmi64r20vc6@corp.supernews.com> Martin Drautzburg wrote: > I would like to validate sql strings, which are spread all over the > code, .... The statements will not be assembled from smaller pieces, > but they will not neccessarily be defined at module level. I could > live with class level, .... > parse the source file, but I am willing to mark the strings so it is > easier to tell sql from non-sql. > > ... Or is there a completely different way to do such a thing? How about using some variation of: class _Dummy: pass OLD_STYLE = type(_Dummy) def generate_strings(module): '''Generate triples for a module''' for top_level_name in dir(module): top_level_value = getattr(module, top_level_name) if isinstance(top_level_value, basestring): # strings yield None, top_level_name, top_level_value elif isinstance(top_level_value, type): # new-style class for name in dir(top_level_value): value = getattr(top_level_value, name) if isinstance(value, basestring): yield top_level_name, name, value def sometest(somestring): '''Your criteria for "is an SQL string and has misspellings".''' return len(somestring) > 20 and ' def investigate(module): for modname in sys.argv[1:]: for class_, name, text in generate_strings( __import__(modname)): if remarkable(text): if class_ is None: print 'Look at %s's top-level string %s.' % ( modname, name) else: print "Look at %s, class %s, string %s.' % modname, class_, name) if __name__ == '__main__': import sys for modname in sys.argv[1: ]: investigate(modname, sometest) -- --Scott David Daniels scott.daniels at acm.org From usenet-mail-0306.20.chr0n0ss at spamgourmet.com Tue Apr 3 09:16:39 2007 From: usenet-mail-0306.20.chr0n0ss at spamgourmet.com (Bjoern Schliessmann) Date: Tue, 03 Apr 2007 15:16:39 +0200 Subject: Question about text in Python References: <4610c366$0$15022$5a62ac22@per-qv1-newsreader-01.iinet.net.au> <57cbejF2cataiU1@mid.individual.net> <4611af55$0$15038$5a62ac22@per-qv1-newsreader-01.iinet.net.au> Message-ID: <57f2dnF2boldgU1@mid.individual.net> Steve wrote: > Yes it is. > > Where else to ask for help but here. http://www.catb.org/~esr/faqs/smart-questions.html#homework Regards&Good luck, Bj?rn -- BOFH excuse #247: Due to Federal Budget problems we have been forced to cut back on the number of users able to access the system at one time. (namely none allowed....) From ecpbm765 at gmail.com Mon Apr 23 21:57:07 2007 From: ecpbm765 at gmail.com (ecpbm765 at gmail.com) Date: 23 Apr 2007 18:57:07 -0700 Subject: Python Widget to read in user input box in blog Message-ID: <1177379827.873957.47760@n76g2000hsh.googlegroups.com> Hey, I am helping to develop a project that displays images based on user input. One possible way of implementing this is via a widget that when it is run, would read in the users input from an input text field (probably from a blog), and replace it with the HTML that would display those images. This is more a proof of concept, so really all I am wondering is if there is a good way in Python to read in the text the user has typed and change it before the user hits submit? Thanks From rNOSPAMon at flownet.com Sat Apr 14 03:10:16 2007 From: rNOSPAMon at flownet.com (Ron Garret) Date: Sat, 14 Apr 2007 00:10:16 -0700 Subject: BaseHTTPServer and Apache References: <1176514240.915684.11410@y5g2000hsa.googlegroups.com> Message-ID: In article <1176514240.915684.11410 at y5g2000hsa.googlegroups.com>, "Luis M. Gonz?lez" wrote: > On Apr 13, 8:44 pm, Ron Garret wrote: > > In article , > > Ron Garret wrote: > > > > > Does > > > anyone know of a straightforward way to get Apache to "forward" requests > > > to a given path to another HTTP server running on a different port? > > > > Never mind, I think I figured it out. Apparently what I need is the > > ProxyPassReverse directive. > > > > I'd still be interested in hearing about people's experience using > > BaseHTTPServer for real applications. > > > > Thanks, > > rg > > > Some python web frameworks use the aproach you described by means of > mod_rewrite. > For example, Karrigell and Cherrypy (although they offer also other > ways of deployment). > This page in Karrigell's docs show how: > http://karrigell.sourceforge.net/en/apache.htm Thanks for that pointer. Using the 502 handler to start the server is a nifty trick. So I've got all that working now. Next question: how do I set things up so that I can communicate to my server through a unix domain socket instead of a TCP socket? (The reason I want to do this is that I'm running multiple copies of this server so that multiple engineers can do development each in their own sandbox, and assigning each of them their own port number is a configuration nightmare.) I got as far as rewriting the server code to use a unix socket, but then I got stuck. rg From wyldwolf at gmail.com Thu Apr 12 12:48:15 2007 From: wyldwolf at gmail.com (Kevin Kelley) Date: Thu, 12 Apr 2007 11:48:15 -0500 Subject: "Cloning" file attributes and permissions In-Reply-To: <1176394818.428367@jubilee.claranet.pt> References: <1176394818.428367@jubilee.claranet.pt> Message-ID: <77895c1d0704120948k377a1be6gd8b3c3758ac5d404@mail.gmail.com> The os module has this ability: http://docs.python.org/lib/os-file-dir.html -- Kevin Kelley On 4/12/07, Paulo da Silva wrote: > > Hi! > > I need to process a file to produce another file that *must* have > *exactly* the same attributes and permissions of the former. What is the > best way to do this? The file must not exist with contents (it may exist > empty) unless it has the same attributes and permissions. > I know how to do this using, let me call it, "C type code" (stat, chmod, > chown, etc). I would like to hear some opinions on if and how it would > be possible in a more elegant/python way. > > Thanks. > Paulo > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From steve at holdenweb.com Mon Apr 23 08:17:23 2007 From: steve at holdenweb.com (Steve Holden) Date: Mon, 23 Apr 2007 08:17:23 -0400 Subject: Python and Javascript equivalence In-Reply-To: References: Message-ID: Sam the Cat wrote: > Hey All, > > I am writing some COM code in Python to control photoshop. Several > functions of PS require an "Array" argument. In the examples of VBscript or > javascript the Array type is used. I have tried what would appear to be the > equivalent in Python -- Lists and Tuples -- but to no avail. Anyone have > any insight on what via the COM interface is equivalent to an Array in > javascript ? > The nest way to approach an answer to your question would be for you to post a VB snippet from one of the examples together with your attempt to do the same thing in Python plus the error traceback (or other such messages as you may see) generated when your attempts fails. Otherwise the question is just a bit too broad to give an answer. 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 Thu Apr 5 17:52:10 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Thu, 05 Apr 2007 18:52:10 -0300 Subject: ipython env References: <15e66e4e0704051448l3f4cb5cesead7ea356729671f@mail.gmail.com> Message-ID: En Thu, 05 Apr 2007 18:48:27 -0300, Greg Donald escribi?: > Anyone know what's up with environment variables when using ipython? > > When I type 'env' and hit return I get a dictionary full of useful > information (trimmed for brevity): > But then when try to access the information in the dictionary it > doesn't seem to exist: > > In [2]: env['EDITOR'] > --------------------------------------------------------------------------- > exceptions.NameError Traceback (most > recent call last) > > /Users/destiney/ > > NameError: name 'env' is not defined Try os.environ -- Gabriel Genellina From DustanGroups at gmail.com Tue Apr 24 19:32:25 2007 From: DustanGroups at gmail.com (Dustan) Date: 24 Apr 2007 16:32:25 -0700 Subject: Where's the source code for __builtin__? Message-ID: <1177457545.075398.204990@r3g2000prh.googlegroups.com> I've been paging through the source code for various C modules in python, and wanted to find the source of some of the builtin functions. I searched through the Modules, Objects, Python, and Parser folder, searched docs.python.org, searched the archived messages of this group, searched the web, and got absolutely nowhere in finding a __builtin__.c, or anything that contains the builtin source code. Help? From erikwickstrom at gmail.com Thu Apr 5 12:01:14 2007 From: erikwickstrom at gmail.com (erikcw) Date: 5 Apr 2007 09:01:14 -0700 Subject: AttributeError: 'tuple' object has no attribute 'encode' In-Reply-To: <1175787697.717321.290600@e65g2000hsc.googlegroups.com> References: <1175787095.862712.297480@n76g2000hsh.googlegroups.com> <1175787697.717321.290600@e65g2000hsc.googlegroups.com> Message-ID: <1175788874.318167.248220@d57g2000hsg.googlegroups.com> On Apr 5, 11:41 am, kyoso... at gmail.com wrote: > On Apr 5, 10:31 am, "erikcw" wrote: > > > Hi, > > > I'm trying to build a SQL string > > > sql = """INSERT INTO ag ('cid', 'ag', 'test') VALUES(%i, %s, %d)""", > > (cid, ag, self.data[parent][child]['results']['test']) > > > It raises this error: AttributeError: 'tuple' object has no attribute > > 'encode' > > > Some of the variables are unicode (test and ag) - is that what is > > causing this error? What do I need to do to make it work? > > > Thanks! > > Erik > > It sounds like you're not calling the "encode" method correctly. But > it's hard to say when you didn't include that bit of code. You may > need to check your database's docs to make sure it accepts unicode > strings and if so, what types (utf-8, 16, 32). > > See this post for a similar problem: > > http://lists.modevia.com/archives/py-transports/2005-December/001719.... > > and this link details tuple usage:http://www.faqs.org/docs/diveintopython/odbchelper_tuple.html > > Mike I tried adding .encode("utf-8") onto each of the variables in the tuple, but that didn't seem to help. The error just changes slightly to AttributeError: 'long' object has no attribute 'encode' I'm using Mysql. From g.brandl at gmx.net Sun Apr 1 19:35:17 2007 From: g.brandl at gmx.net (Georg Brandl) Date: Mon, 02 Apr 2007 01:35:17 +0200 Subject: How can i compare a string which is non null and empty In-Reply-To: <1175469766.979636.65020@e65g2000hsc.googlegroups.com> References: <1175469766.979636.65020@e65g2000hsc.googlegroups.com> Message-ID: Plissken.s at gmail.com schrieb: > Hi, > > how can i compare a string which is non null and empty? > > > i look thru the string methods here, but cant find one which does it? > > http://docs.python.org/lib/string-methods.html#string-methods > > In java,I do this: > if (str != null) && (!str.equals("")) .... > > how can i do that in python? Strings cannot be "null" in Python. If you want to check if a string is not empty, use "if str". This also includes the case that "str" may not only be an empty string, but also None. Georg From robert.kern at gmail.com Tue Apr 3 19:11:43 2007 From: robert.kern at gmail.com (Robert Kern) Date: Tue, 03 Apr 2007 18:11:43 -0500 Subject: Calling Fortran from Python In-Reply-To: <1175640339.648190.207530@y66g2000hsf.googlegroups.com> References: <1175640339.648190.207530@y66g2000hsf.googlegroups.com> Message-ID: Mangabasi wrote: > Has anyone provide a similar example with Pyfort, F2Py or calldll? With the latest f2py in numpy: $ cat sample.pyf ! -*- f90 -*- ! Note: the context of this file is case sensitive. python module sample ! in interface ! in :sample subroutine sample(ierr1,ierr2,ain,aout) ! in :sample:sample.f integer intent(out) :: ierr1 integer intent(out) :: ierr2 real*8 dimension(*),intent(in) :: ain !! This is what I had to modify from the generated interface. I !! changed 'dimension(*)' to 'dimension(len(ain))'. real*8 dimension(len(ain)),intent(out) :: aout end subroutine sample end interface end python module sample ! This file was auto-generated with f2py (version:2_3582). ! See http://cens.ioc.ee/projects/f2py2e/ ]$ f2py -c -m sample sample.pyf sample.f running build running config_fc running build_src building extension "sample" sources creating /tmp/tmpZL8qAw creating /tmp/tmpZL8qAw/src.macosx-10.3-fat-2.5 f2py options: [] f2py: sample.pyf Reading fortran codes... Reading file 'sample.pyf' (format:free) Post-processing... Block: sample Block: sample Post-processing (stage 2)... Building modules... Building module "sample"... Constructing wrapper function "sample"... ierr1,ierr2,aout = sample(ain) Wrote C/API module "sample" to file "/tmp/tmpZL8qAw/src.macosx-10.3-fat-2.5/samplemodule.c" adding '/tmp/tmpZL8qAw/src.macosx-10.3-fat-2.5/fortranobject.c' to sources. adding '/tmp/tmpZL8qAw/src.macosx-10.3-fat-2.5' to include_dirs. ... Etc. $ ipython Activating auto-logging. Current session state plus future input saved. Filename : /Users/rkern/.ipython/ipython.log Mode : backup Output logging : False Raw input log : False Timestamping : False State : active In [1]: import sample In [2]: sample.sample([1, 2, 3]) Out[2]: (0, 0, array([ 4., 6., 0.])) -- 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 gagsl-py2 at yahoo.com.ar Wed Apr 11 15:57:11 2007 From: gagsl-py2 at yahoo.com.ar (Gabriel Genellina) Date: Wed, 11 Apr 2007 16:57:11 -0300 Subject: ValueError: too many values to unpack References: <1176311618.617765.120560@p77g2000hsh.googlegroups.com> <1176319688.666986.183980@o5g2000hsb.googlegroups.com> Message-ID: En Wed, 11 Apr 2007 16:28:08 -0300, fscked escribi?: >> Trying to use CSV to read in a line with 11 fields and I keep getting >> this error. I have googled a bit and have been unable to figure it > > myfile = open('ClientsXMLUpdate.csv') > csvreader = csv.reader(myfile) > > for boxid, mac, activated, hw_ver, sw_ver, heartbeat, name, address, > phone, country, city in csvreader: > mainbox = SubElement(root, "{Boxes}box") > [...] You say all rows have 11 fields, the csv module insists on an error... try using some print statements to see who is right: for index, items in enumerate(csvreader): print index, len(items) if len(items)!=11: print items -- Gabriel Genellina From grante at visi.com Wed Apr 18 13:26:54 2007 From: grante at visi.com (Grant Edwards) Date: Wed, 18 Apr 2007 17:26:54 -0000 Subject: subprocess "handle is invalid" error References: <132cdrpqsmnvpa7@corp.supernews.com> <4626450b$1@nntp.zianet.com> Message-ID: <132cl6ui2ksbjaa@corp.supernews.com> On 2007-04-18, Erik Johnson wrote: > > "Grant Edwards" wrote in message > news:132cdrpqsmnvpa7 at corp.supernews.com... > > >> How does one troubleshoot errors that happen three layers deep >> in the subprocess module? > > I think the problem is more likely in how your py2exe is > getting bundled, rather than any real problem with the > subprocess module. I've switched back to os.popen() since I seem to get the same problems with either. The odd thing is that it only seems to fail when the current directory is mounted via the network _and_ when it's being started by clicking on a file whose filetype is associated with the application. Running the program from the command line (cmd.exe or bash) always works for any current directory. Running the program by cliking on a shortcut icon on the desktop always works for any 'start in' directory. The one case that doesn't work is when its run by clicking on an associated file on a network drive. -- Grant Edwards grante Yow! Now I'm concentrating at on a specific tank battle visi.com toward the end of World War II!